Skip to main content

day_toolkit_appkit/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-appkit: the macos-appkit backend (DESIGN.md §9). objc2, pure Rust, no shim.
5//!
6//! `Handle = Retained<NSView>`. Containers are flipped `NSView`s (top-left origin, so Day's
7//! frames apply directly and survive diffing). One custom target class (`DayTarget`) forwards
8//! target/action + text-delegate callbacks into the Day event sink, node-id keyed (§8.3).
9
10#![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
84/// Icon resolution for a piece renderer's own `NSToolbar` items (see `toolbar::image_for`).
85pub use toolbar::image_for as toolbar_image;
86
87// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
88mod 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
102// ---------------------------------------------------------------------------
103// Event plumbing: node-id keyed sink, thread-local (single UI thread)
104// ---------------------------------------------------------------------------
105
106/// The day-core event sink (node-id keyed).
107type Sink = Rc<dyn Fn(NodeId, Event)>;
108
109day_core::tls_group! {
110    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
111    /// Keeps each control's `DayTarget` alive (target/action holds it weakly).
112    static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
113    /// The style each button currently carries, keyed by its view pointer.
114    ///
115    /// Needed because a tinted title is an attributed string (see `set_button_title`), and
116    /// `ButtonPatch::Title` would otherwise replace it with a plain one and lose the color.
117    static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
118        RefCell::new(HashMap::new());
119    /// Original template images, retained across tint changes and swept on view release.
120    static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
121    /// Each button's selected state (`ButtonProps::selected`), keyed by its view pointer: what
122    /// the `action:` handler restores after a click toggles a push-on/push-off button, and the
123    /// buttons whose `state` `read_native` reports as `checked`.
124    static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
125
126    /// Canvas ptr → its display list. A [`SideTable`], so the release sweep reclaims it
127    /// (replay inserted but nothing ever removed).
128    static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
129    /// Views the app gave an accessibility label (`set_a11y`): a button's title change must then
130    /// leave the label alone (`apply_button_content`). Swept on release like the other tables.
131    static APP_LABELED: SideTable<()> = SideTable::new();
132    /// How each image view renders its glyph (docs/vectors.md "Tint", "Template"): whether it
133    /// was realized as a template, and whether a tint is on it now. Template rendering is a
134    /// property of the NSImage, so a source swap has to re-apply it, and a tint patch of `None`
135    /// keeps a template in the neutral tint rather than returning to the authored art. Swept
136    /// on release.
137    static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
138    /// Each transformed view's `Transform` (`set_transform`). AppKit owns a layer-backed view's
139    /// layer geometry and re-syncs it from the view, so a transform written into the layer
140    /// never showed. It is expressed in the view's own geometry instead (`apply_geometry`).
141    static TRANSFORMS: SideTable<Transform> = SideTable::new();
142    /// Each view's frame as Day laid it out, before any translation, so a translation change can
143    /// move the view without waiting for the next layout.
144    static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
145    static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
146    /// A presented cover sheet's window → its cover node, for Escape (docs/cover.md).
147    static SHEET_NODES: SideTable<NodeId> = SideTable::new();
148    static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
149    /// View ptr → node for `GestureKind::Pan` (docs/shapes.md): macOS pans arrive as trackpad
150    /// scroll events, so `DayCanvas::scrollWheel:` reports them here instead of a recognizer.
151    static PAN_NODES: SideTable<NodeId> = SideTable::new();
152    static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
153    /// View ptr → node for `GestureKind::Hover` (docs/canvas.md "Interaction"). Hover is not a
154    /// recognizer on macOS either: it is an `NSTrackingArea` plus the three mouse methods, so
155    /// like [`PAN_NODES`] this holds the canvases that asked and `DayCanvas` reports for them.
156    static HOVER_NODES: SideTable<NodeId> = SideTable::new();
157    /// View ptr → node for `GestureKind::Rotate` (docs/canvas.md "Zoom and pan"). A trackpad
158    /// rotation arrives as `NSEventTypeRotate` events at the view under it, alongside the
159    /// magnify events the pinch recognizer reads, so `DayCanvas::rotateWithEvent:` reports
160    /// it and the two gestures run at once rather than competing as two recognizers would.
161    static ROTATE_NODES: SideTable<NodeId> = SideTable::new();
162    /// Canvas view ptr → the rotation accumulated since the trackpad gesture's `Began`, in
163    /// radians: the events carry per-event degrees, and Day's contract is cumulative.
164    static ROTATE_ANGLE: SideTable<f64> = SideTable::new();
165    /// Canvas view ptr → its node, so the view's own `keyDown:` knows who to report to. Every
166    /// canvas is registered at realize (unlike [`PAN_NODES`], which only holds the ones that
167    /// asked for a pan) because focus, not a gesture, is what decides who hears a key.
168    static KEY_NODES: SideTable<NodeId> = SideTable::new();
169    /// Focusable container view ptr → its node (docs/focus.md): `Decorate::focusable` opts a
170    /// `DayFlipped` into the canvas contract (accepts first responder, takes focus on a
171    /// press, reports both directions, hears the arrows). Empty for every container that
172    /// never asked, whose behavior is exactly as before.
173    static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
174    /// Canvas view ptr → the text an input method is still composing in it (docs/menus.md
175    /// "The full route"): a dead key's accent, a Japanese reading. Nothing reaches the app
176    /// until the input method commits; the entry is gone the moment it does or cancels.
177    static MARKED: SideTable<String> = SideTable::new();
178    /// The key press the text input system is interpreting right now: its unmodified name and
179    /// the modifier mask, so the text it commits is named by the key that typed it.
180    static INTERPRETING: RefCell<Option<(String, u8)>> = const { RefCell::new(None) };
181
182    /// Keeps each view's gesture targets alive + records which gestures are attached (idempotent).
183    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    /// Handles whose frames are native-owned (nav pages): set_frame skips them.
188    static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
189        RefCell::new(std::collections::HashSet::new());
190    /// Each nav page's pane, recorded at realize because `insert` sees only handles
191    /// (docs/size-classes.md). Identity rather than position: a re-present re-homes the pages
192    /// without changing their order, so "index 0 is the sidebar" stops being true the moment a
193    /// host can morph. A [`SideTable`]: `remove` clears it on the normal path, and the release
194    /// sweep catches a page released without one (a stale entry could mis-pane a recycled ptr).
195    static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
196
197    static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
198    /// INSPECTOR_PANE ptr → is-panel, recorded at realize because `insert` sees only handles.
199    /// A [`SideTable`]: the release sweep drops it with the view.
200    static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
201
202    /// Split host (the wrap around an `NSSplitView`, docs/split.md) ptr → its state.
203    static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
204    /// SPLIT_PANE ptr → is-second, recorded at realize because `insert` sees only handles.
205    static SPLIT_PANES: SideTable<bool> = SideTable::new();
206
207    /// Outline ptr → its data source, for [`DayNavOutlineView::menu_for_event`]'s row lookup.
208    /// A [`SideTable`], reclaimed by the outline-keyed auxiliary sweep in `release`: the entry
209    /// used to outlive its host, so a recycled outline address served the dead menu's rows.
210    static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
211
212    static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
213    /// Tree host scroll-view ptr → (outline, data source) (docs/tree.md).
214    static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
215
216    /// `BitmapId` → the decoded image (docs/images.md). Keyed by the id day-core minted, not by
217    /// a view pointer: a bitmap outlives any one view and may be drawn by several at once.
218    /// Entries leave only through `release_image`, which day-core calls when the app drops its
219    /// last `Bitmap` handle.
220    static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
221    /// The fonts a painting thread's text ops resolve to, keyed by (size bits, font): filled
222    /// by [`OffscreenResources`] for one export at a time (docs/canvas.md "Exporting"), since
223    /// `NSFontManager` belongs to the UI thread. Empty on the UI thread itself.
224    static OFFSCREEN_FONTS: RefCell<Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>> =
225        const { RefCell::new(Vec::new()) };
226    /// View ptr → its summon-time context-menu provider (docs/menus.md). Swept on release
227    /// via `day_spec::sidetable`.
228    static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
229    /// Menu button ptr → the provider its press opens (`set_button_menu`, docs/menus.md "Menu
230    /// buttons"). Swept on release like `CTX_MENU_FNS`.
231    static BUTTON_MENUS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
232
233    /// NAV_MENU scroll-view ptr → (outline, data source) for patches and measure.
234    static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
235
236    /// The app's edit-bridge state (`set_edit_state`), which validateMenuItem consults.
237    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    /// Live modal sheets keyed by request id (for programmatic dismissal).
243    static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
244        RefCell::new(HashMap::new());
245    /// Live file-picker sheets (NSOpenPanel is stored via its NSSavePanel supertype).
246    static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
247        RefCell::new(HashMap::new());
248
249    // NSMenuItem does not retain its target, so one shared target is kept alive for the app's
250    // lifetime.
251    static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
252        const { std::cell::RefCell::new(None) };
253    /// The primary window's content view, for call sites without backend access that must
254    /// address the main window specifically (cover re-homing, DAY_DUMP). With secondary
255    /// windows open, `app.windows().firstObject()` is arbitrary (docs/windows.md).
256    static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
257        const { std::cell::RefCell::new(None) };
258
259}
260
261/// Emit an event into day-core's queue (public: external Day Piece renderers use this too).
262pub fn emit(id: NodeId, ev: Event) {
263    let sink = SINK.with(|s| s.borrow().clone());
264    if let Some(sink) = sink {
265        sink(id, ev);
266    }
267}
268
269fn ptr_of(v: &NSView) -> usize {
270    std::ptr::from_ref::<NSView>(v).cast::<()>() as usize
271}
272
273/// Open a menu button's menu under it (docs/menus.md "Menu buttons"): asks the provider now, so
274/// the entries are the current ones, and pops the `NSMenu` from the button's bottom-leading
275/// corner, the place a pull-down `NSPopUpButton` puts its menu. The button stays highlighted
276/// while the menu tracks, as a pressed pull-down does. Guarded: the provider is app code.
277fn pop_button_menu(btn: &NSButton, f: &day_spec::ContextMenuFn) {
278    ffi_guard::contain((), || {
279        // The provider may remove this button; then no menu opens (docs/menus.md).
280        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            // Modal until the menu closes; a chosen item has queued its `MenuAction` by then.
296            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/// An image view's rendering (`IMAGE_MODES`).
307#[derive(Clone, Copy)]
308struct ImageMode {
309    template: bool,
310    tinted: bool,
311}
312
313impl ImageMode {
314    /// Template rendering: the glyph's alpha as a mask, filled with the tint or the neutral
315    /// template color.
316    fn renders_template(self) -> bool {
317        self.template || self.tinted
318    }
319}
320
321/// A decoded bitmap (docs/images.md), held until day-core drops its last handle.
322///
323/// The `NSBitmapImageRep` is kept beside the image rather than fetched on demand for two
324/// reasons: it is the only thing here that can re-encode to other formats, and it is the only
325/// accurate source of pixel dimensions, since `NSImage.size` is in points and reports a @2x
326/// asset at half its real width.
327struct AppKitBitmap {
328    image: Retained<objc2_app_kit::NSImage>,
329    rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
330    info: day_spec::BitmapInfo,
331}
332
333/// Draw a decoded image into a fresh bitmap `scale`× its pixel size, for [`day_spec::EncodeSpec`]'s
334/// `fit`.
335///
336/// 8 bits across 4 samples with alpha is the one layout every writer here accepts, and the only
337/// one that carries transparency through a PNG round-trip intact.
338fn 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
376/// Re-encode a decoded bitmap (docs/images.md).
377///
378/// A free function rather than the duty's body so each refusal reads as an early return instead
379/// of another copy of the same emit.
380fn 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        // Readable here but not writable: `NSBitmapImageRep` ships no WebP or HEIF writer. That
393        // asymmetry is why `encode_formats` exists instead of letting `Cap::ImageEncode` imply
394        // that everything decodable is also encodable.
395        _ => 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    // `fit` scales the longest side down first. A box larger than the original is ignored:
406    // upscaling on an export path inflates the bytes without adding any detail.
407    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        // AppKit's own compression-factor property; a lossless writer ignores it.
423        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
436/// Replay a display list into the current graphics context. The one painter both the on-screen
437/// `DayCanvas` (its `drawRect:`) and the canvas exports run, so the two cannot drift apart
438/// (docs/canvas.md "Exporting").
439fn paint_ops(ops: &[DrawOp]) {
440    // SAFETY: reading the current graphics context on the thread that set it.
441    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
456/// Paint one op straight into the Core Graphics context when it is a solid fill, a solid
457/// stroke or a clip of a shape the context can take as path calls, and say whether it did.
458/// This is the hot path of a dense drawing (a map tile is a few thousand of these), and the
459/// path object route below it costs an order of magnitude more: every `NSBezierPath` is an
460/// allocation and a message per segment, and its fill or stroke re-derives the graphics state
461/// the context already holds. Everything else (text, images, gradients, stamps, rounded rects
462/// and arcs) keeps the full painter. The fill and stroke color spaces are set to sRGB once per
463/// replay by `cg_begin_replay`, so the components here read as the ones `nscolor` would make.
464fn 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            // SAFETY: four components for the sRGB fill space set at the start of the replay.
473            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            // SAFETY: four components for the sRGB stroke space set at the start of the replay.
487            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            // The bitmap's pixels straight to the context (`drawInRect:` on the image object
510            // costs tens of microseconds per call, and a pattern fill is hundreds of copies).
511            let Some((cg_image, pixels)) = BITMAPS.with(|m| {
512                m.borrow().get(&image.0).and_then(|b| {
513                    // SAFETY: reading the rep's immutable CGImage on the thread holding it.
514                    let cg = unsafe { b.rep.as_ref()?.CGImage() }?;
515                    Some((cg, b.info.pixels))
516                })
517            }) else {
518                return false;
519            };
520            // A region is in the bitmap's pixels with a top-left origin, which is also how
521            // `CGImageCreateWithImageInRect` counts; the shared clamp keeps its mapping into
522            // `rect` when it overhangs the bitmap.
523            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            // The canvas is y-down and `CGContextDrawImage` puts the image's first row at the
547            // TOP of `rect` only in a y-up space, so the image is drawn through a local flip.
548            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
567/// Begin a replay on `cg`: fill and stroke colors are given as sRGB components from here on.
568fn cg_begin_replay(cg: &objc2_core_graphics::CGContext) {
569    use objc2_core_graphics::{CGColorSpace, CGContext};
570    // SAFETY: `kCGColorSpaceSRGB` is an immutable CFString constant.
571    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
576/// Add `shape` as the context's current path and say whether it fills even-odd, or `None` for
577/// a shape that takes the path object route (a rounded rect or an arc).
578fn 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
624/// Put a [`day_spec::StrokeStyle`] on the context. Every field is set, because the graphics
625/// state keeps the previous stroke's cap, join and dash and a plain stroke must not inherit
626/// them.
627fn 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        // SAFETY: a null pattern with a zero count clears the dash, per the CGContext docs.
650        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        // SAFETY: `pattern` outlives the call, and `count` is its length.
654        unsafe {
655            CGContext::set_line_dash(Some(cg), style.dash_phase, pattern.as_ptr(), pattern.len());
656        };
657    }
658}
659
660/// Paint `ops` into `cg` with a top-left origin and y down, as the flipped `DayCanvas` sees
661/// them. `height` is the context's own height in its base units (pixels for a bitmap, points for
662/// a PDF page) and `scale` its units per canvas point.
663///
664/// The CTM flip turns the geometry the right way up; wrapping the context as a FLIPPED
665/// `NSGraphicsContext` is what tells AppKit's text and image drawing to keep glyphs and pictures
666/// upright inside that flip, exactly as they are in a flipped view's `drawRect:`.
667fn 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
680/// A Cocoa object on its way to or from a painting thread (docs/canvas.md "Exporting").
681struct Sendable<T>(T);
682
683// SAFETY: wrapped only around objects AppKit documents as usable from any thread while nothing
684// mutates them — `NSImage` and `NSBitmapImageRep` for drawing, `NSFont`, and a `CGImage`,
685// which is immutable — and a stored bitmap is never mutated after `BITMAPS` takes it. Each
686// wrapped value is used by one thread at a time: the painter borrows it for one export, then
687// the UI thread owns the result.
688unsafe impl<T> Send for Sendable<T> {}
689
690/// Everything the painter would read from the UI thread's tables, resolved there before an
691/// export leaves for a painting thread (docs/canvas.md "Exporting"): the decoded images its
692/// image ops draw, and the font each of its text runs needs, which only the UI thread may ask
693/// `NSFontManager` for.
694struct OffscreenResources {
695    images: Vec<(u64, AppKitBitmap)>,
696    fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>,
697}
698
699impl OffscreenResources {
700    /// Walk `ops` on the UI thread. An image whose handle was already released is simply
701    /// absent, and the painter draws nothing for it, as it does on screen.
702    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    /// Run `paint` with these as the calling thread's own tables, then take them back out.
737    /// Only entries this call added are removed afterwards, so a run on the UI thread itself
738    /// (no painting thread could start) leaves its tables as they were.
739    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
768/// Render a canvas display list offscreen (docs/canvas.md "Exporting"): `export_pixels` of
769/// transparent sRGB, premultiplied RGBA, painted at `scale` pixels per point. The half of the
770/// export that runs on a painting thread: CoreGraphics draws into a bitmap context from any
771/// thread, and the painter's AppKit objects (paths, colors, gradients, fonts, string drawing,
772/// image drawing) are documented safe off the main thread when nothing mutates them.
773///
774/// A `CGBitmapContext` rather than `NSGraphicsContext(bitmapImageRep:)`: it carries a real sRGB
775/// color space, so the `NSBitmapImageRep` built from its image is tagged sRGB like every canvas
776/// color, shows on the display through the same color matching the live canvas gets, and writes
777/// that profile into a PNG.
778fn 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    // SAFETY: `kCGColorSpaceSRGB` is an immutable CoreGraphics constant, valid for the process.
790    let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
791        .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
792    // SAFETY: a null data pointer asks CoreGraphics to allocate (and own) the buffer, and a zero
793    // row stride lets it choose one; 8 bits × RGBA premultiplied is a supported layout.
794    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    // A new bitmap context starts zeroed, which is the transparent background.
809    paint_flipped(&cg, f64::from(ph), scale, ops);
810    CGBitmapContextCreateImage(Some(&cg))
811        .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))
812}
813
814/// The UI-thread half of a bitmap export: the painted `CGImage` wrapped as the `NSBitmapImageRep`
815/// and `NSImage` a decoded bitmap is stored as, so `image`, `encode_image` and `DrawOp::Image`
816/// take it like one.
817fn 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    // Sized in POINTS, pixels over scale, so the image draws at the drawing's size and stays
827    // sharp at `scale`× — the same shape as a staged @2x asset.
828    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
845/// Write `pages` as one PDF document (docs/canvas.md "Exporting"): a `CGPDFContext` on a
846/// `CGDataConsumer` over memory, one page per drawing with its own media box, the title and
847/// author in the document info. Shapes and text stay vector: the same painter draws into the PDF
848/// context, and AppKit's string drawing there emits real glyphs from embedded font subsets.
849fn 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    // SAFETY: the auxiliary-info keys are immutable CoreGraphics constants.
869    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    // SAFETY: `first_box` outlives the call, and the dictionary maps the documented
886    // auxiliary-info string keys to strings, which is the type those keys take.
887    let pdf =
888        unsafe { CGPDFContextCreate(Some(&consumer), &raw const first_box, Some(aux.as_opaque())) }
889            .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
890    for page in pages {
891        let page_box = media(page.size);
892        // SAFETY: `page_box` outlives the call; in a PDF context it becomes the page's MediaBox.
893        unsafe { CGContext::begin_page(Some(&pdf), &raw const page_box) };
894        paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
895        CGContext::end_page(Some(&pdf));
896    }
897    // Closing flushes the trailer into the consumer; the bytes are complete only after it.
898    CGPDFContextClose(Some(&pdf));
899    drop(pdf);
900    drop(consumer);
901    Ok(data.to_vec())
902}
903
904thread_local! {
905    /// Each realized list item's current props, by its view: a patch updates one part and the
906    /// item is re-dressed from the whole (docs/list.md "List items").
907    static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
908        std::cell::RefCell::new(std::collections::HashMap::new());
909}
910
911/// A list row's standard content (docs/list.md "List items"), as an image-and-text table cell
912/// draws it: a 16pt template image, the title in the system font with a smaller secondary
913/// subtitle under it, a secondary trailing value, and the accent checkmark, in a horizontal
914/// stack at least 28pt tall. Parts that are absent are hidden, and the stack closes up around
915/// them.
916///
917/// The row's width is spoken for explicitly, as an image-and-text cell's is: the stack fills
918/// its frame edge to edge, the words take every spare point and give way first, and the
919/// trailing parts keep their own size. Left to the stack's default gravity areas, the spare
920/// width had two equally weak claims, the words' column and the gap before the trailing parts,
921/// so Auto Layout settled it from whatever the row's last layout had been: a checkmark landed
922/// beside the title in one row and at the trailing edge in the next, and stayed put.
923fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
924    const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
925        objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
926    // Hugging: the words stretch (1), the trailing parts hold their size (750), and the stack
927    // keeps its edges on its first and last parts (750), so exactly one part takes the slack.
928    const STRETCH: f32 = 1.0;
929    const HOLD: f32 = 750.0;
930    use objc2_app_kit::{
931        NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
932    };
933    let label = |text: &str, size: f64, secondary: bool| {
934        let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
935        unsafe {
936            tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
937            if secondary {
938                tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
939            }
940            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
941        }
942        tf
943    };
944    let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
945    let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
946    let stack = NSStackView::new(mtm);
947    stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
948    stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
949    stack.setAlignment(NSLayoutAttribute::CenterY);
950    stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
951    stack.setSpacing(6.0);
952    // A table row's breathing room above and below; the list gives the sides.
953    stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
954        top: 4.0,
955        left: 0.0,
956        bottom: 4.0,
957        right: 0.0,
958    });
959    let icon = unsafe { NSImageView::new(mtm) };
960    unsafe {
961        icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
962        icon.widthAnchor()
963            .constraintEqualToConstant(16.0)
964            .setActive(true);
965        icon.heightAnchor()
966            .constraintEqualToConstant(16.0)
967            .setActive(true);
968    }
969    stack.addArrangedSubview(&icon);
970    // The title and subtitle span the words' column (Width alignment), so the column's width is
971    // theirs and nothing is left over inside it.
972    let texts = NSStackView::new(mtm);
973    texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
974    texts.setAlignment(NSLayoutAttribute::Width);
975    texts.setSpacing(1.0);
976    // Its height is its lines', centered in the row, not the row's height with the lines
977    // floating somewhere inside it.
978    texts.setHuggingPriority_forOrientation(
979        HOLD,
980        objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
981    );
982    let title = label("", size, false);
983    let subtitle = label("", small, true);
984    // The words take the width and give way first, truncating, before the trailing parts.
985    for line in [&title, &subtitle] {
986        line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
987        line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
988    }
989    texts.addArrangedSubview(&title);
990    texts.addArrangedSubview(&subtitle);
991    stack.addArrangedSubview(&texts);
992    let detail = label("", size, true);
993    detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
994    detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
995    stack.addArrangedSubview(&detail);
996    let check = unsafe { NSImageView::new(mtm) };
997    unsafe {
998        check.setImage(
999            objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1000                &NSString::from_str("checkmark"),
1001                None,
1002            )
1003            .as_deref(),
1004        );
1005        check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
1006    }
1007    check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
1008    check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
1009    stack.addArrangedSubview(&check);
1010    let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
1011    LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
1012    dress_list_item(&view, p, mtm);
1013    view
1014}
1015
1016/// Show `p` on a list item's stack (see [`make_list_item`]), as one accessibility element.
1017fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
1018    use objc2_app_kit::{NSImageView, NSStackView};
1019    let Some(stack) = view.downcast_ref::<NSStackView>() else {
1020        return;
1021    };
1022    let parts = stack.arrangedSubviews();
1023    if parts.len() < 4 {
1024        return;
1025    }
1026    let icon = parts.objectAtIndex(0);
1027    if let Some(iv) = icon.downcast_ref::<NSImageView>() {
1028        let image = p
1029            .icon
1030            .as_ref()
1031            .and_then(|i| toolbar::image_for(i, &p.title, mtm));
1032        unsafe {
1033            iv.setImage(image.as_deref());
1034            iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
1035        }
1036    }
1037    icon.setHidden(p.icon.is_none());
1038    if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
1039        let lines = texts.arrangedSubviews();
1040        if lines.len() == 2 {
1041            if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
1042                tf.setStringValue(&NSString::from_str(&p.title));
1043            }
1044            let sub = lines.objectAtIndex(1);
1045            if let Some(tf) = sub.downcast_ref::<NSTextField>() {
1046                tf.setStringValue(&NSString::from_str(&p.subtitle));
1047            }
1048            sub.setHidden(p.subtitle.is_empty());
1049        }
1050    }
1051    let detail = parts.objectAtIndex(2);
1052    if let Some(tf) = detail.downcast_ref::<NSTextField>() {
1053        tf.setStringValue(&NSString::from_str(&p.detail));
1054    }
1055    detail.setHidden(p.detail.is_empty());
1056    parts.objectAtIndex(3).setHidden(!p.checked);
1057    let words = [&p.title, &p.subtitle, &p.detail]
1058        .into_iter()
1059        .filter(|w| !w.is_empty())
1060        .map(String::as_str)
1061        .collect::<Vec<_>>()
1062        .join(", ");
1063    unsafe {
1064        view.setAccessibilityElement(true);
1065        view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
1066        view.setAccessibilitySelected(p.checked);
1067    }
1068}
1069
1070/// The `NSImage` behind an [`day_spec::ImageSource`] (docs/images.md).
1071///
1072/// Shared by realize and the `Source` patch: a swapped source must load exactly what a fresh
1073/// realize would have, or a piece would show different pixels depending on whether it was
1074/// built or updated.
1075fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
1076    use objc2::AllocAnyThread as _;
1077    match source {
1078        // A vector glyph's SVG first (docs/vectors.md): NSImage renders SVG at display size
1079        // (macOS 11+), so vectors stay vector with no build-time raster resampling. Then the
1080        // shared image-file resolver (images/ then assets/ then bundle), which is macOS's native
1081        // path: a bundle file loaded straight into NSImage (§18.3).
1082        day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
1083            .or_else(|| day_spec::resource::resolve_image_file(name))
1084            .and_then(|path| unsafe {
1085                objc2_app_kit::NSImage::initWithContentsOfFile(
1086                    objc2_app_kit::NSImage::alloc(),
1087                    &NSString::from_str(&path.to_string_lossy()),
1088                )
1089            }),
1090        // Bytes the app already holds (a download, a picked file, a paste) with no staged
1091        // resource behind them.
1092        day_spec::ImageSource::Bytes(bytes) => unsafe {
1093            objc2_app_kit::NSImage::initWithData(
1094                objc2_app_kit::NSImage::alloc(),
1095                &NSData::with_bytes(bytes),
1096            )
1097        },
1098        // Already decoded: share the one NSImage rather than parsing the same bytes twice.
1099        day_spec::ImageSource::Decoded(id) => {
1100            BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
1101        }
1102    }
1103}
1104
1105/// Day `Role` → the `NSAccessibilityRole` constant to apply (§13). `None` for `Role::None`:
1106/// Day leaves native controls' roles untouched and only applies explicit canvas/custom roles.
1107fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
1108    use day_spec::Role;
1109    use objc2_app_kit::{
1110        NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
1111        NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
1112        NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
1113        NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
1114    };
1115    unsafe {
1116        Some(match role {
1117            Role::Button => NSAccessibilityButtonRole,
1118            Role::Toggle => NSAccessibilityCheckBoxRole,
1119            // A tab is a radio button with the tab-button subrole (`set_a11y` adds it), which
1120            // is how NSTabView's own tabs read to VoiceOver; the strip is a tab group.
1121            Role::Tab => NSAccessibilityRadioButtonRole,
1122            Role::TabList => NSAccessibilityTabGroupRole,
1123            Role::Slider => NSAccessibilitySliderRole,
1124            Role::TextInput => NSAccessibilityTextFieldRole,
1125            // `AXHeading` lands the label in VoiceOver's headings rotor. The level has no
1126            // AppKit attribute of its own: the only convention (the level as `AXValue`) would
1127            // displace the text an NSTextField reports as its value, so the level stays
1128            // unspoken.
1129            Role::Heading(_) => NSAccessibilityHeadingRole,
1130            Role::Image => NSAccessibilityImageRole,
1131            Role::Meter => NSAccessibilityLevelIndicatorRole,
1132            Role::Group => NSAccessibilityGroupRole,
1133            // NSOutlineView already reports these itself; the mapping is for the audit's
1134            // expectation and for any composed stand-in (docs/tree.md).
1135            Role::Tree => NSAccessibilityOutlineRole,
1136            Role::TreeItem => NSAccessibilityRowRole,
1137            Role::None => return None,
1138        })
1139    }
1140}
1141
1142/// Native `AXRole` string → Day `Role` (best-effort, for `read_native`/`a11y_audit`).
1143fn day_role_from_ns(ax: &str) -> day_spec::Role {
1144    use day_spec::Role;
1145    match ax {
1146        "AXButton" => Role::Button,
1147        "AXCheckBox" => Role::Toggle,
1148        "AXSlider" => Role::Slider,
1149        "AXTextField" => Role::TextInput,
1150        // Plain text is ambiguous with a heading, and neither carries a level; the audit
1151        // ignores the level either way.
1152        "AXStaticText" | "AXHeading" => Role::Heading(0),
1153        "AXOutline" => Role::Tree,
1154        "AXImage" => Role::Image,
1155        "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
1156        "AXGroup" => Role::Group,
1157        "AXRadioButton" => Role::Tab,
1158        "AXTabGroup" => Role::TabList,
1159        _ => Role::None,
1160    }
1161}
1162
1163// ---------------------------------------------------------------------------
1164// DayTarget: target/action + text delegate trampoline
1165// ---------------------------------------------------------------------------
1166
1167struct TargetIvars {
1168    node: NodeId,
1169}
1170
1171define_class!(
1172    #[unsafe(super(NSObject))]
1173    #[thread_kind = MainThreadOnly]
1174    #[name = "DayTarget"]
1175    #[ivars = TargetIvars]
1176    struct DayTarget;
1177
1178    unsafe impl NSObjectProtocol for DayTarget {}
1179    unsafe impl NSTextFieldDelegate for DayTarget {}
1180
1181    /// A tabs host's `NSTabView` (docs/navigation.md). A pick emits against the NAV_MENU's
1182    /// node, exactly as the sidebar's outline view does, so as far as everything above this
1183    /// backend is concerned, picking a tab and clicking a sidebar row are the same event, and
1184    /// neither the pieces layer nor dayscript needs to know which chrome the window wears.
1185    unsafe impl NSTabViewDelegate for DayTarget {
1186        #[unsafe(method(tabView:didSelectTabViewItem:))]
1187        fn tab_view_did_select(
1188            &self,
1189            tab_view: &objc2_app_kit::NSTabView,
1190            item: Option<&objc2_app_kit::NSTabViewItem>,
1191        ) {
1192            ffi_guard::contain((), || {
1193                if TAB_PICK_SUPPRESS.with(std::cell::Cell::get) {
1194                    return;
1195                }
1196                if let Some(item) = item {
1197                    let idx = unsafe { tab_view.indexOfTabViewItem(item) };
1198                    if idx >= 0 {
1199                        emit(self.ivars().node, Event::SelectionChanged(idx as i64));
1200                    }
1201                }
1202            });
1203        }
1204    }
1205
1206    impl DayTarget {
1207        // Every trampoline that dispatches into the sink (and through it, app handlers) runs
1208        // its body through `ffi_guard::contain` (§8.5): a Rust panic unwinding out of an ObjC
1209        // frame is an abort, so it is caught, reported, and the reactive runtime recovered.
1210        // The same guard wraps every other target/delegate entry in this backend.
1211        #[unsafe(method(action:))]
1212        fn action(&self, sender: &NSControl) {
1213            ffi_guard::contain((), || {
1214                let node = self.ivars().node;
1215                if sender.downcast_ref::<NSSwitch>().is_some() {
1216                    emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
1217                } else if sender.downcast_ref::<NSSlider>().is_some() {
1218                    let value = unsafe { sender.doubleValue() };
1219                    // The live value first: bindings follow this, so the UI tracks the thumb.
1220                    emit(node, Event::ValueChanged(value));
1221                    // Then, once, the value the user settled on. The slider is `continuous`, so
1222                    // this action fires on every tick of a drag; AppKit's way to tell where in the
1223                    // gesture you are is the event that provoked it. A mouse-up ends a drag; a key
1224                    // press (arrow keys) moves the value by one discrete step and is already settled;
1225                    // anything else (mouse-down, mouse-dragged) is mid-gesture and commits nothing.
1226                    if slider_value_settled() {
1227                        emit(node, Event::ValueCommitted(value));
1228                    }
1229                } else if let (Some(f), Some(btn)) = (
1230                    BUTTON_MENUS.with(|t| t.get(ptr_of(sender))),
1231                    sender.downcast_ref::<NSButton>(),
1232                ) {
1233                    // A menu button's press opens its menu rather than reporting a press.
1234                    pop_button_menu(btn, &f);
1235                } else {
1236                    emit(node, Event::Pressed);
1237                    // A push-on/push-off button toggled its state on the click; Day owns the
1238                    // selected state (`set_button_selected`), so put back what it last asked.
1239                    let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
1240                    if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
1241                        unsafe {
1242                            btn.setState(if on {
1243                                NSControlStateValueOn
1244                            } else {
1245                                NSControlStateValueOff
1246                            });
1247                        };
1248                    }
1249                }
1250            });
1251        }
1252
1253        /// The stack-nav back header's button (docs/navigation.md): a day-initiated pop. The
1254        /// nav host's handler writes it into the path signal, which reconciles the pop.
1255        #[unsafe(method(navBack:))]
1256        fn nav_back(&self, _sender: &NSControl) {
1257            ffi_guard::contain((), || {
1258                emit(
1259                    self.ivars().node,
1260                    Event::NavBack {
1261                        already_popped: false,
1262                    },
1263                );
1264            });
1265        }
1266    }
1267
1268    unsafe impl NSControlTextEditingDelegate for DayTarget {
1269        #[unsafe(method(controlTextDidChange:))]
1270        fn control_text_did_change(&self, notification: &NSNotification) {
1271            ffi_guard::contain((), || {
1272                let node = self.ivars().node;
1273                if let Some(obj) = unsafe { notification.object() }
1274                    && let Ok(tf) = obj.downcast::<NSTextField>() {
1275                        emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
1276                    }
1277            });
1278        }
1279
1280        /// The field editor's commands for a text field with a key handler
1281        /// (docs/textfield.md "Keys"): the plain arrows and Escape arrive as `moveUp:`,
1282        /// `moveDown:` and `cancelOperation:`, which the field claims and reports as
1283        /// `Event::Key`, so the caret stays put and Escape does not open the completion list.
1284        /// Every other command, and these three on a field with no handler, is AppKit's.
1285        #[unsafe(method(control:textView:doCommandBySelector:))]
1286        fn control_do_command(
1287            &self,
1288            _control: &NSControl,
1289            _tv: &NSTextView,
1290            command: objc2::runtime::Sel,
1291        ) -> objc2::runtime::Bool {
1292            ffi_guard::contain(objc2::runtime::Bool::NO, || {
1293                let node = self.ivars().node;
1294                let key = if command == sel!(moveUp:) {
1295                    "ArrowUp"
1296                } else if command == sel!(moveDown:) {
1297                    "ArrowDown"
1298                } else if command == sel!(cancelOperation:) {
1299                    "Escape"
1300                } else {
1301                    return objc2::runtime::Bool::NO;
1302                };
1303                if !day_spec::keys::field_claims(node, key, 0) {
1304                    return objc2::runtime::Bool::NO;
1305                }
1306                emit(node, Event::Key(day_spec::KeyEvent::named(key, 0)));
1307                objc2::runtime::Bool::YES
1308            })
1309        }
1310
1311        /// End of an editing session (docs/focus.md). Return submits: AppKit keeps the field
1312        /// first responder and re-selects, so it is not a focus loss; every other movement
1313        /// (tab, click-away, cancel) reports `FocusChanged(false)`.
1314        #[unsafe(method(controlTextDidEndEditing:))]
1315        fn control_text_did_end_editing(&self, notification: &NSNotification) {
1316            ffi_guard::contain((), || {
1317                let node = self.ivars().node;
1318                let movement = unsafe { notification.userInfo() }
1319                    .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
1320                    .and_then(|n| n.downcast::<NSNumber>().ok())
1321                    .map_or(NSTextMovement::Other, |n| NSTextMovement(n.integerValue()));
1322                if movement == NSTextMovement::Return {
1323                    emit(node, Event::Submitted);
1324                } else {
1325                    emit(node, Event::FocusChanged(false));
1326                }
1327            });
1328        }
1329    }
1330);
1331
1332impl DayTarget {
1333    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1334        let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
1335        unsafe { msg_send![super(this), init] }
1336    }
1337}
1338
1339// ---------------------------------------------------------------------------
1340// DayCursorOwner: the `.cursor()` decorator's tracking-area owner (docs/cursor.md)
1341// ---------------------------------------------------------------------------
1342
1343struct CursorIvars {
1344    /// The shape to set on `cursorUpdate:`; `None` leaves the platform's own choice.
1345    cursor: RefCell<Option<Retained<NSCursor>>>,
1346    /// `Cursor::None`: hide the pointer while it is inside, unhide on exit.
1347    hidden: Cell<bool>,
1348    /// Whether this owner is the one that hid the pointer (balanced by `unhide`).
1349    hiding: Cell<bool>,
1350}
1351
1352// AppKit only re-evaluates the pointer's shape on `cursorUpdate:`, which it sends to a
1353// tracking area's owner when the pointer enters the area (and on request through
1354// `invalidateCursorRectsForView:`). One owner per view keeps the view class untouched: a label,
1355// a button, or a plain container all get the same treatment without subclassing. Nested areas
1356// resolve by entry order: the innermost is entered last, so its shape is the one that stays.
1357define_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/// The `NSCursor` for a [`Cursor`], or `None` where the platform's own choice should stand
1402/// (`Cursor::None`, which the owner hides instead, and a native name AppKit does not have).
1403/// AppKit has no wait, progress, help, or move shape, so those take the arrow; the zoom, frame
1404/// (diagonal) resize, and column/row resize cursors arrived in macOS 15 and are probed by
1405/// nav host, with the nearest older shape below it.
1406// `resizeLeftRightCursor` and `resizeUpDownCursor` are deprecated in favor of the macOS 15
1407// column/row resize cursors, which are probed above them; below 15 they are the shape.
1408#[allow(deprecated)]
1409#[expect(
1410    clippy::match_same_arms,
1411    reason = "each macOS 15 cursor keeps its older fallback arm directly below its probe"
1412)]
1413fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1414    let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1415    Some(match c {
1416        Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1417        Cursor::Pointer => NSCursor::pointingHandCursor(),
1418        Cursor::Text => NSCursor::IBeamCursor(),
1419        Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1420        Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1421        Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1422        Cursor::Grabbing => NSCursor::closedHandCursor(),
1423        Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1424        Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1425        Cursor::Copy => NSCursor::dragCopyCursor(),
1426        Cursor::Alias => NSCursor::dragLinkCursor(),
1427        Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1428        Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1429        Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1430        Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1431        Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1432        Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1433            NSCursor::frameResizeCursorFromPosition_inDirections(
1434                NSCursorFrameResizePosition::TopRight,
1435                NSCursorFrameResizeDirections::All,
1436            )
1437        }
1438        Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1439            NSCursor::frameResizeCursorFromPosition_inDirections(
1440                NSCursorFrameResizePosition::TopLeft,
1441                NSCursorFrameResizeDirections::All,
1442            )
1443        }
1444        Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1445        Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1446        Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1447        Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1448        Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1449        Cursor::None => return None,
1450        Cursor::Native(name) => match &**name {
1451            "disappearingItem" => NSCursor::disappearingItemCursor(),
1452            "dragCopy" => NSCursor::dragCopyCursor(),
1453            "dragLink" => NSCursor::dragLinkCursor(),
1454            "contextualMenu" => NSCursor::contextualMenuCursor(),
1455            "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1456            _ => return None,
1457        },
1458    })
1459}
1460
1461/// Whether the `NSEvent` currently being dispatched ends a slider's interaction (see the
1462/// `ValueCommitted` emission in `DayTarget::action:`). AppKit gives a continuous slider no
1463/// "drag ended" callback, so the event that provoked the action is what says where in the gesture
1464/// we are: a mouse-up ends a drag, an arrow key moves one discrete step and is already settled,
1465/// and mouse-down/mouse-dragged are mid-gesture. No current event at all (a programmatic
1466/// `setDoubleValue:` that fires the action) is not a user commit either.
1467fn slider_value_settled() -> bool {
1468    let Some(mtm) = MainThreadMarker::new() else {
1469        return false;
1470    };
1471    let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1472        return false;
1473    };
1474    matches!(
1475        unsafe { event.r#type() },
1476        NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1477    )
1478}
1479
1480// ---------------------------------------------------------------------------
1481// DayTextField: NSTextField that reports focus gain (docs/focus.md)
1482// ---------------------------------------------------------------------------
1483
1484struct FieldIvars {
1485    node: NodeId,
1486}
1487
1488/// The share picker's delegate (docs/sharing.md): offers the app's own actions as sharing
1489/// services beside the system's, each reporting its choice as `Event::MenuAction`.
1490struct SharePickerIvars {
1491    actions: Vec<day_spec::share::ShareAction>,
1492}
1493
1494define_class!(
1495    #[unsafe(super(NSObject))]
1496    #[thread_kind = MainThreadOnly]
1497    #[name = "DaySharePickerDelegate"]
1498    #[ivars = SharePickerIvars]
1499    struct DaySharePickerDelegate;
1500
1501    unsafe impl NSObjectProtocol for DaySharePickerDelegate {}
1502
1503    impl DaySharePickerDelegate {
1504        #[unsafe(method_id(sharingServicePicker:sharingServicesForItems:proposedSharingServices:))]
1505        fn services(
1506            &self,
1507            _picker: &AnyObject,
1508            _items: &AnyObject,
1509            proposed: &objc2_foundation::NSArray<AnyObject>,
1510        ) -> Retained<objc2_foundation::NSArray<AnyObject>> {
1511            let mut services: Vec<Retained<AnyObject>> = Vec::new();
1512            for action in &self.ivars().actions {
1513                let id = action.id;
1514                let handler = block2::RcBlock::new(move || {
1515                    ffi_guard::contain((), || emit(WINDOW_NODE, Event::MenuAction(id)));
1516                });
1517                let image = action.symbol.and_then(|s| {
1518                    objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1519                        &NSString::from_str(day_spec::sf_symbol_name(s)),
1520                        None,
1521                    )
1522                });
1523                // SAFETY: NSSharingService's documented initializer for a custom service; the
1524                // handler block is copied by the service.
1525                let service: Option<Retained<AnyObject>> = unsafe {
1526                    let alloc: objc2::rc::Allocated<AnyObject> =
1527                        msg_send![objc2::class!(NSSharingService), alloc];
1528                    msg_send![
1529                        alloc,
1530                        initWithTitle: &*NSString::from_str(&action.title),
1531                        image: image.as_deref(),
1532                        alternateImage: None::<&AnyObject>,
1533                        handler: &*handler
1534                    ]
1535                };
1536                services.extend(service);
1537            }
1538            // The system's targets first, then the app's own, as Safari lists Add Bookmark
1539            // after them.
1540            let mut all: Vec<Retained<AnyObject>> = proposed.to_vec();
1541            all.extend(services);
1542            objc2_foundation::NSArray::from_retained_slice(&all)
1543        }
1544    }
1545);
1546
1547define_class!(
1548    #[unsafe(super(NSTextField))]
1549    #[thread_kind = MainThreadOnly]
1550    #[name = "DayTextField"]
1551    #[ivars = FieldIvars]
1552    struct DayTextField;
1553
1554    impl DayTextField {
1555        /// Focus gain. Key events go to the shared field editor, but the field itself receives
1556        /// `becomeFirstResponder` first, the reliable gain hook (`controlTextDidBeginEditing:`
1557        /// waits for the first keystroke). Loss comes from `controlTextDidEndEditing:` on the
1558        /// delegate.
1559        #[unsafe(method(becomeFirstResponder))]
1560        fn become_first_responder(&self) -> bool {
1561            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1562            if ok {
1563                field_gained_focus(self.ivars().node);
1564            }
1565            ok
1566        }
1567    }
1568);
1569
1570impl DayTextField {
1571    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1572        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1573        unsafe { msg_send![super(this), init] }
1574    }
1575}
1576
1577// The secure twin (docs/textfield.md). AppKit hides characters with a class, not a property:
1578// `NSSecureTextField` brings its own cell and field editor, which keep the text out of the
1579// pasteboard, the spelling checker and the accessibility value. A `text_field` that turns
1580// `secure` is rebuilt as this class (`set_input_traits`), with the same focus hook.
1581define_class!(
1582    #[unsafe(super(NSSecureTextField))]
1583    #[thread_kind = MainThreadOnly]
1584    #[name = "DaySecureTextField"]
1585    #[ivars = FieldIvars]
1586    struct DaySecureTextField;
1587
1588    impl DaySecureTextField {
1589        /// Focus gain, as on `DayTextField`.
1590        #[unsafe(method(becomeFirstResponder))]
1591        fn become_first_responder(&self) -> bool {
1592            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1593            if ok {
1594                field_gained_focus(self.ivars().node);
1595            }
1596            ok
1597        }
1598    }
1599);
1600
1601impl DaySecureTextField {
1602    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1603        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1604        unsafe { msg_send![super(this), init] }
1605    }
1606}
1607
1608thread_local! {
1609    /// A plain/secure class swap in flight (`set_input_traits`): focus moves from the old
1610    /// field to its replacement, which the app must not see as a focus change.
1611    static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1612}
1613
1614/// Report a text field's focus gain, unless it is a class swap handing focus to the
1615/// replacement of a field that already had it.
1616fn field_gained_focus(node: NodeId) {
1617    if FIELD_SWAP.with(std::cell::Cell::get) {
1618        return;
1619    }
1620    // Guard only the sink dispatch: the responder change already happened, so a contained
1621    // panic must not flip the answer AppKit acts on.
1622    ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1623}
1624
1625/// The node a `text_field`'s view reports against, or `None` when the view is not one
1626/// (a label is an `NSTextField` too).
1627fn text_field_node(v: &NSView) -> Option<NodeId> {
1628    v.downcast_ref::<DayTextField>()
1629        .map(|f| f.ivars().node)
1630        .or_else(|| {
1631            v.downcast_ref::<DaySecureTextField>()
1632                .map(|f| f.ivars().node)
1633        })
1634}
1635
1636/// Build a `text_field`'s view, plain or secure, with its delegate wired and registered.
1637/// `realize` and the class swap in `set_input_traits` both come through here, so both classes
1638/// report text, submit and focus the same way against the same node.
1639fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1640    let target = DayTarget::new(mtm, node);
1641    // Up to `NSTextField` (the declared superclass of both), so the AsRef<NSView> bound on
1642    // `view_of` resolves and every `NSTextField` downcast sees either class.
1643    let tf: Retained<NSTextField> = if secure {
1644        Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1645    } else {
1646        Retained::into_super(DayTextField::new(mtm, node))
1647    };
1648    unsafe {
1649        tf.setEditable(true);
1650        tf.setBezeled(true);
1651        tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1652    }
1653    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1654    tf
1655}
1656
1657/// Whether `h` (a text field, or the field editor's client) holds its window's focus. A
1658/// focused `NSTextField`'s first responder is the shared field editor, so unwrap it back to
1659/// the field via its delegate.
1660fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1661    window.firstResponder().is_some_and(|fr| {
1662        if Retained::as_ptr(&fr).cast::<()>() as usize == ptr_of(h) {
1663            return true;
1664        }
1665        fr.downcast::<NSText>().is_ok_and(|text| {
1666            unsafe { text.delegate() }
1667                .is_some_and(|d| Retained::as_ptr(&d).cast::<()>() as usize == ptr_of(h))
1668        })
1669    })
1670}
1671
1672/// An `NSTextContentType` constant by symbol name, or `None` on a system that predates it.
1673/// Looked up at run time because most of the vocabulary arrived in macOS 14: a direct
1674/// reference binds at launch, and one missing symbol would keep the whole app from starting
1675/// on an older system.
1676fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1677    unsafe extern "C" {
1678        fn dlsym(
1679            handle: *mut std::ffi::c_void,
1680            symbol: *const std::ffi::c_char,
1681        ) -> *mut std::ffi::c_void;
1682    }
1683    // <dlfcn.h>: search every image loaded in the process.
1684    const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1685    // SAFETY: `symbol` is NUL-terminated. Each name passed here is an AppKit
1686    // `NSString * const`, so a non-null result is the address of a pointer to an immortal
1687    // constant string.
1688    unsafe {
1689        let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1690        if slot.is_null() {
1691            None
1692        } else {
1693            (*slot).as_ref()
1694        }
1695    }
1696}
1697
1698/// Move a view-keyed entry to the view that replaces it.
1699fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1700    if let Some(v) = table.take(old) {
1701        table.insert(new, v);
1702    }
1703}
1704
1705/// A label is the shared field editor's delegate. AppKit does not forward
1706/// `textView:clickedOnLink:atIndex:` to an `NSTextField`'s separate control delegate, so the
1707/// label itself must handle it to prevent the field editor from opening the target externally.
1708/// See Apple's "Working With the Field Editor" and docs/text-runs.md.
1709struct LabelIvars {
1710    node: NodeId,
1711    has_links: Cell<bool>,
1712    has_runs: Cell<bool>,
1713    selectable: Cell<bool>,
1714}
1715
1716define_class!(
1717    #[unsafe(super(NSTextField))]
1718    #[thread_kind = MainThreadOnly]
1719    #[name = "DayLabel"]
1720    #[ivars = LabelIvars]
1721    struct DayLabel;
1722
1723    impl DayLabel {
1724        #[unsafe(method_id(menuForEvent:))]
1725        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1726            ffi_guard::contain(None, || {
1727                if !self.isSelectable()
1728                    && let Some(menu) = inherited_context_menu(self, event)
1729                {
1730                    return menu;
1731                }
1732                unsafe { msg_send![super(self), menuForEvent: event] }
1733            })
1734        }
1735
1736        #[unsafe(method(drawRect:))]
1737        fn draw_rect(&self, dirty: NSRect) {
1738            // AppKit cannot propagate a table cell's background style through arbitrary
1739            // Day containers. Resolve selection at paint time so keyboard focus, window
1740            // activation, and cell reuse all use the actual native row state.
1741            let mut ancestor = unsafe { self.superview() };
1742            let mut selection_color = None;
1743            if !self.ivars().has_runs.get() {
1744                while let Some(view) = ancestor {
1745                    if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1746                        if unsafe { row.isSelected() } {
1747                            selection_color = Some(unsafe {
1748                                if row.isEmphasized() {
1749                                    objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1750                                } else {
1751                                    objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1752                                }
1753                            });
1754                        }
1755                        break;
1756                    }
1757                    ancestor = unsafe { view.superview() };
1758                }
1759            }
1760            let cell = unsafe { self.cell() }
1761                .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1762            if let (Some(color), Some(cell)) = (selection_color, cell) {
1763                let original = unsafe { cell.textColor() };
1764                // Mutate the cell only for this paint; changing the field would invalidate
1765                // the view again. Keep the app's normal color for deselection and reuse.
1766                unsafe {
1767                    cell.setTextColor(Some(&color));
1768                    let _: () = msg_send![super(self), drawRect: dirty];
1769                    cell.setTextColor(original.as_deref());
1770                }
1771            } else {
1772                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1773            }
1774        }
1775    }
1776
1777    unsafe impl NSObjectProtocol for DayLabel {}
1778    unsafe impl NSTextDelegate for DayLabel {}
1779
1780    unsafe impl NSTextViewDelegate for DayLabel {
1781        #[unsafe(method(textView:clickedOnLink:atIndex:))]
1782        fn clicked_on_link(
1783            &self,
1784            _tv: &NSTextView,
1785            link: &objc2::runtime::AnyObject,
1786            _index: usize,
1787        ) -> bool {
1788            ffi_guard::contain(true, || {
1789                // NSString targets stay verbatim (including #route); accept NSURL too.
1790                let url: Retained<NSString> = unsafe { msg_send![link, description] };
1791                emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1792                true // Handled: AppKit must never also open the target itself.
1793            })
1794        }
1795    }
1796);
1797
1798impl DayLabel {
1799    fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1800        let this = Self::alloc(mtm).set_ivars(LabelIvars {
1801            node,
1802            has_links: Cell::new(false),
1803            has_runs: Cell::new(false),
1804            selectable: Cell::new(false),
1805        });
1806        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1807        unsafe {
1808            this.setStringValue(&NSString::from_str(text));
1809            this.setEditable(false);
1810            this.setSelectable(false);
1811            this.setBordered(false);
1812            this.setBezeled(false);
1813            this.setDrawsBackground(false);
1814        }
1815        this
1816    }
1817
1818    fn set_links(&self, has_links: bool) {
1819        self.ivars().has_links.set(has_links);
1820        unsafe {
1821            self.setSelectable(has_links || self.ivars().selectable.get());
1822            self.setAllowsEditingTextAttributes(has_links);
1823        }
1824    }
1825}
1826
1827struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1828impl Drop for PanMonitor {
1829    fn drop(&mut self) {
1830        unsafe { NSEvent::removeMonitor(&self.0) };
1831    }
1832}
1833
1834// Escape closes a cover's window sheet, as it cancels any sheet on macOS (docs/cover.md
1835// "Modal sheet"): the cover hears it as its back request. A local monitor, because the key
1836// window's first responder may be a web view or a field that keeps Escape to itself. A sheet
1837// with its own sheet or alert over it, and app-modal panels, keep their Escape.
1838fn install_sheet_escape_monitor() {
1839    SHEET_ESCAPE_MONITOR.with(|slot| {
1840        if slot.borrow().is_some() {
1841            return;
1842        }
1843        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1844            let event = unsafe { raw.as_ref() };
1845            ffi_guard::contain(raw.as_ptr(), || {
1846                let Some(mtm) = MainThreadMarker::new() else {
1847                    return raw.as_ptr();
1848                };
1849                let escape = unsafe { event.charactersIgnoringModifiers() }
1850                    .is_some_and(|s| s.to_string() == "\u{1b}");
1851                let Some(window) = event.window(mtm).filter(|_| escape) else {
1852                    return raw.as_ptr();
1853                };
1854                let app = NSApplication::sharedApplication(mtm);
1855                if app.modalWindow().is_some() || window.attachedSheet().is_some() {
1856                    return raw.as_ptr();
1857                }
1858                match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
1859                    Some(node) => {
1860                        emit(
1861                            node,
1862                            Event::NavBack {
1863                                already_popped: false,
1864                            },
1865                        );
1866                        std::ptr::null_mut()
1867                    }
1868                    None => raw.as_ptr(),
1869                }
1870            })
1871        });
1872        let monitor = unsafe {
1873            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1874                objc2_app_kit::NSEventMask::KeyDown,
1875                &block,
1876            )
1877        };
1878        *slot.borrow_mut() = monitor.map(PanMonitor);
1879    });
1880}
1881
1882// A container pan observes horizontal wheel events over its descendants, including native
1883// scroll views. Leave vertical scrolling and canvas 2D pans to their existing handlers.
1884fn install_container_pan_monitor() {
1885    PAN_MONITOR.with(|slot| {
1886        if slot.borrow().is_some() {
1887            return;
1888        }
1889        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1890            let event = unsafe { raw.as_ref() };
1891            ffi_guard::contain(raw.as_ptr(), || {
1892                let dx = unsafe { event.scrollingDeltaX() };
1893                let dy = unsafe { event.scrollingDeltaY() };
1894                if dx.abs() <= dy.abs() {
1895                    return raw.as_ptr();
1896                }
1897                let Some(mtm) = MainThreadMarker::new() else {
1898                    return raw.as_ptr();
1899                };
1900                let Some(window) = event.window(mtm) else {
1901                    return raw.as_ptr();
1902                };
1903                let Some(content) = window.contentView() else {
1904                    return raw.as_ptr();
1905                };
1906                let point =
1907                    content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1908                let mut view = content.hitTest(point);
1909                while let Some(v) = view {
1910                    if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1911                        if v.downcast_ref::<DayCanvas>().is_some() {
1912                            return raw.as_ptr();
1913                        }
1914                        let raw_phase = unsafe { event.phase() };
1915                        let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1916                            day_spec::DragPhase::Began
1917                        } else if raw_phase.intersects(
1918                            objc2_app_kit::NSEventPhase::Ended
1919                                | objc2_app_kit::NSEventPhase::Cancelled,
1920                        ) {
1921                            day_spec::DragPhase::Ended
1922                        } else {
1923                            day_spec::DragPhase::Changed
1924                        };
1925                        let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1926                        emit(
1927                            node,
1928                            Event::Pan {
1929                                phase,
1930                                delta: Point::new(dx, dy),
1931                                location: Point::new(p.x, p.y),
1932                            },
1933                        );
1934                        return std::ptr::null_mut();
1935                    }
1936                    view = unsafe { v.superview() };
1937                }
1938                raw.as_ptr()
1939            })
1940        });
1941        *slot.borrow_mut() = unsafe {
1942            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1943                objc2_app_kit::NSEventMask::ScrollWheel,
1944                &block,
1945            )
1946        }
1947        .map(PanMonitor);
1948    });
1949}
1950
1951// ---------------------------------------------------------------------------
1952// DayFlipped: top-left-origin container view
1953// ---------------------------------------------------------------------------
1954
1955/// A `background(..)` fill: `(r, g, b, a, corner_radius)`, painted in `drawRect` with `NSColor`.
1956type Surface = (f64, f64, f64, f64, f64);
1957
1958#[derive(Default)]
1959struct FlippedIvars {
1960    surface: Cell<Option<Surface>>,
1961    /// `SurfaceRole::SectionCard`: `(radius,)`, drawn with a dynamic system fill resolved at
1962    /// draw time, so the card tracks light/dark appearance changes automatically.
1963    section_card: Cell<Option<f64>>,
1964    /// Paint the whole view with the dynamic window background before anything else: the
1965    /// inspector panel wrap (docs/inspector.md). The inspector `NSSplitViewItem` backs its pane
1966    /// with a vibrancy material, and the section cards' thin quaternary fill composites over
1967    /// it into near-black in dark mode (and the material itself captures black offscreen; see
1968    /// the sidebar-screenshot rule, docs/navigation.md). An opaque appearance-resolved
1969    /// backdrop gives the cards the same ground System Settings draws them on.
1970    pane_backdrop: Cell<bool>,
1971}
1972
1973define_class!(
1974    #[unsafe(super(NSView))]
1975    #[thread_kind = MainThreadOnly]
1976    #[name = "DayFlipped"]
1977    #[ivars = FlippedIvars]
1978    struct DayFlipped;
1979
1980    impl DayFlipped {
1981        #[unsafe(method_id(menuForEvent:))]
1982        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1983            ffi_guard::contain(None, || {
1984                inherited_context_menu(self, event)
1985                    .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1986            })
1987        }
1988
1989        #[unsafe(method(isFlipped))]
1990        fn is_flipped(&self) -> bool {
1991            true
1992        }
1993
1994        // Focus, and with it the keyboard (docs/focus.md): the canvas contract, opted into by
1995        // `Decorate::focusable`. A container never in FOCUSABLE_NODES behaves exactly as
1996        // before (refuses first responder, forwards every key).
1997        #[unsafe(method(acceptsFirstResponder))]
1998        fn accepts_first_responder(&self) -> bool {
1999            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2000            FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2001        }
2002
2003        // Clicking a focusable container focuses it, the way clicking a table does. The
2004        // gesture recognizers still see the press: this runs before `super`, which is what
2005        // forwards it to them.
2006        #[unsafe(method(mouseDown:))]
2007        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2008            if transfer::pressed(self, event) { return; }
2009            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2010            if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2011                && let Some(window) = self.window()
2012            {
2013                window.makeFirstResponder(Some(self));
2014            }
2015            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2016        }
2017
2018        #[unsafe(method(becomeFirstResponder))]
2019        fn become_first_responder(&self) -> bool {
2020            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2021            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2022                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2023            }
2024            true
2025        }
2026
2027        #[unsafe(method(resignFirstResponder))]
2028        fn resign_first_responder(&self) -> bool {
2029            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2030            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2031                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
2032            }
2033            true
2034        }
2035
2036        /// The arrows, delivered here while this container is the first responder. Anything
2037        /// else (and every arrow when the app registered no key handler for the node) goes
2038        /// to `super`, which walks the responder chain exactly as it would have without us.
2039        #[unsafe(method(keyDown:))]
2040        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2041            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2042            let handled = ffi_guard::contain(false, || {
2043                let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
2044                    return false;
2045                };
2046                let Some(key) = key_name(event) else {
2047                    return false;
2048                };
2049                if !day_spec::keys::handled(node) {
2050                    return false;
2051                }
2052                emit(
2053                    node,
2054                    Event::Key(day_spec::KeyEvent::named(
2055                        key,
2056                        key_modifiers(event.modifierFlags()),
2057                    )),
2058                );
2059                true
2060            });
2061            if !handled {
2062                let _: () = unsafe { msg_send![super(self), keyDown: event] };
2063            }
2064        }
2065
2066        /// Show the attached context menu (docs/menus.md) explicitly rather than relying on
2067        /// `NSResponder`'s default `.menu` display: popping it ourselves is deterministic
2068        /// regardless of how the click threads through Day's container hierarchy.
2069        #[unsafe(method(rightMouseDown:))]
2070        fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2071            if let Some(menu) = self.menuForEvent(event) {
2072                unsafe {
2073                    objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self);
2074                };
2075            } else {
2076                let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
2077            }
2078        }
2079
2080        #[unsafe(method(drawRect:))]
2081        fn draw_rect(&self, _dirty: NSRect) {
2082            let paint = || {
2083                if self.ivars().pane_backdrop.get() {
2084                    let bounds = self.bounds();
2085                    unsafe {
2086                        // Resolved at draw time, like the section fill below, so the backdrop
2087                        // follows light/dark appearance changes automatically.
2088                        NSColor::windowBackgroundColor().setFill();
2089                        objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
2090                    }
2091                }
2092                if let Some(radius) = self.ivars().section_card.get() {
2093                    let bounds = self.bounds();
2094                    unsafe {
2095                        // quaternarySystemFill (macOS 14+) is the grouped-card material System
2096                        // Settings uses; older systems fall back to the control background.
2097                        let cls = objc2::class!(NSColor);
2098                        let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
2099                        let color: objc2::rc::Retained<NSColor> = if has {
2100                            msg_send![cls, quaternarySystemFillColor]
2101                        } else {
2102                            msg_send![cls, controlBackgroundColor]
2103                        };
2104                        color.setFill();
2105                        let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2106                            bounds, radius, radius,
2107                        );
2108                        path.fill();
2109                    }
2110                }
2111                if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
2112                    let bounds = self.bounds();
2113                    unsafe {
2114                        NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
2115                        let path = if radius > 0.0 {
2116                            objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2117                                bounds, radius, radius,
2118                            )
2119                        } else {
2120                            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
2121                        };
2122                        path.fill();
2123                    }
2124                }
2125            };
2126            // Paint under the standard counterpart of this view's appearance. Inside an
2127            // NSVisualEffectView subtree (the inspector pane) the effective appearance is
2128            // a vibrant one (NSAppearanceNameVibrantDark/-Light), and the system fills'
2129            // vibrant variants are opaque blend colors that only composite correctly in an
2130            // `allowsVibrancy` view: drawn plainly, dark-mode quaternary fill comes out
2131            // near-black instead of lightening. Resolving under aqua/darkAqua gives exactly
2132            // the fills System Settings draws with, and re-resolves on every theme change
2133            // (this runs per draw, and appearance flips redraw).
2134            unsafe {
2135                let names = objc2_foundation::NSArray::from_slice(&[
2136                    objc2_app_kit::NSAppearanceNameAqua,
2137                    objc2_app_kit::NSAppearanceNameDarkAqua,
2138                ]);
2139                let standard = self
2140                    .effectiveAppearance()
2141                    .bestMatchFromAppearancesWithNames(&names)
2142                    .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
2143                match standard {
2144                    Some(appearance) => {
2145                        let block = block2::StackBlock::new(paint);
2146                        appearance.performAsCurrentDrawingAppearance(&block);
2147                    }
2148                    None => paint(),
2149                }
2150            }
2151        }
2152    }
2153    unsafe impl NSObjectProtocol for DayFlipped {}
2154    unsafe impl NSDraggingSource for DayFlipped {
2155        #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
2156        fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
2157    }
2158    impl DayFlipped {
2159        #[unsafe(method(mouseDragged:))]
2160        fn transfer_dragged(&self, event: &NSEvent) {
2161            if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
2162        }
2163        #[unsafe(method(draggingEntered:))]
2164        fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
2165        #[unsafe(method(draggingUpdated:))]
2166        fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
2167        #[unsafe(method(performDragOperation:))]
2168        fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
2169    }
2170
2171);
2172
2173impl DayFlipped {
2174    fn new(mtm: MainThreadMarker) -> Retained<Self> {
2175        let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
2176        unsafe { msg_send![super(this), init] }
2177    }
2178
2179    /// Apply a `background`/`corner_radius` surface. The fill (rounded by `corner_radius`) is
2180    /// drawn in `drawRect` with `NSColor`, not via the layer's `backgroundColor`, whose `CGColorRef`
2181    /// argument objc2's `msg_send` cannot type-check. A rounded child clip does use the `CALayer`
2182    /// (`cornerRadius` + `masksToBounds` are a `CGFloat` + `BOOL`, which are fine).
2183    /// `SurfaceRole::SectionCard`: the fill resolves dynamically in drawRect (theme-adaptive).
2184    fn set_section_card(&self, corner_radius: f64) {
2185        self.ivars().section_card.set(Some(corner_radius));
2186        unsafe {
2187            let _: () = msg_send![self, setNeedsDisplay: true];
2188        }
2189    }
2190
2191    /// Opaque window-background backdrop (the inspector panel wrap; see `FlippedIvars`).
2192    fn set_pane_backdrop(&self) {
2193        self.ivars().pane_backdrop.set(true);
2194        unsafe {
2195            let _: () = msg_send![self, setNeedsDisplay: true];
2196        }
2197    }
2198
2199    fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
2200        self.ivars()
2201            .surface
2202            .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
2203        unsafe {
2204            let _: () = msg_send![self, setNeedsDisplay: true];
2205            if clips || corner_radius > 0.0 {
2206                let _: () = msg_send![self, setWantsLayer: true];
2207                let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
2208                if !layer.is_null() {
2209                    let _: () = msg_send![layer, setCornerRadius: corner_radius];
2210                    let _: () = msg_send![layer, setMasksToBounds: true];
2211                }
2212            }
2213        }
2214    }
2215}
2216
2217// ---------------------------------------------------------------------------
2218// DayCanvas — a flipped view replaying the Day display list in drawRect (§11)
2219// ---------------------------------------------------------------------------
2220
2221struct CanvasIvars;
2222
2223define_class!(
2224    #[unsafe(super(NSView))]
2225    #[thread_kind = MainThreadOnly]
2226    #[name = "DayCanvas"]
2227    #[ivars = CanvasIvars]
2228    struct DayCanvas;
2229
2230    impl DayCanvas {
2231        #[unsafe(method(isFlipped))]
2232        fn is_flipped(&self) -> bool {
2233            true
2234        }
2235
2236        /// A summon-time context menu (docs/menus.md): built when the right-click lands,
2237        /// from the provider `set_context_menu_fn` registered — so a canvas can select what
2238        /// is under the pointer and offer commands for that selection.
2239        #[unsafe(method_id(menuForEvent:))]
2240        fn menu_for_event(
2241            &self,
2242            event: &objc2_app_kit::NSEvent,
2243        ) -> Option<Retained<NSMenu>> {
2244            let f = CTX_MENU_FNS.with(|t| t.get(std::ptr::from_ref::<Self>(self) as usize));
2245            let Some(f) = f else {
2246                return unsafe { msg_send![super(self), menuForEvent: event] };
2247            };
2248            // Guarded: the provider is app code (it usually re-selects, then builds).
2249            ffi_guard::contain(None, || {
2250                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2251                let items = f(day_spec::Point::new(p.x, p.y));
2252                if items.is_empty() {
2253                    return None;
2254                }
2255                Some(build_ns_menu(self.mtm(), "", &items))
2256            })
2257        }
2258
2259        // Focus, and with it the keyboard (docs/focus.md, docs/menus.md). A canvas is the one
2260        // built-in piece with no native control under it, so nothing else would ever make it
2261        // the first responder — and without that, arrow keys aimed at what it draws could only
2262        // be caught by watching the whole app.
2263        #[unsafe(method(acceptsFirstResponder))]
2264        fn accepts_first_responder(&self) -> bool {
2265            true
2266        }
2267
2268        // Clicking a canvas focuses it, the way clicking a table or a text field does. The
2269        // gesture recognizers (tap/drag) still see the press — this runs before `super`, which
2270        // is what forwards it to them.
2271        #[unsafe(method(mouseDown:))]
2272        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2273            if let Some(window) = self.window() {
2274                window.makeFirstResponder(Some(self));
2275            }
2276            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2277        }
2278
2279        // Report focus both ways, so `.focused(signal)` binds two-way and dayscript's
2280        // `assert_focused` can see it.
2281        #[unsafe(method(becomeFirstResponder))]
2282        fn become_first_responder(&self) -> bool {
2283            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2284            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
2285                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2286            }
2287            true
2288        }
2289
2290        #[unsafe(method(resignFirstResponder))]
2291        fn resign_first_responder(&self) -> bool {
2292            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2293            // A composition in progress goes with the focus: the input method is told, so it
2294            // does not commit into whatever is focused next.
2295            if MARKED.with(|t| t.remove(ptr)).is_some()
2296                && let Some(context) = self.inputContext()
2297            {
2298                context.discardMarkedText();
2299            }
2300            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
2301                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
2302            }
2303            true
2304        }
2305
2306        /// The keys, delivered to this canvas because it is the first responder. On the short
2307        /// route the arrows and digits; on the full route (docs/menus.md "The full route")
2308        /// every key, through the text input system for the ones that type. Anything
2309        /// unclaimed — and every key when the app registered no handler for this node — goes
2310        /// to `super`, which walks the responder chain exactly as it would have without us.
2311        #[unsafe(method(keyDown:))]
2312        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2313            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2314            let handled = ffi_guard::contain(false, || {
2315                let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
2316                    return false;
2317                };
2318                // A canvas nobody asked keys from does not get to keep them: an enclosing
2319                // scroll view still scrolls, and an unclaimed key still beeps the way the
2320                // platform means it to.
2321                if !day_spec::keys::handled(node) {
2322                    return false;
2323                }
2324                if day_spec::keys::text(node) {
2325                    return full_route_key_down(self, node, event);
2326                }
2327                let Some(key) = key_name(event) else {
2328                    return false;
2329                };
2330                emit(
2331                    node,
2332                    Event::Key(day_spec::KeyEvent::named(
2333                        key,
2334                        key_modifiers(event.modifierFlags()),
2335                    )),
2336                );
2337                true
2338            });
2339            if !handled {
2340                let _: () = unsafe { msg_send![super(self), keyDown: event] };
2341            }
2342        }
2343
2344        /// The text input context, only for a canvas on the full route: an input context is
2345        /// what makes the input method (and the keyboard layout's dead keys) address this
2346        /// view, and a drawing canvas that hears the arrows alone must not look like a text
2347        /// field to it.
2348        #[unsafe(method_id(inputContext))]
2349        fn input_context(&self) -> Option<Retained<objc2_app_kit::NSTextInputContext>> {
2350            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2351            let takes_keyboard = KEY_NODES
2352                .with(|t| t.get(ptr))
2353                .is_some_and(|node| ffi_guard::contain(false, || day_spec::keys::text(node)));
2354            if takes_keyboard {
2355                unsafe { msg_send![super(self), inputContext] }
2356            } else {
2357                None
2358            }
2359        }
2360
2361        #[unsafe(method(drawRect:))]
2362        fn draw_rect(&self, _dirty: NSRect) {
2363            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2364            let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
2365            paint_ops(&ops);
2366        }
2367
2368        /// Hover entry/motion/exit (docs/canvas.md "Interaction"). The tracking area is installed
2369        /// by `enable_gesture`; `updateTrackingAreas` below keeps it the size of the view.
2370        #[unsafe(method(mouseEntered:))]
2371        fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
2372            self.report_hover(event, day_spec::DragPhase::Began);
2373        }
2374
2375        #[unsafe(method(mouseMoved:))]
2376        fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
2377            self.report_hover(event, day_spec::DragPhase::Changed);
2378        }
2379
2380        #[unsafe(method(mouseExited:))]
2381        fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
2382            self.report_hover(event, day_spec::DragPhase::Ended);
2383        }
2384
2385        /// A trackpad rotation (docs/canvas.md "Zoom and pan"). Each event's `rotation` is that
2386        /// event's own angle in degrees, counterclockwise positive; Day wants radians, clockwise
2387        /// positive, cumulative since `Began`. A gesture is bracketed by the event phases; an
2388        /// event with no phase is a lone `Changed` carrying its own angle.
2389        #[unsafe(method(rotateWithEvent:))]
2390        fn rotate_with_event(&self, event: &objc2_app_kit::NSEvent) {
2391            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2392            let Some(node) = ROTATE_NODES.with(|t| t.get(ptr)) else {
2393                let _: () = unsafe { msg_send![super(self), rotateWithEvent: event] };
2394                return;
2395            };
2396            ffi_guard::contain((), || {
2397                let tick = -f64::from(event.rotation()).to_radians();
2398                let raw = event.phase();
2399                let (phase, rotation) = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
2400                    ROTATE_ANGLE.with(|t| t.insert(ptr, tick));
2401                    (day_spec::DragPhase::Began, tick)
2402                } else if raw.intersects(
2403                    objc2_app_kit::NSEventPhase::Ended | objc2_app_kit::NSEventPhase::Cancelled,
2404                ) {
2405                    let total = ROTATE_ANGLE.with(|t| t.remove(ptr)).unwrap_or(0.0) + tick;
2406                    (day_spec::DragPhase::Ended, total)
2407                } else if raw.contains(objc2_app_kit::NSEventPhase::Changed) {
2408                    let total = ROTATE_ANGLE
2409                        .with(|t| {
2410                            t.with(ptr, |a| {
2411                                *a += tick;
2412                                *a
2413                            })
2414                        })
2415                        .unwrap_or(tick);
2416                    (day_spec::DragPhase::Changed, total)
2417                } else {
2418                    (day_spec::DragPhase::Changed, tick)
2419                };
2420                let win = event.locationInWindow();
2421                let loc = self.convertPoint_fromView(win, None);
2422                emit(
2423                    node,
2424                    Event::Rotate {
2425                        phase,
2426                        rotation,
2427                        location: Point::new(loc.x, loc.y),
2428                    },
2429                );
2430            });
2431        }
2432
2433        #[unsafe(method(scrollWheel:))]
2434        fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
2435            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2436            let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
2437                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
2438                return;
2439            };
2440            ffi_guard::contain((), || {
2441                // Trackpads bracket a pan with phases; a discrete wheel tick has none and
2442                // arrives as a lone Changed — exactly the Event::Pan contract.
2443                let raw = unsafe { event.phase() };
2444                let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
2445                    day_spec::DragPhase::Began
2446                } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
2447                    || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
2448                {
2449                    day_spec::DragPhase::Ended
2450                } else {
2451                    day_spec::DragPhase::Changed
2452                };
2453                let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
2454                    event.scrollingDeltaY()
2455                });
2456                let win = unsafe { event.locationInWindow() };
2457                let loc = self.convertPoint_fromView(win, None);
2458                emit(
2459                    node,
2460                    Event::Pan {
2461                        phase,
2462                        delta,
2463                        location: Point::new(loc.x, loc.y),
2464                    },
2465                );
2466            });
2467        }
2468    }
2469
2470    unsafe impl NSObjectProtocol for DayCanvas {}
2471
2472    /// The text input system's client (docs/menus.md "The full route"): the view a dead key
2473    /// or an input method composes into. A canvas has no document, so the marked text is
2474    /// held here and never shown; what the input method commits is the key event's text.
2475    unsafe impl NSTextInputClient for DayCanvas {
2476        #[unsafe(method(insertText:replacementRange:))]
2477        unsafe fn insert_text(&self, string: &AnyObject, _replacement: NSRange) {
2478            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2479            MARKED.with(|t| t.remove(ptr));
2480            let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
2481                return;
2482            };
2483            let text = text_of_input_string(string);
2484            if text.is_empty() {
2485                return;
2486            }
2487            ffi_guard::contain((), || {
2488                let interpreting = INTERPRETING.with(|i| i.borrow().clone());
2489                let event = match interpreting {
2490                    // One character typed by the key being interpreted: named by that key.
2491                    Some((key, mods)) if text.chars().count() == 1 => {
2492                        day_spec::KeyEvent::typed_by(key, text, mods)
2493                    }
2494                    Some((_, mods)) => day_spec::KeyEvent::typed_text(text, mods),
2495                    // Committed outside any key press (the Character Viewer, dictation).
2496                    None => day_spec::KeyEvent::typed_text(text, 0),
2497                };
2498                emit(node, Event::Key(event));
2499            });
2500        }
2501
2502        /// A key the text input system turned into an editing command (`insertNewline:`,
2503        /// `moveLeft:`, …). `keyDown:` already named every key the route carries before it
2504        /// asked the input system, so nothing is left to do here; anything else (a `noop:`
2505        /// for a function key the vocabulary lacks) types nothing, by design.
2506        #[unsafe(method(doCommandBySelector:))]
2507        unsafe fn do_command_by_selector(&self, _selector: Sel) {}
2508
2509        #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
2510        unsafe fn set_marked_text(&self, string: &AnyObject, _selected: NSRange, _replacement: NSRange) {
2511            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2512            let text = text_of_input_string(string);
2513            if text.is_empty() {
2514                MARKED.with(|t| t.remove(ptr));
2515            } else {
2516                MARKED.with(|t| t.insert(ptr, text));
2517            }
2518        }
2519
2520        #[unsafe(method(unmarkText))]
2521        fn unmark_text(&self) {
2522            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2523            MARKED.with(|t| t.remove(ptr));
2524        }
2525
2526        #[unsafe(method(selectedRange))]
2527        fn selected_range(&self) -> NSRange {
2528            NSRange::new(objc2_foundation::NSNotFound as usize, 0)
2529        }
2530
2531        #[unsafe(method(markedRange))]
2532        fn marked_range(&self) -> NSRange {
2533            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2534            match MARKED.with(|t| t.get(ptr)) {
2535                Some(marked) => NSRange::new(0, marked.encode_utf16().count()),
2536                None => NSRange::new(objc2_foundation::NSNotFound as usize, 0),
2537            }
2538        }
2539
2540        #[unsafe(method(hasMarkedText))]
2541        fn has_marked_text(&self) -> bool {
2542            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2543            MARKED.with(|t| t.contains(ptr))
2544        }
2545
2546        #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
2547        unsafe fn attributed_substring(
2548            &self,
2549            _range: NSRange,
2550            _actual: objc2_foundation::NSRangePointer,
2551        ) -> Option<Retained<objc2_foundation::NSAttributedString>> {
2552            None
2553        }
2554
2555        #[unsafe(method_id(validAttributesForMarkedText))]
2556        fn valid_attributes(&self) -> Retained<NSArray<objc2_foundation::NSAttributedStringKey>> {
2557            NSArray::new()
2558        }
2559
2560        /// Where the input method puts its candidate window: under the canvas, since the
2561        /// canvas does not say where its caret is.
2562        #[unsafe(method(firstRectForCharacterRange:actualRange:))]
2563        unsafe fn first_rect(&self, _range: NSRange, _actual: objc2_foundation::NSRangePointer) -> NSRect {
2564            let bounds = self.bounds();
2565            let in_window = self.convertRect_toView(bounds, None);
2566            match self.window() {
2567                Some(window) => window.convertRectToScreen(in_window),
2568                None => in_window,
2569            }
2570        }
2571
2572        #[unsafe(method(characterIndexForPoint:))]
2573        fn character_index_for_point(&self, _point: NSPoint) -> objc2_foundation::NSUInteger {
2574            objc2_foundation::NSNotFound as objc2_foundation::NSUInteger
2575        }
2576    }
2577);
2578
2579impl DayCanvas {
2580    fn new(mtm: MainThreadMarker) -> Retained<Self> {
2581        let this = Self::alloc(mtm).set_ivars(CanvasIvars);
2582        unsafe { msg_send![super(this), init] }
2583    }
2584
2585    /// One hover phase, reported to whichever node asked for it (docs/canvas.md "Interaction").
2586    ///
2587    /// `mouseEntered:`/`mouseExited:` are scoped by the tracking area, but **`mouseMoved:` is
2588    /// not**: it walks the responder chain, so a focused canvas hears about motion anywhere in
2589    /// its window — including outside itself. Hence the bounds test, without which a canvas
2590    /// reports a hover for a pointer that is nowhere near it (measured: a pointer parked outside
2591    /// the window entirely still produced hover positions).
2592    fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
2593        let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
2594        let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
2595            return;
2596        };
2597        ffi_guard::contain((), || {
2598            let win = unsafe { event.locationInWindow() };
2599            let loc = self.convertPoint_fromView(win, None);
2600            let b = self.bounds();
2601            let inside = loc.x >= b.origin.x
2602                && loc.x <= b.origin.x + b.size.width
2603                && loc.y >= b.origin.y
2604                && loc.y <= b.origin.y + b.size.height;
2605            // An exit is reported wherever it happens — that is the point of it — but a move
2606            // outside the view is not this view's hover.
2607            if !inside && phase != day_spec::DragPhase::Ended {
2608                return;
2609            }
2610            emit(
2611                node,
2612                Event::Hover {
2613                    phase,
2614                    location: Point::new(loc.x, loc.y),
2615                },
2616            );
2617        });
2618    }
2619}
2620
2621/// The tracking area a hovering canvas needs. `InVisibleRect` makes it follow the view's bounds,
2622/// so there is no rect to keep in step with layout; `ActiveInKeyWindow` matches the cursor areas
2623/// already installed here — a background window does not report hovers.
2624fn install_tracking_area(h: &NSView) {
2625    let opts = NSTrackingAreaOptions::MouseEnteredAndExited
2626        | NSTrackingAreaOptions::MouseMoved
2627        | NSTrackingAreaOptions::ActiveInKeyWindow
2628        | NSTrackingAreaOptions::InVisibleRect;
2629    let any: &objc2::runtime::AnyObject = h;
2630    let area = unsafe {
2631        NSTrackingArea::initWithRect_options_owner_userInfo(
2632            NSTrackingArea::alloc(),
2633            NSRect::ZERO,
2634            opts,
2635            Some(any),
2636            None,
2637        )
2638    };
2639    unsafe { h.addTrackingArea(&area) };
2640}
2641
2642// ---------------------------------------------------------------------------
2643// DayGesture — tap/drag recognizer target, node-id keyed (docs/shapes.md)
2644// ---------------------------------------------------------------------------
2645
2646struct GestureIvars {
2647    node: NodeId,
2648    kind: day_spec::GestureKind,
2649}
2650
2651define_class!(
2652    #[unsafe(super(NSObject))]
2653    #[thread_kind = MainThreadOnly]
2654    #[name = "DayGesture"]
2655    #[ivars = GestureIvars]
2656    struct DayGesture;
2657
2658    unsafe impl NSObjectProtocol for DayGesture {}
2659
2660    impl DayGesture {
2661        #[unsafe(method(fire:))]
2662        fn fire(&self, g: &NSGestureRecognizer) {
2663            ffi_guard::contain((), || {
2664                let node = self.ivars().node;
2665                let view = g.view();
2666                let loc = g.locationInView(view.as_deref());
2667                let at = Point::new(loc.x, loc.y);
2668                let phase = match g.state() {
2669                    NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
2670                    NSGestureRecognizerState::Ended
2671                    | NSGestureRecognizerState::Cancelled
2672                    | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
2673                    _ => day_spec::DragPhase::Changed,
2674                };
2675                let obj: &objc2::runtime::AnyObject = g.as_ref();
2676                match self.ivars().kind {
2677                    day_spec::GestureKind::Drag => {
2678                        let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
2679                            let t = unsafe { pan.translationInView(view.as_deref()) };
2680                            Point::new(t.x, t.y)
2681                        } else {
2682                            Point::ZERO
2683                        };
2684                        emit(node, Event::Drag { phase, location: at, translation });
2685                    }
2686                    day_spec::GestureKind::Pinch => {
2687                        // Cumulative since Began: `magnification` is the total delta (0 =
2688                        // unchanged), and Day's contract wants a factor.
2689                        let scale = if let Some(m) =
2690                            obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
2691                        {
2692                            1.0 + unsafe { m.magnification() }
2693                        } else {
2694                            1.0
2695                        };
2696                        emit(node, Event::Pinch { phase, scale, location: at });
2697                    }
2698                    _ => emit(node, Event::Tap(at)),
2699                }
2700            });
2701        }
2702    }
2703);
2704
2705impl DayGesture {
2706    fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2707        let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2708        unsafe { msg_send![super(this), init] }
2709    }
2710}
2711
2712// ---------------------------------------------------------------------------
2713// Navigation (docs/navigation.md): NSSplitView host, sidebar + detail panes.
2714// Page FRAMES are pane-owned (autoresized); Day lays content inside the size each
2715// page reports from setFrameSize:. Day's set_frame on pages is skipped.
2716// ---------------------------------------------------------------------------
2717
2718/// The stack presentation's back header (desktop has no system back affordance — this bar
2719/// gives a pushed page its way out, like `AdwNavigationView`'s header on GTK). Hidden at root.
2720struct NavHeader {
2721    bar: Retained<NSView>,
2722    title: Retained<NSTextField>,
2723    /// Title per stack level (index 0 = root); the field shows the last.
2724    titles: Vec<String>,
2725    _target: Retained<DayTarget>,
2726}
2727
2728/// Height of the stack-nav back header while a pushed page is showing.
2729const NAV_HEADER_H: f64 = 34.0;
2730
2731// Drag limits for both draggable panes come from day-spec (`NAV_SIDEBAR_MIN_W` and friends): a
2732// sidebar NSSplitViewItem enforces them itself, which is why the divider no longer needs
2733// restoring by hand after every window resize.
2734use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2735
2736/// The content-list width to place divider 1 at, once, the first time the pane is showing —
2737/// `None` when the pane is collapsed or has already been placed. Latches on the way out, so the
2738/// two callers (the first frame pass, and the patch that reveals the pane) cannot both spend it.
2739fn take_list_placement(state: &mut NavState) -> Option<f64> {
2740    if !state.list_visible || state.list_positioned {
2741        return None;
2742    }
2743    state.list_positioned = true;
2744    state.list_width
2745}
2746
2747/// A tabs host's `NSTabView` margins inside its pane: the sides and the foot, and the top —
2748/// deeper, since the tabs themselves stand about a segment's height above the bezel.
2749const NAV_TABVIEW_INSET: f64 = 12.0;
2750const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2751
2752/// The `NavPresentation::Tabs` container: a real `NSTabView` — the Mac's own tab control, top
2753/// tabs on a bezel — whose items own the detail pages. The page frames stay native-owned
2754/// exactly as in a split: the tab view frames the selected item's view, and the page's
2755/// `setFrameSize:` reports it. The labels come from the `NAV_MENU`'s rows, which arrive after
2756/// the pages' host (day-core mounts top-down: the rows page joins the host before its menu is
2757/// built), so `adopt_menu_for_tabs` runs when the menu is inserted and whenever its rows are
2758/// rebuilt.
2759///
2760/// Until 2026-09-12 this was an `NSSegmentedControl` docked at the foot, built from the rows
2761/// page's menu at the moment that page was inserted — before the menu existed — so no bar was
2762/// ever built and a tabs host showed its first page alone.
2763struct TabHost {
2764    view: Retained<objc2_app_kit::NSTabView>,
2765    /// The delegate reporting a native tab pick against the `NAV_MENU`'s node; set once the menu
2766    /// is known.
2767    target: Option<Retained<DayTarget>>,
2768}
2769
2770thread_local! {
2771    /// A Day-driven tab selection in flight (`NavPatch::Select`, a label sync): the tab view's
2772    /// delegate must not echo it back as `SelectionChanged`.
2773    static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2774}
2775
2776/// Give the tab view its labels from the rows, and its selection. Rows and items are
2777/// index-aligned (destination `i` is item `i`); a count mismatch mid-rebuild labels what both
2778/// have.
2779fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2780    unsafe {
2781        let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2782        for (i, title) in titles.iter().enumerate().take(n) {
2783            tabs.view
2784                .tabViewItemAtIndex(i as isize)
2785                .setLabel(&NSString::from_str(title));
2786        }
2787        if n > 0 {
2788            TAB_PICK_SUPPRESS.with(|s| s.set(true));
2789            tabs.view
2790                .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2791            TAB_PICK_SUPPRESS.with(|s| s.set(false));
2792        }
2793    }
2794}
2795
2796/// A `NAV_MENU` reached a tabs host (its rows page sits in the host's collapsed sidebar pane):
2797/// the menu's rows become the tab labels and its node the delegate's target. Walks up from the
2798/// menu, so the innermost host — the one whose rows these are — is the one that takes them.
2799fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2800    let Some((titles, node)) = NAV_MENUS.with(|m| {
2801        m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2802            let ivars = d.ivars();
2803            (
2804                ivars
2805                    .items
2806                    .borrow()
2807                    .iter()
2808                    .map(std::string::ToString::to_string)
2809                    .collect::<Vec<String>>(),
2810                ivars.node,
2811            )
2812        })
2813    }) else {
2814        return;
2815    };
2816    let mut up = unsafe { menu.superview() };
2817    while let Some(v) = up {
2818        let reached = NAV_STATE.with(|m| {
2819            let mut m = m.borrow_mut();
2820            let Some(s) = m.get_mut(&ptr_of(&v)) else {
2821                return false;
2822            };
2823            let selected = s.selected;
2824            if let Some(tabs) = s.tabs.as_mut() {
2825                if tabs.target.is_none() {
2826                    let target = DayTarget::new(mtm, node);
2827                    unsafe {
2828                        tabs.view
2829                            .setDelegate(Some(ProtocolObject::from_ref(&*target)));
2830                    };
2831                    tabs.target = Some(target);
2832                }
2833                sync_tab_labels(tabs, &titles, selected);
2834            }
2835            true
2836        });
2837        if reached {
2838            return;
2839        }
2840        up = unsafe { v.superview() };
2841    }
2842}
2843
2844struct NavState {
2845    sidebar_wrap: Retained<NSView>,
2846    detail_wrap: Retained<NSView>,
2847    /// The container behind the host view. A view holds NO strong reference to its controller,
2848    /// and the split view controller is what owns the items, their holding priorities, the
2849    /// sidebar's material and the split's delegate duties — so it has to be retained here or
2850    /// the sidebar loses its treatment the moment this realize returns.
2851    split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2852    /// The sidebar item, for the `SidebarToggle` duty (docs/toolbars.md). AppKit's own
2853    /// `NSToolbarToggleSidebarItem` reaches the controller through the responder chain; this is
2854    /// the path dayscript and any non-toolbar caller take.
2855    sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2856    /// The content-list pane (docs/navigation.md), `Some` only on a host whose
2857    /// `NavProps::list_width` was set: the wrap its `Pane::List` page fills, and the
2858    /// `contentList` split item `NavPatch::ListVisible` collapses. The pane PERSISTS through
2859    /// every presentation (`Cap::NavContentList` = Native) — a narrow window collapses the
2860    /// sidebar and keeps the list, exactly as a narrow Mail.app does.
2861    list_wrap: Option<Retained<NSView>>,
2862    list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2863    /// The app's requested content-list width (`NavProps::list_width`) — applied once, at the
2864    /// first frame pass, by placing divider 1 (see `set_frame`).
2865    list_width: Option<f64>,
2866    /// Whether the content-list pane is showing (`NavProps::list_visible`, then
2867    /// `NavPatch::ListVisible`). Placing divider 1 for a pane that is collapsed is what re-opens
2868    /// it, so both placement paths ask first.
2869    list_visible: bool,
2870    /// Whether divider 1 has been placed at the app's requested width yet. Separate from
2871    /// `positioned` because the pane may not exist on screen when the first frame pass runs: an
2872    /// app opening on a full-width destination has nothing to size then, and spending the
2873    /// one-time placement there is what left the list at the solver's own width when it did
2874    /// appear.
2875    list_positioned: bool,
2876    /// Detail pages in stack order (the sidebar page is not in here in split mode; in stack
2877    /// mode `split == false`, the root page is here too, so push/pop visibility covers it).
2878    pages: Vec<Retained<NSView>>,
2879    /// The host's sidebar page, once it has one — what a re-present moves between the sidebar
2880    /// pane and the head of `pages` (docs/size-classes.md).
2881    sidebar_page: Option<Retained<NSView>>,
2882    /// The content-list pane's page, re-framed when the pane is first revealed: it was inserted
2883    /// into a collapsed wrap, where autoresizing can only keep it at zero.
2884    list_page: Option<Retained<NSView>>,
2885    positioned: bool,
2886    /// Which of the four presentations is drawn right now (docs/size-classes.md). All of them are
2887    /// the same `NSSplitViewController`: a stack is that split with its sidebar collapsed, a rail
2888    /// is it with a narrow one, and a tab bar is a collapsed sidebar plus the bottom bar below.
2889    presentation: NavPresentation,
2890    /// The detail page on screen, as an index into `pages`. Maintained by every patch that
2891    /// changes it — push, pop and select alike — so a re-present can carry it across.
2892    selected: usize,
2893    /// The tab view (`NavPresentation::Tabs` only), holding the detail pages as its items and
2894    /// labeled from the same rows the sidebar's outline view shows; a pick emits
2895    /// `SelectionChanged` against the same `NAV_MENU` node.
2896    tabs: Option<TabHost>,
2897    /// Back header (stack presentation only).
2898    header: Option<NavHeader>,
2899    /// The host's own title, kept so a re-present into a stack can seed a fresh back header
2900    /// with the same root title the initial build would have used.
2901    root_title: String,
2902    /// The host's node, for the same reason — a back header's button targets it.
2903    node: NodeId,
2904    /// How far the host reaches up under the window's title bar (see `pane_under_title_bar`):
2905    /// the strip each pane's wrap is kept below. Zero for a host that does not start at the top
2906    /// of a pinned window.
2907    title_strip: f64,
2908}
2909
2910/// A split item's view: a transparent pane that runs the item's full height, with `wrap` (the
2911/// view Day's pages and the rest of this backend frame themselves against) inside it.
2912///
2913/// `NSSplitViewController` expects its split view to reach the top of a full-size-content window
2914/// and lays its title-bar treatment over the top of every item: a title-bar background, and on
2915/// macOS 26 and later the frosted scroll pocket. Day pins its content below the title bar
2916/// (`pin_below_title_bar`), so a split framed where Day lays it out put that treatment over the
2917/// first strip of every page instead, blurring a detail page's heading. The host is framed up
2918/// under the bar instead (`set_frame`), and each wrap is held below the strip inside its pane, so
2919/// the treatment lands on the bar, the sidebar's material runs to the top of the window as
2920/// `allowsFullHeightLayout` intends, and every page still starts where Day laid it out.
2921fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2922    let pane = view_of(&DayFlipped::new(mtm));
2923    unsafe {
2924        wrap.setFrame(pane.bounds());
2925        wrap.setAutoresizingMask(
2926            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2927                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2928        );
2929        pane.addSubview(wrap);
2930    }
2931    pane
2932}
2933
2934/// Hold `wrap` `strip` points below the top of the pane that holds it.
2935fn place_below_strip(wrap: &NSView, strip: f64) {
2936    let Some(pane) = (unsafe { wrap.superview() }) else {
2937        return;
2938    };
2939    let b = pane.bounds();
2940    unsafe {
2941        wrap.setFrame(NSRect::new(
2942            NSPoint::new(0.0, strip),
2943            NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2944        ));
2945    };
2946}
2947
2948/// The stack presentation's back header: a chevron + centered title docked above the pages,
2949/// hidden at the root. Desktop has no system back affordance, so a pushed page carries its own
2950/// way out (docs/navigation.md).
2951///
2952/// Built here rather than inline because a host that RE-PRESENTS into a stack needs one at that
2953/// moment (docs/size-classes.md), and a header that differed from the one a stack-at-launch host
2954/// gets would be a second shape to keep in step.
2955fn build_nav_header(
2956    mtm: MainThreadMarker,
2957    id: NodeId,
2958    detail_wrap: &NSView,
2959    root_title: &str,
2960) -> NavHeader {
2961    let bar = view_of(&DayFlipped::new(mtm));
2962    let target = DayTarget::new(mtm, id);
2963    let back = unsafe {
2964        // Invariant: NSImageNameGoBackTemplate is one of AppKit's own named images, present
2965        // on every macOS release this backend builds for.
2966        let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2967            .expect("NSGoBackTemplate");
2968        let tobj: &objc2::runtime::AnyObject = target.as_ref();
2969        objc2_app_kit::NSButton::buttonWithImage_target_action(
2970            &img,
2971            Some(tobj),
2972            Some(sel!(navBack:)),
2973            mtm,
2974        )
2975    };
2976    let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2977    unsafe {
2978        back.setFrame(NSRect::new(
2979            NSPoint::new(6.0, 4.0),
2980            NSSize::new(30.0, NAV_HEADER_H - 8.0),
2981        ));
2982        title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2983        title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2984        title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2985        title.setFrame(NSRect::new(
2986            NSPoint::new(44.0, 9.0),
2987            NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2988        ));
2989        title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2990        bar.setFrame(NSRect::new(
2991            NSPoint::new(0.0, 0.0),
2992            NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2993        ));
2994        bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2995        bar.addSubview(&back);
2996        bar.addSubview(&title);
2997        bar.setHidden(true);
2998        detail_wrap.addSubview(&bar);
2999    }
3000    NavHeader {
3001        bar,
3002        title,
3003        titles: vec![root_title.to_string()],
3004        _target: target,
3005    }
3006}
3007
3008/// The frame a stack page occupies inside the detail wrap: full bounds at the root, inset below
3009/// the back header while a pushed page is showing. (A tabs host's pages are framed by its
3010/// `NSTabView`, never through here.)
3011fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
3012    let b = wrap.bounds();
3013    let top = if header_visible { NAV_HEADER_H } else { 0.0 };
3014    NSRect::new(
3015        NSPoint::new(0.0, top),
3016        NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
3017    )
3018}
3019
3020/// The row titles and the `NAV_MENU` node of the menu inside `page`, if it has one.
3021///
3022/// The tab bar needs the same rows the sidebar shows, and they arrive at the `NAV_MENU` rather
3023/// than at the host. Rather than plumb a second copy through the props, this walks down to the
3024/// menu that is already there — the sidebar page is Day-built and shallow, so the search is a
3025/// handful of views — and reads the titles it has stored for its own outline view.
3026fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
3027    fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
3028        if out.is_some() {
3029            return;
3030        }
3031        let found = NAV_MENUS.with(|m| {
3032            m.borrow()
3033                .get(&(std::ptr::from_ref::<NSView>(v) as usize))
3034                .map(|(_, d)| {
3035                    let ivars = d.ivars();
3036                    (
3037                        ivars
3038                            .items
3039                            .borrow()
3040                            .iter()
3041                            .map(std::string::ToString::to_string)
3042                            .collect(),
3043                        ivars.node,
3044                    )
3045                })
3046        });
3047        if found.is_some() {
3048            *out = found;
3049            return;
3050        }
3051        for sub in &unsafe { v.subviews() } {
3052            walk(&sub, out);
3053        }
3054    }
3055    let mut out = None;
3056    walk(page, &mut out);
3057    out
3058}
3059
3060/// Apply a presentation to the sidebar split item. All four are the same item at a different
3061/// thickness or collapsed outright, which is why a morph never rebuilds the split.
3062fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
3063    let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
3064    unsafe {
3065        item.setCanCollapse(shown);
3066        item.setCollapsed(!shown);
3067        match pres {
3068            // macOS has no rail: nothing in AppKit is a vertical strip of icon-only
3069            // destinations, and a source list pinned to icon width just truncates every row to an
3070            // ellipsis. `NavPresentation::Rail` is explicitly ROUNDABLE for exactly this case, so
3071            // it lands on the neighbor a Mac does have — an ordinary sidebar. Windows rounds the
3072            // other way (`PaneDisplayMode = LeftCompact` is a real rail there).
3073            NavPresentation::Split | NavPresentation::Rail => {
3074                item.setAllowsFullHeightLayout(true);
3075                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
3076                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
3077            }
3078            // Zero the thickness bounds before collapsing takes effect, or the pane keeps a
3079            // minimum width and the detail never reaches the window edge.
3080            NavPresentation::Stack | NavPresentation::Tabs => {
3081                item.setMinimumThickness(0.0);
3082                item.setMaximumThickness(0.0);
3083            }
3084        }
3085    }
3086}
3087
3088/// Show/hide the stack-nav back header for the given page stack and re-frame the pages under
3089/// it. The header shows exactly while a pushed page (depth ≥ 1 above the root) is on top; each
3090/// page's `DayNavPage::setFrameSize` reports the new size so Day re-lays its content.
3091/// The split view of the navigation host in `window` that has a content-list pane, for the
3092/// tracking separator pinned to its second divider (docs/toolbars.md).
3093pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
3094    NAV_STATE.with(|m| {
3095        m.borrow()
3096            .values()
3097            .find(|st| {
3098                st.list_item.is_some()
3099                    && st
3100                        .sidebar_wrap
3101                        .window()
3102                        .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
3103            })
3104            .map(|st| unsafe { st.split_vc.splitView() })
3105    })
3106}
3107
3108fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
3109    let visible = pages.len() >= 2;
3110    hdr.bar.setHidden(!visible);
3111    unsafe {
3112        hdr.title.setStringValue(&NSString::from_str(
3113            hdr.titles.last().map_or("", String::as_str),
3114        ));
3115    }
3116    let frame = nav_page_frame(wrap, visible);
3117    for page in pages {
3118        unsafe { page.setFrame(frame) };
3119    }
3120}
3121
3122/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
3123/// chrome changes but the pages do not.
3124///
3125/// Both presentations already share one `NSSplitViewController` — a stack is the same split with
3126/// its sidebar item collapsed to zero thickness — so the morph is three moves, and none of them
3127/// touches a page's CONTENT:
3128///
3129/// 1. the sidebar item collapses or expands (AppKit animates it and re-runs the titlebar
3130///    separator on its own),
3131/// 2. the sidebar PAGE moves between the sidebar wrap and the head of the detail stack,
3132/// 3. the back header appears or hides, since only a stack has one.
3133///
3134/// `addSubview` re-parents a view rather than rebuilding it, so every page keeps its subtree,
3135/// its scroll position, and its first responder across the move.
3136fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
3137    let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
3138        NAV_STATE.with(|m| {
3139            let st = m.borrow();
3140            let s = st.get(&ptr_of(host))?;
3141            Some((
3142                s.sidebar_page.clone(),
3143                s.detail_wrap.clone(),
3144                s.sidebar_wrap.clone(),
3145                s.sidebar_item.clone(),
3146                s.presentation,
3147                s.root_title.clone(),
3148                s.node,
3149                s.selected,
3150            ))
3151        })
3152    else {
3153        return;
3154    };
3155    if was == next {
3156        return;
3157    }
3158    apply_sidebar_item(&sidebar_item, next);
3159    // Settle the split now rather than at the next natural layout pass. `setCollapsed` marks the
3160    // split view as needing layout; without this the pane keeps its old width for one more frame,
3161    // which the dayscript screenshot seam captures (it renders the window offscreen the instant
3162    // the patch returns) and which a user crossing a breakpoint sees as a stutter.
3163    NAV_STATE.with(|m| {
3164        if let Some(s) = m.borrow().get(&ptr_of(host)) {
3165            unsafe { s.split_vc.splitView().layoutSubtreeIfNeeded() };
3166        }
3167    });
3168    // A stack needs a back header; nothing else may show one. Built on demand and kept
3169    // afterwards — rebuilding it on every morph would leak a target per crossing.
3170    let stacked = next == NavPresentation::Stack;
3171    let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
3172    if stacked && header.is_none() {
3173        header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
3174    }
3175    if let Some(hdr) = header.as_ref() {
3176        hdr.bar.setHidden(true);
3177    }
3178    // No tab view here: `Tabs` is a PINNED style on this backend (`Cap::NavTabsAdaptive` is
3179    // off), resolved the same at every width, so a host never morphs into or out of it — its
3180    // `NSTabView` is built at realize and lives for the host.
3181    // Which page is on screen, by IDENTITY: moving the sidebar page in or out of the detail list
3182    // shifts every index past it, so an index captured now would name the wrong page after.
3183    let mut pages = NAV_STATE.with(|m| {
3184        m.borrow()
3185            .get(&ptr_of(host))
3186            .map_or_default(|s| s.pages.clone())
3187    });
3188    let shown_page = pages.get(sel).cloned();
3189    // The sidebar page is a stack ROOT only while stacked; otherwise it lives in its own pane,
3190    // which is the sidebar in `Split`/`Rail` and a collapsed one behind a tab bar in `Tabs`.
3191    if let Some(page) = sidebar_page {
3192        pages.retain(|p| ptr_of(p) != ptr_of(&page));
3193        unsafe {
3194            if stacked {
3195                detail_wrap.addSubview(&page);
3196                pages.insert(0, page.clone());
3197            } else {
3198                page.setFrame(sidebar_wrap.bounds());
3199                sidebar_wrap.addSubview(&page);
3200            }
3201        }
3202        // A pane always shows its page; as a stack root it may have been hidden under a push.
3203        page.setHidden(false);
3204    }
3205    let shown = shown_page
3206        .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
3207        .unwrap_or_else(|| pages.len().saturating_sub(1));
3208    for (i, page) in pages.iter().enumerate() {
3209        page.setHidden(i != shown);
3210    }
3211    NAV_STATE.with(|m| {
3212        let mut m = m.borrow_mut();
3213        if let Some(s) = m.get_mut(&ptr_of(host)) {
3214            s.presentation = next;
3215            s.pages = pages;
3216            s.selected = shown;
3217            s.header = header;
3218            if let Some(hdr) = s.header.as_ref() {
3219                // Depth drives visibility, and the header is meaningless anywhere but a stack.
3220                if stacked {
3221                    sync_nav_header(hdr, &s.detail_wrap, &s.pages);
3222                } else {
3223                    hdr.bar.setHidden(true);
3224                }
3225            }
3226            if !stacked {
3227                // Leaving the stack: the pages were inset below the header, so give them the
3228                // pane back.
3229                let frame = nav_page_frame(&s.detail_wrap, false);
3230                for page in &s.pages {
3231                    unsafe { page.setFrame(frame) };
3232                }
3233            }
3234        }
3235    });
3236}
3237
3238// ---------------------------------------------------------------------------
3239// The sidebar pane holds its width through NSSplitViewController's own holding priorities
3240// (docs/navigation.md) — a sidebar NSSplitViewItem pins its thickness and lets the detail
3241// absorb a window resize, which is exactly the Finder/Mail behavior the hand-rolled
3242// `splitView:shouldAdjustSizeOfSubview:` delegate used to approximate. The controller IS the
3243// split's delegate, so Day must not install one of its own.
3244// ---------------------------------------------------------------------------
3245
3246struct CoverSheet(Retained<NSWindow>);
3247impl Drop for CoverSheet {
3248    fn drop(&mut self) {
3249        // try_with: the table may already be gone when the thread's locals tear down.
3250        let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
3251        // Sheet transitions may run a nested AppKit update cycle. Defer them until the
3252        // core's tree borrow has ended; this retained pointer travels only to the main queue.
3253        let raw = Retained::into_raw(self.0.clone()) as usize;
3254        dispatch2::DispatchQueue::main().exec_async(move || {
3255            ffi_guard::contain((), || unsafe {
3256                let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
3257                if let Some(parent) = window.sheetParent() {
3258                    parent.endSheet(&window);
3259                }
3260                window.orderOut(None);
3261                window.setContentView(None);
3262            });
3263        });
3264    }
3265}
3266struct NavPageIvars {
3267    node: NodeId,
3268    /// A presented cover's strip under the window's title bar: the page paints it (its frame
3269    /// starts above the layout area) but lays its content out below it, and reports the
3270    /// remaining height (see `pin_below_title_bar`).
3271    top_inset: Cell<f64>,
3272    sheet: Cell<bool>,
3273    /// A half sheet (docs/cover.md): the window sheet stands half the parent's height.
3274    half: Cell<bool>,
3275    /// A large sheet (docs/cover.md "Large sheet"): the window sheet grows to
3276    /// `LARGE_SHEET_MAX`.
3277    large: Cell<bool>,
3278}
3279
3280define_class!(
3281    #[unsafe(super(NSView))]
3282    #[thread_kind = MainThreadOnly]
3283    #[name = "DayNavPage"]
3284    #[ivars = NavPageIvars]
3285    struct DayNavPage;
3286
3287    impl DayNavPage {
3288        #[unsafe(method(isFlipped))]
3289        fn is_flipped(&self) -> bool {
3290            true
3291        }
3292
3293        #[unsafe(method(setFrameSize:))]
3294        fn set_frame_size(&self, size: NSSize) {
3295            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
3296            // Pane-driven resize (splitter drag, window resize): report the usable size
3297            // so NavLayout re-lays this page's content (enqueue-only, §8.3).
3298            ffi_guard::contain((), || {
3299                let inset = self.ivars().top_inset.get();
3300                emit(
3301                    self.ivars().node,
3302                    Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
3303                );
3304            });
3305        }
3306    }
3307);
3308
3309impl DayNavPage {
3310    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
3311        let this = Self::alloc(mtm).set_ivars(NavPageIvars {
3312            node,
3313            top_inset: Cell::new(0.0),
3314            sheet: Cell::new(false),
3315            half: Cell::new(false),
3316            large: Cell::new(false),
3317        });
3318        unsafe { msg_send![super(this), init] }
3319    }
3320}
3321
3322// ---------------------------------------------------------------------------
3323// Inspector (docs/inspector.md): an NSSplitViewController whose trailing pane is a REAL
3324// inspector item (`inspectorWithViewController:`) — the system treatment for exactly this
3325// surface: its own backing material, the standard thickness handling, full-height layout
3326// under the titlebar. Day's bound signal is the only visibility driver (the item cannot be
3327// user-collapsed), so this backend never emits `Event::InspectorChanged`.
3328// ---------------------------------------------------------------------------
3329
3330struct InspectorState {
3331    content_wrap: Handle,
3332    panel_wrap: Handle,
3333    /// Retained so the controller (the split's delegate) lives as long as its split.
3334    split_vc: Retained<objc2_app_kit::NSSplitViewController>,
3335    panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
3336}
3337
3338// ---------------------------------------------------------------------------
3339// Split (docs/split.md): a plain `NSSplitView` inside a flipped wrap (the wrap is the handle,
3340// so `set_frame`'s nav-host treatment of split views never sees it), two arranged flipped
3341// subviews as the panes, and a delegate that places the divider by the bound share, keeps
3342// both panes above the minimum, and reports a drag back as the new share.
3343// ---------------------------------------------------------------------------
3344
3345struct SplitState {
3346    split: Retained<objc2_app_kit::NSSplitView>,
3347    first_wrap: Handle,
3348    second_wrap: Handle,
3349    delegate: Retained<DaySplitDelegate>,
3350}
3351
3352struct SplitDelegateIvars {
3353    node: NodeId,
3354    min_pane: f64,
3355    /// The share as last patched or reported: what a report is compared against, and where
3356    /// the divider goes when the split first has a size or turns.
3357    share: Cell<f64>,
3358    /// The divider has been placed once; before that the split has no size to place it in.
3359    positioned: Cell<bool>,
3360    /// Day is moving the divider itself: the resize that follows is not a report.
3361    suppress: Cell<bool>,
3362}
3363
3364define_class!(
3365    #[unsafe(super(NSObject))]
3366    #[thread_kind = MainThreadOnly]
3367    #[name = "DaySplitDelegate"]
3368    #[ivars = SplitDelegateIvars]
3369    struct DaySplitDelegate;
3370
3371    unsafe impl NSObjectProtocol for DaySplitDelegate {}
3372
3373    unsafe impl NSSplitViewDelegate for DaySplitDelegate {
3374        #[unsafe(method(splitViewDidResizeSubviews:))]
3375        fn did_resize(&self, notification: &NSNotification) {
3376            ffi_guard::contain((), || {
3377                let Some(obj) = notification.object() else {
3378                    return;
3379                };
3380                let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
3381                    return;
3382                };
3383                let iv = self.ivars();
3384                let usable = split_usable(&sv);
3385                if usable <= 0.0 {
3386                    return;
3387                }
3388                // The first resize with a size: place the divider by the share, once.
3389                if !iv.positioned.replace(true) {
3390                    split_place(&sv, iv);
3391                    return;
3392                }
3393                if iv.suppress.get() {
3394                    return;
3395                }
3396                let Some(first) = sv.subviews().iter().next() else {
3397                    return;
3398                };
3399                let f = first.frame();
3400                let a = if sv.isVertical() {
3401                    f.size.width
3402                } else {
3403                    f.size.height
3404                };
3405                let share = (a / usable).clamp(0.0, 1.0);
3406                if (share - iv.share.get()).abs() > 1e-4 {
3407                    iv.share.set(share);
3408                    emit(iv.node, Event::ValueChanged(share));
3409                }
3410            });
3411        }
3412
3413        #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
3414        fn constrain_min(
3415            &self,
3416            _sv: &objc2_app_kit::NSSplitView,
3417            proposed: f64,
3418            _index: isize,
3419        ) -> f64 {
3420            proposed.max(self.ivars().min_pane)
3421        }
3422
3423        #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
3424        fn constrain_max(
3425            &self,
3426            sv: &objc2_app_kit::NSSplitView,
3427            proposed: f64,
3428            _index: isize,
3429        ) -> f64 {
3430            proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
3431        }
3432    }
3433);
3434
3435impl DaySplitDelegate {
3436    fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
3437        let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
3438            node,
3439            min_pane,
3440            share: Cell::new(share.clamp(0.0, 1.0)),
3441            positioned: Cell::new(false),
3442            suppress: Cell::new(false),
3443        });
3444        unsafe { msg_send![super(this), init] }
3445    }
3446}
3447
3448/// The length the two panes share along the split's axis: the frame minus the divider.
3449fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
3450    let frame = sv.frame();
3451    let len = if sv.isVertical() {
3452        frame.size.width
3453    } else {
3454        frame.size.height
3455    };
3456    (len - sv.dividerThickness()).max(0.0)
3457}
3458
3459/// Move the divider so the first pane takes the share, silently (Day's own write, not a drag).
3460fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
3461    let usable = split_usable(sv);
3462    if usable <= 0.0 {
3463        return;
3464    }
3465    iv.suppress.set(true);
3466    unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
3467    iv.suppress.set(false);
3468}
3469
3470// ---------------------------------------------------------------------------
3471
3472// ---------------------------------------------------------------------------
3473// DayNavMenuData — flat NSOutlineView source list for nav_menu() (docs/navigation.md)
3474// ---------------------------------------------------------------------------
3475
3476struct NavMenuIvars {
3477    node: NodeId,
3478    items: RefCell<Vec<Retained<NSString>>>,
3479    /// Pre-resolved template icons per row (docs/navigation.md), `None` where a row has no icon.
3480    /// Template images tint with the source-list's selection/appearance, so they read in light,
3481    /// dark, and while selected — the macOS-idiomatic sidebar look (Finder/Mail).
3482    icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
3483    /// How much of each icon's box its drawing spans (`nav_icon_fill`), index-aligned with
3484    /// `icons`: the cell sizes the icon so the drawing matches a system sidebar glyph.
3485    icon_fills: RefCell<Vec<f64>>,
3486    /// Per-row icon tint (docs/vectors.md): recolors the template glyph via contentTintColor;
3487    /// `None` keeps the source-list's neutral template tint.
3488    tints: RefCell<Vec<Option<day_spec::Color>>>,
3489    /// Trailing accessory per item row (an unread count), `None` where a row has none.
3490    badges: RefCell<Vec<Option<Retained<NSString>>>>,
3491    /// Trailing accessory GLYPH per row, in the same slot as `badges` and drawn after it —
3492    /// a starred page's star. Resolved to images once per rebuild, like `icons`.
3493    icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
3494    badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
3495    /// Tint for `badge_icons`; `None` keeps the neutral template tint.
3496    badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
3497    /// Per-row context menu (docs/menus.md), empty = none. Built into an `NSMenu` and attached
3498    /// to the row's cell view, so a secondary click pops it like any native sidebar menu.
3499    menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
3500    /// Which items drag to reorder (`NavMenuProps::movable`); empty when none do.
3501    movable: RefCell<Vec<bool>>,
3502    /// Movable rows may cross section headers (`NavMenuProps::regroup`); set at creation.
3503    regroup: std::cell::Cell<bool>,
3504    /// Which movable items keep their section's sorted order (`NavMenuProps::sorted`).
3505    sorted: RefCell<Vec<bool>>,
3506    /// The outline's rows, in display order: `Some(i)` is item `i`, `None` is a section
3507    /// header. Day addresses rows by ITEM index, so every selection crossing the boundary
3508    /// goes through this map — a header must never shift what index 3 means.
3509    rows: RefCell<Vec<Option<usize>>>,
3510    /// One retained `NSString` per outline row: the row's text (a header's or an item's).
3511    row_objects: RefCell<Vec<Retained<NSString>>>,
3512    /// One `NSNumber` per outline row, holding the row's index: the outline's item IDENTITY.
3513    /// `NSOutlineView` matches items with `isEqual:`, so an `NSString` cannot be the identity —
3514    /// a section header titled "Controls" and an item titled "Controls" would collapse into one
3515    /// row, and the header would wear the item's icon. Row indexes are unique by construction.
3516    row_ids: RefCell<Vec<Retained<NSNumber>>>,
3517    /// Programmatic selection in flight: don't re-emit `SelectionChanged`.
3518    suppress: std::cell::Cell<bool>,
3519}
3520
3521struct NavCellIvars {
3522    /// The trailing accessories (an unread count, a status glyph), when the row has any: the
3523    /// label ends before them.
3524    accessory: RefCell<Option<Retained<NSView>>>,
3525    /// The unread count among them, sized to follow the row's text.
3526    count: RefCell<Option<Retained<NSTextField>>>,
3527    /// How much of the icon's box its drawing spans (`nav_icon_fill`).
3528    icon_fill: std::cell::Cell<f64>,
3529}
3530
3531define_class!(
3532    /// A sidebar row's cell. `NSTableCellView` lays out its icon and label itself, at the
3533    /// size the outline's row size style gives them: the system's Sidebar icon size setting,
3534    /// followed live (docs/navigation.md). This only makes room for the trailing accessories,
3535    /// which AppKit knows nothing about.
3536    #[unsafe(super(objc2_app_kit::NSTableCellView))]
3537    #[thread_kind = MainThreadOnly]
3538    #[name = "DayNavCell"]
3539    #[ivars = NavCellIvars]
3540    struct DayNavCell;
3541
3542    unsafe impl NSObjectProtocol for DayNavCell {}
3543
3544    impl DayNavCell {
3545        #[unsafe(method(layout))]
3546        fn layout(&self) {
3547            let _: () = unsafe { msg_send![super(self), layout] };
3548            ffi_guard::contain((), || self.fit_accessories());
3549        }
3550    }
3551);
3552
3553impl DayNavCell {
3554    fn new(mtm: MainThreadMarker) -> Retained<Self> {
3555        let this = Self::alloc(mtm).set_ivars(NavCellIvars {
3556            accessory: RefCell::new(None),
3557            count: RefCell::new(None),
3558            icon_fill: std::cell::Cell::new(1.0),
3559        });
3560        unsafe { msg_send![super(this), init] }
3561    }
3562
3563    /// After AppKit's layout: the count takes a size two points under the label's, and the
3564    /// label, which AppKit stretches to the cell's trailing edge, ends 6pt before the
3565    /// accessories so a long title truncates instead of running under its count. A showing
3566    /// progress ring re-fits the icon AppKit just sized.
3567    fn fit_accessories(&self) {
3568        let label = unsafe { self.textField() };
3569        if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
3570            let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
3571                (f.pointSize() - 2.0).max(9.0)
3572            });
3573            #[expect(
3574                clippy::float_cmp,
3575                reason = "unchanged-value check against the exact size set below"
3576            )]
3577            let resize = unsafe { count.font() }.is_none_or(|f| f.pointSize() != size);
3578            if resize {
3579                unsafe {
3580                    count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
3581                        size,
3582                        objc2_app_kit::NSFontWeightRegular,
3583                    )));
3584                }
3585                self.layoutSubtreeIfNeeded();
3586            }
3587        }
3588        if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
3589            let mut frame = label.frame();
3590            let end = accessory.frame().origin.x - 6.0;
3591            if frame.origin.x + frame.size.width > end {
3592                frame.size.width = (end - frame.origin.x).max(0.0);
3593                label.setFrame(frame);
3594            }
3595        }
3596        if let Some(icon) = unsafe { self.imageView() } {
3597            fit_nav_icon(&icon, self.ivars().icon_fill.get());
3598            nav_progress::fit(&icon);
3599        }
3600    }
3601}
3602
3603thread_local! {
3604    /// The side of a system sidebar glyph per symbol configuration (see `fit_nav_icon`).
3605    static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
3606}
3607
3608/// Draw a sidebar row's icon so its drawing is the size a system sidebar draws its SF Symbol,
3609/// centered in the slot AppKit lays out for it; `fill` is how much of the image's box the
3610/// drawing spans (`nav_icon_fill`). The slot is wider than the glyph AppKit puts there (22pt for a
3611/// 16pt glyph at Medium), and Day's icons are artwork that fills whatever frame it gets, so
3612/// left at the slot's size they read a third larger and heavier than Finder's or Mail's.
3613/// The side is measured, not tabled: a square symbol (`gearshape`) drawn with the symbol
3614/// configuration the row size style gave this image view, so it tracks the Sidebar icon size
3615/// setting and whatever a later macOS draws.
3616fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
3617    let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
3618        return;
3619    };
3620    let slot = icon.frame();
3621    // Configurations compare by value, and AppKit gives every cell of a row size style an
3622    // equal one, so the hash names the style.
3623    let key = config.hash() as u64;
3624    let side = NAV_GLYPH_SIDES
3625        .with(|m| m.borrow().get(&key).copied())
3626        .or_else(|| {
3627            let symbol =
3628                objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
3629                    &NSString::from_str("gearshape"),
3630                    None,
3631                )?;
3632            let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
3633            NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
3634            Some(side)
3635        });
3636    // The box that puts the drawing itself at the glyph's size: a Material Symbols icon keeps
3637    // the margin of its grid inside the box, so its box is that much larger.
3638    let Some(side) = side
3639        .filter(|s| *s > 0.0)
3640        .map(|s| (s / fill.clamp(0.25, 1.0)).round())
3641    else {
3642        return;
3643    };
3644    if slot.size.width <= side && slot.size.height <= side {
3645        return;
3646    }
3647    icon.setFrame(NSRect::new(
3648        NSPoint::new(
3649            (slot.origin.x + (slot.size.width - side) / 2.0).round(),
3650            (slot.origin.y + (slot.size.height - side) / 2.0).round(),
3651        ),
3652        NSSize::new(side, side),
3653    ));
3654}
3655
3656define_class!(
3657    #[unsafe(super(objc2_app_kit::NSTableRowView))]
3658    #[thread_kind = MainThreadOnly]
3659    #[name = "DayNavRowView"]
3660    struct DayNavRowView;
3661
3662    unsafe impl NSObjectProtocol for DayNavRowView {}
3663
3664    impl DayNavRowView {
3665        /// Always report the emphasized (key-window) state, so the selected sidebar row draws
3666        /// the accent pill with auto-whitened label/icon in both themes. Without this, a run
3667        /// whose window never becomes key (scripted screenshot captures) falls back to the
3668        /// unemphasized selection fill, which under a forced appearance rendered as a
3669        /// near-black pill that swallowed the row's label.
3670        #[unsafe(method(isEmphasized))]
3671        fn is_emphasized(&self) -> bool {
3672            true
3673        }
3674    }
3675);
3676
3677define_class!(
3678    #[unsafe(super(objc2_app_kit::NSOutlineView))]
3679    #[thread_kind = MainThreadOnly]
3680    #[name = "DayNavOutlineView"]
3681    struct DayNavOutlineView;
3682
3683    unsafe impl NSObjectProtocol for DayNavOutlineView {}
3684
3685    impl DayNavOutlineView {
3686        /// The clicked row's context menu (docs/menus.md): NSTableView-family views consume
3687        /// right-clicks themselves, so per-row menus are served here — resolve the row under
3688        /// the click, then build the same NSMenu the piece decorator would.
3689        #[unsafe(method_id(menuForEvent:))]
3690        fn menu_for_event(
3691            &self,
3692            event: &objc2_app_kit::NSEvent,
3693        ) -> Option<Retained<NSMenu>> {
3694            ffi_guard::contain(None, || {
3695                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3696                let row = unsafe { self.rowAtPoint(point) };
3697                let data = NAV_OUTLINE_MENUS.with(|t| t.get(std::ptr::from_ref(self) as usize));
3698                // `define_class!` rewrites the return, so no early `return` — one expression.
3699                match data {
3700                    None => None,
3701                    Some(d) => {
3702                        let items = d
3703                            .item_of_row(row)
3704                            .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
3705                            .unwrap_or_default();
3706                        if items.is_empty() {
3707                            None
3708                        } else {
3709                            Some(build_ns_menu(d.mtm(), "", &items))
3710                        }
3711                    }
3712                }
3713            })
3714        }
3715    }
3716);
3717
3718define_class!(
3719    #[unsafe(super(NSObject))]
3720    #[thread_kind = MainThreadOnly]
3721    #[name = "DayNavMenuData"]
3722    #[ivars = NavMenuIvars]
3723    struct DayNavMenuData;
3724
3725    unsafe impl NSObjectProtocol for DayNavMenuData {}
3726
3727    unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3728        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3729        fn number_of_children(
3730            &self,
3731            _ov: &objc2_app_kit::NSOutlineView,
3732            item: Option<&objc2::runtime::AnyObject>,
3733        ) -> isize {
3734            if item.is_none() {
3735                self.ivars().row_objects.borrow().len() as isize
3736            } else {
3737                0
3738            }
3739        }
3740
3741        #[unsafe(method_id(outlineView:child:ofItem:))]
3742        fn child_of_item(
3743            &self,
3744            _ov: &objc2_app_kit::NSOutlineView,
3745            index: isize,
3746            _item: Option<&objc2::runtime::AnyObject>,
3747        ) -> Retained<objc2::runtime::AnyObject> {
3748            let ids = self.ivars().row_ids.borrow();
3749            // AppKit only asks for children it was told exist, but a stale query racing a
3750            // reload must degrade (an unmatched identity) rather than index out of bounds —
3751            // a panic here unwinds into an ObjC frame and aborts.
3752            let id = ids
3753                .get(index as usize)
3754                .cloned()
3755                .unwrap_or_else(|| NSNumber::new_isize(-1));
3756            unsafe { objc2::rc::Retained::cast_unchecked(id) }
3757        }
3758
3759        #[unsafe(method(outlineView:isItemExpandable:))]
3760        fn is_expandable(
3761            &self,
3762            _ov: &objc2_app_kit::NSOutlineView,
3763            _item: &objc2::runtime::AnyObject,
3764        ) -> bool {
3765            false
3766        }
3767
3768        // --- drag-to-reorder (docs/navigation.md "Reordering sidebar destinations"): the
3769        // outline's own drag pipeline, with the Gap placeholder Finder's sidebar shows. A row
3770        // moves within the run of movable rows around it, or, regrouping, into any section of
3771        // movable rows (`regroup_gap`); the app's data change brings the new order back as
3772        // `NavMenuPatch::Items`.
3773
3774        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3775        fn pasteboard_writer_for_item(
3776            &self,
3777            _ov: &objc2_app_kit::NSOutlineView,
3778            item: &objc2::runtime::AnyObject,
3779        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3780            let make = || {
3781                let row = Self::outline_row(item);
3782                let index = self.item_of_row(row)?;
3783                if !self.is_movable(index) {
3784                    return None;
3785                }
3786                let pbitem = objc2_app_kit::NSPasteboardItem::new();
3787                unsafe {
3788                    pbitem.setString_forType(
3789                        &NSString::from_str(&row.to_string()),
3790                        &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3791                    );
3792                }
3793                Some(ProtocolObject::from_retained(pbitem))
3794            };
3795            ffi_guard::contain(None, make)
3796        }
3797
3798        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3799        fn validate_drop(
3800            &self,
3801            ov: &objc2_app_kit::NSOutlineView,
3802            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3803            item: Option<&objc2::runtime::AnyObject>,
3804            child_index: isize,
3805        ) -> objc2_app_kit::NSDragOperation {
3806            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3807                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3808                    return objc2_app_kit::NSDragOperation::None;
3809                };
3810                // A drop past the run's end lands at that end: move the gap there.
3811                if drop.retarget {
3812                    unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3813                }
3814                objc2_app_kit::NSDragOperation::Move
3815            })
3816        }
3817
3818        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3819        fn accept_drop(
3820            &self,
3821            ov: &objc2_app_kit::NSOutlineView,
3822            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3823            item: Option<&objc2::runtime::AnyObject>,
3824            child_index: isize,
3825        ) -> bool {
3826            ffi_guard::contain(false, || {
3827                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3828                    return false;
3829                };
3830                // Deferred through the event queue: the app's callback never runs inside
3831                // AppKit's drop, and its data change reloads the rows in the new order.
3832                match drop.moves {
3833                    Some(NavMove::Reorder { from, to }) => {
3834                        emit(self.ivars().node, Event::ListReorder { from, to });
3835                    }
3836                    Some(NavMove::Regroup {
3837                        from,
3838                        section,
3839                        before,
3840                    }) => emit(
3841                        self.ivars().node,
3842                        Event::NavRegroup {
3843                            from,
3844                            section,
3845                            before,
3846                        },
3847                    ),
3848                    None => {}
3849                }
3850                true
3851            })
3852        }
3853    }
3854
3855    unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3856
3857    unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3858        /// Section headers are AppKit group rows: the source-list treatment (small, bold,
3859        /// secondary) comes free, and they are excluded from selection below.
3860        #[unsafe(method(outlineView:isGroupItem:))]
3861        fn is_group_item(
3862            &self,
3863            _ov: &objc2_app_kit::NSOutlineView,
3864            item: &objc2::runtime::AnyObject,
3865        ) -> bool {
3866            let row = Self::outline_row(item);
3867            row >= 0 && self.item_of_row(row).is_none()
3868        }
3869
3870        #[unsafe(method(outlineView:shouldSelectItem:))]
3871        fn should_select(
3872            &self,
3873            _ov: &objc2_app_kit::NSOutlineView,
3874            item: &objc2::runtime::AnyObject,
3875        ) -> bool {
3876            self.item_of_row(Self::outline_row(item)).is_some()
3877        }
3878
3879        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3880        fn view_for(
3881            &self,
3882            ov: &objc2_app_kit::NSOutlineView,
3883            _col: Option<&objc2_app_kit::NSTableColumn>,
3884            item: &objc2::runtime::AnyObject,
3885        ) -> Option<Retained<NSView>> {
3886            let mtm = self.mtm();
3887            let row = Self::outline_row(item);
3888            let text = self
3889                .ivars()
3890                .row_objects
3891                .borrow()
3892                .get(usize::try_from(row).unwrap_or(usize::MAX))
3893                .cloned();
3894            // No early returns: the method_id macro owns the return conversion.
3895            text.map(|text| {
3896                let text: &NSString = &text;
3897                let Some(index) = self.item_of_row(row) else {
3898                    // A section header: a plain label. AppKit gives group rows their own
3899                    // typography and places the text, so this only supplies it.
3900                    let cell = DayNavCell::new(mtm);
3901                    let label = unsafe { NSTextField::labelWithString(text, mtm) };
3902                    unsafe {
3903                        label.cell().inspect(|c| {
3904                            c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
3905                        });
3906                        cell.addSubview(&label);
3907                        cell.setTextField(Some(&label));
3908                    }
3909                    return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3910                };
3911                let icon = self
3912                    .ivars()
3913                    .icons
3914                    .borrow()
3915                    .get(index)
3916                    .and_then(std::clone::Clone::clone);
3917                let badge = self
3918                    .ivars()
3919                    .badges
3920                    .borrow()
3921                    .get(index)
3922                    .and_then(std::clone::Clone::clone);
3923                let badge_icon = self
3924                    .ivars()
3925                    .badge_icons
3926                    .borrow()
3927                    .get(index)
3928                    .and_then(std::clone::Clone::clone);
3929                let badge_tint = self
3930                    .ivars()
3931                    .badge_tints
3932                    .borrow()
3933                    .get(index)
3934                    .copied()
3935                    .flatten();
3936                // The cell places the icon and the label itself, at the row size style's size
3937                // (the system's Sidebar icon size); `DayNavCell` keeps the label clear of the
3938                // trailing accessories.
3939                let cell = DayNavCell::new(mtm);
3940                let label = unsafe { NSTextField::labelWithString(text, mtm) };
3941                unsafe {
3942                    // Feed titles are arbitrarily long, so the label truncates with an
3943                    // ellipsis within the frame the cell gives it.
3944                    label.cell().inspect(|c| {
3945                        c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
3946                    });
3947                    cell.addSubview(&label);
3948                    cell.setTextField(Some(&label));
3949                    // The badge sits at the trailing edge and keeps its intrinsic width; the
3950                    // label truncates into whatever is left, so a long feed name never pushes
3951                    // its own unread count off the pane.
3952                    // Both accessories share the trailing slot: the count (if any) and then
3953                    // the status glyph (if any), in a stack so a row can carry either or both
3954                    // without the constraints below caring which it got.
3955                    let accessory = objc2_app_kit::NSStackView::new(mtm);
3956                    accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3957                    accessory.setOrientation(
3958                        objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3959                    );
3960                    accessory.setSpacing(4.0);
3961                    let mut has_accessory = false;
3962                    let trailing: Retained<NSView> = match &badge {
3963                        Some(text) => {
3964                            let b = NSTextField::labelWithString(text, mtm);
3965                            b.setTranslatesAutoresizingMaskIntoConstraints(false);
3966                            b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3967                            b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3968                            b.setFont(Some(
3969                                &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3970                                    objc2_app_kit::NSFont::smallSystemFontSize(),
3971                                    objc2_app_kit::NSFontWeightRegular,
3972                                ),
3973                            ));
3974                            b.setContentCompressionResistancePriority_forOrientation(
3975                                objc2_app_kit::NSLayoutPriorityRequired,
3976                                objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3977                            );
3978                            *cell.ivars().count.borrow_mut() = Some(b.clone());
3979                            accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3980                                objc2::rc::Retained::into_super(b),
3981                            ));
3982                            has_accessory = true;
3983                            let v: Retained<NSView> =
3984                                objc2::rc::Retained::into_super(accessory.clone());
3985                            v
3986                        }
3987                        None => objc2::rc::Retained::into_super(accessory.clone()),
3988                    };
3989                    // The status glyph, tinted where the app gave it a meaning-bearing color
3990                    // (a star is yellow because that is what a star IS, not because the theme
3991                    // says so). Template images take contentTintColor exactly as the row's
3992                    // leading icon does.
3993                    if let Some(img) = &badge_icon {
3994                        let iv = objc2_app_kit::NSImageView::new(mtm);
3995                        iv.setImage(Some(img));
3996                        iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3997                        if let Some(c) = badge_tint {
3998                            iv.setContentTintColor(Some(&nscolor(c)));
3999                        }
4000                        iv.setContentCompressionResistancePriority_forOrientation(
4001                            objc2_app_kit::NSLayoutPriorityRequired,
4002                            objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
4003                        );
4004                        accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
4005                        has_accessory = true;
4006                    }
4007                    cell.addSubview(&trailing);
4008                    if has_accessory {
4009                        *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
4010                    }
4011                    objc2_app_kit::NSLayoutConstraint::activateConstraints(
4012                        &objc2_foundation::NSArray::from_retained_slice(&[
4013                            trailing
4014                                .trailingAnchor()
4015                                .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
4016                            trailing
4017                                .centerYAnchor()
4018                                .constraintEqualToAnchor(&cell.centerYAnchor()),
4019                        ]),
4020                    );
4021                }
4022                if let Some(img) = icon {
4023                    let fill = self.ivars().icon_fills.borrow().get(index).copied();
4024                    cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
4025                    let tint = self.ivars().tints.borrow().get(index).copied().flatten();
4026                    let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
4027                    unsafe {
4028                        iv.setImage(Some(&img));
4029                        // Per-row tint (docs/vectors.md): the icons are template images, so
4030                        // contentTintColor recolors the alpha mask; None keeps the neutral look.
4031                        if let Some(t) = tint {
4032                            iv.setContentTintColor(Some(&nscolor(t)));
4033                        }
4034                        iv.setImageScaling(
4035                            objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
4036                        );
4037                        cell.addSubview(&iv);
4038                        cell.setImageView(Some(&iv));
4039                        let progress = self
4040                            .ivars()
4041                            .icon_progress
4042                            .borrow()
4043                            .iter()
4044                            .find(|(row, _)| *row == index)
4045                            .map(|(_, f)| *f);
4046                        nav_progress::update(&iv, progress);
4047                    }
4048                }
4049                objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
4050            })
4051        }
4052
4053        #[unsafe(method_id(outlineView:rowViewForItem:))]
4054        fn row_view_for(
4055            &self,
4056            _ov: &objc2_app_kit::NSOutlineView,
4057            _item: &objc2::runtime::AnyObject,
4058        ) -> Retained<objc2_app_kit::NSTableRowView> {
4059            let row: Retained<DayNavRowView> =
4060                unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
4061            objc2::rc::Retained::into_super(row)
4062        }
4063
4064        #[unsafe(method(outlineViewSelectionDidChange:))]
4065        fn selection_did_change(&self, notification: &NSNotification) {
4066            ffi_guard::contain((), || {
4067                if self.ivars().suppress.get() {
4068                    return;
4069                }
4070                let Some(obj) = (unsafe { notification.object() }) else {
4071                    return;
4072                };
4073                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
4074                    return;
4075                };
4076                let row = unsafe { ov.selectedRow() };
4077                if let Some(item) = self.item_of_row(row) {
4078                    emit(self.ivars().node, Event::SelectionChanged(item as i64));
4079                }
4080            });
4081        }
4082    }
4083);
4084
4085thread_local! {
4086    /// `nav_icon_fill` per icon name: a sidebar rebuilds its rows on every count change, and an
4087    /// icon's drawing does not change with them.
4088    static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
4089}
4090
4091/// `nav_icon_fill` for each resolved icon, by name; 1 where a row has none.
4092fn nav_icon_fills(
4093    names: &[Option<String>],
4094    images: &[Option<Retained<objc2_app_kit::NSImage>>],
4095) -> Vec<f64> {
4096    names
4097        .iter()
4098        .zip(images)
4099        .map(|(name, image)| match (name, image) {
4100            (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
4101                *m.borrow_mut()
4102                    .entry(name.clone())
4103                    .or_insert_with(|| nav_icon_fill(image))
4104            }),
4105            _ => 1.0,
4106        })
4107        .collect()
4108}
4109
4110/// How much of an icon's box its drawing spans along its longer side, in (0, 1]: a Material
4111/// Symbols glyph keeps the 80-unit margin of its 960-unit grid (about 0.83), an SF Symbol export
4112/// is boxed to its content (1), and artwork usually fills its square. Measured from the alpha of
4113/// one small render, since a plain SVG says nothing about where its drawing sits.
4114fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
4115    const PX: f64 = 64.0;
4116    let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
4117        return 1.0;
4118    };
4119    let (w, h) = (
4120        rep.pixelsWide().max(0) as usize,
4121        rep.pixelsHigh().max(0) as usize,
4122    );
4123    let stride = rep.bytesPerRow().max(0) as usize;
4124    let data = unsafe { rep.bitmapData() };
4125    if data.is_null() || stride < w * 4 {
4126        return 1.0;
4127    }
4128    // SAFETY: `scaled_rep` made a meshed 8-bit RGBA bitmap of `h` rows of `stride` bytes, which
4129    // `rep` owns and keeps alive for this borrow.
4130    let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
4131    let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
4132    for y in 0..h {
4133        for x in 0..w {
4134            if bytes[y * stride + x * 4 + 3] > 24 {
4135                (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
4136            }
4137        }
4138    }
4139    if x1 <= x0 || y1 <= y0 {
4140        return 1.0;
4141    }
4142    // The render stretched the image to a square; back in the image's own proportions, the
4143    // drawing's longer extent over the image's longer side is what proportional scaling keeps.
4144    let size = image.size();
4145    let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
4146    let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
4147    ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
4148}
4149
4150fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
4151    // A bundled icon name → a template NSImage (tinted by the source list); `None` per iconless row.
4152    icons
4153        .iter()
4154        .map(|ic| {
4155            use objc2::AllocAnyThread as _;
4156            let name = ic.as_deref()?;
4157            // Prefer the glyph SVG (docs/vectors.md): NSImage renders it at display size.
4158            let path = day_spec::resource::resolve_vector_svg(name)
4159                .or_else(|| day_spec::resource::resolve_image_file(name))?;
4160            let img = unsafe {
4161                objc2_app_kit::NSImage::initWithContentsOfFile(
4162                    objc2_app_kit::NSImage::alloc(),
4163                    &NSString::from_str(&path.to_string_lossy()),
4164                )
4165            }?;
4166            // Downloaded/user-file icons are artwork; bundled glyphs remain templates.
4167            unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
4168            Some(img)
4169        })
4170        .collect()
4171}
4172
4173impl DayNavMenuData {
4174    #[allow(clippy::too_many_arguments)]
4175    fn new(
4176        mtm: MainThreadMarker,
4177        node: NodeId,
4178        items: &[String],
4179        icons: &[Option<String>],
4180        badges: &[Option<String>],
4181        badge_icons: &[Option<String>],
4182        badge_tints: &[Option<day_spec::Color>],
4183        sections: &[Option<String>],
4184        tints: &[Option<day_spec::Color>],
4185        menus: &[Vec<day_spec::MenuItem>],
4186    ) -> Retained<Self> {
4187        let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
4188            node,
4189            items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
4190            icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
4191            icons: RefCell::new(resolve_nav_icons(icons)),
4192            tints: RefCell::new(tints.to_vec()),
4193            menus: RefCell::new(menus.to_vec()),
4194            movable: RefCell::new(Vec::new()),
4195            regroup: std::cell::Cell::new(false),
4196            sorted: RefCell::new(Vec::new()),
4197            badges: RefCell::new(ns_badges(badges)),
4198            icon_progress: RefCell::new(Vec::new()),
4199            badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
4200            badge_tints: RefCell::new(badge_tints.to_vec()),
4201            rows: RefCell::new(Vec::new()),
4202            row_objects: RefCell::new(Vec::new()),
4203            row_ids: RefCell::new(Vec::new()),
4204            suppress: std::cell::Cell::new(false),
4205        });
4206        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
4207        this.rebuild_rows(items, sections);
4208        this
4209    }
4210
4211    /// Data-driven rows changed (`NavMenuPatch::Items`): swap the stored decorations in place.
4212    // The parameters are the patch's payload: index-aligned per-row decoration arrays, each
4213    // landing in its own ivar. Bundling them would just move the same eight fields.
4214    #[allow(clippy::too_many_arguments)]
4215    fn set_items(
4216        &self,
4217        items: &[String],
4218        icons: &[Option<String>],
4219        badges: &[Option<String>],
4220        badge_icons: &[Option<String>],
4221        badge_tints: &[Option<day_spec::Color>],
4222        sections: &[Option<String>],
4223        tints: &[Option<day_spec::Color>],
4224        menus: &[Vec<day_spec::MenuItem>],
4225    ) {
4226        *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
4227        let resolved = resolve_nav_icons(icons);
4228        *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
4229        *self.ivars().icons.borrow_mut() = resolved;
4230        *self.ivars().tints.borrow_mut() = tints.to_vec();
4231        *self.ivars().menus.borrow_mut() = menus.to_vec();
4232        *self.ivars().badges.borrow_mut() = ns_badges(badges);
4233        self.ivars().icon_progress.borrow_mut().clear();
4234        *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
4235        *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
4236        self.rebuild_rows(items, sections);
4237    }
4238
4239    /// Flatten items + section headers into the outline's display rows. Each row gets its own
4240    /// retained `NSString` so the outline can tell two rows apart by identity even when their
4241    /// labels match (two feeds legitimately share a title).
4242    fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
4243        let mut rows = Vec::with_capacity(items.len());
4244        let mut objects = Vec::with_capacity(items.len());
4245        for (i, label) in items.iter().enumerate() {
4246            if let Some(Some(header)) = sections.get(i) {
4247                rows.push(None);
4248                objects.push(NSString::from_str(header));
4249            }
4250            rows.push(Some(i));
4251            objects.push(NSString::from_str(label));
4252        }
4253        let ids = (0..objects.len())
4254            .map(|i| NSNumber::new_isize(i as isize))
4255            .collect();
4256        *self.ivars().rows.borrow_mut() = rows;
4257        *self.ivars().row_objects.borrow_mut() = objects;
4258        *self.ivars().row_ids.borrow_mut() = ids;
4259    }
4260
4261    /// The outline row an item object names — the index its `NSNumber` identity carries — or
4262    /// `-1` for anything that is not one of ours (a stale query racing a reload).
4263    fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
4264        item.downcast_ref::<NSNumber>()
4265            .map_or(-1, objc2_foundation::NSNumber::integerValue)
4266    }
4267
4268    /// Outline row → day item index.
4269    fn item_of_row(&self, row: isize) -> Option<usize> {
4270        if row < 0 {
4271            return None;
4272        }
4273        self.ivars()
4274            .rows
4275            .borrow()
4276            .get(row as usize)
4277            .copied()
4278            .flatten()
4279    }
4280
4281    /// Day item index → outline row.
4282    fn row_of_item(&self, item: usize) -> Option<usize> {
4283        self.ivars()
4284            .rows
4285            .borrow()
4286            .iter()
4287            .position(|r| *r == Some(item))
4288    }
4289
4290    fn is_movable(&self, item: usize) -> bool {
4291        self.ivars()
4292            .movable
4293            .borrow()
4294            .get(item)
4295            .copied()
4296            .unwrap_or(false)
4297    }
4298
4299    /// What a drop proposal means for a reorder, or `None` when it is no drop of ours: a drag
4300    /// from another view, of a row that cannot move, or (regrouping) to a gap no rule allows.
4301    /// Reordering, the gap clamps to the run of movable rows around the dragged one, which
4302    /// section headers and fixed rows end ([`reorder_gap`]); regrouping, see [`regroup_gap`].
4303    fn nav_drop(
4304        &self,
4305        ov: &objc2_app_kit::NSOutlineView,
4306        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4307        item: Option<&objc2::runtime::AnyObject>,
4308        child_index: isize,
4309    ) -> Option<NavDrop> {
4310        let src = unsafe { info.draggingSource() }?;
4311        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
4312            != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
4313        {
4314            return None;
4315        }
4316        let pb = unsafe { info.draggingPasteboard() };
4317        let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
4318            .to_string()
4319            .parse::<usize>()
4320            .ok()?;
4321        let rows = self.ivars().rows.borrow();
4322        // The flat outline proposes a gap among the root's children, or a row itself (a drop
4323        // ONTO it, index -1).
4324        let proposed = match item {
4325            Some(item) => Self::outline_row(item),
4326            None => child_index,
4327        };
4328        let proposed = usize::try_from(proposed).unwrap_or(rows.len());
4329        if self.ivars().regroup.get() {
4330            regroup_gap(
4331                &rows,
4332                &self.ivars().movable.borrow(),
4333                &self.ivars().sorted.borrow(),
4334                from_row,
4335                proposed,
4336                item.is_some(),
4337            )
4338        } else {
4339            reorder_gap(
4340                &rows,
4341                &self.ivars().movable.borrow(),
4342                from_row,
4343                proposed,
4344                item.is_some(),
4345            )
4346        }
4347    }
4348}
4349
4350/// A drop in a sidebar outline (`DayNavMenuData::nav_drop`).
4351#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4352struct NavDrop {
4353    /// The gap the row drops into, among the outline's rows.
4354    gap: usize,
4355    /// The proposal named some other place, and the gap moves here.
4356    retarget: bool,
4357    /// What the drop reports, or `None` for a drop back in place.
4358    moves: Option<NavMove>,
4359}
4360
4361/// What a sidebar drop reports, in item indices (the rows before the move).
4362#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4363enum NavMove {
4364    /// `Event::ListReorder`: `from` takes `to`'s place.
4365    Reorder { from: usize, to: usize },
4366    /// `Event::NavRegroup`: `from` joins the section whose first row is `section`, before
4367    /// `before` or at the section's end.
4368    Regroup {
4369        from: usize,
4370        section: usize,
4371        before: Option<usize>,
4372    },
4373}
4374
4375/// A reorder drop at `proposed`, a gap among the outline's `rows` (`None` a header, `Some(i)`
4376/// item `i`), for the row at `from_row`; `onto` when the proposal named a row itself, which
4377/// reads as the gap above it. The gap clamps to the run of movable rows around the dragged
4378/// one, which section headers and fixed rows end. `None` when that row cannot move.
4379fn reorder_gap(
4380    rows: &[Option<usize>],
4381    movable: &[bool],
4382    from_row: usize,
4383    proposed: usize,
4384    onto: bool,
4385) -> Option<NavDrop> {
4386    let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
4387    let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
4388    let in_run = |r: usize| rows[r].is_some_and(is_movable);
4389    let first = (0..from_row)
4390        .rev()
4391        .take_while(|r| in_run(*r))
4392        .last()
4393        .unwrap_or(from_row);
4394    let last = (from_row + 1..rows.len())
4395        .take_while(|r| in_run(*r))
4396        .last()
4397        .unwrap_or(from_row);
4398    let gap = proposed.clamp(first, last + 1);
4399    // The row's place once it has left its own: the row whose position it takes.
4400    let target_row = if gap > from_row { gap - 1 } else { gap };
4401    let moves = (target_row != from_row)
4402        .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
4403        .flatten();
4404    Some(NavDrop {
4405        gap,
4406        retarget: gap != proposed || onto,
4407        moves,
4408    })
4409}
4410
4411/// A regroup drop at `proposed`, a gap among the outline's `rows` (as [`reorder_gap`]'s), for
4412/// the row at `from_row` (docs/navigation.md "Moving rows between sections"). The gap's section
4413/// is the nearest header above it, or the rows above the first header; `before` is the item
4414/// right below the gap when that row is in the same section. A drop ONTO a header reads as
4415/// that section's first gap, onto an item as the gap above it. `None` when the row cannot
4416/// move, the gap is above the first header with no rows there, the section holds a fixed row,
4417/// or the gap is in the row's own section and the row is sorted. Gaps are never clamped.
4418fn regroup_gap(
4419    rows: &[Option<usize>],
4420    movable: &[bool],
4421    sorted: &[bool],
4422    from_row: usize,
4423    proposed: usize,
4424    onto: bool,
4425) -> Option<NavDrop> {
4426    let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
4427    let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
4428    let gap = match rows.get(proposed) {
4429        Some(None) if onto => proposed + 1,
4430        _ => proposed.min(rows.len()),
4431    };
4432    // The first outline row of the section a gap (or a row, as the gap above it) sits in.
4433    let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
4434        Some(header) => Some(header + 1),
4435        None => rows.first().copied().flatten().map(|_| 0),
4436    };
4437    let first = section_start(gap)?;
4438    let end = (first..rows.len())
4439        .find(|r| rows[*r].is_none())
4440        .unwrap_or(rows.len());
4441    let section = rows.get(first).copied().flatten()?;
4442    if !rows[first..end]
4443        .iter()
4444        .all(|r| r.is_some_and(|i| flag(movable, i)))
4445    {
4446        return None;
4447    }
4448    let own = section_start(from_row) == Some(first);
4449    if own && flag(sorted, from) {
4450        return None;
4451    }
4452    let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
4453        from,
4454        section,
4455        before: rows.get(gap).copied().flatten(),
4456    });
4457    Some(NavDrop {
4458        gap,
4459        retarget: gap != proposed || onto,
4460        moves,
4461    })
4462}
4463
4464#[cfg(test)]
4465mod nav_gap_tests {
4466    use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
4467
4468    /// 0 today, 1 [news], 2 a, 3 b, 4 e, 5 [tech], 6 c, 7 d, 8 [smart], 9 starred: items 0..=6.
4469    const ROWS: [Option<usize>; 10] = [
4470        Some(0),
4471        None,
4472        Some(1),
4473        Some(2),
4474        Some(3),
4475        None,
4476        Some(4),
4477        Some(5),
4478        None,
4479        Some(6),
4480    ];
4481    /// The feeds move; today and starred are fixed.
4482    const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
4483    const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
4484    const UNSORTED: [bool; 7] = [false; 7];
4485
4486    fn regroup(from: usize, section: usize, before: Option<usize>) -> NavMove {
4487        NavMove::Regroup {
4488            from,
4489            section,
4490            before,
4491        }
4492    }
4493
4494    #[test]
4495    fn regroup_gaps_name_the_section_above_and_the_row_below() {
4496        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4497        // a, into tech's first gap: before c.
4498        assert_eq!(
4499            at(2, 6),
4500            Some(NavDrop {
4501                gap: 6,
4502                retarget: false,
4503                moves: Some(regroup(1, 4, Some(4))),
4504            })
4505        );
4506        // c, into the gap above tech's header: the end of news.
4507        assert_eq!(at(6, 5).and_then(|d| d.moves), Some(regroup(4, 1, None)));
4508        // a, between c and d, and at tech's end above smart's header.
4509        assert_eq!(at(2, 7).and_then(|d| d.moves), Some(regroup(1, 4, Some(5))));
4510        assert_eq!(at(2, 8).and_then(|d| d.moves), Some(regroup(1, 4, None)));
4511    }
4512
4513    #[test]
4514    fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
4515        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4516        // Smart holds starred, and the rows above the first header hold today.
4517        for gap in [0, 1, 9, 10] {
4518            assert_eq!(at(2, gap), None, "gap {gap}");
4519        }
4520        // A sorted row's own section offers no gap, its own place included.
4521        for gap in [2, 3, 4, 5] {
4522            assert_eq!(at(2, gap), None, "gap {gap}");
4523        }
4524        // Fixed rows and headers never drag.
4525        assert_eq!(at(0, 6), None);
4526        assert_eq!(at(1, 6), None);
4527        assert_eq!(at(9, 6), None);
4528    }
4529
4530    #[test]
4531    fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
4532        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
4533        // a, between b and e.
4534        assert_eq!(at(2, 4).and_then(|d| d.moves), Some(regroup(1, 1, Some(3))));
4535        // a, at news's end above tech's header.
4536        assert_eq!(at(2, 5).and_then(|d| d.moves), Some(regroup(1, 1, None)));
4537        // Back in place, either side of itself: a drop that reports nothing.
4538        for gap in [2, 3] {
4539            let drop = at(2, gap).expect("offered");
4540            assert_eq!(drop.moves, None, "gap {gap}");
4541        }
4542    }
4543
4544    #[test]
4545    fn regroup_drops_onto_a_row_move_to_a_gap() {
4546        // Onto tech's header: its first gap. Onto d: the gap above d.
4547        assert_eq!(
4548            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
4549            Some(NavDrop {
4550                gap: 6,
4551                retarget: true,
4552                moves: Some(regroup(1, 4, Some(4))),
4553            })
4554        );
4555        assert_eq!(
4556            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
4557            Some(NavDrop {
4558                gap: 7,
4559                retarget: true,
4560                moves: Some(regroup(1, 4, Some(5))),
4561            })
4562        );
4563    }
4564
4565    #[test]
4566    fn regroup_offers_nothing_above_a_leading_header() {
4567        // 0 [news], 1 a, 2 [tech], 3 b.
4568        let rows = [None, Some(0), None, Some(1)];
4569        let movable = [true, true];
4570        let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
4571        assert_eq!(at(0), None);
4572        assert_eq!(at(1).map(|d| d.moves), Some(None));
4573        assert_eq!(at(2).map(|d| d.moves), Some(None));
4574        assert_eq!(at(3).and_then(|d| d.moves), Some(regroup(0, 1, Some(1))));
4575        assert_eq!(at(4).and_then(|d| d.moves), Some(regroup(0, 1, None)));
4576    }
4577
4578    #[test]
4579    fn reorder_gaps_clamp_to_the_run() {
4580        // a past the run's end lands at its end: e's place.
4581        assert_eq!(
4582            reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
4583            Some(NavDrop {
4584                gap: 5,
4585                retarget: true,
4586                moves: Some(NavMove::Reorder { from: 1, to: 3 }),
4587            })
4588        );
4589        // Back in place.
4590        assert_eq!(
4591            reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
4592            Some(None)
4593        );
4594        // b above the run's start lands at a's place; a fixed row offers nothing.
4595        assert_eq!(
4596            reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
4597            Some(NavMove::Reorder { from: 2, to: 1 })
4598        );
4599        assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
4600    }
4601}
4602
4603/// The private pasteboard type carrying a dragged sidebar row (local reorder only).
4604const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
4605
4606/// Badge strings, retained once per rebuild rather than per cell.
4607fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
4608    badges
4609        .iter()
4610        .map(|b| b.as_deref().map(NSString::from_str))
4611        .collect()
4612}
4613
4614// ---------------------------------------------------------------------------
4615/// Force the table's visible rows to exist on the next main-loop turn — outside any `with_tree`
4616/// borrow, so `bind_row` may build them. `layoutSubtreeIfNeeded` is not enough: an occluded
4617/// window's table skips row tiling entirely, so `viewAtColumn:row:makeIfNecessary:` is the only
4618/// reliable way to realize rows without a draw pass (§10; see the Reload patch for why).
4619fn post_realize_visible_rows(key: usize) {
4620    <AppKit as Platform>::post(Box::new(move || {
4621        if let Some((table, data)) = list_entry(key) {
4622            unsafe { table.layoutSubtreeIfNeeded() };
4623            let range = unsafe { table.rowsInRect(table.visibleRect()) };
4624            if let Some(source) = data.ivars().source.borrow().clone()
4625                && let Some(report) = &source.first_visible
4626            {
4627                report(range.location.min((source.len)().saturating_sub(1)));
4628            }
4629            for row in range.location..range.location + range.length {
4630                let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
4631                // A snapshot/layout can have requested this cell while day-core held its
4632                // tree borrow. The delegate then returned an empty container; AppKit caches
4633                // it and will not ask viewForRow again. Complete that skipped bind here.
4634                if let Some(cell) = cell
4635                    && cell.subviews().is_empty()
4636                {
4637                    let source = data.ivars().source.borrow().clone();
4638                    if let Some(source) = source {
4639                        (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
4640                    }
4641                }
4642            }
4643        }
4644        // The builds above queued their styling effects; drain them now — outside the pump, no
4645        // event may arrive for a while (idle app), and a snapshot would capture bare rows.
4646        day_core::pump_events();
4647    }));
4648}
4649
4650/// A native drop changes the snapshot synchronously and suppresses the app's echo Reload.
4651/// Once AppKit has unwound its drop/gap tracking, reconcile the table with that snapshot:
4652/// the incremental move alone can leave its row tiling and scroll extent out of sync.
4653/// Preserve the user's viewport and selection; never force a jump to the moved row.
4654fn post_settle_list_drop(key: usize) {
4655    <AppKit as Platform>::post(Box::new(move || {
4656        // Publish the deferred on_reorder before reading the final row set. App code may
4657        // remove rows or close the list, so resolve the native handles only after the drain.
4658        day_core::pump_events();
4659        let Some((table, data)) = list_entry(key) else {
4660            return;
4661        };
4662        let Some(scroll) = table.enclosingScrollView() else {
4663            return;
4664        };
4665        let clip = scroll.contentView();
4666        let origin = clip.bounds().origin;
4667        let selected = table.selectedRowIndexes();
4668        let suppressed = data.ivars().suppress.replace(true);
4669        table.reloadData();
4670        // Outside with_tree: tiling is allowed to bind/rebind Day's cell contents here.
4671        table.layoutSubtreeIfNeeded();
4672        let restored = objc2_foundation::NSMutableIndexSet::new();
4673        for row in 0..table.numberOfRows().max(0) as usize {
4674            if selected.containsIndex(row) {
4675                restored.addIndex(row);
4676            }
4677        }
4678        table.selectRowIndexes_byExtendingSelection(&restored, false);
4679        let mut bounds = clip.bounds();
4680        bounds.origin = origin;
4681        clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
4682        scroll.reflectScrolledClipView(&clip);
4683        data.ivars().suppress.set(suppressed);
4684        post_realize_visible_rows(key);
4685    }));
4686}
4687
4688// DayListData — NSTableView data-source + delegate for the recycling list (docs/list.md, §10)
4689//
4690// No custom NSTableRowView: the table runs the PLAIN style, whose standard row view lays cell
4691// views out at the full row bounds — no inset to pin away — and whose cell-frame slide is what
4692// animates a row-action swipe. (A `layout`-override pin lived here under FullWidth until
4693// 2026-08; it also froze row content mid-swipe, revealing actions behind a motionless row.)
4694// ---------------------------------------------------------------------------
4695
4696define_class!(
4697    #[unsafe(super(NSTableView))]
4698    #[thread_kind = MainThreadOnly]
4699    #[name = "DayListView"]
4700    struct DayListView;
4701    unsafe impl NSObjectProtocol for DayListView {}
4702    impl DayListView {
4703        /// NSTableView consumes right-clicks before the row's container sees them. Resolve
4704        /// its summon-time provider from the visible cell, never from the selected row.
4705        #[unsafe(method_id(menuForEvent:))]
4706        fn menu_for_event(
4707            &self,
4708            event: &objc2_app_kit::NSEvent,
4709        ) -> Option<Retained<NSMenu>> {
4710            ffi_guard::contain(None, || {
4711                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4712                let row = unsafe { self.rowAtPoint(point) };
4713                let provider = if row >= 0 {
4714                    unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
4715                        .and_then(|cell| list_row_menu_provider(&cell))
4716                } else {
4717                    None
4718                };
4719                match provider {
4720                    Some((view, provider)) => {
4721                        let point = view.convertPoint_fromView(
4722                            unsafe { event.locationInWindow() }, None,
4723                        );
4724                        let items = provider(day_spec::Point::new(point.x, point.y));
4725                        if items.is_empty() {
4726                            None
4727                        } else {
4728                            Some(build_ns_menu(self.mtm(), "", &items))
4729                        }
4730                    }
4731                    None => unsafe { msg_send![super(self), menuForEvent: event] },
4732                }
4733            })
4734        }
4735
4736        #[unsafe(method(becomeFirstResponder))]
4737        fn become_first_responder(&self) -> bool {
4738            let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4739            if accepted {
4740                self.report_focus(true);
4741            }
4742            accepted
4743        }
4744
4745        #[unsafe(method(resignFirstResponder))]
4746        fn resign_first_responder(&self) -> bool {
4747            let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4748            if accepted {
4749                self.report_focus(false);
4750            }
4751            accepted
4752        }
4753
4754        #[unsafe(method(keyDown:))]
4755        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4756            ffi_guard::contain((), || {
4757                let key = unsafe { event.keyCode() };
4758                if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4759                    let row = unsafe { self.selectedRow() };
4760                    if row >= 0 && let Some(target) = unsafe { self.target() } {
4761                        let _: () = unsafe { msg_send![&*target, activateRow: self] };
4762                        return;
4763                    }
4764                }
4765                let _: () = unsafe { msg_send![super(self), keyDown: event] };
4766            });
4767        }
4768    }
4769);
4770
4771/// The cell can wrap its decorated row in layout containers. Search only this visible
4772/// cell, not other rows; cloning the provider releases the registry borrow before app code.
4773fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4774    if let Some(provider) =
4775        CTX_MENU_FNS.with(|t| t.get(std::ptr::from_ref::<NSView>(view) as usize))
4776    {
4777        return Some((view.retain(), provider));
4778    }
4779    view.subviews()
4780        .iter()
4781        .find_map(|view| list_row_menu_provider(&view))
4782}
4783
4784/// Plain labels receive the mouse event before their row does. Resolve the nearest dynamic
4785/// owner without copying providers onto descendants (which would go stale on recycling).
4786/// `Some(None)` means an owner deliberately returned no menu; do not fall through to a parent.
4787#[expect(
4788    clippy::option_option,
4789    reason = "`None` defers to AppKit's own menu while `Some(None)` is an owner's deliberate no-menu answer"
4790)]
4791fn inherited_context_menu(
4792    view: &NSView,
4793    event: &objc2_app_kit::NSEvent,
4794) -> Option<Option<Retained<NSMenu>>> {
4795    let mut current = Some(view.retain());
4796    while let Some(view) = current {
4797        if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4798            let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4799            let items = provider(day_spec::Point::new(point.x, point.y));
4800            return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4801        }
4802        current = unsafe { view.superview() };
4803    }
4804    None
4805}
4806
4807impl DayListView {
4808    fn report_focus(&self, focused: bool) {
4809        ffi_guard::contain((), || {
4810            if let Some(target) = unsafe { self.target() }
4811                && let Some(data) = target.downcast_ref::<DayListData>()
4812            {
4813                emit(data.ivars().node, Event::FocusChanged(focused));
4814            }
4815        });
4816    }
4817}
4818
4819struct ListIvars {
4820    node: NodeId,
4821    /// Injected by `attach_list` once day-core wires the driver.
4822    source: RefCell<Option<ListSource>>,
4823    selectable: std::cell::Cell<bool>,
4824    /// Multi-select mode (docs/list.md): every change reports the FULL selected set.
4825    multi: std::cell::Cell<bool>,
4826    /// Programmatic selection in flight: don't re-emit `SelectionChanged`.
4827    suppress: std::cell::Cell<bool>,
4828    /// The row-token order this table currently displays — the baseline `permutation_moves`
4829    /// diffs a Reload against (docs/list.md: a same-set reorder animates as row moves).
4830    tokens: RefCell<Vec<u64>>,
4831    /// `RowHeight::Automatic` (docs/list.md "Row heights"): each row is as tall as Day laid
4832    /// it, through `tableView:heightOfRow:`. A uniform list never answers that selector, so
4833    /// `NSTableView` keeps its fixed-pitch fast path.
4834    automatic: bool,
4835    /// The list has section headers (docs/list.md "Sections"): AppKit group rows, which float
4836    /// at the top as their section scrolls under them. A header sizes to its content in any
4837    /// list, so a sectioned list answers `tableView:heightOfRow:` even when it is uniform.
4838    sections: bool,
4839    /// The height a header nobody has bound yet is given, like `estimate` for rows.
4840    header_estimate: std::cell::Cell<f64>,
4841    /// Each self-sizing row's height by row token, as Day last laid it. By token, not row: a
4842    /// splice or a drag moves rows without rebinding them.
4843    heights: RefCell<std::collections::HashMap<u64, f64>>,
4844    /// The row token each bound cell shows, so `RowSizeInvalidated` (which names the cell)
4845    /// finds the height it corrects.
4846    cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4847    /// The height a row nobody has bound yet is given: the last one Day measured, so a list
4848    /// of like rows scrolls without its rows jumping as they arrive.
4849    estimate: std::cell::Cell<f64>,
4850    /// A height pass is posted and not yet run (`post_row_heights` coalesces).
4851    heights_pending: std::cell::Cell<bool>,
4852}
4853
4854define_class!(
4855    #[unsafe(super(NSObject))]
4856    #[thread_kind = MainThreadOnly]
4857    #[name = "DayListData"]
4858    #[ivars = ListIvars]
4859    struct DayListData;
4860
4861    unsafe impl NSObjectProtocol for DayListData {}
4862    unsafe impl NSControlTextEditingDelegate for DayListData {}
4863
4864    impl DayListData {
4865        /// Only a self-sizing list answers `tableView:heightOfRow:`: NSTableView asks that
4866        /// of every row on each reload, and a uniform list's fixed `rowHeight` is the fast
4867        /// path. NSTableView reads this once, at `setDelegate:`, after `automatic` is set.
4868        #[unsafe(method(respondsToSelector:))]
4869        fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4870            if selector == objc2::sel!(tableView:heightOfRow:)
4871                && !self.ivars().automatic
4872                && !self.ivars().sections
4873            {
4874                false
4875            } else {
4876                unsafe { msg_send![super(self), respondsToSelector: selector] }
4877            }
4878        }
4879
4880        #[unsafe(method(listViewportChanged:))]
4881        fn list_viewport_changed(&self, notification: &NSNotification) {
4882            ffi_guard::contain((), || {
4883                let source = self.ivars().source.borrow().clone();
4884                if let Some(source) = source && let Some(report) = &source.first_visible
4885                    && let Some(object) = notification.object()
4886                    && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4887                    && let Some(document) = clip.documentView()
4888                    && let Some(table) = document.downcast_ref::<NSTableView>() {
4889                    let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4890                    report(visible.location.min((source.len)().saturating_sub(1)));
4891                }
4892            });
4893        }
4894
4895        #[unsafe(method(activateRow:))]
4896        fn activate_row(&self, table: &NSTableView) {
4897            ffi_guard::contain((), || {
4898                let row = unsafe { table.selectedRow() };
4899                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4900            });
4901        }
4902        #[unsafe(method(doubleClickRow:))]
4903        fn double_click_row(&self, table: &NSTableView) {
4904            ffi_guard::contain((), || {
4905                let row = unsafe { table.clickedRow() };
4906                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4907            });
4908        }
4909    }
4910
4911    unsafe impl NSTableViewDataSource for DayListData {
4912        #[unsafe(method(numberOfRowsInTableView:))]
4913        fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4914            // Reads the piece's snapshot only (no tree access) — safe even when called
4915            // synchronously from reloadData inside a with_tree borrow. Guarded because
4916            // `len` is a day-core closure.
4917            ffi_guard::contain(0, || {
4918                self.ivars()
4919                    .source
4920                    .borrow()
4921                    .as_ref()
4922                    .map_or(0, |s| (s.len)() as isize)
4923            })
4924        }
4925
4926        // --- drag-to-reorder (docs/list.md): NSTableView's native drag pipeline. The dragged
4927        // row rides the pasteboard as a private-typed string; `validateDrop` consults the app's
4928        // guard live (the `.gap` feedback style opens the placeholder gap only where the guard
4929        // allows), and `acceptDrop` commits through the sync seam, then animates the native move.
4930
4931        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4932        fn pasteboard_writer_for_row(
4933            &self,
4934            _tv: &NSTableView,
4935            row: isize,
4936        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4937            // (Closure body: define_class converts only the TAIL expression, so early `return`s
4938            // must not escape the method itself.)
4939            let make = || {
4940                // Only reorderable lists write drag items — no seam, no drag.
4941                let reorderable = self
4942                    .ivars()
4943                    .source
4944                    .borrow()
4945                    .as_ref()
4946                    .is_some_and(|s| s.reorder.is_some());
4947                // A group row (a section header) never lifts (docs/list.md "Sections").
4948                if !reorderable || row < 0 || self.is_header(row) {
4949                    return None;
4950                }
4951                let item = objc2_app_kit::NSPasteboardItem::new();
4952                unsafe {
4953                    item.setString_forType(
4954                        &NSString::from_str(&row.to_string()),
4955                        &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4956                    );
4957                }
4958                Some(ProtocolObject::from_retained(item))
4959            };
4960            ffi_guard::contain(None, make)
4961        }
4962
4963        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4964        fn validate_drop(
4965            &self,
4966            tv: &NSTableView,
4967            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4968            row: isize,
4969            _op: objc2_app_kit::NSTableViewDropOperation,
4970        ) -> objc2_app_kit::NSDragOperation {
4971            // Guarded: `can_move` consults the app's reorder guard closure.
4972            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4973                let Some((from, len)) = self.drag_context(tv, info) else {
4974                    return objc2_app_kit::NSDragOperation::None;
4975                };
4976                // Normalize to an above insertion point (the gap style's semantics), convert to
4977                // the post-removal target index, and ask the guard.
4978                let ins = row.clamp(0, len as isize) as usize;
4979                let to = insertion_to_target(from, ins, len);
4980                let accepted = self.can_move(from, to);
4981                if accepted < 0 {
4982                    return objc2_app_kit::NSDragOperation::None;
4983                }
4984                let accepted = (accepted as usize).min(len.saturating_sub(1));
4985                if accepted != to {
4986                    // The guard retargeted: move the gap to where the drop would actually land.
4987                    unsafe {
4988                        tv.setDropRow_dropOperation(
4989                            target_to_insertion(from, accepted) as isize,
4990                            objc2_app_kit::NSTableViewDropOperation::Above,
4991                        );
4992                    }
4993                }
4994                objc2_app_kit::NSDragOperation::Move
4995            })
4996        }
4997
4998        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4999        fn accept_drop(
5000            &self,
5001            tv: &NSTableView,
5002            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5003            row: isize,
5004            _op: objc2_app_kit::NSTableViewDropOperation,
5005        ) -> bool {
5006            // (Closure body: early `return`s must not escape the define_class method itself.)
5007            let drop = || {
5008                let Some((from, len)) = self.drag_context(tv, info) else {
5009                    return false;
5010                };
5011                let ins = row.clamp(0, len as isize) as usize;
5012                let to = insertion_to_target(from, ins, len);
5013                let accepted = self.can_move(from, to);
5014                if accepted < 0 {
5015                    return false;
5016                }
5017                let accepted = (accepted as usize).min(len.saturating_sub(1));
5018                if accepted == from {
5019                    return true; // dropped back home — nothing to commit
5020                }
5021                // Commit through the sync seam (rotates Day's snapshot, defers the app
5022                // callback), THEN animate the native move — the data source already answers in
5023                // the new order.
5024                let mv = self
5025                    .ivars()
5026                    .source
5027                    .borrow()
5028                    .as_ref()
5029                    .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
5030                let Some(mv) = mv else { return false };
5031                mv(from, accepted);
5032                // Keep the displayed-order cache in step (the commit's echo skips the Reload
5033                // that would otherwise refresh it — see `permutation_moves`).
5034                {
5035                    let mut toks = self.ivars().tokens.borrow_mut();
5036                    if from < toks.len() && accepted < toks.len() {
5037                        let t = toks.remove(from);
5038                        toks.insert(accepted, t);
5039                    }
5040                }
5041                unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
5042                if let Some(scroll) = tv.enclosingScrollView() {
5043                    post_settle_list_drop(ptr_of(&scroll));
5044                }
5045                true
5046            };
5047            // Guarded: the commit runs the seam's move closure into day-core and the app.
5048            ffi_guard::contain(false, drop)
5049        }
5050    }
5051
5052    unsafe impl NSTableViewDelegate for DayListData {
5053        /// A self-sizing row's height (docs/list.md "Row heights"): the height Day laid it at
5054        /// once it has been bound, the running estimate until then. Asked before the row's view
5055        /// exists, often from inside `reloadData` under a day-core borrow, so it reads only this
5056        /// table's own record and the source's token snapshot.
5057        #[unsafe(method(tableView:heightOfRow:))]
5058        fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
5059            ffi_guard::contain(44.0, || {
5060                let ivars = self.ivars();
5061                let header = self.is_header(row);
5062                // A uniform sectioned list: rows keep the fixed pitch, headers size themselves.
5063                if !header && !ivars.automatic {
5064                    return unsafe { tv.rowHeight() };
5065                }
5066                let token = ivars
5067                    .source
5068                    .borrow()
5069                    .as_ref()
5070                    .filter(|s| row >= 0 && (row as usize) < (s.len)())
5071                    .map(|s| (s.token_at)(row as usize));
5072                token
5073                    .and_then(|t| ivars.heights.borrow().get(&t).copied())
5074                    .unwrap_or_else(|| {
5075                        if header {
5076                            ivars.header_estimate.get()
5077                        } else {
5078                            ivars.estimate.get()
5079                        }
5080                    })
5081            })
5082        }
5083
5084        /// Section headers are AppKit group rows (docs/list.md "Sections"): drawn in the
5085        /// group style, spanning the row, and floated over their section by
5086        /// `floatsGroupRows`.
5087        #[unsafe(method(tableView:isGroupRow:))]
5088        fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
5089            ffi_guard::contain(false, || self.is_header(row))
5090        }
5091
5092        /// A header is not an item: clicks and arrow keys pass over it.
5093        #[unsafe(method(tableView:shouldSelectRow:))]
5094        fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
5095            ffi_guard::contain(true, || !self.is_header(row))
5096        }
5097
5098        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
5099        fn view_for_row(
5100            &self,
5101            tv: &NSTableView,
5102            _col: Option<&NSTableColumn>,
5103            row: isize,
5104        ) -> Option<Retained<NSView>> {
5105            // Guarded: `bind_row` builds the app's row content.
5106            ffi_guard::contain(None, || {
5107                let mtm = self.mtm();
5108                // Headers pool apart from rows, so a recycled cell keeps its kind and rebinds.
5109                let header = self.is_header(row);
5110                let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
5111                // Recycle a cell view if one is free; else make a fresh flipped container.
5112                let cell: Retained<NSView> =
5113                    unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5114                        let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
5115                        unsafe { v.setIdentifier(Some(&ident)) };
5116                        v
5117                    });
5118                // Day builds row content the first time it sees this cell, and rebinds
5119                // (slot-write) when the cell is recycled. NSTableView calls this outside
5120                // reloadData's stack, so the re-entry into with_tree is safe.
5121                let source = self.ivars().source.borrow().clone();
5122                if let Some(source) = source {
5123                    let raw = Retained::as_ptr(&cell) as RawHandle;
5124                    (source.bind_row)(row as usize, raw);
5125                    if self.ivars().automatic || header {
5126                        self.note_row_height(tv, &source, row, raw, header);
5127                    }
5128                }
5129                Some(cell)
5130            })
5131        }
5132
5133        #[unsafe(method(tableView:didRemoveRowView:forRow:))]
5134        fn did_remove_row_view(
5135            &self,
5136            _tv: &NSTableView,
5137            row_view: &objc2_app_kit::NSTableRowView,
5138            _row: isize,
5139        ) {
5140            // The row went back to the reuse pool (a reload dropping it past a shrunk source, a
5141            // scroll): clear its day element ids so it stops answering lookups, as the tree's
5142            // `outlineView:didRemoveRowView:forRow:` does. Deferred, since this fires inside
5143            // reload stacks that hold the day-core borrow, and re-checked: a cell the same
5144            // turn's reload already reused has a window again, and its fresh ids must survive.
5145            ffi_guard::contain((), || {
5146                let Some(cell) = row_view.subviews().iter().find(|sub| {
5147                    sub.identifier()
5148                        .is_some_and(|i| {
5149                            let i = i.to_string();
5150                            i == DAY_ROW_CELL || i == DAY_HEADER_CELL
5151                        })
5152                }) else {
5153                    return;
5154                };
5155                // Raw +1 pointers across the post (the closure must be Send, which Retained is
5156                // not; everything stays on the main thread). AppKit may free a removed row view.
5157                let cell = Retained::into_raw(cell) as usize;
5158                let Some(this) = (unsafe {
5159                    Retained::retain(std::ptr::from_ref::<DayListData>(self).cast_mut())
5160                }) else {
5161                    return;
5162                };
5163                let this = Retained::into_raw(this) as usize;
5164                <AppKit as Platform>::post(Box::new(move || {
5165                    // Reclaim both +1s first, so every early return balances them.
5166                    let this = unsafe { Retained::from_raw(this as *mut DayListData) };
5167                    let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
5168                    let (Some(this), Some(cell)) = (this, cell) else {
5169                        return;
5170                    };
5171                    if cell.window().is_some() {
5172                        return; // reused already: its ids are the live row's
5173                    }
5174                    let recycle = this
5175                        .ivars()
5176                        .source
5177                        .borrow()
5178                        .as_ref()
5179                        .map(|s| s.recycle.clone());
5180                    if let Some(recycle) = recycle {
5181                        recycle(Retained::as_ptr(&cell) as RawHandle);
5182                    }
5183                }));
5184            });
5185        }
5186
5187        #[unsafe(method(tableViewSelectionDidChange:))]
5188        fn selection_did_change(&self, notification: &NSNotification) {
5189            ffi_guard::contain((), || {
5190                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5191                    return;
5192                }
5193                let Some(obj) = (unsafe { notification.object() }) else {
5194                    return;
5195                };
5196                let Ok(tv) = obj.downcast::<NSTableView>() else {
5197                    return;
5198                };
5199                if self.ivars().multi.get() {
5200                    // Multi-select: report the FULL set (ascending; empty = cleared).
5201                    let idx = unsafe { tv.selectedRowIndexes() };
5202                    let mut rows = Vec::with_capacity(idx.count());
5203                    let mut i = idx.firstIndex();
5204                    while i != objc2_foundation::NSNotFound as usize {
5205                        rows.push(i as i64);
5206                        i = unsafe { idx.indexGreaterThanIndex(i) };
5207                    }
5208                    emit(self.ivars().node, Event::SelectionSet(rows));
5209                } else {
5210                    let row = unsafe { tv.selectedRow() };
5211                    if row >= 0 {
5212                        emit(self.ivars().node, Event::SelectionChanged(row as i64));
5213                    } else {
5214                        // CLEARED. `selectedRow()` answers -1, which is not a row, so there is
5215                        // nothing for `SelectionChanged` to carry and nothing for `on_select` to
5216                        // be called with — but the app still has to hear about it, or a detail
5217                        // pane goes on showing the row the user just deselected. The empty set is
5218                        // how that is said (`on_selection`, docs/list.md); reporting nothing was
5219                        // a silent contract break, since single-selection backends are documented
5220                        // as firing it with a one-element OR EMPTY set.
5221                        emit(self.ivars().node, Event::SelectionSet(Vec::new()));
5222                    }
5223                }
5224            });
5225        }
5226
5227        // --- swipe actions (docs/list.md): NSTableView's row-action pipeline. AppKit calls
5228        // this as the two-finger swipe starts, so the offer reflects the row's state at
5229        // GESTURE time; a full swipe across activates the first action (AppKit's own
5230        // full-slide behavior). The handler commits through the seam, which defers the app's
5231        // callback to the event drain.
5232        #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
5233        fn row_actions_for_row(
5234            &self,
5235            tv: &NSTableView,
5236            row: isize,
5237            edge: objc2_app_kit::NSTableRowActionEdge,
5238        ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
5239            // Guarded: `actions_at` runs the app's provider closure.
5240            ffi_guard::contain(NSArray::new(), || {
5241                let sw = self
5242                    .ivars()
5243                    .source
5244                    .borrow()
5245                    .as_ref()
5246                    .and_then(|s| s.swipe.clone());
5247                let Some(sw) = sw else {
5248                    return NSArray::new();
5249                };
5250                if row < 0 {
5251                    return NSArray::new();
5252                }
5253                // AppKit's Leading/Trailing already speak reading direction, same as ours.
5254                let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
5255                    day_spec::SwipeEdge::Leading
5256                } else {
5257                    day_spec::SwipeEdge::Trailing
5258                };
5259                let offer = (sw.actions_at)(row as usize, day_edge);
5260                let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
5261                    .iter()
5262                    .enumerate()
5263                    .map(|(i, a)| {
5264                        let style = if a.destructive {
5265                            objc2_app_kit::NSTableViewRowActionStyle::Destructive
5266                        } else {
5267                            objc2_app_kit::NSTableViewRowActionStyle::Regular
5268                        };
5269                        let perform = sw.perform.clone();
5270                        // Retained only for the swipe session: AppKit releases the actions
5271                        // (and this block) when the revealed buttons close.
5272                        let table = tv.retain();
5273                        let handler = block2::RcBlock::new(
5274                            move |_action: std::ptr::NonNull<
5275                                objc2_app_kit::NSTableViewRowAction,
5276                            >,
5277                                  row: isize| {
5278                                ffi_guard::contain((), || {
5279                                    perform(row as usize, day_edge, i);
5280                                    // A button press leaves the buttons revealed; close
5281                                    // them (a full slide already closed itself).
5282                                    unsafe { table.setRowActionsVisible(false) };
5283                                });
5284                            },
5285                        );
5286                        let action =
5287                            objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
5288                                style,
5289                                &NSString::from_str(&a.label),
5290                                &handler,
5291                            );
5292                        if let Some(t) = a.tint {
5293                            unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
5294                        }
5295                        // Glyph above the label — the Mail row-action look. The SF symbol
5296                        // resolves per OS release; an unknown name yields no image and the
5297                        // button keeps its label alone.
5298                        if let Some(sym) = a.symbol {
5299                            let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
5300                                &NSString::from_str(day_spec::sf_symbol_name(sym)),
5301                                None,
5302                            );
5303                            if let Some(img) = img {
5304                                unsafe { action.setImage(Some(&img)) };
5305                            }
5306                        }
5307                        action
5308                    })
5309                    .collect();
5310                NSArray::from_retained_slice(&actions)
5311            })
5312        }
5313    }
5314);
5315
5316impl DayListData {
5317    fn new(
5318        mtm: MainThreadMarker,
5319        node: NodeId,
5320        selectable: bool,
5321        multi: bool,
5322        automatic: bool,
5323        sections: bool,
5324    ) -> Retained<Self> {
5325        let this = Self::alloc(mtm).set_ivars(ListIvars {
5326            node,
5327            source: RefCell::new(None),
5328            selectable: std::cell::Cell::new(selectable),
5329            multi: std::cell::Cell::new(multi),
5330            suppress: std::cell::Cell::new(false),
5331            tokens: RefCell::new(Vec::new()),
5332            automatic,
5333            sections,
5334            header_estimate: std::cell::Cell::new(28.0),
5335            heights: RefCell::new(std::collections::HashMap::new()),
5336            cell_tokens: RefCell::new(std::collections::HashMap::new()),
5337            estimate: std::cell::Cell::new(44.0),
5338            heights_pending: std::cell::Cell::new(false),
5339        });
5340        unsafe { msg_send![super(this), init] }
5341    }
5342
5343    /// A self-sizing row was just bound to `cell`: record the height Day laid it at, and if
5344    /// the table drew the row at another height (the estimate, or the row's old content),
5345    /// correct it on the next turn. Not here: this runs inside `NSTableView`'s own tiling.
5346    fn note_row_height(
5347        &self,
5348        table: &NSTableView,
5349        source: &ListSource,
5350        row: isize,
5351        cell: RawHandle,
5352        header: bool,
5353    ) {
5354        let height = (source.cell_height)(cell);
5355        if height <= 0.0 || row < 0 {
5356            return;
5357        }
5358        let token = (source.token_at)(row as usize);
5359        self.ivars()
5360            .cell_tokens
5361            .borrow_mut()
5362            .insert(cell as usize, token);
5363        self.ivars().heights.borrow_mut().insert(token, height);
5364        if header {
5365            self.ivars().header_estimate.set(height);
5366        } else {
5367            self.ivars().estimate.set(height);
5368        }
5369        let drawn = unsafe { table.rectOfRow(row) }.size.height;
5370        if (drawn - height).abs() > 0.5 {
5371            self.post_row_heights(table);
5372        }
5373    }
5374
5375    /// Whether display row `row` is a section header (docs/list.md "Sections").
5376    fn is_header(&self, row: isize) -> bool {
5377        row >= 0
5378            && self
5379                .ivars()
5380                .source
5381                .borrow()
5382                .as_ref()
5383                .and_then(|s| s.is_header.clone())
5384                .is_some_and(|is_header| is_header(row as usize))
5385    }
5386
5387    /// `ListPatch::RowSizeInvalidated`: the row in `cell` was re-laid at `height`. Arrives under
5388    /// the day-core borrow, so it only records the height; the table is told after the pass.
5389    fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
5390        let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
5391        if let Some(token) = token {
5392            self.ivars().heights.borrow_mut().insert(token, height);
5393            self.post_row_heights(table);
5394        }
5395    }
5396
5397    /// Tell the table, on the next main-loop turn, about every row near the viewport whose drawn
5398    /// height differs from the one Day laid it at. Coalesced: a pass that re-lays many rows
5399    /// posts one correction.
5400    fn post_row_heights(&self, table: &NSTableView) {
5401        if self.ivars().heights_pending.replace(true) {
5402            return;
5403        }
5404        // Raw +1 pointers across the post (the closure must be Send, which Retained is not;
5405        // everything stays on the main thread).
5406        let Some(this) = (unsafe { Retained::retain(std::ptr::from_ref::<Self>(self).cast_mut()) })
5407        else {
5408            return;
5409        };
5410        let this = Retained::into_raw(this) as usize;
5411        let table = Retained::into_raw(table.retain()) as usize;
5412        <AppKit as Platform>::post(Box::new(move || {
5413            // Reclaim both +1s first, so every early return balances them.
5414            let this = unsafe { Retained::from_raw(this as *mut DayListData) };
5415            let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
5416            let (Some(this), Some(table)) = (this, table) else {
5417                return;
5418            };
5419            this.ivars().heights_pending.set(false);
5420            ffi_guard::contain((), || this.apply_row_heights(&table));
5421        }));
5422    }
5423
5424    fn apply_row_heights(&self, table: &NSTableView) {
5425        let Some(source) = self.ivars().source.borrow().clone() else {
5426            return;
5427        };
5428        let count = unsafe { table.numberOfRows() }.max(0) as usize;
5429        let shown = unsafe { table.rowsInRect(table.visibleRect()) };
5430        // The viewport and the rows AppKit prepares around it.
5431        let first = shown.location.saturating_sub(8);
5432        let last = (shown.location + shown.length + 8)
5433            .min(count)
5434            .min((source.len)());
5435        let changed = objc2_foundation::NSMutableIndexSet::new();
5436        {
5437            let heights = self.ivars().heights.borrow();
5438            for row in first..last {
5439                if let Some(&height) = heights.get(&(source.token_at)(row)) {
5440                    let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
5441                    if (drawn - height).abs() > 0.5 {
5442                        unsafe { changed.addIndex(row) };
5443                    }
5444                }
5445            }
5446        }
5447        if changed.count() == 0 {
5448            return;
5449        }
5450        // Unanimated: the row takes its content's height, it does not grow into it.
5451        NSAnimationContext::beginGrouping();
5452        NSAnimationContext::currentContext().setDuration(0.0);
5453        unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
5454        NSAnimationContext::endGrouping();
5455    }
5456
5457    /// If this Reload is the same row set in a new order, the incremental `moveRowAtIndex`
5458    /// steps (each `(from, to)` interpreted against the already-moved rows, `NSTableView`'s
5459    /// semantics) that transform the displayed order into the new one — and `None` for
5460    /// anything else (insert/remove/content change/no change), which reloads flat. Always
5461    /// refreshes the displayed-order cache.
5462    ///
5463    /// Every row that changes position must have a REALIZED row view (`table`): moving a
5464    /// viewless row (its old position sat outside the viewport, so it was never bound)
5465    /// animates nothing and leaves the row unbound at its new position — its content, and any
5466    /// element ids inside it, would simply not exist. Such a reorder returns `None` and
5467    /// reloads flat, which realizes and binds the row at its new position.
5468    fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
5469        let source = self.ivars().source.borrow();
5470        let source = source.as_ref()?;
5471        let n = (source.len)();
5472        let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
5473        let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
5474        if old.len() != n || n == 0 || old == new {
5475            return None;
5476        }
5477        let (mut so, mut sn) = (old.clone(), new.clone());
5478        so.sort_unstable();
5479        sn.sort_unstable();
5480        if so != sn {
5481            return None;
5482        }
5483        for i in 0..n {
5484            if old[i] != new[i]
5485                && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
5486            {
5487                return None;
5488            }
5489        }
5490        let mut work = old;
5491        let mut moves = Vec::new();
5492        for i in 0..n {
5493            if work[i] == new[i] {
5494                continue;
5495            }
5496            let j = (i + 1..n).find(|&j| work[j] == new[i])?;
5497            let t = work.remove(j);
5498            work.insert(i, t);
5499            moves.push((j, i));
5500        }
5501        Some(moves)
5502    }
5503
5504    /// The dragged row + current row count for an in-flight LOCAL reorder drag — `None` when the
5505    /// drag came from anywhere but this table (day never accepts foreign drops into a list) or
5506    /// the pasteboard doesn't carry the day row type.
5507    fn drag_context(
5508        &self,
5509        tv: &NSTableView,
5510        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5511    ) -> Option<(usize, usize)> {
5512        let src = unsafe { info.draggingSource() }?;
5513        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
5514            != std::ptr::from_ref::<NSTableView>(tv).cast::<std::ffi::c_void>()
5515        {
5516            return None;
5517        }
5518        let pb = unsafe { info.draggingPasteboard() };
5519        let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
5520            .to_string()
5521            .parse::<usize>()
5522            .ok()?;
5523        let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
5524        (from < len).then_some((from, len))
5525    }
5526
5527    /// The guard's verdict for `from -> to` (accepted index, or -1), through the sync seam.
5528    fn can_move(&self, from: usize, to: usize) -> i64 {
5529        self.ivars()
5530            .source
5531            .borrow()
5532            .as_ref()
5533            .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
5534            .unwrap_or(-1)
5535    }
5536}
5537
5538/// The reuse identifiers of a list's row cells and its section-header cells.
5539const DAY_ROW_CELL: &str = "day.cell";
5540const DAY_HEADER_CELL: &str = "day.header";
5541
5542/// The private pasteboard type carrying a dragged day list row's index (local reorder only).
5543const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
5544
5545/// An `NSTableView` drop lands at an INSERTION point (`row` with `.Above` semantics, 0..=len);
5546/// day's seam speaks post-removal target indices. Dropping `from` at insertion `ins`:
5547fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
5548    let to = if ins > from { ins - 1 } else { ins };
5549    to.min(len.saturating_sub(1))
5550}
5551
5552/// The inverse, for retargeting the drop gap: where the gap sits for a post-removal target.
5553fn target_to_insertion(from: usize, to: usize) -> usize {
5554    if to > from { to + 1 } else { to }
5555}
5556
5557/// A realized LIST's scroll view ptr → (table, data source) for `attach_list` / update / measure.
5558type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
5559
5560/// Clone a list's (table, data) out of `LIST_STATE` under a SHORT borrow. Every caller then
5561/// talks to AppKit with the map free: table calls that look innocuous (`endUpdates`, a scroll's
5562/// tiling, `viewAtColumn:row:makeIfNecessary:`, even `layoutSubtreeIfNeeded`) can synchronously
5563/// re-enter `viewForRow` → `bind_row` → a flush that tears nodes down — and `release` must be
5564/// able to take its own borrow at that depth. Holding the map across any of them was the
5565/// "`RefCell` already borrowed" contained panic every list walkthrough used to log, 24 a run.
5566fn list_entry(key: usize) -> Option<ListEntry> {
5567    LIST_STATE.with(|m| m.borrow().get(&key).cloned())
5568}
5569
5570// ---------------------------------------------------------------------------
5571// DayTreeData — NSOutlineView data-source + delegate for the hierarchical tree (docs/tree.md)
5572// ---------------------------------------------------------------------------
5573
5574struct TreeIvars {
5575    node: NodeId,
5576    /// Injected by `attach_tree` once day-core wires the driver.
5577    source: RefCell<Option<TreeSource>>,
5578    selectable: std::cell::Cell<bool>,
5579    /// Programmatic selection/disclosure in flight: don't re-emit the event (echo rule).
5580    suppress: std::cell::Cell<bool>,
5581    /// token → its interned `NSNumber`. `NSOutlineView` tracks items (selection, expansion,
5582    /// rowForItem) by object identity/equality, so every query for a token must answer with
5583    /// the same object — which is also what preserves expansion across reloadData.
5584    items: RefCell<HashMap<u64, Retained<NSNumber>>>,
5585}
5586
5587define_class!(
5588    #[unsafe(super(NSObject))]
5589    #[thread_kind = MainThreadOnly]
5590    #[name = "DayTreeData"]
5591    #[ivars = TreeIvars]
5592    struct DayTreeData;
5593
5594    unsafe impl NSObjectProtocol for DayTreeData {}
5595
5596    unsafe impl NSOutlineViewDataSource for DayTreeData {
5597        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
5598        fn number_of_children(
5599            &self,
5600            _ov: &objc2_app_kit::NSOutlineView,
5601            item: Option<&objc2::runtime::AnyObject>,
5602        ) -> isize {
5603            // Reads the piece's snapshot only (no tree access) — safe even when called
5604            // synchronously from reloadData inside a with_tree borrow. Guarded because
5605            // the closures are day-core's.
5606            ffi_guard::contain(0, || {
5607                let parent = item.and_then(Self::token_of_item);
5608                if item.is_some() && parent.is_none() {
5609                    return 0; // not one of ours (stale query racing a reload)
5610                }
5611                self.ivars()
5612                    .source
5613                    .borrow()
5614                    .as_ref()
5615                    .map_or(0, |s| (s.children_len)(parent) as isize)
5616            })
5617        }
5618
5619        #[unsafe(method_id(outlineView:child:ofItem:))]
5620        fn child_of_item(
5621            &self,
5622            _ov: &objc2_app_kit::NSOutlineView,
5623            index: isize,
5624            item: Option<&objc2::runtime::AnyObject>,
5625        ) -> Retained<objc2::runtime::AnyObject> {
5626            // AppKit only asks for children it was told exist, but a stale query racing a
5627            // reload must degrade (token 0, an unmatched identity) rather than panic — an
5628            // unwind here crosses an ObjC frame and aborts.
5629            let token = ffi_guard::contain(0, || {
5630                let parent = item.and_then(Self::token_of_item);
5631                self.ivars()
5632                    .source
5633                    .borrow()
5634                    .as_ref()
5635                    .map_or(0, |s| (s.child_token)(parent, index.max(0) as usize))
5636            });
5637            let ns = self.intern(token);
5638            unsafe { objc2::rc::Retained::cast_unchecked(ns) }
5639        }
5640
5641        #[unsafe(method(outlineView:isItemExpandable:))]
5642        fn is_expandable(
5643            &self,
5644            _ov: &objc2_app_kit::NSOutlineView,
5645            item: &objc2::runtime::AnyObject,
5646        ) -> bool {
5647            ffi_guard::contain(false, || {
5648                let Some(token) = Self::token_of_item(item) else {
5649                    return false;
5650                };
5651                self.ivars()
5652                    .source
5653                    .borrow()
5654                    .as_ref()
5655                    .is_some_and(|s| (s.expandable)(token))
5656            })
5657        }
5658
5659        // --- drag-to-move (docs/tree.md): the dragged node rides the pasteboard as a
5660        // private-typed token string; `validateDrop` consults the guard live (forbidden
5661        // cursor where it denies, including ONTO-a-row drops via childIndex -1), and
5662        // `acceptDrop` commits through the sync seam — the app's own data write reloads.
5663
5664        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
5665        fn pasteboard_writer_for_item(
5666            &self,
5667            _ov: &objc2_app_kit::NSOutlineView,
5668            item: &objc2::runtime::AnyObject,
5669        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
5670            let make = || {
5671                let movable = self
5672                    .ivars()
5673                    .source
5674                    .borrow()
5675                    .as_ref()
5676                    .is_some_and(|s| s.moves.is_some());
5677                let token = Self::token_of_item(item)?;
5678                if !movable {
5679                    return None;
5680                }
5681                let pbitem = objc2_app_kit::NSPasteboardItem::new();
5682                unsafe {
5683                    pbitem.setString_forType(
5684                        &NSString::from_str(&token.to_string()),
5685                        &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
5686                    );
5687                }
5688                Some(ProtocolObject::from_retained(pbitem))
5689            };
5690            ffi_guard::contain(None, make)
5691        }
5692
5693        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
5694        fn validate_drop(
5695            &self,
5696            ov: &objc2_app_kit::NSOutlineView,
5697            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5698            item: Option<&objc2::runtime::AnyObject>,
5699            child_index: isize,
5700        ) -> objc2_app_kit::NSDragOperation {
5701            ffi_guard::contain(
5702                objc2_app_kit::NSDragOperation::None,
5703                || match Self::drop_proposal(ov, info, item, child_index) {
5704                    Some((token, parent, index)) if self.can_move(token, parent, index) => {
5705                        objc2_app_kit::NSDragOperation::Move
5706                    }
5707                    _ => objc2_app_kit::NSDragOperation::None,
5708                },
5709            )
5710        }
5711
5712        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
5713        fn accept_drop(
5714            &self,
5715            ov: &objc2_app_kit::NSOutlineView,
5716            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5717            item: Option<&objc2::runtime::AnyObject>,
5718            child_index: isize,
5719        ) -> bool {
5720            let drop = || {
5721                let Some((token, parent, index)) = Self::drop_proposal(ov, info, item, child_index)
5722                else {
5723                    return false;
5724                };
5725                if !self.can_move(token, parent, index) {
5726                    return false;
5727                }
5728                // Commit through the sync seam: defers the app's `on_move`; the app's own
5729                // data write drives the Reload (no native row animation on this path).
5730                let mv = self
5731                    .ivars()
5732                    .source
5733                    .borrow()
5734                    .as_ref()
5735                    .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5736                let Some(mv) = mv else { return false };
5737                mv(token, parent, index);
5738                true
5739            };
5740            ffi_guard::contain(false, drop)
5741        }
5742    }
5743
5744    unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5745
5746    unsafe impl NSOutlineViewDelegate for DayTreeData {
5747        #[unsafe(method(outlineView:isGroupItem:))]
5748        fn is_group_item(
5749            &self,
5750            _ov: &objc2_app_kit::NSOutlineView,
5751            item: &objc2::runtime::AnyObject,
5752        ) -> bool {
5753            Self::token_of_item(item).is_some_and(|t| {
5754                self.ivars()
5755                    .source
5756                    .borrow()
5757                    .as_ref()
5758                    .is_some_and(|s| (s.section_header)(t))
5759            })
5760        }
5761        #[unsafe(method(outlineView:shouldSelectItem:))]
5762        fn should_select_item(
5763            &self,
5764            _ov: &objc2_app_kit::NSOutlineView,
5765            item: &objc2::runtime::AnyObject,
5766        ) -> bool {
5767            Self::token_of_item(item).is_some_and(|t| {
5768                self.ivars()
5769                    .source
5770                    .borrow()
5771                    .as_ref()
5772                    .is_some_and(|s| !(s.section_header)(t))
5773            })
5774        }
5775
5776        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5777        fn view_for_item(
5778            &self,
5779            ov: &objc2_app_kit::NSOutlineView,
5780            _col: Option<&NSTableColumn>,
5781            item: &objc2::runtime::AnyObject,
5782        ) -> Option<Retained<NSView>> {
5783            // Guarded: `bind_row` builds the app's row content.
5784            ffi_guard::contain(None, || {
5785                let mtm = self.mtm();
5786                let token = Self::token_of_item(item)?;
5787                let ident = NSString::from_str("day.tree.cell");
5788                // Recycle a cell view if one is free; else make a fresh flipped container
5789                // (DayTreeCell re-lays its Day row at its own width — indentation makes
5790                // every tree cell's width per-row).
5791                let cell: Retained<NSView> =
5792                    unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5793                        let v: Retained<NSView> =
5794                            Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5795                        unsafe { v.setIdentifier(Some(&ident)) };
5796                        v
5797                    });
5798                if let Some(source) = self.ivars().source.borrow().as_ref() {
5799                    let raw = Retained::as_ptr(&cell) as RawHandle;
5800                    if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5801                        unsafe {
5802                            cell.setTextField(None);
5803                        }
5804                    }
5805                    (source.bind_row)(token, raw);
5806                    // Associate the actual Day label with NSTableCellView so AppKit can
5807                    // apply group typography and source-list background styles normally.
5808                    if (source.section_header)(token) {
5809                        fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5810                            for child in &unsafe { view.subviews() } {
5811                                if let Ok(label) = child.clone().downcast::<NSTextField>() {
5812                                    return Some(label);
5813                                }
5814                                if let Some(label) = label_in(&child) {
5815                                    return Some(label);
5816                                }
5817                            }
5818                            None
5819                        }
5820                        if let Some(label) = label_in(&cell) {
5821                            let cell = cell.downcast_ref::<DayTreeCell>()?;
5822                            unsafe {
5823                                cell.setTextField(Some(&label));
5824                            }
5825                        }
5826                    }
5827                }
5828                Some(cell)
5829            })
5830        }
5831
5832        #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5833        fn type_select_string(
5834            &self,
5835            _ov: &objc2_app_kit::NSOutlineView,
5836            _col: Option<&NSTableColumn>,
5837            item: &objc2::runtime::AnyObject,
5838        ) -> Option<Retained<NSString>> {
5839            ffi_guard::contain(None, || {
5840                let token = Self::token_of_item(item)?;
5841                let text = self
5842                    .ivars()
5843                    .source
5844                    .borrow()
5845                    .as_ref()
5846                    .map_or_default(|s| (s.type_select_text)(token));
5847                // Empty = this row doesn't participate in type-select.
5848                (!text.is_empty()).then(|| NSString::from_str(&text))
5849            })
5850        }
5851
5852        #[unsafe(method_id(outlineView:rowViewForItem:))]
5853        fn row_view_for_item(
5854            &self,
5855            ov: &objc2_app_kit::NSOutlineView,
5856            _item: &objc2::runtime::AnyObject,
5857        ) -> Retained<objc2_app_kit::NSTableRowView> {
5858            if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5859                // AppKit owns source-list group backgrounds, floating headers and selection.
5860                unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5861            } else {
5862                // The rounded-selection row (see DayTreeRowView).
5863                let rv: Retained<DayTreeRowView> =
5864                    unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5865                Retained::into_super(rv)
5866            }
5867        }
5868
5869        #[unsafe(method(outlineViewSelectionDidChange:))]
5870        fn selection_did_change(&self, notification: &NSNotification) {
5871            ffi_guard::contain((), || {
5872                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5873                    return;
5874                }
5875                let Some(obj) = (unsafe { notification.object() }) else {
5876                    return;
5877                };
5878                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5879                    return;
5880                };
5881                // Always the FULL token set (docs/tree.md): a tree cannot speak row indices.
5882                let idx = unsafe { ov.selectedRowIndexes() };
5883                let mut tokens = Vec::with_capacity(idx.count());
5884                let mut i = idx.firstIndex();
5885                while i != objc2_foundation::NSNotFound as usize {
5886                    if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5887                        && let Some(tok) = Self::token_of_item(&item)
5888                    {
5889                        tokens.push(tok);
5890                    }
5891                    i = unsafe { idx.indexGreaterThanIndex(i) };
5892                }
5893                emit(self.ivars().node, Event::TreeSelection(tokens));
5894            });
5895        }
5896
5897        #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5898        fn did_remove_row_view(
5899            &self,
5900            ov: &objc2_app_kit::NSOutlineView,
5901            row_view: &objc2_app_kit::NSTableRowView,
5902            _row: isize,
5903        ) {
5904            // The row went back to the reuse pool (a collapse, a reload dropping it): clear
5905            // its day element ids so it stops answering `find_by_id`. DEFERRED — this fires
5906            // inside collapse/reload stacks that hold the day-core borrow — and re-checked:
5907            // a cell already reused by the same turn's reload has a window again, and its
5908            // fresh ids must survive.
5909            ffi_guard::contain((), || {
5910                let mut cell_ptr: Option<usize> = None;
5911                for sub in &row_view.subviews() {
5912                    let is_cell = sub
5913                        .identifier()
5914                        .is_some_and(|i| i.to_string() == "day.tree.cell");
5915                    if is_cell {
5916                        cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5917                    }
5918                }
5919                let Some(cell) = cell_ptr else { return };
5920                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5921                    return;
5922                };
5923                let key = Retained::as_ptr(&scroll) as usize;
5924                // Carry a RETAIN across the post as a raw +1 pointer (the boxed closure must
5925                // be Send, which Retained is not; we stay on the main thread throughout).
5926                // AppKit is free to dealloc removed row views — a bare pointer died here once.
5927                let retained =
5928                    unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5929                        as usize;
5930                <AppKit as Platform>::post(Box::new(move || {
5931                    // Reclaim the +1 first, unconditionally — every early return below must
5932                    // still balance the retain.
5933                    let cell_view: Retained<NSView> =
5934                        match unsafe { Retained::from_raw(retained as *mut NSView) } {
5935                            Some(v) => v,
5936                            None => return,
5937                        };
5938                    let recycle = tree_entry(key).and_then(|(_, data)| {
5939                        data.ivars()
5940                            .source
5941                            .borrow()
5942                            .as_ref()
5943                            .map(|s| s.recycle.clone())
5944                    });
5945                    let Some(recycle) = recycle else { return };
5946                    if cell_view.window().is_some() {
5947                        return; // reused already — its ids are the live row's
5948                    }
5949                    recycle(cell as RawHandle);
5950                }));
5951            });
5952        }
5953
5954        #[unsafe(method(outlineViewItemDidExpand:))]
5955        fn item_did_expand(&self, notification: &NSNotification) {
5956            self.report_disclosure(notification, true);
5957        }
5958
5959        #[unsafe(method(outlineViewItemDidCollapse:))]
5960        fn item_did_collapse(&self, notification: &NSNotification) {
5961            self.report_disclosure(notification, false);
5962        }
5963    }
5964);
5965
5966impl DayTreeData {
5967    fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5968        let this = Self::alloc(mtm).set_ivars(TreeIvars {
5969            node,
5970            source: RefCell::new(None),
5971            selectable: std::cell::Cell::new(selectable),
5972            suppress: std::cell::Cell::new(false),
5973            items: RefCell::new(HashMap::new()),
5974        });
5975        unsafe { msg_send![super(this), init] }
5976    }
5977
5978    /// The same `NSNumber` for a token, every time — `NSOutlineView`'s item identity.
5979    fn intern(&self, token: u64) -> Retained<NSNumber> {
5980        self.ivars()
5981            .items
5982            .borrow_mut()
5983            .entry(token)
5984            .or_insert_with(|| NSNumber::new_u64(token))
5985            .clone()
5986    }
5987
5988    fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5989        item.downcast_ref::<NSNumber>()
5990            .map(objc2_foundation::NSNumber::as_u64)
5991    }
5992
5993    /// A native disclosure (user click, keyboard left/right) → `Event::TreeExpanded`.
5994    /// Programmatic `TreePatch::Expand` applications are suppressed (the echo rule).
5995    fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5996        ffi_guard::contain((), || {
5997            if self.ivars().suppress.get() {
5998                return;
5999            }
6000            let token = unsafe { notification.userInfo() }
6001                .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
6002                .and_then(|item| Self::token_of_item(&item));
6003            if let Some(token) = token {
6004                emit(self.ivars().node, Event::TreeExpanded { token, expanded });
6005            }
6006        });
6007    }
6008
6009    /// The full drop proposal — `(dragged token, parent token, index)` — for a LOCAL drag
6010    /// from this outline; `None` for a foreign drag or an unparseable one. `index: None`
6011    /// means "ONTO the parent" (`NSOutlineView`'s childIndex -1, `NSOutlineViewDropOnItemIndex`).
6012    fn drop_proposal(
6013        ov: &objc2_app_kit::NSOutlineView,
6014        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
6015        item: Option<&objc2::runtime::AnyObject>,
6016        child_index: isize,
6017    ) -> Option<(u64, Option<u64>, Option<usize>)> {
6018        let src = unsafe { info.draggingSource() }?;
6019        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
6020            != std::ptr::from_ref::<objc2_app_kit::NSOutlineView>(ov).cast::<std::ffi::c_void>()
6021        {
6022            return None;
6023        }
6024        let pb = unsafe { info.draggingPasteboard() };
6025        let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
6026            .to_string()
6027            .parse::<u64>()
6028            .ok()?;
6029        let parent = match item {
6030            Some(i) => Some(Self::token_of_item(i)?), // a non-token item is not ours
6031            None => None,
6032        };
6033        let index = (child_index >= 0).then_some(child_index as usize);
6034        Some((token, parent, index))
6035    }
6036
6037    /// The guard's live verdict through the sync seam.
6038    fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
6039        self.ivars()
6040            .source
6041            .borrow()
6042            .as_ref()
6043            .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
6044            .is_some_and(|v| v == MoveVerdict::Allow)
6045    }
6046}
6047
6048// DayOutlineView — an NSOutlineView that PINS its width to its clip on every layout pass.
6049// A table sizes itself from its COLUMNS, and the autoresizing mask only tracks deltas, so
6050// any early pass at a different pane width leaves a permanent offset (a 233pt table in a
6051// 220pt pane, whose selection pill then clips mid-corner). Enforcing it in `layout` — not
6052// in occasional deferred posts — closes every window where a stale width could draw.
6053define_class!(
6054    #[unsafe(super(objc2_app_kit::NSOutlineView))]
6055    #[thread_kind = MainThreadOnly]
6056    #[name = "DayOutlineView"]
6057    struct DayOutlineView;
6058
6059    impl DayOutlineView {
6060        #[unsafe(method(layout))]
6061        fn layout(&self) {
6062            sync_tree_width(self);
6063            let _: () = unsafe { msg_send![super(self), layout] };
6064        }
6065
6066        /// A summon-time ROW context menu (docs/menus.md, docs/tree.md): right-click asks
6067        /// the tree's `row_menu` provider for the row under the pointer.
6068        #[unsafe(method_id(menuForEvent:))]
6069        fn menu_for_event(
6070            &self,
6071            event: &objc2_app_kit::NSEvent,
6072        ) -> Option<Retained<NSMenu>> {
6073            ffi_guard::contain(None, || {
6074                let scroll = unsafe { self.enclosingScrollView() }?;
6075                let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
6076                let row_menu = data
6077                    .ivars()
6078                    .source
6079                    .borrow()
6080                    .as_ref()
6081                    .and_then(|s| s.row_menu.clone())?;
6082                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
6083                let row = unsafe { self.rowAtPoint(p) };
6084                if row < 0 {
6085                    return None;
6086                }
6087                let token =
6088                    unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
6089                let items = row_menu(token);
6090                if items.is_empty() {
6091                    return None;
6092                }
6093                Some(build_ns_menu(self.mtm(), "", &items))
6094            })
6095        }
6096    }
6097);
6098
6099// DayTreeRowView — a tree row with the MODERN selection: a rounded pill, inset from the
6100// pane's edges, in the system's semantic selection colors (accent when the tree has focus,
6101// the quiet gray otherwise). Drawn by hand rather than through `NSTableViewStyle::Inset`,
6102// whose machinery pads the table wider than its clip and fights day's fixed-frame layout —
6103// and a hand-drawn plain color also captures correctly offscreen, where materials go black
6104// (docs/navigation.md's sidebar-screenshot rule).
6105define_class!(
6106    #[unsafe(super(objc2_app_kit::NSTableRowView))]
6107    #[thread_kind = MainThreadOnly]
6108    #[name = "DayTreeRowView"]
6109    struct DayTreeRowView;
6110
6111    impl DayTreeRowView {
6112        #[unsafe(method(drawSelectionInRect:))]
6113        fn draw_selection_in_rect(&self, _dirty: NSRect) {
6114            if !unsafe { self.isSelected() } {
6115                return;
6116            }
6117            let color = if unsafe { self.isEmphasized() } {
6118                unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
6119            } else {
6120                unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
6121            };
6122            let b = self.bounds();
6123            let pill = NSRect::new(
6124                NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
6125                NSSize::new(
6126                    (b.size.width - 10.0).max(0.0),
6127                    (b.size.height - 2.0).max(0.0),
6128                ),
6129            );
6130            unsafe {
6131                color.setFill();
6132                objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
6133                    pill, 5.0, 5.0,
6134                )
6135                .fill();
6136            }
6137        }
6138    }
6139);
6140
6141// DayTreeCell — a tree row's flipped cell container. NSOutlineView frames it at the row's
6142// INDENTED position, so its width is per-row; every native layout pass re-lays the Day row
6143// content inside it at that width through the seam's `layout_cell`.
6144define_class!(
6145    #[unsafe(super(objc2_app_kit::NSTableCellView))]
6146    #[thread_kind = MainThreadOnly]
6147    #[name = "DayTreeCell"]
6148    struct DayTreeCell;
6149
6150    impl DayTreeCell {
6151        #[unsafe(method(isFlipped))]
6152        fn is_flipped(&self) -> bool {
6153            true
6154        }
6155
6156        #[unsafe(method(layout))]
6157        fn layout(&self) {
6158            let _: () = unsafe { msg_send![super(self), layout] };
6159            ffi_guard::contain((), || {
6160                let width = self.bounds().size.width;
6161                if width <= 0.0 {
6162                    return;
6163                }
6164                // This cell's tree: walk up to the outline, then to its scroll host, which
6165                // keys TREE_STATE. (The cell may be in the reuse pool — no outline — or the
6166                // tree may be mid-teardown; both just skip.)
6167                let mut cur = unsafe { self.superview() };
6168                let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
6169                while let Some(v) = cur {
6170                    cur = unsafe { v.superview() };
6171                    if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
6172                        outline = Some(ov);
6173                        break;
6174                    }
6175                }
6176                let Some(ov) = outline else { return };
6177                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
6178                    return;
6179                };
6180                let f = tree_entry(Retained::as_ptr(&scroll) as usize)
6181                    .and_then(|(_, data)| {
6182                        data.ivars()
6183                            .source
6184                            .borrow()
6185                            .as_ref()
6186                            .map(|s| s.layout_cell_size.clone())
6187                    });
6188                if let Some(f) = f {
6189                    f(std::ptr::from_ref::<Self>(self) as RawHandle, Size::new(width, self.bounds().size.height));
6190                }
6191            });
6192        }
6193    }
6194);
6195
6196impl DayTreeCell {
6197    fn new(mtm: MainThreadMarker) -> Retained<Self> {
6198        unsafe { msg_send![Self::alloc(mtm), init] }
6199    }
6200}
6201
6202/// The private pasteboard type carrying a dragged day tree node's token (local moves only).
6203const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
6204
6205/// A realized TREE's scroll view ptr → (outline, data source).
6206type TreeEntry = (
6207    Retained<objc2_app_kit::NSOutlineView>,
6208    Retained<DayTreeData>,
6209);
6210
6211/// Clone a tree's (outline, data) out of `TREE_STATE` under a SHORT borrow — the same
6212/// re-entrancy rule as `list_entry` (its comment has the war story).
6213fn tree_entry(key: usize) -> Option<TreeEntry> {
6214    TREE_STATE.with(|m| m.borrow().get(&key).cloned())
6215}
6216
6217/// Keep the outline exactly as wide as its clip — `DayOutlineView` calls this on every layout
6218/// pass (its comment has the why). The list never noticed the width drift because it lays
6219/// row content at the HOST's width; tree rows lay out at the CELL's, which exposes it.
6220fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
6221    let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
6222        return;
6223    };
6224    let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
6225    let f = outline.frame();
6226    if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
6227        unsafe {
6228            outline.setFrameSize(NSSize::new(clip_w, f.size.height));
6229            outline.sizeLastColumnToFit();
6230        }
6231    }
6232}
6233
6234/// Realize the tree's visible rows on the next main-loop turn, outside any borrow — the
6235/// tree twin of `post_realize_visible_rows` (its comment explains the occluded-window trap).
6236fn post_realize_visible_tree_rows(key: usize) {
6237    <AppKit as Platform>::post(Box::new(move || {
6238        if let Some((outline, _)) = tree_entry(key) {
6239            let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
6240            for row in range.location..range.location + range.length {
6241                let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
6242            }
6243        }
6244        day_core::pump_events();
6245    }));
6246}
6247
6248/// A realized `NAV_MENU`'s native outline view paired with its data-source object.
6249type NavMenuEntry = (
6250    Retained<objc2_app_kit::NSOutlineView>,
6251    Retained<DayNavMenuData>,
6252);
6253
6254fn ns_rect(r: day_spec::Rect) -> NSRect {
6255    NSRect::new(
6256        NSPoint::new(r.origin.x, r.origin.y),
6257        NSSize::new(r.size.width, r.size.height),
6258    )
6259}
6260
6261fn draw_op(op: &DrawOp) {
6262    unsafe {
6263        match op {
6264            // One path for the whole batch, then one fill or stroke: the template is appended
6265            // once per position, so the rasterizer is entered once however many copies there are
6266            // (docs/canvas.md "Stamping"). A gradient resolves against the batch's own bounds,
6267            // which is what makes a stamped scatter shade across the group rather than repeating
6268            // the ramp inside every dot.
6269            DrawOp::Stamp(st) => {
6270                let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
6271                for p in &st.at {
6272                    if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
6273                        unsafe { batch.appendBezierPath(&copy) };
6274                    }
6275                }
6276                let color = match &st.paint {
6277                    day_spec::Paint::Solid(c) => *c,
6278                    // A gradient over a stamped batch clips to the whole batch path; the solid
6279                    // fallback below keeps the marks visible on a backend path that cannot.
6280                    _ => day_spec::Color::WHITE,
6281                };
6282                match &st.stroke {
6283                    None => {
6284                        nscolor(color).setFill();
6285                        unsafe { batch.fill() };
6286                    }
6287                    Some(style) => {
6288                        nscolor(color).setStroke();
6289                        apply_stroke_style(&batch, style);
6290                        unsafe { batch.stroke() };
6291                    }
6292                }
6293            }
6294            DrawOp::Fill(shape, paint) => match paint {
6295                day_spec::Paint::Solid(color) => {
6296                    nscolor(*color).setFill();
6297                    if let Some(p) = bezier(shape) {
6298                        p.fill();
6299                    }
6300                }
6301                day_spec::Paint::Linear(g) => {
6302                    // Native linear gradient: clip to the shape's path, then NSGradient along
6303                    // the line resolved from the gradient's unit points in the shape's bounds.
6304                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
6305                        let b = shape.bounds();
6306                        let (s, e) = (g.start.resolve(b), g.end.resolve(b));
6307                        NSGraphicsContext::saveGraphicsState_class();
6308                        p.addClip();
6309                        grad.drawFromPoint_toPoint_options(
6310                            NSPoint::new(s.x, s.y),
6311                            NSPoint::new(e.x, e.y),
6312                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6313                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
6314                        );
6315                        NSGraphicsContext::restoreGraphicsState_class();
6316                    }
6317                }
6318                day_spec::Paint::Radial(g) => {
6319                    // Native radial gradient: clip to the path, map unit space onto the bounds
6320                    // (elliptical in non-square bounds), draw circular in unit coordinates.
6321                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
6322                        let b = shape.bounds();
6323                        NSGraphicsContext::saveGraphicsState_class();
6324                        p.addClip();
6325                        concat_unit_to_bounds(b);
6326                        let c = NSPoint::new(g.center.x, g.center.y);
6327                        grad.drawFromCenter_radius_toCenter_radius_options(
6328                            c,
6329                            0.0,
6330                            c,
6331                            g.radius,
6332                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6333                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
6334                        );
6335                        NSGraphicsContext::restoreGraphicsState_class();
6336                    }
6337                }
6338            },
6339            DrawOp::Stroke(shape, paint, style) => {
6340                if let Some(p) = bezier(shape) {
6341                    apply_stroke_style(&p, style);
6342                    if let day_spec::Paint::Solid(color) = paint {
6343                        nscolor(*color).setStroke();
6344                        p.stroke();
6345                    } else {
6346                        // No gradient-stroke primitive here either: turn the stroke into the
6347                        // region it covers and draw the gradient through that clip.
6348                        // No gradient-stroke primitive: convert the stroke into the REGION it
6349                        // covers (CoreGraphics can, and NSGraphicsContext hands us its context),
6350                        // clip to that, then draw the gradient through it.
6351                        let Some(ctx) = NSGraphicsContext::currentContext() else {
6352                            return;
6353                        };
6354                        let cg = ctx.CGContext();
6355                        NSGraphicsContext::saveGraphicsState_class();
6356                        objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
6357                        objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(&cg));
6358                        objc2_core_graphics::CGContext::clip(Some(&cg));
6359                        draw_gradient_in(paint, shape.bounds());
6360                        NSGraphicsContext::restoreGraphicsState_class();
6361                    }
6362                }
6363            }
6364            DrawOp::Clip(shape) => {
6365                // `addClip` intersects with the current clip and honors the path's winding rule.
6366                if let Some(p) = bezier(shape) {
6367                    p.addClip();
6368                }
6369            }
6370            DrawOp::Text {
6371                text,
6372                at,
6373                size,
6374                color,
6375                anchor,
6376                font,
6377            } => {
6378                let font = canvas_nsfont(*size, font);
6379                let attrs = canvas_text_attrs(&font, *color);
6380                let ns = NSString::from_str(text);
6381                let mut origin = NSPoint::new(at.x, at.y);
6382                // `drawAtPoint:` takes the top-leading corner of the line box, so any other
6383                // anchor is an offset from it. The size comes from the attributes the draw is
6384                // about to use, which is why the alignment belongs here and not in the app: the
6385                // caller would have to ask for these same metrics through `measure_text` first.
6386                if *anchor != day_spec::TextAnchor::LEADING {
6387                    let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
6388                    let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
6389                    origin.x += dx;
6390                    origin.y += dy;
6391                }
6392                let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
6393            }
6394            // A released bitmap draws nothing rather than a placeholder: the canvas re-records
6395            // on every tracked read, so a handle can be dropped between the record and the
6396            // replay, and a frame that flashes a grey box is worse than one that omits the image.
6397            DrawOp::Image {
6398                image,
6399                rect,
6400                opacity,
6401                source,
6402            } => {
6403                let held = BITMAPS.with(|m| {
6404                    m.borrow()
6405                        .get(&image.0)
6406                        .map(|b| (b.image.clone(), b.info.pixels))
6407                });
6408                if let Some((img, pixels)) = held {
6409                    // A zero `fromRect` means the whole image. A region (`source`, in the
6410                    // bitmap's pixels) clamps to the bitmap with its mapping into `rect` kept,
6411                    // and an empty intersection draws nothing. `fromRect` is in the image's own
6412                    // space: its point size, origin at the BOTTOM-left the way NSImage counts,
6413                    // so the pixel region converts by the points-per-pixel ratio and flips.
6414                    let region = match source {
6415                        None => Some((NSRect::ZERO, *rect)),
6416                        Some(src) => {
6417                            day_spec::clamp_image_source(*src, *rect, pixels).map(|(src, dest)| {
6418                                let sz = img.size();
6419                                let (rx, ry) = (sz.width / pixels.width, sz.height / pixels.height);
6420                                let from = NSRect::new(
6421                                    NSPoint::new(
6422                                        src.origin.x * rx,
6423                                        (pixels.height - src.origin.y - src.size.height) * ry,
6424                                    ),
6425                                    NSSize::new(src.size.width * rx, src.size.height * ry),
6426                                );
6427                                (from, dest)
6428                            })
6429                        }
6430                    };
6431                    if let Some((from, dest)) = region {
6432                        let dest = NSRect::new(
6433                            NSPoint::new(dest.origin.x, dest.origin.y),
6434                            NSSize::new(dest.size.width, dest.size.height),
6435                        );
6436                        // DayCanvas is flipped (top-left origin). Respect that context so image
6437                        // rows stay upright, including under the canvas's rotation/zoom
6438                        // transforms. `fraction` multiplies the image's alpha.
6439                        img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
6440                            dest,
6441                            from,
6442                            objc2_app_kit::NSCompositingOperation::SourceOver,
6443                            *opacity,
6444                            true,
6445                            None,
6446                        );
6447                    }
6448                }
6449            }
6450            DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
6451            DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
6452            DrawOp::Concat(m) => {
6453                let t = NSAffineTransform::new();
6454                t.setTransformStruct(NSAffineTransformStruct {
6455                    m11: m.a,
6456                    m12: m.b,
6457                    m21: m.c,
6458                    m22: m.d,
6459                    tX: m.tx,
6460                    tY: m.ty,
6461                });
6462                t.concat();
6463            }
6464        }
6465    }
6466}
6467
6468/// An `NSGradient` from a display-list gradient's stops (sRGB, like every canvas color).
6469fn nsgradient(
6470    stops: &[(f64, day_spec::Color)],
6471) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
6472    if stops.is_empty() {
6473        return None;
6474    }
6475    let colors = objc2_foundation::NSArray::from_retained_slice(
6476        &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
6477    );
6478    let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
6479    unsafe {
6480        objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
6481            objc2_app_kit::NSGradient::alloc(),
6482            &colors,
6483            locations.as_ptr(),
6484            &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
6485        )
6486    }
6487}
6488
6489/// Concat a bounds-mapping transform (unit gradient space → `b`) onto the current context, so a
6490/// circular gradient drawn in unit coordinates renders elliptically stretched to the bounds.
6491fn concat_unit_to_bounds(b: day_spec::Rect) {
6492    let t = NSAffineTransform::new();
6493    t.setTransformStruct(NSAffineTransformStruct {
6494        m11: b.size.width,
6495        m12: 0.0,
6496        m21: 0.0,
6497        m22: b.size.height,
6498        tX: b.origin.x,
6499        tY: b.origin.y,
6500    });
6501    unsafe { t.concat() };
6502}
6503
6504/// Put a [`day_spec::StrokeStyle`] onto a path.
6505///
6506/// NOTE: this backend used to force ROUND caps on every stroke. It now honors the style, whose
6507/// default is BUTT — the same default the spec and every other backend use. A line that wants
6508/// round ends asks for `StrokeStyle::round`.
6509fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
6510    use day_spec::{LineCap, LineJoin};
6511    unsafe {
6512        p.setLineWidth(style.width);
6513        p.setLineCapStyle(match style.cap {
6514            LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
6515            LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
6516            LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
6517        });
6518        if style.is_plain() {
6519            return;
6520        }
6521        p.setLineJoinStyle(match style.join {
6522            LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
6523            LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
6524            LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
6525        });
6526        p.setMiterLimit(style.miter_limit);
6527        if !style.dash.is_empty() {
6528            let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
6529            p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
6530        }
6531    }
6532}
6533
6534/// Draw a gradient through whatever clip is installed, in AppKit's own `NSGradient` terms.
6535/// Shared by the gradient FILL arms and the gradient STROKE arm, which differ only in what they
6536/// clipped to first.
6537fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
6538    let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6539        | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
6540    match paint {
6541        day_spec::Paint::Linear(g) => {
6542            if let Some(grad) = nsgradient(&g.stops) {
6543                let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
6544                unsafe {
6545                    grad.drawFromPoint_toPoint_options(
6546                        NSPoint::new(s.x, s.y),
6547                        NSPoint::new(e.x, e.y),
6548                        opts,
6549                    );
6550                };
6551            }
6552        }
6553        day_spec::Paint::Radial(g) => {
6554            if let Some(grad) = nsgradient(&g.stops) {
6555                NSGraphicsContext::saveGraphicsState_class();
6556                concat_unit_to_bounds(bounds);
6557                let c = NSPoint::new(g.center.x, g.center.y);
6558                unsafe {
6559                    grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts);
6560                };
6561                NSGraphicsContext::restoreGraphicsState_class();
6562            }
6563        }
6564        day_spec::Paint::Solid(_) => {}
6565    }
6566}
6567
6568fn apply_button_content(
6569    btn: &NSButton,
6570    title: &str,
6571    icon: Option<&day_spec::Icon>,
6572    icon_only: bool,
6573) {
6574    let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
6575    if let Some(image) = &image {
6576        let size = image.size();
6577        let longest = size.width.max(size.height);
6578        if longest > 0.0 {
6579            image.setSize(objc2_foundation::NSSize::new(
6580                size.width * 20.0 / longest,
6581                size.height * 20.0 / longest,
6582            ));
6583        }
6584    }
6585    let style = BUTTON_STYLES
6586        .with(|m| m.borrow().get(&ptr_of(btn)).copied())
6587        .unwrap_or_default();
6588    BUTTON_IMAGES.with(|images| {
6589        let _ = images.remove(ptr_of(btn));
6590        if let Some(image) = &image {
6591            images.insert(ptr_of(btn), image.clone());
6592        }
6593    });
6594    set_button_title(btn, title, style);
6595    // The position first: the image setter pads a glyph that sits beside a title, and leaves
6596    // an icon-only one alone, by reading it.
6597    unsafe {
6598        btn.setImagePosition(if image.is_none() {
6599            objc2_app_kit::NSCellImagePosition::NoImage
6600        } else if icon_only {
6601            objc2_app_kit::NSCellImagePosition::ImageOnly
6602        } else {
6603            objc2_app_kit::NSCellImagePosition::ImageLeading
6604        });
6605    }
6606    set_button_image(btn, style);
6607    unsafe {
6608        // The title is the spoken name (an icon-only button shows none), unless the app named
6609        // the button itself; overwriting that here replaced app labels on every title change.
6610        if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
6611            btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
6612        }
6613        let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
6614        btn.setToolTip(tooltip.as_deref());
6615    }
6616}
6617
6618/// Bordered buttons do not reliably apply contentTintColor to template images. Keep
6619/// the native button, but supply an image that draws the original vector's alpha in
6620/// the requested contrast color at the destination resolution.
6621fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
6622    use day_spec::props::ButtonStyleSpec as S;
6623    let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
6624    let image = image.map(|source| {
6625        let S::Tinted(fill) = style else {
6626            return source;
6627        };
6628        let size = source.size();
6629        let ink = nscolor(S::on_tint(fill));
6630        let draw = block2::RcBlock::new(move |rect: NSRect| {
6631            source.drawInRect_fromRect_operation_fraction(
6632                rect,
6633                NSRect::ZERO,
6634                objc2_app_kit::NSCompositingOperation::SourceOver,
6635                1.0,
6636            );
6637            unsafe {
6638                ink.setFill();
6639                objc2_app_kit::NSRectFillUsingOperation(
6640                    rect,
6641                    objc2_app_kit::NSCompositingOperation::SourceIn,
6642                );
6643            }
6644            objc2::runtime::Bool::YES
6645        });
6646        objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
6647    });
6648    unsafe {
6649        let position = btn.imagePosition();
6650        // Beside a title, the glyph gets a clear gap: AppKit draws a leading image flush
6651        // against the text, so the image carries the space itself (a template stays one, so
6652        // the label color still tints it). The cell centers the image in its slot, so half
6653        // the extra width lands on each side.
6654        let image = image.map(|source| {
6655            // The position is set after this on a fresh button, so an unset one counts as
6656            // "beside a title"; only an icon-only button keeps the glyph as drawn.
6657            if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
6658                return source;
6659            }
6660            let size = source.size();
6661            let template = source.isTemplate();
6662            let padded = NSSize::new(size.width + 8.0, size.height);
6663            let draw = block2::RcBlock::new(move |_rect: NSRect| {
6664                source.drawInRect_fromRect_operation_fraction(
6665                    NSRect::new(NSPoint::new(0.0, 0.0), size),
6666                    NSRect::ZERO,
6667                    objc2_app_kit::NSCompositingOperation::SourceOver,
6668                    1.0,
6669                );
6670                objc2::runtime::Bool::YES
6671            });
6672            let out =
6673                objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
6674            out.setTemplate(template);
6675            out
6676        });
6677        btn.setImage(image.as_deref());
6678        btn.setImagePosition(position);
6679        btn.setImageHugsTitle(true);
6680    }
6681}
6682
6683/// Put `ButtonProps::selected` on an `NSButton`, keeping it an `NSButton`. A momentary button
6684/// shows no state, so the first `true` makes it push-on/push-off, whose on state AppKit draws
6685/// as the bezel's highlighted fill and VoiceOver reads as selected; a button that never
6686/// selects keeps its momentary type. A click toggles the state natively before the action
6687/// runs, so the `action:` handler restores the value recorded here.
6688fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
6689    BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
6690    unsafe {
6691        if on {
6692            btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
6693        }
6694        btn.setState(if on {
6695            NSControlStateValueOn
6696        } else {
6697            NSControlStateValueOff
6698        });
6699    }
6700}
6701
6702/// The corner radius of the tint painted behind a tinted button's bezel: the rounded push
6703/// bezel's own, so the fill reads as the bezel rather than as a box around it.
6704const TINT_CORNER_RADIUS: f64 = 6.0;
6705
6706/// Put a [`day_spec::props::ButtonStyleSpec`] on an `NSButton`, keeping it an `NSButton`.
6707///
6708/// Prominent = the return-key default button. Tinted = `bezelColor`, which AppKit composites
6709/// through the button's own bezel — so the pressed darkening, the focus ring and the disabled
6710/// look all still come from the control rather than from us painting a rectangle. macOS 26
6711/// composites the push bezel as a system material that ignores `bezelColor` on screen (an
6712/// offscreen `cacheDisplay` still honors it), so the tint is also painted on the control's
6713/// backing layer, where the translucent material lets it through; on older systems the opaque
6714/// tinted bezel covers that layer, so nothing changes there.
6715fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
6716    use day_spec::props::ButtonStyleSpec as S;
6717    let title = unsafe { btn.title() }.to_string();
6718    unsafe {
6719        // Reset first, so a patch from one style to another leaves nothing of the old one.
6720        btn.setKeyEquivalent(&NSString::from_str(""));
6721        btn.setBezelColor(None);
6722        btn.setBordered(!matches!(style, S::Plain));
6723        match style {
6724            S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
6725            S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
6726            // Bordered is the stock NSButton look already; Automatic asks for nothing, and an
6727            // NSButton hugs a one-glyph title already, so Compact asks for nothing either.
6728            S::Bordered | S::Automatic | S::Compact | S::Plain => {}
6729        }
6730        btn.setWantsLayer(true);
6731        if let Some(layer) = btn.layer() {
6732            match style {
6733                S::Tinted(c) => {
6734                    layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
6735                    layer.setCornerRadius(TINT_CORNER_RADIUS);
6736                }
6737                _ => layer.setBackgroundColor(None),
6738            }
6739        }
6740    }
6741    BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6742    let ink = match style {
6743        S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6744        _ => None,
6745    };
6746    unsafe {
6747        btn.setContentTintColor(ink.as_deref());
6748    }
6749    set_button_title(btn, &title, style);
6750    set_button_image(btn, style);
6751}
6752
6753/// Set a button's title, coloring it for the tint where there is one.
6754///
6755/// `contentTintColor` is NOT the seam for this: on a bordered `NSButton`,
6756/// AppKit keeps drawing the title in its own control text color — which is how a
6757/// white-on-rust button came out black-on-rust. An ATTRIBUTED title is the documented way to
6758/// control the text color, so that is what a tinted button gets.
6759///
6760/// The button's own font is carried into the attributes: an attributed title supplies the whole
6761/// run, so leaving the font out would drop the control font and render at the system default.
6762fn set_button_title(
6763    btn: &objc2_app_kit::NSButton,
6764    title: &str,
6765    style: day_spec::props::ButtonStyleSpec,
6766) {
6767    use day_spec::props::ButtonStyleSpec as S;
6768    // Changing an attributed title can reset NSButton's image placement. A reactive
6769    // tint must keep an icon-only button icon-only, including its native template tint.
6770    let position = unsafe { btn.imagePosition() };
6771    let S::Tinted(fill) = style else {
6772        // Plain title: AppKit picks the label color that suits the bezel it is drawing.
6773        unsafe {
6774            btn.setTitle(&NSString::from_str(title));
6775            btn.setImagePosition(position);
6776        }
6777        return;
6778    };
6779    unsafe {
6780        let col = nscolor(S::on_tint(fill));
6781        let font = btn
6782            .font()
6783            .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6784        // Centered, matching a plain NSButton title: an attributed title carries its own
6785        // paragraph style, and the default is left-aligned.
6786        let para = objc2_app_kit::NSMutableParagraphStyle::new();
6787        para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6788        let keys: [&NSString; 3] = [
6789            objc2_app_kit::NSFontAttributeName,
6790            objc2_app_kit::NSForegroundColorAttributeName,
6791            objc2_app_kit::NSParagraphStyleAttributeName,
6792        ];
6793        let objs: [&objc2::runtime::AnyObject; 3] = [
6794            font.as_ref() as &objc2::runtime::AnyObject,
6795            col.as_ref() as &objc2::runtime::AnyObject,
6796            para.as_ref() as &objc2::runtime::AnyObject,
6797        ];
6798        let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6799        let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6800            objc2_foundation::NSAttributedString::alloc(),
6801            &NSString::from_str(title),
6802            Some(&attrs),
6803        );
6804        btn.setAttributedTitle(&s);
6805        btn.setImagePosition(position);
6806    }
6807}
6808
6809// NSImageView supports aspect-fit but not aspect-fill. Expand its native drawing about
6810// the center and clip to the view; this retains vector rendering and template tinting.
6811define_class!(
6812    #[unsafe(super(objc2_app_kit::NSImageView))]
6813    #[thread_kind = MainThreadOnly]
6814    #[name = "DayFillImageView"]
6815    struct FillImageView;
6816
6817    impl FillImageView {
6818        #[unsafe(method(drawRect:))]
6819        fn draw_rect(&self, dirty: NSRect) {
6820            let bounds = self.bounds();
6821            let image = unsafe { self.image() };
6822            let Some(size) = image.map(|image| image.size()).filter(|size| {
6823                size.width > 0.0 && size.height > 0.0
6824                    && bounds.size.width > 0.0 && bounds.size.height > 0.0
6825            }) else {
6826                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6827                return;
6828            };
6829            let x = bounds.size.width / size.width;
6830            let y = bounds.size.height / size.height;
6831            let scale = x.max(y) / x.min(y);
6832            let cx = bounds.origin.x + bounds.size.width / 2.0;
6833            let cy = bounds.origin.y + bounds.size.height / 2.0;
6834            NSGraphicsContext::saveGraphicsState_class();
6835            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6836            let transform = NSAffineTransform::transform();
6837            transform.translateXBy_yBy(cx, cy);
6838            transform.scaleBy(scale);
6839            transform.translateXBy_yBy(-cx, -cy);
6840            transform.concat();
6841            let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6842            NSGraphicsContext::restoreGraphicsState_class();
6843        }
6844
6845        #[unsafe(method(setFrameSize:))]
6846        fn set_frame_size(&self, size: NSSize) {
6847            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6848            NSView::setNeedsDisplay(self, true);
6849        }
6850    }
6851);
6852
6853fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6854    use day_spec::Shape;
6855    use objc2_app_kit::NSBezierPath;
6856    unsafe {
6857        Some(match shape {
6858            Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6859            Shape::RoundedRect(r, rad) => {
6860                NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6861            }
6862            Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6863            Shape::Arc {
6864                rect,
6865                start_deg,
6866                sweep_deg,
6867            } => {
6868                let p = NSBezierPath::new();
6869                let center = NSPoint::new(
6870                    rect.origin.x + rect.size.width / 2.0,
6871                    rect.origin.y + rect.size.height / 2.0,
6872                );
6873                let radius = rect.size.width.min(rect.size.height) / 2.0;
6874                // Flipped view: increasing angle is visually clockwise, matching the spec.
6875                p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6876                    center,
6877                    radius,
6878                    *start_deg,
6879                    *start_deg + *sweep_deg,
6880                );
6881                p
6882            }
6883            Shape::Line(a, b) => {
6884                let p = NSBezierPath::new();
6885                p.moveToPoint(NSPoint::new(a.x, a.y));
6886                p.lineToPoint(NSPoint::new(b.x, b.y));
6887                p
6888            }
6889            Shape::Polygon(pts) => {
6890                if pts.len() < 2 {
6891                    return None;
6892                }
6893                let p = NSBezierPath::new();
6894                p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6895                for pt in &pts[1..] {
6896                    p.lineToPoint(NSPoint::new(pt.x, pt.y));
6897                }
6898                p.closePath();
6899                p
6900            }
6901            Shape::Path(path) => {
6902                use day_spec::PathSeg;
6903                if path.segs.is_empty() {
6904                    return None;
6905                }
6906                let p = NSBezierPath::new();
6907                // NSBezierPath's own quadratic API is macOS 14+, so quads are ELEVATED to
6908                // cubics with the standard formula (c1 = p0 + 2/3(c - p0), c2 = p1 + 2/3(c -
6909                // p1)), which is exact rather than an approximation.
6910                let mut cur = NSPoint::new(0.0, 0.0);
6911                for seg in &path.segs {
6912                    match seg {
6913                        PathSeg::Move(a) => {
6914                            cur = NSPoint::new(a.x, a.y);
6915                            p.moveToPoint(cur);
6916                        }
6917                        PathSeg::Line(a) => {
6918                            cur = NSPoint::new(a.x, a.y);
6919                            p.lineToPoint(cur);
6920                        }
6921                        PathSeg::Quad(c, a) => {
6922                            let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6923                            let c1 = NSPoint::new(
6924                                cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6925                                cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6926                            );
6927                            let c2 = NSPoint::new(
6928                                end.x + 2.0 / 3.0 * (ctl.x - end.x),
6929                                end.y + 2.0 / 3.0 * (ctl.y - end.y),
6930                            );
6931                            p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6932                            cur = end;
6933                        }
6934                        PathSeg::Cubic(c1, c2, a) => {
6935                            cur = NSPoint::new(a.x, a.y);
6936                            p.curveToPoint_controlPoint1_controlPoint2(
6937                                cur,
6938                                NSPoint::new(c1.x, c1.y),
6939                                NSPoint::new(c2.x, c2.y),
6940                            );
6941                        }
6942                        PathSeg::Close => p.closePath(),
6943                    }
6944                }
6945                p.setWindingRule(match path.rule {
6946                    day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6947                    day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6948                });
6949                p
6950            }
6951        })
6952    }
6953}
6954
6955// ---------------------------------------------------------------------------
6956// DayUndoManager — the native FRONT of the app's one undo stack (docs/model.md)
6957// ---------------------------------------------------------------------------
6958
6959/// The mirrored [`day_spec::UndoState`]: what the stock Edit menu reads through the standard
6960/// `undo:`/`redo:` validation. The stack itself lives in day-model; this object only answers
6961/// questions and forwards invocations — two histories can never fork.
6962struct UndoIvars {
6963    state: std::cell::RefCell<day_spec::UndoState>,
6964}
6965
6966define_class!(
6967    #[unsafe(super(objc2_foundation::NSUndoManager))]
6968    #[thread_kind = MainThreadOnly]
6969    #[name = "DayUndoManager"]
6970    #[ivars = UndoIvars]
6971    struct DayUndoManager;
6972
6973    /// Overrides of the questions AppKit's menu validation asks, answered from the mirrored
6974    /// state — and of the two verbs, forwarded as `Event::Undo` (enqueue-only, like every
6975    /// other event). Registration/grouping machinery of the superclass is never used.
6976    impl DayUndoManager {
6977        #[unsafe(method(canUndo))]
6978        fn can_undo(&self) -> bool {
6979            self.ivars().state.borrow().can_undo
6980        }
6981
6982        #[unsafe(method(canRedo))]
6983        fn can_redo(&self) -> bool {
6984            self.ivars().state.borrow().can_redo
6985        }
6986
6987        #[unsafe(method(undo))]
6988        fn do_undo(&self) {
6989            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }));
6990        }
6991
6992        #[unsafe(method(redo))]
6993        fn do_redo(&self) {
6994            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }));
6995        }
6996
6997        #[unsafe(method_id(undoMenuItemTitle))]
6998        fn undo_menu_item_title(&self) -> Retained<NSString> {
6999            // Route through the superclass's own title former, so "Undo" itself comes out in
7000            // the system language; the action label arrived already localized from the app.
7001            let label = self.ivars().state.borrow().undo_label.clone();
7002            unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
7003        }
7004
7005        #[unsafe(method_id(redoMenuItemTitle))]
7006        fn redo_menu_item_title(&self) -> Retained<NSString> {
7007            let label = self.ivars().state.borrow().redo_label.clone();
7008            unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
7009        }
7010    }
7011);
7012
7013fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
7014    UNDO_FRONT.with(|u| {
7015        u.borrow_mut()
7016            .get_or_insert_with(|| {
7017                let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
7018                    state: std::cell::RefCell::new(day_spec::UndoState::default()),
7019                });
7020                unsafe { msg_send![super(this), init] }
7021            })
7022            .clone()
7023    })
7024}
7025
7026// ---------------------------------------------------------------------------
7027// DayWinDelegate — resize + close + key tracking, per window
7028// ---------------------------------------------------------------------------
7029
7030/// `node`: the day window-root id this delegate's window reports to. `None` = the PRIMARY
7031/// window — resize goes to `WINDOW_NODE` and close terminates the app; a secondary window
7032/// (docs/windows.md) reports to its own root and close tears down just that window.
7033struct WinIvars {
7034    node: Option<NodeId>,
7035    /// The tab group this window was opened in (`WindowTabbing::Group`/`Preferred`): the
7036    /// tab bar's "+" opens another window of the same group.
7037    group: Option<String>,
7038    /// The last display state reported (`WindowState::code`), so a resize that does not change
7039    /// the zoom state reports nothing.
7040    last_state: Cell<i32>,
7041}
7042
7043define_class!(
7044    #[unsafe(super(NSObject))]
7045    #[thread_kind = MainThreadOnly]
7046    #[name = "DayWinDelegate"]
7047    #[ivars = WinIvars]
7048    struct DayWinDelegate;
7049
7050    unsafe impl NSObjectProtocol for DayWinDelegate {}
7051
7052    /// The responder chain's last stop for the standard edit nav hosts: a focused text view
7053    /// answered `cut:`/`copy:`/`paste:` long before the window asked its delegate, so what
7054    /// arrives here is the app's to handle — the same precedence the undo manager route uses.
7055    impl DayWinDelegate {
7056        /// Edit ▸ Undo. The stock item's nil-target `undo:` finds no implementor among Day's
7057        /// plain views, so the delegate is where the chain lands — resolving through the
7058        /// acting manager keeps a focused field's typing undo ahead of the document stack.
7059        #[unsafe(method(undo:))]
7060        fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7061            ffi_guard::contain((), || {
7062                if let Some(m) = self.acting_undo_manager() {
7063                    unsafe { m.undo() };
7064                }
7065            });
7066        }
7067
7068        /// Edit ▸ Redo.
7069        #[unsafe(method(redo:))]
7070        fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7071            ffi_guard::contain((), || {
7072                if let Some(m) = self.acting_undo_manager() {
7073                    unsafe { m.redo() };
7074                }
7075            });
7076        }
7077
7078        #[unsafe(method(cut:))]
7079        fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7080            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
7081        }
7082
7083        #[unsafe(method(copy:))]
7084        fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7085            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
7086        }
7087
7088        #[unsafe(method(paste:))]
7089        fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7090            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
7091        }
7092
7093        #[unsafe(method(selectAll:))]
7094        fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7095            ffi_guard::contain((), || {
7096                emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
7097            });
7098        }
7099
7100        /// AppKit's menu validation, the same machinery that greys Edit items for text views:
7101        /// the bridge state answers for cut/copy, and paste additionally requires the
7102        /// pasteboard to actually hold text.
7103        #[unsafe(method(validateMenuItem:))]
7104        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
7105            ffi_guard::contain(false, || {
7106                let state = EDIT_STATE.with(std::cell::Cell::get);
7107                match unsafe { item.action() } {
7108                    // The undo pair enables from the acting manager and takes its titles
7109                    // ("Undo Move Shape"), exactly as AppKit's own windows do.
7110                    Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
7111                        Some(m) => {
7112                            item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
7113                            unsafe { m.canUndo() }
7114                        }
7115                        None => false,
7116                    },
7117                    Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
7118                        Some(m) => {
7119                            item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
7120                            unsafe { m.canRedo() }
7121                        }
7122                        None => false,
7123                    },
7124                    Some(a) if a == sel!(selectAll:) => state.can_select_all,
7125                    Some(a) if a == sel!(cut:) => state.can_cut,
7126                    Some(a) if a == sel!(copy:) => state.can_copy,
7127                    Some(a) if a == sel!(paste:) => {
7128                        state.can_paste && {
7129                            let pb = unsafe { NSPasteboard::generalPasteboard() };
7130                            pb.types().is_some_and(|types| !types.is_empty())
7131                        }
7132                    }
7133                    _ => true,
7134                }
7135            })
7136        }
7137    }
7138
7139    unsafe impl NSWindowDelegate for DayWinDelegate {
7140        #[unsafe(method(windowDidResize:))]
7141        fn window_did_resize(&self, notification: &NSNotification) {
7142            ffi_guard::contain((), || {
7143                if let Some(obj) = unsafe { notification.object() }
7144                    && let Ok(win) = obj.downcast::<NSWindow>()
7145                    && let Some(size) = pin_below_title_bar(&win)
7146                {
7147                    let target = self.ivars().node.unwrap_or(WINDOW_NODE);
7148                    emit(target, Event::WindowResized(size));
7149                }
7150                // Zooming is a resize with no notification of its own.
7151                self.report_state_of(notification);
7152            });
7153        }
7154
7155        #[unsafe(method(windowShouldClose:))]
7156        fn window_should_close(&self, _window: &NSWindow) -> bool {
7157            ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
7158        }
7159
7160        #[unsafe(method(windowWillClose:))]
7161        fn window_will_close(&self, _notification: &NSNotification) {
7162            ffi_guard::contain((), || {
7163                match self.ivars().node {
7164                    // Secondary window: confirm the close to day-core, which tears the
7165                    // subtree down on a DEFERRED hop (never inside this AppKit close frame).
7166                    Some(node) => emit(node, Event::WindowClosed),
7167                    // Primary window: closing it quits, taking secondaries with it
7168                    // (docs/windows.md close policy), unless the app keeps running without a
7169                    // window (a status item, `KeepRunning::Always`): then it closes like any
7170                    // other window and day-core decides.
7171                    None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
7172                    None => {
7173                        let app = NSApplication::sharedApplication(self.mtm());
7174                        unsafe { app.terminate(None) };
7175                    }
7176                }
7177            });
7178        }
7179
7180        #[unsafe(method_id(windowWillReturnUndoManager:))]
7181        fn window_will_return_undo_manager(
7182            &self,
7183            _window: &NSWindow,
7184        ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
7185            // The responder chain already gave a focused text field its OWN manager before
7186            // asking the window — typing undo stays the field's, the model stack gets the
7187            // rest, exactly the precedence the plan's typing rule wants.
7188            ffi_guard::contain(None, || {
7189                UNDO_FRONT.with(|u| {
7190                    u.borrow()
7191                        .as_ref()
7192                        .map(|m| Retained::into_super(m.clone()))
7193                })
7194            })
7195        }
7196
7197        #[unsafe(method(windowDidBecomeKey:))]
7198        fn window_did_become_key(&self, _notification: &NSNotification) {
7199            ffi_guard::contain((), || {
7200                if let Some(node) = self.ivars().node {
7201                    emit(node, Event::WindowFocused(true));
7202                }
7203            });
7204        }
7205
7206        #[unsafe(method(windowDidResignKey:))]
7207        fn window_did_resign_key(&self, _notification: &NSNotification) {
7208            ffi_guard::contain((), || {
7209                if let Some(node) = self.ivars().node {
7210                    emit(node, Event::WindowFocused(false));
7211                }
7212            });
7213        }
7214
7215        #[unsafe(method(windowDidMiniaturize:))]
7216        fn window_did_miniaturize(&self, notification: &NSNotification) {
7217            ffi_guard::contain((), || self.report_state_of(notification));
7218        }
7219
7220        #[unsafe(method(windowDidDeminiaturize:))]
7221        fn window_did_deminiaturize(&self, notification: &NSNotification) {
7222            ffi_guard::contain((), || self.report_state_of(notification));
7223        }
7224
7225        #[unsafe(method(windowDidEnterFullScreen:))]
7226        fn window_did_enter_full_screen(&self, notification: &NSNotification) {
7227            ffi_guard::contain((), || self.report_state_of(notification));
7228        }
7229
7230        #[unsafe(method(windowDidExitFullScreen:))]
7231        fn window_did_exit_full_screen(&self, notification: &NSNotification) {
7232            ffi_guard::contain((), || self.report_state_of(notification));
7233        }
7234    }
7235
7236    // The tab bar's "+" button walks the responder chain (window → delegate) for
7237    // `newWindowForTab:` — present only when the app registered a new-window builder
7238    // (otherwise automatic tabbing is off and no "+" exists).
7239    impl DayWinDelegate {
7240        #[unsafe(method(newWindowForTab:))]
7241        fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
7242            ffi_guard::contain((), || {
7243                // A window in a tab group of its own gets another window of that group
7244                // (`register_new_window_for`); everything else gets File ▸ New Window's.
7245                let _ = match self.ivars().group.as_deref() {
7246                    Some(group) => day_core::windows::open_new_window_for_group(group),
7247                    None => day_core::windows::open_new_window(),
7248                };
7249            });
7250        }
7251    }
7252);
7253
7254impl DayWinDelegate {
7255    fn report_state_of(&self, notification: &NSNotification) {
7256        if let Some(obj) = unsafe { notification.object() }
7257            && let Ok(win) = obj.downcast::<NSWindow>()
7258        {
7259            self.report_state(&win);
7260        }
7261    }
7262}
7263
7264/// The day name for a key press, or `None` for every key the route does not carry — the
7265/// [`day_spec::KeyEvent`] names (docs/menus.md).
7266fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
7267    match unsafe { event.keyCode() } {
7268        123 => Some("ArrowLeft"),
7269        124 => Some("ArrowRight"),
7270        125 => Some("ArrowDown"),
7271        126 => Some("ArrowUp"),
7272        // Not the delete keys. This backend draws a menu bar, so a Delete accelerator on a
7273        // menu item owns them (docs/menus.md) — and a focused piece that CLAIMS a key stops
7274        // that accelerator from ever seeing it, which is how a canvas ends up swallowing the
7275        // Delete its own Edit menu was going to act on.
7276        //
7277        // A digit, main row or keypad, named by what it types. Never under ⌘, ⌥ or ⌃: those
7278        // combinations are accelerators, and claiming one would starve the menu the same way.
7279        _ => {
7280            let held = NSEventModifierFlags::Command
7281                | NSEventModifierFlags::Option
7282                | NSEventModifierFlags::Control;
7283            if event.modifierFlags().intersects(held) {
7284                return None;
7285            }
7286            let typed = event.characters()?.to_string();
7287            let mut chars = typed.chars();
7288            match (chars.next(), chars.next()) {
7289                (Some(c), None) => day_spec::KeyEvent::digit_name(c),
7290                _ => None,
7291            }
7292        }
7293    }
7294}
7295
7296/// The web name for a key that types nothing, by its virtual key code, or `None` for a key
7297/// that types (docs/menus.md "The full route").
7298fn named_key(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
7299    Some(match unsafe { event.keyCode() } {
7300        123 => "ArrowLeft",
7301        124 => "ArrowRight",
7302        125 => "ArrowDown",
7303        126 => "ArrowUp",
7304        36 | 76 => "Enter",
7305        48 => "Tab",
7306        53 => "Escape",
7307        51 => "Backspace",
7308        117 => "Delete",
7309        115 => "Home",
7310        119 => "End",
7311        116 => "PageUp",
7312        121 => "PageDown",
7313        114 => "Insert",
7314        122 => "F1",
7315        120 => "F2",
7316        99 => "F3",
7317        118 => "F4",
7318        96 => "F5",
7319        97 => "F6",
7320        98 => "F7",
7321        100 => "F8",
7322        101 => "F9",
7323        109 => "F10",
7324        103 => "F11",
7325        111 => "F12",
7326        _ => return None,
7327    })
7328}
7329
7330/// A key press on the full route (`Decorate::keyboard`, docs/menus.md "The full route"), for
7331/// a canvas that took the whole keyboard. Answers whether the press was claimed.
7332///
7333/// The order is the policy: a ⌘ chord is the menu's and goes back to AppKit first, whatever
7334/// the key; a composition in progress owns every key until the input method commits or
7335/// cancels it; a key that types nothing is named; a ⌃ chord names its key and types nothing;
7336/// everything else is handed to the text input system, which turns a dead key into marked
7337/// text, an input method's keys into a composition, and a plain or ⌥ key into `insertText:`
7338/// with what it typed (⌥ types on a Mac: ⌥8 is "{" on a German layout; the piece still sees
7339/// [`day_spec::KeyEvent::ALT`] and decides).
7340fn full_route_key_down(view: &DayCanvas, node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
7341    let ptr = std::ptr::from_ref::<DayCanvas>(view).cast::<NSView>() as usize;
7342    let flags = event.modifierFlags();
7343    let mods = key_modifiers(flags);
7344    if flags.contains(NSEventModifierFlags::Command) {
7345        return false;
7346    }
7347    let composing = MARKED.with(|t| t.contains(ptr));
7348    if !composing && let Some(named) = named_key(event) {
7349        emit(node, Event::Key(day_spec::KeyEvent::named(named, mods)));
7350        return true;
7351    }
7352    let unmodified =
7353        unsafe { event.charactersIgnoringModifiers() }.map_or_default(|s| s.to_string());
7354    // A function or editing key the vocabulary lacks types a private-use glyph.
7355    let typeable = !unmodified.is_empty()
7356        && !unmodified
7357            .chars()
7358            .any(|c| c.is_control() || ('\u{f700}'..='\u{f8ff}').contains(&c));
7359    if !composing && flags.contains(NSEventModifierFlags::Control) {
7360        if typeable {
7361            emit(
7362                node,
7363                Event::Key(day_spec::KeyEvent::named(unmodified, mods)),
7364            );
7365        }
7366        return true;
7367    }
7368    if !composing && !typeable {
7369        return true;
7370    }
7371    INTERPRETING.with(|i| *i.borrow_mut() = Some((unmodified, mods)));
7372    view.interpretKeyEvents(&NSArray::from_slice(&[event]));
7373    INTERPRETING.with(|i| *i.borrow_mut() = None);
7374    true
7375}
7376
7377/// The text of an `NSString` or `NSAttributedString` the text input system hands over.
7378fn text_of_input_string(string: &AnyObject) -> String {
7379    if let Some(s) = string.downcast_ref::<NSString>() {
7380        s.to_string()
7381    } else if let Some(s) = string.downcast_ref::<objc2_foundation::NSAttributedString>() {
7382        s.string().to_string()
7383    } else {
7384        String::new()
7385    }
7386}
7387
7388/// AppKit's modifier flags as day's mask.
7389fn key_modifiers(f: NSEventModifierFlags) -> u8 {
7390    let mut modifiers = 0u8;
7391    if f.contains(NSEventModifierFlags::Shift) {
7392        modifiers |= day_spec::KeyEvent::SHIFT;
7393    }
7394    if f.contains(NSEventModifierFlags::Command) {
7395        modifiers |= day_spec::KeyEvent::PRIMARY;
7396    }
7397    if f.contains(NSEventModifierFlags::Option) {
7398        modifiers |= day_spec::KeyEvent::ALT;
7399    }
7400    if f.contains(NSEventModifierFlags::Control) {
7401        modifiers |= day_spec::KeyEvent::CONTROL;
7402    }
7403    modifiers
7404}
7405
7406impl DayWinDelegate {
7407    /// The manager AppKit's own undo mechanics act on: ask the FIRST RESPONDER, whose
7408    /// `undoManager` walks the chain itself — a field editor answers with its typing
7409    /// history, everything else falls through to `windowWillReturnUndoManager` and lands on
7410    /// the app's front. Falls back to the front when no window is key yet.
7411    fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
7412        let responder = NSApplication::sharedApplication(self.mtm())
7413            .keyWindow()
7414            .and_then(|w| w.firstResponder());
7415        responder
7416            .and_then(|r| unsafe { r.undoManager() })
7417            .or_else(|| {
7418                UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
7419            })
7420    }
7421}
7422
7423impl DayWinDelegate {
7424    fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
7425        let this = Self::alloc(mtm).set_ivars(WinIvars {
7426            node,
7427            group,
7428            last_state: Cell::new(day_spec::WindowState::Normal.code()),
7429        });
7430        unsafe { msg_send![super(this), init] }
7431    }
7432
7433    /// Report the window's display state if it changed since the last report
7434    /// (docs/windows.md "Window properties"): to the window's root node, or `WINDOW_NODE` for the
7435    /// primary, the same routing as `WindowResized`.
7436    fn report_state(&self, window: &NSWindow) {
7437        let state = ns_window_state(window);
7438        if self.ivars().last_state.replace(state.code()) != state.code() {
7439            log::debug!("appkit: window state now {state:?}");
7440            let target = self.ivars().node.unwrap_or(WINDOW_NODE);
7441            emit(target, Event::WindowStateChanged(state));
7442        }
7443    }
7444}
7445
7446/// What AppKit says a window is showing as: miniaturized wins (a fullscreen window can be
7447/// neither), then fullscreen (whose frame also reads as zoomed), then zoomed.
7448fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
7449    if window.isMiniaturized() {
7450        day_spec::WindowState::Minimized
7451    } else if window
7452        .styleMask()
7453        .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
7454    {
7455        day_spec::WindowState::Fullscreen
7456    } else if window.isZoomed() {
7457        day_spec::WindowState::Maximized
7458    } else {
7459        day_spec::WindowState::Normal
7460    }
7461}
7462
7463/// Ask AppKit for `state`, undoing whatever the window is in first: fullscreen and miniaturized
7464/// have to be left before a window can zoom, and each is its own toggle.
7465fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
7466    use day_spec::WindowState as S;
7467    let current = ns_window_state(window);
7468    if current == state {
7469        return;
7470    }
7471    unsafe {
7472        match current {
7473            S::Minimized => window.deminiaturize(None),
7474            // Leaving fullscreen animates; asking for another state in the same turn would be
7475            // dropped by AppKit mid-transition, so the request stops at leaving it. The state
7476            // signal reads back `Normal`, and a second request takes it from there.
7477            S::Fullscreen => {
7478                window.toggleFullScreen(None);
7479                return;
7480            }
7481            S::Maximized if state != S::Minimized => window.zoom(None),
7482            _ => {}
7483        }
7484        match state {
7485            S::Normal => {}
7486            S::Minimized => window.miniaturize(None),
7487            S::Maximized => {
7488                if !window.isZoomed() {
7489                    window.zoom(None);
7490                }
7491            }
7492            S::Fullscreen => window.toggleFullScreen(None),
7493        }
7494    }
7495}
7496
7497// ---------------------------------------------------------------------------
7498// The backend
7499// ---------------------------------------------------------------------------
7500
7501/// Renderers registered by external Day Piece crates (§8.2 layer 3 — linkme convenience).
7502#[distributed_slice]
7503pub static RENDERERS: [fn() -> Renderer<AppKit>];
7504
7505/// A live secondary window (docs/windows.md). The delegate is RETAINED here —
7506/// `setDelegate:` holds it weakly, and unlike the primary's (kept alive because `run`
7507/// never returns) a secondary's delegate would die at the end of `open_window` otherwise.
7508struct SecondaryWin {
7509    window: Retained<NSWindow>,
7510    #[allow(dead_code)] // held for lifetime only; AppKit talks to it via the weak delegate ref
7511    delegate: Retained<DayWinDelegate>,
7512    content: Handle,
7513}
7514
7515/// Deliver an explicitly registered Escape accelerator before a field editor swallows it.
7516/// The monitor is local to this process and removed with the backend.
7517struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
7518impl Drop for MenuEscapeMonitor {
7519    fn drop(&mut self) {
7520        unsafe { NSEvent::removeMonitor(&self.0) };
7521    }
7522}
7523
7524pub struct AppKit {
7525    menu_escape_monitor: Option<MenuEscapeMonitor>,
7526    sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
7527    /// The picker's delegate, which the picker holds only weakly.
7528    sharing_delegate: Option<Retained<DaySharePickerDelegate>>,
7529
7530    mtm: MainThreadMarker,
7531    registry: Registry<AppKit>,
7532    window: Option<Retained<NSWindow>>,
7533    content: Option<Handle>,
7534    secondary: Vec<SecondaryWin>,
7535    app_name: String,
7536    /// Where the next secondary window's top-left goes (docs/windows.md). macOS staggers new
7537    /// windows rather than stacking them: `cascadeTopLeftFromPoint:` places the window and
7538    /// answers the point after it, so threading that answer through here is the whole
7539    /// mechanism. `None` until the primary exists — the cascade starts from its corner.
7540    cascade: Option<NSPoint>,
7541    /// One tracking-area owner per view carrying a `.cursor()` (docs/cursor.md), keyed by the
7542    /// view pointer. Removed when the cursor goes back to `Default`.
7543    cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
7544}
7545
7546impl AppKit {
7547    /// Rebuild a `text_field` as the other class (plain ⇄ secure) and put the replacement
7548    /// where the old view was: same text, look and place among its siblings, same focus and
7549    /// selection, and every view-keyed entry moved to it. day-core drops the old handle
7550    /// without a `release`, so nothing keyed by it may stay behind.
7551    fn swap_text_field(
7552        &mut self,
7553        h: &Handle,
7554        old: &NSTextField,
7555        node: NodeId,
7556        secure: bool,
7557    ) -> Retained<NSTextField> {
7558        let new = new_text_field(self.mtm, node, secure);
7559        let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
7560        // Focus and selection first: reading them is only meaningful while the old field
7561        // still edits. `stringValue` below answers the field editor's live text.
7562        let window = h.window();
7563        let focused = window
7564            .as_deref()
7565            .is_some_and(|w| owns_first_responder(w, h));
7566        let selection = old.currentEditor().map(|e| e.selectedRange());
7567        unsafe {
7568            new.setStringValue(&old.stringValue());
7569            new.setPlaceholderString(old.placeholderString().as_deref());
7570            new.setEnabled(old.isEnabled());
7571            new.setFont(old.font().as_deref());
7572            new.setFrame(h.frame());
7573            new.setHidden(h.isHidden());
7574            new.setMenu(h.menu().as_deref());
7575            new.setToolTip(h.toolTip().as_deref());
7576            // Opacity and transform ride the layer (`set_opacity` / `set_transform`).
7577            if h.wantsLayer() {
7578                new.setWantsLayer(true);
7579                new.setAlphaValue(h.alphaValue());
7580                let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
7581                let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
7582                if !from.is_null() && !to.is_null() {
7583                    let t: CGAffineTransform = msg_send![from, affineTransform];
7584                    let _: () = msg_send![to, setAffineTransform: t];
7585                }
7586            }
7587            // Accessibility (`set_a11y`): only what was set explicitly, so the new class
7588            // keeps its own defaults (a secure field's role and hidden value) for the rest.
7589            if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
7590                new.setAccessibilityIdentifier(Some(&id));
7591            }
7592            if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
7593                new.setAccessibilityLabel(Some(&label));
7594            }
7595            if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
7596                new.setAccessibilityHelp(Some(&help));
7597            }
7598            if !h.isAccessibilityElement() {
7599                new.setAccessibilityElement(false);
7600            }
7601        }
7602        // Recognizers and the cursor's tracking area move as objects, keeping their targets.
7603        for r in &unsafe { h.gestureRecognizers() } {
7604            unsafe {
7605                h.removeGestureRecognizer(&r);
7606                new.addGestureRecognizer(&r);
7607            }
7608        }
7609        GESTURES.with(|m| {
7610            let mut m = m.borrow_mut();
7611            if let Some(targets) = m.remove(&old_key) {
7612                m.insert(new_key, targets);
7613            }
7614        });
7615        if let Some((owner, area)) = self.cursors.remove(&old_key) {
7616            unsafe {
7617                h.removeTrackingArea(&area);
7618                new.addTrackingArea(&area);
7619            }
7620            self.cursors.insert(new_key, (owner, area));
7621        }
7622        PAN_NODES.with(|t| rekey(t, old_key, new_key));
7623        HOVER_NODES.with(|t| rekey(t, old_key, new_key));
7624        ROTATE_NODES.with(|t| rekey(t, old_key, new_key));
7625        ROTATE_ANGLE.with(|t| rekey(t, old_key, new_key));
7626        KEY_NODES.with(|t| rekey(t, old_key, new_key));
7627        FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
7628        CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
7629        transfer::moved(h, &new);
7630        // The old field goes silent before it leaves: ending its editing session would
7631        // otherwise report a focus loss for a node that keeps its focus.
7632        unsafe { old.setDelegate(None) };
7633        TARGETS.with(|m| {
7634            m.borrow_mut().remove(&old_key);
7635        });
7636        if let Some(parent) = unsafe { h.superview() } {
7637            unsafe {
7638                parent.addSubview_positioned_relativeTo(
7639                    &new,
7640                    objc2_app_kit::NSWindowOrderingMode::Above,
7641                    Some(h),
7642                );
7643                h.removeFromSuperview();
7644            }
7645        }
7646        if focused && let Some(window) = window {
7647            FIELD_SWAP.with(|s| s.set(true));
7648            let taken = window.makeFirstResponder(Some(&new));
7649            FIELD_SWAP.with(|s| s.set(false));
7650            // Taking focus selects the whole text; put back what was selected (the caret,
7651            // usually). Both classes count in UTF-16 units, so the range carries over.
7652            if taken && let Some(editor) = new.currentEditor() {
7653                let len = unsafe { new.stringValue() }.length();
7654                let range = selection
7655                    .filter(|r| r.location.saturating_add(r.length) <= len)
7656                    .unwrap_or(objc2_foundation::NSRange::new(len, 0));
7657                editor.setSelectedRange(range);
7658            }
7659        }
7660        // Whatever else was keyed by the old view goes with it.
7661        day_spec::sidetable::sweep(old_key);
7662        new
7663    }
7664
7665    /// Create the AppKit toolkit with every registered renderer.
7666    ///
7667    /// # Panics
7668    ///
7669    /// Panics when called off the main thread.
7670    #[must_use]
7671    pub fn new() -> Self {
7672        let mtm =
7673            MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
7674        let mut registry = Registry::default();
7675        for f in RENDERERS {
7676            registry.register(f());
7677        }
7678        AppKit {
7679            menu_escape_monitor: None,
7680            mtm,
7681            registry,
7682            window: None,
7683            sharing: None,
7684            sharing_delegate: None,
7685            content: None,
7686            secondary: Vec::new(),
7687            app_name: "Day".into(),
7688            cascade: None,
7689            cursors: HashMap::new(),
7690        }
7691    }
7692
7693    /// Public helper for external renderers.
7694    #[must_use]
7695    pub fn mtm(&self) -> MainThreadMarker {
7696        self.mtm
7697    }
7698
7699    /// The `NSWindow` whose content container is `host`: a secondary window, or the primary.
7700    /// What the main window's capture should show when the main window itself is hidden.
7701    ///
7702    /// Native document tabs (`group_windows`) move every document into its own window of an
7703    /// `NSWindowTabGroup` and leave the primary window an off-screen host. A capture of that
7704    /// host is an empty frame (or no frame at all), while the user sees the group's selected
7705    /// tab: that window's content is the stand-in, preferring the group of the app's main
7706    /// window. `None` while the primary window is on screen, or when no document window is.
7707    fn shown_document_content(&self, content: &NSView) -> Option<Handle> {
7708        if content.window().is_none_or(|w| w.isVisible()) {
7709            return None;
7710        }
7711        let main = NSApplication::sharedApplication(self.mtm).mainWindow();
7712        let anchor = main
7713            .filter(|m| {
7714                self.secondary
7715                    .iter()
7716                    .any(|w| std::ptr::eq(&raw const *w.window, &raw const **m))
7717            })
7718            .or_else(|| {
7719                self.secondary
7720                    .iter()
7721                    .find(|w| w.window.isVisible())
7722                    .map(|w| w.window.clone())
7723            })?;
7724        let shown = anchor
7725            .tabGroup()
7726            .and_then(|g| g.selectedWindow())
7727            .unwrap_or(anchor);
7728        self.secondary
7729            .iter()
7730            .find(|w| std::ptr::eq(&raw const *w.window, &raw const *shown) && w.window.isVisible())
7731            .map(|w| w.content.clone())
7732    }
7733
7734    fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
7735        if let Some(w) = self
7736            .secondary
7737            .iter()
7738            .find(|w| ptr_of(&w.content) == ptr_of(host))
7739        {
7740            return Some(w.window.clone());
7741        }
7742        self.content
7743            .as_ref()
7744            .filter(|c| ptr_of(c) == ptr_of(host))
7745            .and(self.window.clone())
7746    }
7747
7748    /// Build a Day window: titled + closable (Preferences kind drops resize/minimize and
7749    /// disallows tabbing per macOS convention; Normal windows share the `day.normal`
7750    /// tabbing group), a flipped content view, and a per-window delegate (`node`: `None` =
7751    /// primary). The window is NOT released-when-closed — Rust's `Retained` owns it, and
7752    /// the AppKit default would double-release under us on close.
7753    fn make_window(
7754        &self,
7755        options: &WindowOptions,
7756        prefs_style: bool,
7757        node: Option<NodeId>,
7758    ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
7759        use day_spec::WindowTabbing as T;
7760        use objc2_app_kit::NSWindowTabbingMode as M;
7761        let mtm = self.mtm;
7762        let (title, size, min_size, tabbing) = (
7763            options.title.as_str(),
7764            options.size,
7765            options.min_size,
7766            &options.tabbing,
7767        );
7768        let content_rect =
7769            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
7770        // The kind decides the controls, the chrome decides the frame (docs/window-chrome.md).
7771        let style = window_chrome::style_mask(options, prefs_style);
7772        let window = window_chrome::alloc_window(
7773            mtm,
7774            content_rect,
7775            style,
7776            options.chrome == day_spec::WindowChrome::Frameless,
7777        );
7778        unsafe { window.setReleasedWhenClosed(false) };
7779        window.setTitle(&NSString::from_str(title));
7780        if let Some(min) = min_size {
7781            unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
7782        }
7783        if let Some(max) = options.max_size {
7784            unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
7785        }
7786        let group = match tabbing {
7787            T::Group(g) | T::Preferred(g) => Some(g.clone()),
7788            T::Automatic | T::Disallowed => None,
7789        };
7790        match tabbing {
7791            _ if prefs_style => window.setTabbingMode(M::Disallowed),
7792            T::Disallowed => window.setTabbingMode(M::Disallowed),
7793            // Same-kind Day windows group as native tabs (System Settings "prefer tabs",
7794            // View ▸ Show Tab Bar, Merge All Windows) — meaningful once a second Normal
7795            // window can exist; inert while automatic tabbing is globally off (see `run`).
7796            T::Automatic => unsafe {
7797                window.setTabbingIdentifier(&NSString::from_str("day.normal"));
7798            },
7799            T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
7800            T::Preferred(g) => {
7801                unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
7802                window.setTabbingMode(M::Preferred);
7803            }
7804        }
7805        if group.is_some() {
7806            // A named group is the app asking for tabs, so the class-wide switch `run` may have
7807            // turned off (no New Window builder) goes back on for it.
7808            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
7809        }
7810        let delegate = DayWinDelegate::new(mtm, node, group);
7811        window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7812        let content = view_of(&DayFlipped::new(mtm));
7813        window.setContentView(Some(&content));
7814        window_chrome::apply(&window, &content, options);
7815        // Tab / Shift-Tab (docs/focus.md). AppKit does NOT derive the key view loop from the view
7816        // hierarchy: `nextKeyView` is nil on a programmatically built window and the loop stays
7817        // empty, so Tab moves focus OUT of a text field and onto nothing — measured on the
7818        // showcase's Focus page, where three Tabs in a row left every field unfocused. Every other
7819        // Day backend gets traversal from its widget order for free; this is the one that has to
7820        // ask. Autorecalculation rather than a call at the end of each layout because Day's tree
7821        // is reactive: fields appear, move, and vanish between passes, and AppKit rebuilding the
7822        // loop on hierarchy changes is the same rule expressed once.
7823        window.setAutorecalculatesKeyViewLoop(true);
7824        (window, delegate, content)
7825    }
7826}
7827
7828impl Default for AppKit {
7829    fn default() -> Self {
7830        Self::new()
7831    }
7832}
7833
7834fn view_of<T: AsRef<NSView>>(x: &Retained<T>) -> Handle {
7835    Retained::from((**x).as_ref())
7836}
7837
7838fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
7839    unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
7840}
7841
7842/// The macOS native semantic text style for a logical [`Font`] (`None` for a custom size).
7843/// `NSFont.preferredFont(forTextStyle:)` gives the OS's own typography, tracking the system settings.
7844fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
7845    use objc2_app_kit::*;
7846    unsafe {
7847        Some(match f {
7848            Font::LargeTitle => NSFontTextStyleLargeTitle,
7849            Font::Title => NSFontTextStyleTitle1,
7850            Font::Title2 => NSFontTextStyleTitle2,
7851            Font::Title3 => NSFontTextStyleTitle3,
7852            Font::Headline => NSFontTextStyleHeadline,
7853            Font::Subheadline => NSFontTextStyleSubheadline,
7854            Font::Body => NSFontTextStyleBody,
7855            Font::Callout => NSFontTextStyleCallout,
7856            Font::Footnote => NSFontTextStyleFootnote,
7857            Font::Caption => NSFontTextStyleCaption1,
7858            Font::Caption2 => NSFontTextStyleCaption2,
7859            Font::System(_) | Font::Custom(..) => return None,
7860        })
7861    }
7862}
7863
7864fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
7865    use day_spec::FontWeight as W;
7866    use objc2_app_kit::*;
7867    unsafe {
7868        match w {
7869            W::UltraLight => NSFontWeightUltraLight,
7870            W::Thin => NSFontWeightThin,
7871            W::Light => NSFontWeightLight,
7872            W::Regular => NSFontWeightRegular,
7873            W::Medium => NSFontWeightMedium,
7874            W::Semibold => NSFontWeightSemibold,
7875            W::Bold => NSFontWeightBold,
7876            W::Heavy => NSFontWeightHeavy,
7877            W::Black => NSFontWeightBlack,
7878        }
7879    }
7880}
7881
7882/// The `NSFontManager` weight rung (0 … 15) for a Day weight — the scale
7883/// `fontWithFamily:traits:weight:size:` matches faces on (5 = regular, 9 = bold).
7884fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7885    use day_spec::FontWeight as W;
7886    match w {
7887        W::UltraLight => 2,
7888        W::Thin => 3,
7889        W::Light => 4,
7890        W::Regular => 5,
7891        W::Medium => 6,
7892        W::Semibold => 8,
7893        W::Bold => 9,
7894        W::Heavy => 10,
7895        W::Black => 12,
7896    }
7897}
7898
7899/// Resolve a canvas font (docs/fonts.md) at an absolute size: the system face for `None`,
7900/// else the family's nearest member through `NSFontManager` (which also synthesizes a bold or
7901/// italic the family lacks), falling back to a PostScript/full-name lookup (a bundled font
7902/// registered in `run`) and then to the system font with one warning.
7903fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7904    use objc2_app_kit::*;
7905    let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7906    // A painting thread draws with the fonts the UI thread resolved for this export
7907    // (`OffscreenResources`); on the UI thread the table is empty and the lookup falls through.
7908    let prepared = OFFSCREEN_FONTS.with(|t| {
7909        t.borrow()
7910            .iter()
7911            .find(|(key, _)| key.0 == size.to_bits() && key.1 == *font)
7912            .map(|(_, f)| f.clone())
7913    });
7914    if let Some(f) = prepared {
7915        return f;
7916    }
7917    let Some(mtm) = objc2::MainThreadMarker::new() else {
7918        // Off the UI thread with a font the collector never saw (it walks every text op, so
7919        // this is a guard, not a path): the system face, since `NSFontManager` is not ours to
7920        // call here. `NSFont` itself is usable from any thread.
7921        return unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7922    };
7923    let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7924    let mut traits = NSFontTraitMask::empty();
7925    if weight >= day_spec::FontWeight::Semibold {
7926        traits |= NSFontTraitMask::BoldFontMask;
7927    }
7928    if font.italic {
7929        traits |= NSFontTraitMask::ItalicFontMask;
7930    }
7931    let Some(family) = font.family.as_deref() else {
7932        let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7933        return if font.italic {
7934            unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7935        } else {
7936            base
7937        };
7938    };
7939    let ns_family = NSString::from_str(family);
7940    if let Some(f) = unsafe {
7941        manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7942    } {
7943        return f;
7944    }
7945    if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7946        return if traits.is_empty() {
7947            f
7948        } else {
7949            unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7950        };
7951    }
7952    log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7953    unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7954}
7955
7956/// The attribute dictionary canvas text draws and measures with (the same one, so
7957/// `measure_text` and `replay` agree on the line box).
7958fn canvas_text_attrs(
7959    font: &NSFont,
7960    color: day_spec::Color,
7961) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7962    let col = nscolor(color);
7963    // SAFETY: both are AppKit's own attribute-name constants, valid for the process lifetime.
7964    let keys: [&NSString; 2] = unsafe {
7965        [
7966            objc2_app_kit::NSFontAttributeName,
7967            objc2_app_kit::NSForegroundColorAttributeName,
7968        ]
7969    };
7970    let objs: [&objc2::runtime::AnyObject; 2] = [
7971        font as &objc2::runtime::AnyObject,
7972        col.as_ref() as &objc2::runtime::AnyObject,
7973    ];
7974    objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7975}
7976
7977/// Resolve a [`FontSpec`] to a native `NSFont`: a semantic style via `preferredFont(forTextStyle:)`
7978/// (or a custom system size), then an optional weight override (at the same size) and italic trait.
7979fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7980    use objc2_app_kit::*;
7981    let base: Retained<NSFont> = match spec.style {
7982        Font::System(pt) => {
7983            let w = spec
7984                .weight
7985                .map_or(unsafe { NSFontWeightRegular }, ns_weight);
7986            unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7987        }
7988        // A bundled family (§18.4), registered with CoreText in run(). fontWithName resolves
7989        // family, full, and PostScript names. A weight override maps to the bold trait (the
7990        // family decides what it can supply); unknown families fall back to the system font.
7991        Font::Custom(name, pt) => {
7992            if let Some(f) = unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7993                if spec
7994                    .weight
7995                    .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7996                {
7997                    let mtm =
7998                        objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7999                    unsafe {
8000                        NSFontManager::sharedFontManager(mtm)
8001                            .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
8002                    }
8003                } else {
8004                    f
8005                }
8006            } else {
8007                log::warn!(
8008                    "unknown font family {name:?} — falling back to the system font \
8009                     (is the file in the project's fonts/ directory?)"
8010                );
8011                let w = spec
8012                    .weight
8013                    .map_or(unsafe { NSFontWeightRegular }, ns_weight);
8014                unsafe { NSFont::systemFontOfSize_weight(pt, w) }
8015            }
8016        }
8017        style => {
8018            // Invariant: System/Custom matched above, so only the semantic styles — which
8019            // `ns_text_style` maps exhaustively — can reach this arm.
8020            let ts = ns_text_style(style).expect("semantic style");
8021            let opts = objc2_foundation::NSDictionary::new();
8022            let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
8023            match spec.weight {
8024                // A weight override keeps the style's (system-resolved) size but re-picks the weight.
8025                Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
8026                None => f,
8027            }
8028        }
8029    };
8030    // Tabular figures. Cocoa exposes them as a whole font, not a trait, so this re-picks the
8031    // system font at the resolved size/weight rather than converting — which is why it only
8032    // applies to the system styles: a bundled `Font::Custom` family keeps its own figures (asking
8033    // for the system's monospaced-digit face there would silently swap the typeface).
8034    let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
8035        let w = spec
8036            .weight
8037            .map_or(unsafe { NSFontWeightRegular }, ns_weight);
8038        unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
8039    } else {
8040        base
8041    };
8042    // Monospace, by the same rule as tabular: Cocoa ships it as a whole font, so this re-picks
8043    // the system's monospaced face at the resolved size and weight. Skipped for a bundled family
8044    // — swapping a chosen typeface for the system mono would be a surprise, not a refinement.
8045    let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
8046        let w = spec
8047            .weight
8048            .map_or(unsafe { NSFontWeightRegular }, ns_weight);
8049        unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
8050    } else {
8051        base
8052    };
8053    // Relative size (`FontSpec::scale`). Applied last, over whatever face the traits above
8054    // settled on, and through `convertFont_toSize` so a bundled family keeps its typeface —
8055    // re-picking the system font here would undo the Custom/monospace/tabular work above.
8056    #[expect(
8057        clippy::float_cmp,
8058        reason = "1.0 is the exact unscaled default of `FontSpec::scale`"
8059    )]
8060    let base = if spec.scale == 1.0 {
8061        base
8062    } else {
8063        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
8064        let pts = spec.resolved_points(base.pointSize());
8065        unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
8066    };
8067    if spec.italic {
8068        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
8069        unsafe {
8070            NSFontManager::sharedFontManager(mtm)
8071                .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
8072        }
8073    } else {
8074        base
8075    }
8076}
8077
8078/// Build an `NSAttributedString` for a label's text + runs (docs/text-runs.md).
8079///
8080/// Ranges arrive as BYTE offsets into a Rust `str`; `NSAttributedString` indexes UTF-16. The
8081/// conversion is per-run rather than a blanket assumption: any text with an emoji or a CJK
8082/// character makes the two disagree, and an off-by-N range there styles the wrong words.
8083/// Stamp a paragraph alignment across a label's whole attributed string.
8084///
8085/// Separate from `setAlignment:` because the two live in different places: the cell has a
8086/// paragraph style, the attributed string carries its own, and the string's wins.
8087fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
8088    use objc2_foundation::{NSMutableAttributedString, NSRange};
8089    unsafe {
8090        let cur = tf.attributedStringValue();
8091        let m = NSMutableAttributedString::initWithAttributedString(
8092            NSMutableAttributedString::alloc(),
8093            &cur,
8094        );
8095        let style = objc2_app_kit::NSMutableParagraphStyle::new();
8096        style.setAlignment(align);
8097        // Wrapping is what makes alignment observable at all, and the default paragraph style a
8098        // fresh NSMutableParagraphStyle carries would otherwise reset it to clipping.
8099        style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
8100        m.addAttribute_value_range(
8101            objc2_app_kit::NSParagraphStyleAttributeName,
8102            &style,
8103            NSRange::new(0, cur.length()),
8104        );
8105        tf.setAttributedStringValue(&m);
8106    }
8107}
8108
8109fn attributed_label(
8110    text: &str,
8111    base_font: &NSFont,
8112    color: Option<day_spec::Color>,
8113    role: day_spec::props::TextRole,
8114    runs: &[day_spec::TextRun],
8115) -> Retained<objc2_foundation::NSAttributedString> {
8116    use objc2_foundation::{NSMutableAttributedString, NSRange};
8117    let ns = NSString::from_str(text);
8118    let s = unsafe {
8119        NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
8120    };
8121    let whole = NSRange::new(0, ns.length());
8122    unsafe {
8123        s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
8124        // Always a foreground: an attributed range with no color attribute draws in black,
8125        // which is unreadable in dark mode. `labelColor` is the adaptive default the field
8126        // would have used on its own.
8127        // An explicit color wins; otherwise the ROLE picks which adaptive system color to use.
8128        // Both are adaptive, which is the point of asking for a role instead of a grey: the
8129        // secondary label is legible against either appearance's background, and a literal one
8130        // cannot be.
8131        let fg = color.map_or_else(
8132            || match role {
8133                day_spec::props::TextRole::Secondary => {
8134                    objc2_app_kit::NSColor::secondaryLabelColor()
8135                }
8136                day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
8137            },
8138            nscolor,
8139        );
8140        s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
8141    }
8142    for r in runs {
8143        let Some(range) = utf16_range(text, &r.range) else {
8144            continue;
8145        };
8146        unsafe {
8147            s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
8148            if let Some(c) = r.color {
8149                s.addAttribute_value_range(
8150                    objc2_app_kit::NSForegroundColorAttributeName,
8151                    &nscolor(c),
8152                    range,
8153                );
8154            }
8155            if let Some(c) = r.background {
8156                s.addAttribute_value_range(
8157                    objc2_app_kit::NSBackgroundColorAttributeName,
8158                    &nscolor(c),
8159                    range,
8160                );
8161            }
8162            if r.underline.is_on() {
8163                let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
8164                s.addAttribute_value_range(
8165                    objc2_app_kit::NSUnderlineStyleAttributeName,
8166                    &style,
8167                    range,
8168                );
8169            }
8170            if r.strikethrough {
8171                let one = objc2_foundation::NSNumber::new_i64(1);
8172                s.addAttribute_value_range(
8173                    objc2_app_kit::NSStrikethroughStyleAttributeName,
8174                    &one,
8175                    range,
8176                );
8177            }
8178            if let Some(url) = r.link.as_deref() {
8179                // The native field editor hit-tests this attribute; DayLabel handles its
8180                // delegate callback and reports LinkActivated without opening the URL itself.
8181                let value = NSString::from_str(url);
8182                s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
8183            }
8184        }
8185    }
8186    s.into_super()
8187}
8188
8189/// [`Underline`](day_spec::Underline) as an `NSUnderlineStyle` bitmask: the line style in the low
8190/// byte, the pattern in the second. `Dotted`/`Wavy` are patterns over a single line, which is
8191/// exactly how AppKit spells them.
8192fn ns_underline(u: day_spec::Underline) -> i64 {
8193    use day_spec::Underline as U;
8194    match u {
8195        U::None => 0,
8196        U::Single => 0x01,
8197        U::Double => 0x09,
8198        U::Dotted => 0x01 | 0x0100,
8199        U::Wavy => 0x01 | 0x0400,
8200    }
8201}
8202
8203/// A byte range in `text` as an `NSRange` in UTF-16 units, or `None` if it is out of bounds.
8204fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
8205    let start = text.get(..r.start)?.encode_utf16().count();
8206    let len = text.get(r.clone())?.encode_utf16().count();
8207    Some(objc2_foundation::NSRange::new(start, len))
8208}
8209
8210/// Register every bundled font file (the project's `fonts/`, staged per §18.4) with CoreText for
8211/// this process, so `Font::Custom` family names resolve through `NSFont::fontWithName`. Called
8212/// once from `run()`; a failure (already registered on a hot relaunch, or a broken file) only
8213/// means that family won't resolve, so it logs and moves on.
8214fn register_bundled_fonts() {
8215    // CFURLRef is toll-free bridged with NSURL, so the NSURL pointer passes straight through.
8216    #[link(name = "CoreText", kind = "framework")]
8217    unsafe extern "C" {
8218        fn CTFontManagerRegisterFontsForURL(
8219            font_url: *const std::ffi::c_void,
8220            scope: u32, // kCTFontManagerScopeProcess = 1
8221            error: *mut *const std::ffi::c_void,
8222        ) -> bool;
8223    }
8224    for path in day_spec::fonts::bundled_fonts() {
8225        let url = unsafe {
8226            objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
8227        };
8228        let ok = unsafe {
8229            CTFontManagerRegisterFontsForURL(
8230                Retained::as_ptr(&url).cast::<std::ffi::c_void>(),
8231                1,
8232                std::ptr::null_mut(),
8233            )
8234        };
8235        if !ok {
8236            log::warn!("could not register bundled font {}", path.display());
8237        }
8238    }
8239}
8240
8241/// `TextAlign` → AppKit. `Natural` rather than `Left` for the leading case: it follows the
8242/// writing direction, so an RTL locale aligns right without the app asking (docs/localization.md).
8243fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
8244    match a {
8245        day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
8246        day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
8247        day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
8248    }
8249}
8250
8251fn configure_label_cell(tf: &NSTextField) {
8252    if let Some(cell) = unsafe { tf.cell() } {
8253        unsafe {
8254            cell.setWraps(true);
8255            cell.setUsesSingleLineMode(false);
8256            cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
8257        }
8258    }
8259}
8260
8261/// If `parent` is a scroll view, children go into its (flipped) document view.
8262fn content_of(parent: &Handle) -> Retained<NSView> {
8263    if let Some(sv) = parent.downcast_ref::<NSScrollView>()
8264        && let Some(doc) = unsafe { sv.documentView() }
8265    {
8266        return doc;
8267    }
8268    parent.clone()
8269}
8270
8271/// Run `body` (which sets animatable properties on a layer-backed view) inside an
8272/// `NSAnimationContext` group so AppKit interpolates the change on the render server with the
8273/// curve's timing function, or immediately when `anim` is `None` (§8.4). `allowsImplicitAnimation`
8274/// makes direct property changes on layer-backed views animate. A spring maps to an overshooting
8275/// cubic-bezier timing function (a visible bounce without an explicit `CASpringAnimation`).
8276fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
8277    let Some(a) = anim else {
8278        body();
8279        return;
8280    };
8281    let (dur, timing) = appkit_timing(a);
8282    unsafe {
8283        NSAnimationContext::beginGrouping();
8284        let ctx = NSAnimationContext::currentContext();
8285        ctx.setDuration(dur);
8286        ctx.setTimingFunction(Some(&timing));
8287        ctx.setAllowsImplicitAnimation(true);
8288        body();
8289        NSAnimationContext::endGrouping();
8290    }
8291}
8292
8293/// The `(duration_secs, timing function)` for a curve. Springs render as an overshooting bezier
8294/// (control point y > 1) whose overshoot grows as damping falls, over a response-derived duration.
8295fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
8296    unsafe {
8297        let named = |n| {
8298            (
8299                a.duration_secs().max(0.01),
8300                CAMediaTimingFunction::functionWithName(n),
8301            )
8302        };
8303        match a.curve {
8304            Curve::Linear => named(kCAMediaTimingFunctionLinear),
8305            Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
8306            Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
8307            Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
8308            Curve::Spring { damping, .. } => {
8309                // Overshoot bezier over exactly the specified duration (authoritative timing).
8310                let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
8311                (
8312                    a.duration_secs().max(0.05),
8313                    CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
8314                )
8315            }
8316        }
8317    }
8318}
8319
8320/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
8321/// a visible placeholder. A missing renderer usually means the piece's `appkit` feature wasn't enabled
8322/// (Tier A.2 derives it automatically under `day build`; a bare `cargo` build may miss it). Deduped
8323/// per kind so a placeholder rendered every frame doesn't spam the log.
8324fn warn_missing_renderer(kind: PieceKind) {
8325    day_spec::placeholder::report(kind, "appkit");
8326}
8327
8328/// The visible-but-harmless placeholder label the unregistered-kind arm renders. Shared with
8329/// the [`props_of`] mismatch fallback, so a wrong props payload degrades to the same surface
8330/// (the warning is already reported by `props_of` itself).
8331pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
8332    view_of(&unsafe {
8333        NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
8334    })
8335}
8336
8337impl Toolkit for AppKit {
8338    /// Settled unless a toolbar edit is still painting (toolbar.rs `CHROME_SETTLE`); AppKit's
8339    /// own transitions (sheets, nav pushes) complete within the turn that starts them.
8340    fn ui_idle(&mut self) -> bool {
8341        toolbar::chrome_settled()
8342    }
8343
8344    type Handle = Handle;
8345
8346    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
8347        use day_spec::SystemColor;
8348        let result = std::cell::Cell::new(role.fallback(self.dark_mode()));
8349        let block = block2::StackBlock::new(|| {
8350            let color = match role {
8351                SystemColor::Accent => NSColor::controlAccentColor(),
8352                SystemColor::Text => NSColor::labelColor(),
8353                SystemColor::SecondaryText => NSColor::secondaryLabelColor(),
8354                SystemColor::Background => NSColor::windowBackgroundColor(),
8355                SystemColor::Surface => NSColor::controlBackgroundColor(),
8356            };
8357            if let Some(rgb) =
8358                color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())
8359            {
8360                result.set(day_spec::Color::rgba(
8361                    rgb.redComponent(),
8362                    rgb.greenComponent(),
8363                    rgb.blueComponent(),
8364                    rgb.alphaComponent(),
8365                ));
8366            }
8367        });
8368        NSApplication::sharedApplication(self.mtm())
8369            .effectiveAppearance()
8370            .performAsCurrentDrawingAppearance(&block);
8371        result.get()
8372    }
8373
8374    fn dark_mode(&mut self) -> bool {
8375        // The app's EFFECTIVE appearance — one source for the system setting, the DAY_THEME
8376        // launch force (applied as an NSApp override at startup), and a set_appearance call.
8377        let app = NSApplication::sharedApplication(self.mtm());
8378        app.effectiveAppearance()
8379            .name()
8380            .to_string()
8381            .contains("Dark")
8382    }
8383
8384    /// System Settings › Accessibility › Display › "Reduce motion", as `NSWorkspace` reports it
8385    /// (docs/accessibility.md). `install_reduce_motion_observer` re-reads it on a flip.
8386    fn reduce_motion(&mut self) -> bool {
8387        objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
8388    }
8389
8390    /// macOS is the one platform whose badge takes arbitrary text: `NSDockTile.badgeLabel` is a
8391    /// `String`, so `Text` renders literally and a count is just its decimal form. A nil label
8392    /// clears it (docs/badge.md).
8393    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
8394        use day_spec::AppBadge;
8395        let label = match badge {
8396            // Zero clears, matching the platform convention the doc states.
8397            AppBadge::None | AppBadge::Count(0) => None,
8398            AppBadge::Count(n) => Some(n.to_string()),
8399            AppBadge::Text(t) if t.is_empty() => None,
8400            AppBadge::Text(t) => Some(t.clone()),
8401            // No dedicated dot on the Dock; the smallest honest mark is a single bullet.
8402            AppBadge::Dot => Some("\u{2022}".to_string()),
8403        };
8404        let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
8405        let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
8406        unsafe { tile.setBadgeLabel(ns.as_deref()) };
8407        tile.display();
8408    }
8409
8410    fn set_appearance(&mut self, dark: Option<bool>) {
8411        let app = NSApplication::sharedApplication(self.mtm());
8412        let appearance = dark.and_then(|d| {
8413            objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
8414                if d {
8415                    objc2_app_kit::NSAppearanceNameDarkAqua
8416                } else {
8417                    objc2_app_kit::NSAppearanceNameAqua
8418                }
8419            })
8420        });
8421        // `None` clears the override — back to the system appearance.
8422        unsafe { app.setAppearance(appearance.as_deref()) };
8423    }
8424
8425    fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
8426        controls::refresh_gesture::attach(handle, host);
8427    }
8428
8429    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
8430        unsafe {
8431            handle.setHidden(!visible);
8432        }
8433    }
8434
8435    #[expect(
8436        clippy::match_same_arms,
8437        reason = "one arm per capability, each documented with the AppKit mechanism behind it"
8438    )]
8439    fn capability(&self, cap: Cap) -> Support {
8440        match cap {
8441            // An `NSSharingService` per app action, from the picker's delegate.
8442            Cap::ShareActions => Support::Native,
8443            Cap::SearchField => Support::Native,
8444            Cap::ComboBox => Support::Native,
8445            Cap::Stepper => Support::Native,
8446            Cap::DateTimePicker => Support::Native,
8447            Cap::ColorPicker => Support::Native,
8448            Cap::PullRefresh => Support::Emulated,
8449            Cap::Pager => Support::Emulated,
8450            Cap::PullRefreshGesture => Support::Emulated,
8451            // A tracking-area owner sets an `NSCursor` per view (docs/cursor.md). Wait, progress,
8452            // help, and move take the arrow — AppKit draws no such shapes — and the zoom and
8453            // diagonal-resize cursors need macOS 15.
8454            Cap::Cursor => Support::Native,
8455            // `NSFontManager` enumerates every family and member (docs/fonts.md).
8456            Cap::FontList => Support::Native,
8457            // An image-and-text table cell's content (docs/list.md "List items").
8458            Cap::ListItem => Support::Native,
8459            // ImageIO behind `NSBitmapImageRep` reads every container macOS knows and writes
8460            // back PNG/JPEG/TIFF/BMP/GIF, and carries the container's own metadata dictionary
8461            // (docs/images.md).
8462            Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
8463            // Canvas export (docs/canvas.md "Exporting"): the canvas painter replayed into a
8464            // CGBitmapContext, or a CGPDFContext that keeps shapes and text vector.
8465            Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
8466            // The announcement-requested notification, posted from the primary window
8467            // (docs/accessibility.md).
8468            Cap::Announce => Support::Native,
8469            // `NSWorkspace.accessibilityDisplayShouldReduceMotion`, re-read when the workspace
8470            // posts its display-options change (docs/accessibility.md).
8471            Cap::ReduceMotion => Support::Native,
8472            Cap::Snapshot
8473            | Cap::NativeSymbols
8474            // The rows as chrome: `Rail` is the same source list pinned narrow, `Tabs` an
8475            // NSSegmentedControl docked below the pages. AppKit has no app-level tab bar —
8476            // NSTabView owns its own page content, the opposite of Day's model — so the bar
8477            // is composed from the control a Mac uses for a one-of-N switch this size.
8478            //
8479            // `Cap::NavTabsAdaptive` is deliberately NOT here: a Mac app may PIN a tab bar, but
8480            // a narrow Mac window hides its sidebar and pushes rather than growing one. It falls
8481            // through to the `Unsupported` arm below.
8482            | Cap::NavTabs
8483            | Cap::NavSplit
8484            // Both presentations are the same NSSplitViewController — a stack is that split with
8485            // its sidebar item collapsed — so re-presenting is a collapse plus one `addSubview`
8486            // that re-parents the sidebar page (docs/size-classes.md).
8487            | Cap::NavRepresent
8488            // A REAL `contentList` NSSplitViewItem between sidebar and detail; the pane
8489            // persists through every presentation (docs/navigation.md).
8490            | Cap::NavContentList
8491            | Cap::Dialogs
8492            | Cap::FileDialogs
8493            // NSOpenPanel with `canChooseDirectories` (docs/files.md).
8494            | Cap::FolderDialog
8495            | Cap::Animation
8496            // NSTextView natively honors all three text-area attributes.
8497            | Cap::TextEditable
8498            | Cap::TextSelectable
8499            | Cap::TextSpellCheck
8500            // NSTableView's own drag pipeline, with the `.gap` placeholder (docs/list.md), in
8501            // lists and in the source-list sidebar itself (docs/navigation.md).
8502            | Cap::NavReorder | Cap::ListReorder
8503            // NSTableView's view-based reuse queue (`makeViewWithIdentifier`) hands Day's cells
8504            // back for new rows; `didRemoveRowView` recycles them (docs/list.md).
8505            | Cap::ListRecycling
8506            // NSTableView row actions: reveal-as-you-swipe buttons with the native full-slide
8507            // activation (docs/list.md).
8508            | Cap::ListSwipeActions
8509            // NSTableView group rows with `floatsGroupRows` (docs/list.md "Sections").
8510            | Cap::ListSections
8511            // NSOutlineView hosts Day-built rows natively, drag-reparent included
8512            // (docs/tree.md).
8513            | Cap::Tree
8514            | Cap::TreeSections
8515            | Cap::TreeMove
8516            // Real NSWindows with native tabbing + the Windows menu (docs/windows.md).
8517            | Cap::MultiWindow
8518            // `miniaturize:` / `zoom:` / `toggleFullScreen:`, reported back through the window
8519            // delegate's notifications (docs/windows.md "Window properties").
8520            | Cap::WindowStates
8521            | Cap::WindowFullscreen
8522            // `NSWindowSharingNone`: captures, recordings and screen sharing see an empty window.
8523            | Cap::ContentProtection
8524            // Per-window `tabbingIdentifier` / `tabbingMode`, with the "+" opening the group's
8525            // own builder.
8526            | Cap::WindowTabbing
8527            // `applicationDockMenu:` on the app delegate (docs/menus.md).
8528            | Cap::DockMenu
8529            // Borderless windows that still take key, a transparent title bar over the
8530            // content, a clear window background, and `NSVisualEffectView` materials behind the
8531            // content (docs/window-chrome.md).
8532            | Cap::FramelessWindow
8533            | Cap::OverlayTitleBar
8534            | Cap::TransparentWindow
8535            | Cap::WindowMaterial
8536            // `performWindowDragWithEvent:` from a press on the region's own background.
8537            | Cap::DragRegion
8538            // `NSStatusItem`s in the menu bar, a progress bar drawn on the Dock tile, and the
8539            // accessory activation policy (docs/status-item.md).
8540            | Cap::StatusItem
8541            | Cap::AppProgress
8542            | Cap::DockVisibility
8543            // Frame, limits, level, Spaces, style-mask controls, per-window appearance, Dock
8544            // bounces, and `NSScreen` (docs/windows.md "Window properties").
8545            | Cap::WindowGeometry
8546            | Cap::WindowPosition
8547            | Cap::WindowLevel
8548            | Cap::WindowAppearance
8549            | Cap::RequestAttention
8550            | Cap::Monitors
8551            // Run-time shortcuts appear in the Dock menu beside the declared ones.
8552            | Cap::DynamicShortcuts
8553            // A real NSToolbar in the title bar (docs/toolbars.md).
8554            | Cap::Toolbar
8555            // The bar holds a native search field (docs/search.md).
8556            | Cap::ToolbarSearch
8557            | Cap::AppMenu
8558            // NSDockTile.badgeLabel is an arbitrary String, so all three payloads render — the
8559            // only backend where Text is real (docs/badge.md).
8560            | Cap::AppBadgeCount
8561            | Cap::AppBadgeText
8562            // NSUndoManager fronted by DayUndoManager: the stock Edit menu retitles and
8563            // enables itself, ⌘Z/⇧⌘Z land through the responder chain (docs/model.md).
8564            | Cap::UndoBridge
8565            | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
8566            | Cap::AppBadgeDot
8567            | Cap::Appearance
8568            // firstBaselineOffsetFromTop — the platform's own answer (docs/baseline.md).
8569            | Cap::BaselineAlignment
8570            // A REAL inspector NSSplitViewItem (`inspectorWithViewController:`): the system
8571            // trailing-pane material and full-height layout (docs/inspector.md).
8572            | Cap::Inspector
8573            // A plain NSSplitView with two arranged panes (docs/split.md).
8574            | Cap::Split
8575            | Cap::TextRuns
8576            | Cap::TextLinks => Support::Native,
8577            // A topmost autoresizing child of the content view — not a system modal
8578            // (docs/cover.md's ArkUI tier).
8579            Cap::Cover => Support::Emulated,
8580            // `.sheet()` is a window sheet on the primary window (docs/cover.md "Modal sheet").
8581            Cap::CoverSheet => Support::Native,
8582            _ => Support::Unsupported,
8583        }
8584    }
8585
8586    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
8587        let mtm = self.mtm;
8588        match Builtin::from_key(kind) {
8589            Some(Builtin::Container) => {
8590                let v = DayFlipped::new(mtm);
8591                if let Some(p) = props.downcast_ref::<ContainerProps>() {
8592                    if p.role == Some(day_spec::SurfaceRole::SectionCard) {
8593                        v.set_section_card(p.corner_radius);
8594                    } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
8595                        v.set_surface(p.background, p.corner_radius, p.clips);
8596                    }
8597                }
8598                view_of(&v)
8599            }
8600            Some(Builtin::Scroll) => {
8601                let horizontal = props
8602                    .downcast_ref::<day_spec::props::ScrollProps>()
8603                    .is_some_and(|p| p.horizontal);
8604                let sv = unsafe { NSScrollView::new(mtm) };
8605                unsafe {
8606                    sv.setHasVerticalScroller(!horizontal);
8607                    sv.setHasHorizontalScroller(horizontal);
8608                    sv.setDrawsBackground(false);
8609                    // Overlay scrollers ALWAYS: day lays content out at the scroll's full frame
8610                    // width, and a legacy scroller (the "always show scroll bars" system
8611                    // setting, or a mouse attached) would reserve ~15pt and clip trailing
8612                    // content. Overlay floats above content instead — and matches the GTK/Qt
8613                    // backends.
8614                    sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8615                }
8616                let doc = DayFlipped::new(mtm);
8617                unsafe { sv.setDocumentView(Some(doc.as_ref())) };
8618                view_of(&sv)
8619            }
8620            Some(Builtin::Label) => {
8621                // `props_of`, not a panicking downcast, for every typed-props arm: a mismatch
8622                // (a piece registered under a builtin key, or a day-core regression) warns once
8623                // per kind and degrades to the placeholder — realize runs inside native
8624                // up-calls, where a panic is a process kill.
8625                let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
8626                    return placeholder_view(mtm, kind);
8627                };
8628                let tf = DayLabel::new(mtm, id, &p.text);
8629                configure_label_cell(&tf);
8630                if !p.wraps || p.max_lines > 0 {
8631                    unsafe {
8632                        tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
8633                        if !p.wraps || p.max_lines == 1 {
8634                            tf.setUsesSingleLineMode(true);
8635                            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
8636                        }
8637                    }
8638                }
8639                unsafe { tf.setFont(Some(&nsfont(p.font))) };
8640                // The PLAIN path needs the role as much as the attributed one below: a label
8641                // with no runs never reaches `attributed_label`, and reading the role only there
8642                // left every ordinary `.secondary()` label rendering in the primary color.
8643                match (p.color, p.role) {
8644                    (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
8645                    (None, day_spec::props::TextRole::Secondary) => unsafe {
8646                        tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
8647                    },
8648                    (None, day_spec::props::TextRole::Primary) => {}
8649                }
8650                if !p.runs.is_empty() {
8651                    let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
8652                    unsafe { tf.setAttributedStringValue(&s) };
8653                }
8654                tf.ivars().has_runs.set(!p.runs.is_empty());
8655                tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
8656                // Alignment goes on last and, for a runs label, has to reach inside the
8657                // attributed string. `setAlignment:` writes the cell's paragraph style, which an
8658                // attributed string then overrides wholesale with its own — so a markdown label
8659                // set only through the cell comes out leading-aligned no matter what was asked.
8660                if p.align != day_spec::props::TextAlign::Leading {
8661                    unsafe { tf.setAlignment(nstextalign(p.align)) };
8662                    if !p.runs.is_empty() {
8663                        set_paragraph_alignment(&tf, nstextalign(p.align));
8664                    }
8665                }
8666                view_of(&Retained::into_super(tf))
8667            }
8668            Some(Builtin::Button) => {
8669                let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
8670                    return placeholder_view(mtm, kind);
8671                };
8672                let target = DayTarget::new(mtm, id);
8673                let btn = unsafe {
8674                    NSButton::buttonWithTitle_target_action(
8675                        &NSString::from_str(&p.title),
8676                        Some(&*target),
8677                        Some(sel!(action:)),
8678                        mtm,
8679                    )
8680                };
8681                apply_button_style(&btn, p.style);
8682                if p.icon.is_some() {
8683                    apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
8684                }
8685                unsafe { btn.setEnabled(p.enabled) };
8686                set_button_selected(&btn, p.selected);
8687                let view = view_of(&btn);
8688                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8689                view
8690            }
8691            Some(Builtin::Toggle) => {
8692                let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
8693                    return placeholder_view(mtm, kind);
8694                };
8695                let target = DayTarget::new(mtm, id);
8696                let sw = unsafe { NSSwitch::new(mtm) };
8697                unsafe {
8698                    sw.setState(isize::from(p.on));
8699                    sw.setEnabled(p.enabled);
8700                    sw.setTarget(Some(&*target));
8701                    sw.setAction(Some(sel!(action:)));
8702                }
8703                let view = view_of(&sw);
8704                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8705                view
8706            }
8707            Some(Builtin::Slider) => {
8708                let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
8709                    return placeholder_view(mtm, kind);
8710                };
8711                let target = DayTarget::new(mtm, id);
8712                let sl = unsafe {
8713                    NSSlider::sliderWithValue_minValue_maxValue_target_action(
8714                        p.value,
8715                        p.min,
8716                        p.max,
8717                        Some(&*target),
8718                        Some(sel!(action:)),
8719                        mtm,
8720                    )
8721                };
8722                unsafe { sl.setContinuous(true) };
8723                let view = view_of(&sl);
8724                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8725                view
8726            }
8727            Some(Builtin::Picker) => picker::realize_any(self, props, id),
8728            Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
8729            Some(Builtin::TextField) => {
8730                let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
8731                    return placeholder_view(mtm, kind);
8732                };
8733                let tf = new_text_field(mtm, id, false);
8734                unsafe {
8735                    tf.setStringValue(&NSString::from_str(&p.text));
8736                    tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
8737                }
8738                view_of(&tf)
8739            }
8740            Some(Builtin::Divider) => {
8741                let b = unsafe { NSBox::new(mtm) };
8742                unsafe { b.setBoxType(NSBoxType::Separator) };
8743                view_of(&b)
8744            }
8745            Some(Builtin::Progress) => {
8746                let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
8747                    return placeholder_view(mtm, kind);
8748                };
8749                if p.value.is_none() {
8750                    return crate::controls::spinner::make(self, p, id);
8751                }
8752                let pi = unsafe { NSProgressIndicator::new(mtm) };
8753                unsafe {
8754                    if let Some(v) = p.value {
8755                        pi.setStyle(NSProgressIndicatorStyle::Bar);
8756                        pi.setIndeterminate(false);
8757                        pi.setMinValue(0.0);
8758                        pi.setMaxValue(1.0);
8759                        pi.setDoubleValue(v);
8760                    } else {
8761                        pi.setStyle(NSProgressIndicatorStyle::Spinning);
8762                        pi.setIndeterminate(true);
8763                        pi.startAnimation(None);
8764                    }
8765                }
8766                view_of(&pi)
8767            }
8768            Some(Builtin::Canvas) => {
8769                let canvas = DayCanvas::new(mtm);
8770                KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
8771                view_of(&canvas)
8772            }
8773            Some(Builtin::Inspector) => {
8774                let (visible, width, leading) =
8775                    props
8776                        .downcast_ref::<InspectorProps>()
8777                        .map_or((false, 280.0, false), |p| {
8778                            (
8779                                p.visible,
8780                                p.width,
8781                                p.edge == day_spec::props::PaneEdge::Leading,
8782                            )
8783                        });
8784                let content_wrap = view_of(&DayFlipped::new(mtm));
8785                let panel_flipped = DayFlipped::new(mtm);
8786                // The panel draws an opaque window-background backdrop over the item's
8787                // vibrancy material — without it the section cards' thin quaternary fill
8788                // composites into near-black in dark mode (see `FlippedIvars`).
8789                panel_flipped.set_pane_backdrop();
8790                let panel_wrap = view_of(&panel_flipped);
8791                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8792                // Force loadView before the items go in — the same lifecycle rule the nav
8793                // host below documents.
8794                let _ = unsafe { split_vc.view() };
8795                let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8796                let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8797                unsafe {
8798                    content_vc.setView(&content_wrap);
8799                    panel_vc.setView(&panel_wrap);
8800                }
8801                let content_item = unsafe {
8802                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
8803                };
8804                // A TRAILING pane is a real inspector item (the system treatment). A LEADING
8805                // one is a plain item placed first: `sidebarWithViewController:` would bring
8806                // sidebar material, which captures black offscreen (docs/navigation.md), and
8807                // the panel wrap already paints its own backdrop.
8808                let panel_item = unsafe {
8809                    if leading {
8810                        objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
8811                    } else {
8812                        objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
8813                    }
8814                };
8815                unsafe {
8816                    // Day's signal is the only visibility driver: with the pinned width the
8817                    // divider has nothing to drag and the pane cannot be user-collapsed, so
8818                    // there is no native-initiated change to report back.
8819                    panel_item.setCanCollapse(false);
8820                    panel_item.setCollapsed(!visible);
8821                    panel_item.setMinimumThickness(width);
8822                    panel_item.setMaximumThickness(width);
8823                    panel_item.setAllowsFullHeightLayout(true);
8824                    if leading {
8825                        split_vc.addSplitViewItem(&panel_item);
8826                        split_vc.addSplitViewItem(&content_item);
8827                    } else {
8828                        split_vc.addSplitViewItem(&content_item);
8829                        split_vc.addSplitViewItem(&panel_item);
8830                    }
8831                }
8832                let split = unsafe { split_vc.splitView() };
8833                unsafe {
8834                    split.setVertical(true);
8835                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8836                    // The same Auto Layout hand-back as the nav host below: Day owns this
8837                    // view's frame outside the split; the controller's own constraints keep
8838                    // doing the pane sizing inside it.
8839                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
8840                }
8841                let view = view_of(&split);
8842                INSPECTOR_STATE.with(|m| {
8843                    m.borrow_mut().insert(
8844                        ptr_of(&view),
8845                        InspectorState {
8846                            content_wrap,
8847                            panel_wrap,
8848                            split_vc,
8849                            panel_item,
8850                        },
8851                    )
8852                });
8853                view
8854            }
8855            Some(Builtin::InspectorPane) => {
8856                // A DayNavPage for its `setFrameSize:` → `FrameChanged` report: the pane's
8857                // frame is native-owned (the split sizes it), exactly like a nav page —
8858                // NAV_PAGES membership is what makes `set_frame` skip it.
8859                let pane = view_of(&DayNavPage::new(mtm, id));
8860                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8861                let panel = props
8862                    .downcast_ref::<InspectorPaneProps>()
8863                    .is_some_and(|p| p.panel);
8864                INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
8865                pane
8866            }
8867            Some(Builtin::Split) => {
8868                let (axis, fraction, min_pane) = props
8869                    .downcast_ref::<SplitProps>()
8870                    .map_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0), |p| {
8871                        (p.axis, p.fraction, p.min_pane)
8872                    });
8873                let wrap = view_of(&DayFlipped::new(mtm));
8874                let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
8875                let first_wrap = view_of(&DayFlipped::new(mtm));
8876                let second_wrap = view_of(&DayFlipped::new(mtm));
8877                unsafe {
8878                    // AppKit's "vertical" is the divider's orientation: panes side by side.
8879                    split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
8880                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8881                    split.addArrangedSubview(&first_wrap);
8882                    split.addArrangedSubview(&second_wrap);
8883                    split.setFrame(wrap.bounds());
8884                    split.setAutoresizingMask(
8885                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8886                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8887                    );
8888                    wrap.addSubview(&split);
8889                }
8890                let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
8891                split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
8892                SPLIT_STATE.with(|m| {
8893                    m.borrow_mut().insert(
8894                        ptr_of(&wrap),
8895                        SplitState {
8896                            split,
8897                            first_wrap,
8898                            second_wrap,
8899                            delegate,
8900                        },
8901                    )
8902                });
8903                wrap
8904            }
8905            Some(Builtin::SplitPane) => {
8906                // A DayNavPage, as an inspector pane: the splitter owns its frame, and its
8907                // `setFrameSize:` reports `FrameChanged`.
8908                let pane = view_of(&DayNavPage::new(mtm, id));
8909                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8910                let second = props
8911                    .downcast_ref::<SplitPaneProps>()
8912                    .is_some_and(|p| p.second);
8913                SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
8914                pane
8915            }
8916            Some(Builtin::Nav) => {
8917                let presentation = props
8918                    .downcast_ref::<NavProps>()
8919                    .map_or(NavPresentation::Split, |p| p.presentation);
8920                let is_split = presentation.is_split();
8921                // The host is an NSSplitViewController, not a bare NSSplitView. Handing the
8922                // sidebar pane to `NSSplitViewItem::sidebarWithViewController:` is what buys
8923                // the system treatment: AppKit installs its own backing material and vibrancy
8924                // (so no hand-rolled NSVisualEffectView), pins the thickness with a sidebar
8925                // holding priority, animates collapse/expand, and drives the window's titlebar
8926                // separator. Day still owns the CONTENT of each pane — the two wraps below are
8927                // the item view controllers' views, so `insert`/`remove`/the NAV patches are
8928                // unchanged.
8929                let sidebar_wrap = view_of(&DayFlipped::new(mtm));
8930                let detail_wrap = view_of(&DayFlipped::new(mtm));
8931                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8932                // Force loadView/viewDidLoad before the items go in. NSSplitViewController
8933                // installs an item's view into the split as the item is added, which it can
8934                // only do once its own view exists — and reading `splitView` does not trigger
8935                // the lifecycle the way reading `view` does. Skipping this leaves a split view
8936                // with zero subviews: correct frame, nothing in it.
8937                let _ = unsafe { split_vc.view() };
8938                // Plain NSViewControllers with their view set explicitly: setting `view` up
8939                // front is what stops NSViewController looking for a nib named after itself.
8940                let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8941                let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8942                unsafe {
8943                    sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8944                    detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8945                }
8946                let sidebar_item = unsafe {
8947                    objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8948                };
8949                let detail_item = unsafe {
8950                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8951                };
8952                // The content-list pane (docs/navigation.md): a REAL `contentList`
8953                // NSSplitViewItem between the sidebar and the detail — Mail's own machinery,
8954                // holding priorities included. Its `Pane::List` page fills `list_wrap` exactly
8955                // as the sidebar page fills its own wrap, and the pane persists through every
8956                // presentation (only `NavPatch::ListVisible` collapses it).
8957                let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8958                // Set before the item joins the split, exactly as the sidebar's is below. A
8959                // collapsed state applied afterwards — by `NavPatch::ListVisible`, on a window
8960                // that has not been displayed — reports as collapsed and is then laid back out
8961                // from the item's holding priorities, which is how an app whose first
8962                // destination has no list opened with one beside it anyway.
8963                let list_visible = props
8964                    .downcast_ref::<NavProps>()
8965                    .is_none_or(|p| p.list_visible);
8966                let (list_wrap, list_item) = match list_width {
8967                    Some(w) => {
8968                        let wrap = view_of(&DayFlipped::new(mtm));
8969                        let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8970                        unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8971                        let item = unsafe {
8972                            objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8973                        };
8974                        unsafe {
8975                            item.setCanCollapse(true);
8976                            item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8977                            item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8978                            item.setCollapsed(!list_visible);
8979                        }
8980                        (Some(wrap), Some(item))
8981                    }
8982                    None => (None, None),
8983                };
8984                unsafe {
8985                    // A stack presentation has no sidebar to show: collapse the (empty) pane
8986                    // and refuse the drag, so the detail owns the full width.
8987                    sidebar_item.setCanCollapse(is_split);
8988                    sidebar_item.setCollapsed(!is_split);
8989                    if is_split {
8990                        // Run the sidebar's material to the top of the window, under the
8991                        // titlebar, the way Mail and Finder do. Pairs with the unified toolbar
8992                        // style the window already uses (toolbar.rs).
8993                        sidebar_item.setAllowsFullHeightLayout(true);
8994                        sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8995                        sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8996                    } else {
8997                        sidebar_item.setMinimumThickness(0.0);
8998                        sidebar_item.setMaximumThickness(0.0);
8999                    }
9000                    split_vc.addSplitViewItem(&sidebar_item);
9001                    if let Some(item) = list_item.as_ref() {
9002                        split_vc.addSplitViewItem(item);
9003                    }
9004                    split_vc.addSplitViewItem(&detail_item);
9005                }
9006                let split = unsafe { split_vc.splitView() };
9007                // NSToolbarToggleSidebarItem sends `toggleSidebar:` down the RESPONDER chain,
9008                // and NSSplitViewController implements it — but a view controller only patches
9009                // itself into that chain when it is parented (a window's contentViewController
9010                // or another controller's child), and Day's tree is view-based all the way to
9011                // the window. Insert it by hand, directly after the split view, so a first
9012                // responder anywhere inside either pane walks up through it.
9013                unsafe {
9014                    let after = split.nextResponder();
9015                    split.setNextResponder(Some(&split_vc));
9016                    // The controller must never end up aiming at itself or at its OWN view,
9017                    // or its dealloc aborts the process: `-[NSViewController dealloc]`
9018                    // splices itself out with `view.nextResponder = self.nextResponder`, and
9019                    // if that lands the view on itself AppKit raises "The next responder
9020                    // should never be yourself!" — an NSException that unwinds into Rust and
9021                    // aborts. Both shapes occur here naturally: before macOS 15 the freshly
9022                    // loaded split view's next IS the controller, and on 15+ `view` is a
9023                    // WRAPPER above `splitView` whose auto-wiring makes the split's next
9024                    // that wrapper. Neither is a real upstream hop, so drop them.
9025                    let own_view = split_vc.view();
9026                    let vc_resp: *const objc2_app_kit::NSResponder = {
9027                        let r: &objc2_app_kit::NSResponder = &split_vc;
9028                        r
9029                    };
9030                    let view_resp: *const objc2_app_kit::NSResponder = {
9031                        let r: &objc2_app_kit::NSResponder = &own_view;
9032                        r
9033                    };
9034                    let upstream = after.filter(|a| {
9035                        let p: *const objc2_app_kit::NSResponder = &raw const **a;
9036                        p != vc_resp && p != view_resp
9037                    });
9038                    split_vc.setNextResponder(upstream.as_deref());
9039                }
9040                unsafe {
9041                    split.setVertical(true);
9042                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
9043                    // Day owns this view's frame (`set_frame`). A split view vended by
9044                    // NSSplitViewController arrives switched over to Auto Layout, which
9045                    // ignores that frame and lays the split out at zero — a window with
9046                    // chrome and nothing under it. Hand it back to autoresizing translation
9047                    // so Day stays the layout owner outside the split; the constraints the
9048                    // controller installs BETWEEN the split and its panes are untouched and
9049                    // keep doing the pane sizing.
9050                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
9051                }
9052                let root_title = props
9053                    .downcast_ref::<NavProps>()
9054                    .map_or_default(|p| p.title.clone());
9055                // Stack presentation: a back header (hidden at root) — desktop has no system
9056                // back affordance, so a pushed page needs its own way out (docs/navigation.md).
9057                let header = if presentation == NavPresentation::Stack {
9058                    Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
9059                } else {
9060                    None
9061                };
9062                // A tabs host: the Mac's own tab control fills the detail pane and takes the
9063                // detail pages as its items (`TabHost`).
9064                let tabs = (presentation == NavPresentation::Tabs).then(|| {
9065                    let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
9066                    let documents = props
9067                        .downcast_ref::<NavProps>()
9068                        .is_some_and(|p| p.documents.is_some());
9069                    // Inset from the pane, the way a tab view sits in any Mac window: its
9070                    // tabs stand above the bezel, so flush to the top they run into the
9071                    // toolbar's edge, and flush to the sides the bezel hugs the sidebar. The
9072                    // autoresizing mask keeps the margins as the pane resizes. A document host
9073                    // draws no tabs and no bezel, so its pages fill the pane edge to edge.
9074                    let (inset, inset_top) = if documents {
9075                        (0.0, 0.0)
9076                    } else {
9077                        (NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP)
9078                    };
9079                    let b = detail_wrap.bounds();
9080                    let frame = NSRect::new(
9081                        NSPoint::new(inset, inset_top),
9082                        NSSize::new(
9083                            (b.size.width - 2.0 * inset).max(0.0),
9084                            (b.size.height - inset_top - inset).max(0.0),
9085                        ),
9086                    );
9087                    unsafe {
9088                        tv.setTabViewType(if documents {
9089                            objc2_app_kit::NSTabViewType::NoTabsNoBorder
9090                        } else {
9091                            objc2_app_kit::NSTabViewType::TopTabsBezelBorder
9092                        });
9093                        tv.setFrame(frame);
9094                        tv.setAutoresizingMask(
9095                            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9096                                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9097                        );
9098                        detail_wrap.addSubview(&tv);
9099                    }
9100                    TabHost {
9101                        view: tv,
9102                        target: None,
9103                    }
9104                });
9105                let view = view_of(&split);
9106                NAV_STATE.with(|m| {
9107                    m.borrow_mut().insert(
9108                        ptr_of(&view),
9109                        NavState {
9110                            sidebar_wrap,
9111                            detail_wrap,
9112                            split_vc,
9113                            sidebar_item,
9114                            list_wrap,
9115                            list_item,
9116                            pages: Vec::new(),
9117                            list_page: None,
9118                            sidebar_page: None,
9119                            list_width,
9120                            list_visible,
9121                            list_positioned: false,
9122                            positioned: false,
9123                            presentation,
9124                            selected: 0,
9125                            tabs,
9126                            header,
9127                            root_title,
9128                            node: id,
9129                            title_strip: 0.0,
9130                        },
9131                    )
9132                });
9133                view
9134            }
9135            Some(Builtin::NavPage) => {
9136                let page = view_of(&DayNavPage::new(mtm, id));
9137                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
9138                if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
9139                    PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
9140                }
9141                page
9142            }
9143            // Emulated fullscreen cover (docs/cover.md, the ArkUI tier): a DayNavPage — its
9144            // setFrameSize: override reports FrameChanged, so a window resize re-lays the cover
9145            // content for free — parked hidden until CoverPatch::Present re-homes it on top.
9146            Some(Builtin::Cover) => {
9147                let page = DayNavPage::new(mtm, id);
9148                let cover_props = props.downcast_ref::<CoverProps>();
9149                // A half sheet is a sheet here: macOS has no half-height presentation of its
9150                // own, so the window sheet stands in, at half the parent's height.
9151                page.ivars()
9152                    .sheet
9153                    .set(cover_props.is_some_and(|p| p.sheet || p.half));
9154                page.ivars().half.set(cover_props.is_some_and(|p| p.half));
9155                page.ivars().large.set(cover_props.is_some_and(|p| p.large));
9156                unsafe { page.setHidden(true) };
9157                view_of(&page)
9158            }
9159            Some(Builtin::NavMenu) => {
9160                let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
9161                    return placeholder_view(mtm, kind);
9162                };
9163                let data = DayNavMenuData::new(
9164                    mtm,
9165                    id,
9166                    &p.items,
9167                    &p.icons,
9168                    &p.badges,
9169                    &p.badge_icons,
9170                    &p.badge_tints,
9171                    &p.sections,
9172                    &p.tints,
9173                    &p.menus,
9174                );
9175                (*data.ivars().movable.borrow_mut()).clone_from(&p.movable);
9176                data.ivars().regroup.set(p.regroup);
9177                (*data.ivars().sorted.borrow_mut()).clone_from(&p.sorted);
9178                // The Day subclass serves per-row context menus via menuForEvent:.
9179                let outline: Retained<objc2_app_kit::NSOutlineView> = {
9180                    let o: Retained<DayNavOutlineView> =
9181                        unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
9182                    NAV_OUTLINE_MENUS
9183                        .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
9184                    unsafe { msg_send![&*o, self] }
9185                };
9186                let col = unsafe {
9187                    objc2_app_kit::NSTableColumn::initWithIdentifier(
9188                        objc2_app_kit::NSTableColumn::alloc(mtm),
9189                        &NSString::from_str("item"),
9190                    )
9191                };
9192                unsafe {
9193                    outline.addTableColumn(&col);
9194                    outline.setOutlineTableColumn(Some(&col));
9195                    outline.setHeaderView(None);
9196                    // SourceList: the real sidebar treatment (Finder/Mail). The outline now
9197                    // lives inside a sidebar NSSplitViewItem, so AppKit supplies the backing
9198                    // material and the vibrancy the source-list selection composites through.
9199                    // This was Inset until 2026-08 because the earlier hand-rolled
9200                    // NSVisualEffectView blended behind the window, and an offscreen capture
9201                    // (`cacheDisplayInRect`) has no backdrop to sample — the selection came out
9202                    // a black pill that swallowed the row label. The material is AppKit's own
9203                    // now, and captures go through the window server (`snapshot_view`), which
9204                    // composites the material for real instead of guessing at it.
9205                    // `style = SourceList` is the whole switch: the matching
9206                    // `selectionHighlightStyle` constant is deprecated precisely because the
9207                    // style property now implies it.
9208                    outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
9209                    // The default row size style follows the system's Sidebar icon size
9210                    // (Small, Medium, Large), live, as Finder's and Mail's sidebars do: AppKit
9211                    // sets the row height, the label's font and the icon's size. A table made
9212                    // in code starts at Custom, which ignores the setting.
9213                    outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
9214                    // Section headers pin to the top of the scroll as their group passes under
9215                    // it, the way Finder's sidebar groups do.
9216                    outline.setFloatsGroupRows(true);
9217                    outline.setIndentationPerLevel(0.0);
9218                    // Drag-to-reorder within this sidebar only (docs/navigation.md): rows that
9219                    // cannot move offer no drag, so registering costs a plain sidebar nothing.
9220                    outline.registerForDraggedTypes(
9221                        &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9222                            DAY_NAV_PASTEBOARD_TYPE,
9223                        )]),
9224                    );
9225                    outline.setDraggingSourceOperationMask_forLocal(
9226                        objc2_app_kit::NSDragOperation::Move,
9227                        true,
9228                    );
9229                    outline.setDraggingSourceOperationMask_forLocal(
9230                        objc2_app_kit::NSDragOperation::None,
9231                        false,
9232                    );
9233                    outline.setDraggingDestinationFeedbackStyle(
9234                        objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
9235                    );
9236                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9237                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9238                    outline.reloadData();
9239                }
9240                let scroll = unsafe { NSScrollView::new(mtm) };
9241                unsafe {
9242                    scroll.setDrawsBackground(false);
9243                    scroll.setHasVerticalScroller(true);
9244                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
9245                    // clip the trailing edge of rows laid out at the full frame width (see
9246                    // the SCROLL realize).
9247                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9248                    // One column, sized to the pane: a sidebar never scrolls sideways.
9249                    scroll.setHasHorizontalScroller(false);
9250                    outline.setAutoresizingMask(
9251                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
9252                    );
9253                    outline.setColumnAutoresizingStyle(
9254                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9255                    );
9256                    scroll.setDocumentView(Some(&outline));
9257                }
9258                let view = view_of(&scroll);
9259                // Day selects by ITEM index; section headers make that differ from the
9260                // outline's row index, so every programmatic selection maps through `rows`.
9261                if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
9262                    data.ivars().suppress.set(true);
9263                    unsafe {
9264                        outline.selectRowIndexes_byExtendingSelection(
9265                            &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9266                            false,
9267                        );
9268                    };
9269                    data.ivars().suppress.set(false);
9270                }
9271                NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
9272                view
9273            }
9274            Some(Builtin::List) => {
9275                let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
9276                    return placeholder_view(mtm, kind);
9277                };
9278                // Every list reports responder changes, even without an activation handler.
9279                let table: Retained<DayListView> =
9280                    unsafe { msg_send![DayListView::alloc(mtm), init] };
9281                let table = Retained::into_super(table);
9282                if p.inset_grouped {
9283                    // macOS 11's inset style: rows set in from the edges with rounded selection,
9284                    // the grouped look `ListProps::inset_grouped` asks for.
9285                    unsafe { table.setStyle(objc2_app_kit::NSTableViewStyle::Inset) };
9286                }
9287                let col = unsafe {
9288                    NSTableColumn::initWithIdentifier(
9289                        NSTableColumn::alloc(mtm),
9290                        &NSString::from_str("day.list.col"),
9291                    )
9292                };
9293                let data = DayListData::new(
9294                    mtm,
9295                    id,
9296                    p.selectable,
9297                    p.multi_select,
9298                    p.row_height == RowHeight::Automatic,
9299                    p.sections,
9300                );
9301                unsafe {
9302                    if p.multi_select {
9303                        table.setAllowsMultipleSelection(true);
9304                    }
9305                    table.addTableColumn(&col);
9306                    table.setHeaderView(None);
9307                    // PLAIN, the classic edge-to-edge style: the macOS 11+ decorated styles
9308                    // (automatic ~14pt, FullWidth ~6pt) inset every cell view, clipping day
9309                    // row content laid out at the host's full frame width. This table ran
9310                    // FullWidth with a custom NSTableRowView pinning cells back to the row
9311                    // bounds until 2026-08 — and that pin also clobbered the cell-frame slide
9312                    // AppKit performs for row-action swipes, so the actions revealed behind a
9313                    // row whose CONTENT never moved. Plain has no inset to fight: standard
9314                    // row views, standard cell frames, and the swipe slide works untouched.
9315                    table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
9316                    // ...and the default intercell spacing (3pt × 2pt) shaves the column the
9317                    // same way — the last few points of a trailing control. Day rows own all
9318                    // of their spacing.
9319                    table.setIntercellSpacing(NSSize::new(0.0, 0.0));
9320                    // Host-drawn row separators (docs/list.md): the native horizontal grid
9321                    // line, which sits exactly at the row boundary — aligned with the
9322                    // selection, stationary under a row-action swipe, the Mail look.
9323                    if p.separators == Some(true) {
9324                        table.setGridStyleMask(
9325                            objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
9326                        );
9327                        table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
9328                    }
9329                    table.setColumnAutoresizingStyle(
9330                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9331                    );
9332                    // Section headers pin to the top while their section scrolls under them,
9333                    // the way Mail's and Finder's group rows do (docs/list.md "Sections").
9334                    table.setFloatsGroupRows(p.sections);
9335                    match p.row_height {
9336                        RowHeight::Uniform(h) => table.setRowHeight(h),
9337                        RowHeight::Automatic => table.setRowHeight(44.0),
9338                    }
9339                    if !p.selectable {
9340                        table.setSelectionHighlightStyle(
9341                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
9342                        );
9343                    }
9344                    // Transparent: day panes own their backgrounds — the stock
9345                    // controlBackgroundColor would paint an appearance-colored slab that
9346                    // fights a themed app (visible whenever rows don't fill the viewport).
9347                    table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
9348                    table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9349                    table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9350                    table.setTarget(Some(&*data));
9351                    if p.activatable {
9352                        table.setDoubleAction(Some(sel!(doubleClickRow:)));
9353                    }
9354                    if p.reorderable {
9355                        // Native drag-to-reorder (docs/list.md): rows drag within this table
9356                        // only (move locally, nothing leaves the app), and the drop target shows
9357                        // macOS's temporary placeholder GAP while the drag is over the table.
9358                        table.registerForDraggedTypes(
9359                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9360                                DAY_ROW_PASTEBOARD_TYPE,
9361                            )]),
9362                        );
9363                        table.setDraggingSourceOperationMask_forLocal(
9364                            objc2_app_kit::NSDragOperation::Move,
9365                            true,
9366                        );
9367                        table.setDraggingSourceOperationMask_forLocal(
9368                            objc2_app_kit::NSDragOperation::None,
9369                            false,
9370                        );
9371                        table.setDraggingDestinationFeedbackStyle(
9372                            objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
9373                        );
9374                    }
9375                }
9376                let scroll = unsafe { NSScrollView::new(mtm) };
9377                unsafe {
9378                    scroll.setDrawsBackground(false);
9379                    scroll.setHasVerticalScroller(true);
9380                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
9381                    // clip the trailing edge of rows laid out at the full frame width (see
9382                    // the SCROLL realize).
9383                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9384                    scroll.setDocumentView(Some(&table));
9385                    let clip = scroll.contentView();
9386                    clip.setPostsBoundsChangedNotifications(true);
9387                    objc2_foundation::NSNotificationCenter::defaultCenter()
9388                        .addObserver_selector_name_object(
9389                            &data,
9390                            sel!(listViewportChanged:),
9391                            Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
9392                            Some(&clip),
9393                        );
9394                }
9395                let view = view_of(&scroll);
9396                LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
9397                view
9398            }
9399            Some(Builtin::Tree) => {
9400                let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
9401                    return placeholder_view(mtm, kind);
9402                };
9403                // The width-pinning subclass (see DayOutlineView).
9404                let outline: Retained<objc2_app_kit::NSOutlineView> = {
9405                    let o: Retained<DayOutlineView> =
9406                        unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
9407                    unsafe { msg_send![&*o, self] }
9408                };
9409                let col = unsafe {
9410                    NSTableColumn::initWithIdentifier(
9411                        NSTableColumn::alloc(mtm),
9412                        &NSString::from_str("day.tree.col"),
9413                    )
9414                };
9415                let data = DayTreeData::new(mtm, id, p.selectable);
9416                unsafe {
9417                    if p.multi_select {
9418                        outline.setAllowsMultipleSelection(true);
9419                    }
9420                    outline.addTableColumn(&col);
9421                    outline.setOutlineTableColumn(Some(&col));
9422                    outline.setHeaderView(None);
9423                    if p.section_headers {
9424                        // Real source-list groups use AppKit's trailing, hover-revealed
9425                        // show/hide button and float over their children while scrolling.
9426                        outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
9427                        outline.setFloatsGroupRows(true);
9428                    } else {
9429                        // Generic trees keep their existing full-width cells and rounded
9430                        // DayTreeRowView selection. Source lists use native row drawing.
9431                        outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
9432                        outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
9433                    }
9434                    outline.setColumnAutoresizingStyle(
9435                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9436                    );
9437                    outline.setAutoresizesOutlineColumn(true);
9438                    if let Some(indent) = p.indent {
9439                        outline.setIndentationPerLevel(indent);
9440                    }
9441                    match p.row_height {
9442                        RowHeight::Uniform(h) => outline.setRowHeight(h),
9443                        RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
9444                        RowHeight::Automatic => {}
9445                    }
9446                    if !p.selectable {
9447                        outline.setSelectionHighlightStyle(
9448                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
9449                        );
9450                    }
9451                    outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
9452                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9453                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9454                    if p.movable {
9455                        // Native drag-to-move (docs/tree.md): nodes drag within this outline
9456                        // only. The REGULAR feedback style (not the list's Gap): a tree drop
9457                        // must distinguish "between rows" (insertion line) from "ONTO a row"
9458                        // (the highlighted-parent drop), and Gap has no onto affordance.
9459                        outline.registerForDraggedTypes(
9460                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9461                                DAY_TREE_PASTEBOARD_TYPE,
9462                            )]),
9463                        );
9464                        outline.setDraggingSourceOperationMask_forLocal(
9465                            objc2_app_kit::NSDragOperation::Move,
9466                            true,
9467                        );
9468                        outline.setDraggingSourceOperationMask_forLocal(
9469                            objc2_app_kit::NSDragOperation::None,
9470                            false,
9471                        );
9472                    }
9473                }
9474                let scroll = unsafe { NSScrollView::new(mtm) };
9475                unsafe {
9476                    scroll.setDrawsBackground(false);
9477                    scroll.setHasVerticalScroller(true);
9478                    scroll.setHasHorizontalScroller(false);
9479                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9480                    outline.setAutoresizingMask(
9481                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
9482                    );
9483                    scroll.setDocumentView(Some(&outline));
9484                }
9485                let view = view_of(&scroll);
9486                TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
9487                view
9488            }
9489            Some(Builtin::Image) => {
9490                let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
9491                    return placeholder_view(mtm, kind);
9492                };
9493                let iv: Retained<objc2_app_kit::NSImageView> =
9494                    if p.content_mode == ContentMode::Fill {
9495                        let view: Retained<FillImageView> =
9496                            unsafe { msg_send![FillImageView::alloc(mtm), init] };
9497                        Retained::from(
9498                            <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
9499                        )
9500                    } else {
9501                        unsafe { objc2_app_kit::NSImageView::new(mtm) }
9502                    };
9503                // Fill expands the native aspect-fit drawing in FillImageView; Stretch
9504                // scales each axis independently, and Fit keeps the stock image view.
9505                let scaling = match p.content_mode {
9506                    ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
9507                    _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
9508                };
9509                unsafe { iv.setImageScaling(scaling) };
9510                if let Some(img) = appkit_image_for(&p.source) {
9511                    // Vector-glyph tint (docs/vectors.md): template rendering + the view's
9512                    // content tint — AppKit recolors the alpha mask natively. A template with
9513                    // no tint keeps the view's nil tint: the neutral template color the nav
9514                    // menu's own rows draw with, light in dark mode, dark in light.
9515                    if p.tint.is_some() || p.template {
9516                        unsafe { img.setTemplate(true) };
9517                    }
9518                    unsafe { iv.setImage(Some(&img)) };
9519                }
9520                if let Some(t) = p.tint {
9521                    unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
9522                }
9523                IMAGE_MODES.with(|t| {
9524                    t.insert(
9525                        ptr_of(&iv),
9526                        ImageMode {
9527                            template: p.template,
9528                            tinted: p.tint.is_some(),
9529                        },
9530                    )
9531                });
9532                view_of(&iv)
9533            }
9534            Some(Builtin::ListItem) => {
9535                let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
9536                else {
9537                    return placeholder_view(mtm, kind);
9538                };
9539                make_list_item(p, mtm)
9540            }
9541            // A recycled list cell is ADOPTED from the native list, never realized
9542            // through this path; anything else is an extension piece.
9543            Some(Builtin::ListCell) | None => {
9544                if let Some(make) = self.registry.get(kind).map(|r| r.make) {
9545                    return make(self, props, id);
9546                }
9547                // Unregistered kind: LOUD once-per-kind warning, then a visible-but-harmless
9548                // placeholder (§8.2's debug check will panic first in debug builds once the
9549                // required-kinds set lands).
9550                warn_missing_renderer(kind);
9551                placeholder_view(mtm, kind)
9552            }
9553        }
9554    }
9555
9556    fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
9557        match kind {
9558            kinds::LIST_ITEM => {
9559                let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
9560                    return;
9561                };
9562                let props = LIST_ITEMS.with(|m| {
9563                    use day_spec::props::ListItemPatch as P;
9564                    let mut m = m.borrow_mut();
9565                    let props = m.get_mut(&ptr_of(h))?;
9566                    match p {
9567                        P::Title(t) => props.title.clone_from(t),
9568                        P::Subtitle(t) => props.subtitle.clone_from(t),
9569                        P::Detail(t) => props.detail.clone_from(t),
9570                        P::Icon(i) => props.icon.clone_from(i),
9571                        P::IconTint(c) => props.icon_tint = *c,
9572                        P::Checked(on) => props.checked = *on,
9573                    }
9574                    Some(props.clone())
9575                });
9576                if let Some(props) = props {
9577                    dress_list_item(h, &props, self.mtm());
9578                }
9579            }
9580            kinds::IMAGE => {
9581                if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
9582                    match p {
9583                        day_spec::props::ImagePatch::Tint(c) => {
9584                            // Template rendering + the view's content tint, exactly as at realize
9585                            // — the glyph repaints in place rather than being rebuilt
9586                            // (docs/vectors.md). A template glyph stays one when the tint goes.
9587                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
9588                                let key = ptr_of(&iv);
9589                                let template = IMAGE_MODES
9590                                    .with(|t| {
9591                                        t.with(key, |m| {
9592                                            m.tinted = c.is_some();
9593                                            m.renders_template()
9594                                        })
9595                                    })
9596                                    .unwrap_or(c.is_some());
9597                                if let Some(img) = unsafe { iv.image() } {
9598                                    unsafe { img.setTemplate(template) };
9599                                }
9600                                unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
9601                            }
9602                        }
9603                        // A source swap repaints the same view (docs/images.md), so an `image()`
9604                        // bound to a signal shows new pixels without rebuilding its subtree —
9605                        // which is what makes a decode-then-show flow a patch and not a rebuild.
9606                        day_spec::props::ImagePatch::Source(source) => {
9607                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
9608                                // A source that will not load leaves the view showing what it
9609                                // was — the patch's contract, and what GTK, Qt and Android do.
9610                                // The new image renders the way the view does: a tinted or
9611                                // template glyph stays one, so a recycled sidebar row shows the
9612                                // icon it was rebound to in the same color.
9613                                if let Some(img) = appkit_image_for(source) {
9614                                    let template = IMAGE_MODES
9615                                        .with(|t| t.get(ptr_of(&iv)))
9616                                        .is_some_and(ImageMode::renders_template);
9617                                    unsafe {
9618                                        img.setTemplate(template);
9619                                        iv.setImage(Some(&img));
9620                                    }
9621                                }
9622                            }
9623                        }
9624                    }
9625                }
9626            }
9627            kinds::CONTAINER => {
9628                if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
9629                    patch.downcast_ref::<ContainerPatch>(),
9630                    h.clone().downcast::<DayFlipped>(),
9631                ) {
9632                    // A background patch only targets a background container (corner radius 0).
9633                    // The AnimSpec is not honored: the fill is drawRect content
9634                    // (rasterized by our own drawing code so dynamic system colors re-resolve
9635                    // per appearance), not a CALayer property, and Core Animation only
9636                    // interpolates layer properties, so there is nothing for the render server
9637                    // to tween. Day animates only what the toolkit's animator can execute
9638                    // (§8.4), so an animated background change applies at commit here.
9639                    v.set_surface(*c, 0.0, false);
9640                }
9641            }
9642            kinds::LABEL => {
9643                if let (Some(p), Ok(tf)) = (
9644                    patch.downcast_ref::<LabelPatch>(),
9645                    h.clone().downcast::<NSTextField>(),
9646                ) {
9647                    match p {
9648                        LabelPatch::Text(t) => {
9649                            unsafe { tf.setStringValue(&NSString::from_str(t)) };
9650                            if let Some(label) = h.downcast_ref::<DayLabel>() {
9651                                label.ivars().has_runs.set(false);
9652                                label.set_links(false);
9653                            }
9654                        }
9655                        LabelPatch::Color(c) => unsafe {
9656                            tf.setTextColor(c.map(nscolor).as_deref());
9657                        },
9658                        LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
9659                        LabelPatch::Runs(text, runs) => {
9660                            // The field's current font is the base the runs sit on, taken as the
9661                            // live object rather than rebuilt from a `FontSpec`, which would lose
9662                            // the semantic style behind the resolved size.
9663                            let base = unsafe { tf.font() };
9664                            let s = match base.as_deref() {
9665                                Some(f) => {
9666                                    attributed_label(text, f, None, TextRole::default(), runs)
9667                                }
9668                                None => attributed_label(
9669                                    text,
9670                                    &nsfont(day_spec::FontSpec::default()),
9671                                    None,
9672                                    TextRole::default(),
9673                                    runs,
9674                                ),
9675                            };
9676                            unsafe { tf.setAttributedStringValue(&s) };
9677                            // Preserve paragraph alignment and activate links introduced by a
9678                            // reactive markdown update without replacing the native label.
9679                            set_paragraph_alignment(&tf, unsafe { tf.alignment() });
9680                            if let Some(label) = h.downcast_ref::<DayLabel>() {
9681                                label.ivars().has_runs.set(!runs.is_empty());
9682                                label.set_links(runs.iter().any(|r| r.link.is_some()));
9683                            }
9684                        }
9685                    }
9686                }
9687            }
9688            kinds::BUTTON => {
9689                if let (Some(p), Ok(btn)) = (
9690                    patch.downcast_ref::<ButtonPatch>(),
9691                    h.clone().downcast::<NSButton>(),
9692                ) {
9693                    match p {
9694                        ButtonPatch::Content(c) => {
9695                            apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only);
9696                        }
9697                        ButtonPatch::Title(t) => {
9698                            let style = BUTTON_STYLES
9699                                .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
9700                                .unwrap_or_default();
9701                            set_button_title(&btn, t, style);
9702                        }
9703                        ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
9704                        ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
9705                        ButtonPatch::Style(s) => apply_button_style(&btn, *s),
9706                    }
9707                }
9708            }
9709            kinds::TOGGLE => {
9710                if let (Some(p), Ok(sw)) = (
9711                    patch.downcast_ref::<TogglePatch>(),
9712                    h.clone().downcast::<NSSwitch>(),
9713                ) {
9714                    match p {
9715                        TogglePatch::On(on) => {
9716                            let want = isize::from(*on);
9717                            if unsafe { sw.state() } != want {
9718                                unsafe { sw.setState(want) };
9719                            }
9720                        }
9721                        TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
9722                    }
9723                }
9724            }
9725            kinds::SLIDER => {
9726                if let (Some(p), Ok(sl)) = (
9727                    patch.downcast_ref::<SliderPatch>(),
9728                    h.clone().downcast::<NSSlider>(),
9729                ) {
9730                    match p {
9731                        SliderPatch::Value(v) => {
9732                            if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
9733                                unsafe { sl.setDoubleValue(*v) };
9734                            }
9735                        }
9736                        SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
9737                    }
9738                }
9739            }
9740            kinds::PROGRESS => {
9741                if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
9742                {
9743                    crate::controls::spinner::update(self, h, p);
9744                    return;
9745                }
9746
9747                if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
9748                    patch.downcast_ref::<ProgressPatch>(),
9749                    h.clone().downcast::<NSProgressIndicator>(),
9750                ) {
9751                    unsafe {
9752                        if let Some(val) = v {
9753                            if pi.isIndeterminate() {
9754                                pi.stopAnimation(None);
9755                                pi.setIndeterminate(false);
9756                                pi.setStyle(NSProgressIndicatorStyle::Bar);
9757                                pi.setMinValue(0.0);
9758                                pi.setMaxValue(1.0);
9759                            }
9760                            if (pi.doubleValue() - val).abs() > 0.0001 {
9761                                pi.setDoubleValue(*val);
9762                            }
9763                        } else {
9764                            pi.setIndeterminate(true);
9765                            pi.setStyle(NSProgressIndicatorStyle::Spinning);
9766                            pi.startAnimation(None);
9767                        }
9768                    }
9769                }
9770            }
9771            kinds::NAV_MENU => {
9772                if let Some(NavMenuPatch::Items {
9773                    items,
9774                    icons,
9775                    badges,
9776                    badge_icons,
9777                    badge_tints,
9778                    sections,
9779                    tints,
9780                    menus,
9781                    movable,
9782                    sorted,
9783                    selected,
9784                    rows_changed,
9785                    ..
9786                }) = patch.downcast_ref::<NavMenuPatch>()
9787                {
9788                    NAV_MENUS.with(|m| {
9789                        let m = m.borrow();
9790                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
9791                            return;
9792                        };
9793                        (*data.ivars().movable.borrow_mut()).clone_from(movable);
9794                        (*data.ivars().sorted.borrow_mut()).clone_from(sorted);
9795                        data.set_items(
9796                            items,
9797                            icons,
9798                            badges,
9799                            badge_icons,
9800                            badge_tints,
9801                            sections,
9802                            tints,
9803                            menus,
9804                        );
9805                        data.ivars().suppress.set(true);
9806                        // The same rows with new words or counts: reload just those rows, which
9807                        // keeps the selection and every other row's view.
9808                        if let Some(rows) = rows_changed {
9809                            let set = objc2_foundation::NSMutableIndexSet::new();
9810                            for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
9811                                unsafe { set.addIndex(row) };
9812                            }
9813                            unsafe {
9814                                outline.reloadDataForRowIndexes_columnIndexes(
9815                                    &set,
9816                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
9817                                );
9818                            };
9819                            data.ivars().suppress.set(false);
9820                            return;
9821                        }
9822                        unsafe {
9823                            outline.reloadData();
9824                            match selected.and_then(|i| data.row_of_item(i)) {
9825                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
9826                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9827                                    false,
9828                                ),
9829                                None => outline.deselectAll(None),
9830                            }
9831                        }
9832                        data.ivars().suppress.set(false);
9833                    });
9834                    // The rows are a tabs host's labels where the menu sits in one.
9835                    adopt_menu_for_tabs(self.mtm(), h);
9836                } else if let Some(NavMenuPatch::IconProgress(progress)) =
9837                    patch.downcast_ref::<NavMenuPatch>()
9838                {
9839                    NAV_MENUS.with(|menus| {
9840                        let menus = menus.borrow();
9841                        let Some((outline, data)) = menus.get(&ptr_of(h)) else {
9842                            return;
9843                        };
9844                        let previous = data.ivars().icon_progress.replace(progress.clone());
9845                        for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
9846                            let Some(index) = item else {
9847                                continue;
9848                            };
9849                            let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
9850                            if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
9851                                continue;
9852                            }
9853                            if let Some(view) = unsafe {
9854                                outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
9855                            } && let Some(cell) =
9856                                view.downcast_ref::<objc2_app_kit::NSTableCellView>()
9857                                && let Some(icon) = unsafe { cell.imageView() }
9858                            {
9859                                nav_progress::update(&icon, value);
9860                            }
9861                        }
9862                    });
9863                } else if let Some(NavMenuPatch::Selected(sel)) =
9864                    patch.downcast_ref::<NavMenuPatch>()
9865                {
9866                    NAV_MENUS.with(|m| {
9867                        let m = m.borrow();
9868                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
9869                            return;
9870                        };
9871                        data.ivars().suppress.set(true);
9872                        unsafe {
9873                            match sel.and_then(|i| data.row_of_item(i)) {
9874                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
9875                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9876                                    false,
9877                                ),
9878                                None => outline.deselectAll(None),
9879                            }
9880                        }
9881                        data.ivars().suppress.set(false);
9882                    });
9883                }
9884            }
9885            kinds::INSPECTOR => {
9886                if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
9887                    INSPECTOR_STATE.with(|m| {
9888                        if let Some(state) = m.borrow().get(&ptr_of(h)) {
9889                            // Directly, not through the animator proxy: a screenshot must not
9890                            // catch a mid-animation pane (the sidebar-toggle rule).
9891                            state.panel_item.setCollapsed(!*v);
9892                        }
9893                    });
9894                }
9895            }
9896            kinds::SPLIT => {
9897                if let Some(p) = patch.downcast_ref::<SplitPatch>() {
9898                    SPLIT_STATE.with(|m| {
9899                        let m = m.borrow();
9900                        let Some(state) = m.get(&ptr_of(h)) else {
9901                            return;
9902                        };
9903                        let iv = state.delegate.ivars();
9904                        match p {
9905                            SplitPatch::Fraction(f) => {
9906                                iv.share.set(f.clamp(0.0, 1.0));
9907                                if iv.positioned.get() {
9908                                    split_place(&state.split, iv);
9909                                }
9910                            }
9911                            SplitPatch::Axis(axis) => unsafe {
9912                                state
9913                                    .split
9914                                    .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
9915                                state.split.adjustSubviews();
9916                                if iv.positioned.get() {
9917                                    split_place(&state.split, iv);
9918                                }
9919                            },
9920                        }
9921                    });
9922                }
9923            }
9924            kinds::NAV => {
9925                if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
9926                    nav_present(self.mtm(), h, *next);
9927                    return;
9928                }
9929                if let Some(p) = patch.downcast_ref::<NavPatch>() {
9930                    NAV_STATE.with(|m| {
9931                        let mut m = m.borrow_mut();
9932                        let Some(state) = m.get_mut(&ptr_of(h)) else {
9933                            return;
9934                        };
9935                        match p {
9936                            NavPatch::Pushed { title, .. } => {
9937                                // Only the new top detail page stays visible.
9938                                let last = state.pages.len().saturating_sub(1);
9939                                state.selected = last;
9940                                for (i, page) in state.pages.iter().enumerate() {
9941                                    page.setHidden(i != last);
9942                                }
9943                                if let Some(hdr) = state.header.as_mut() {
9944                                    hdr.titles.push(title.clone());
9945                                    sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9946                                }
9947                            }
9948                            NavPatch::Popped => {
9949                                // Hide the outgoing top; reveal its predecessor (Day
9950                                // removes the popped page right after this patch).
9951                                let n = state.pages.len();
9952                                if let Some(top) = state.pages.last() {
9953                                    top.setHidden(true);
9954                                }
9955                                if n >= 2 {
9956                                    state.pages[n - 2].setHidden(false);
9957                                }
9958                                state.selected = n.saturating_sub(2);
9959                                if let Some(hdr) = state.header.as_mut() {
9960                                    if hdr.titles.len() > 1 {
9961                                        hdr.titles.pop();
9962                                    }
9963                                    // The popped page is still in `pages` here (Day removes
9964                                    // it right after this patch), so frame for depth-after-pop.
9965                                    let after: Vec<Retained<NSView>> = state
9966                                        .pages
9967                                        .iter()
9968                                        .take(n.saturating_sub(1))
9969                                        .cloned()
9970                                        .collect();
9971                                    sync_nav_header(hdr, &state.detail_wrap, &after);
9972                                }
9973                            }
9974                            NavPatch::Title(t) => {
9975                                if let Some(hdr) = state.header.as_mut() {
9976                                    if let Some(last) = hdr.titles.last_mut() {
9977                                        last.clone_from(t);
9978                                    }
9979                                    unsafe {
9980                                        hdr.title.setStringValue(&NSString::from_str(t));
9981                                    }
9982                                }
9983                            }
9984                            // The custom back header always routes back through Day
9985                            // (NavBack{already_popped:false}), so there is no native auto-pop to
9986                            // suppress; the guard runs in the pieces layer (docs/navigation.md).
9987                            #[expect(
9988                                clippy::match_same_arms,
9989                                reason = "each no-op patch keeps its own arm and the comment saying why it is one"
9990                            )]
9991                            NavPatch::GuardTop(_) => {}
9992                            NavPatch::Reorder(order) => {
9993                                let old = state.pages.clone();
9994                                state.pages =
9995                                    order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9996                                if let Some(tabs) = &state.tabs {
9997                                    TAB_PICK_SUPPRESS.with(|s| s.set(true));
9998                                    unsafe {
9999                                        let items = tabs.view.tabViewItems();
10000                                        for item in &items {
10001                                            tabs.view.removeTabViewItem(&item);
10002                                        }
10003                                        for i in order {
10004                                            if let Some(item) = items.iter().nth(*i) {
10005                                                tabs.view.addTabViewItem(&item);
10006                                            }
10007                                        }
10008                                    }
10009                                    TAB_PICK_SUPPRESS.with(|s| s.set(false));
10010                                }
10011                            }
10012                            // Handled outside this borrow (it re-homes views and builds chrome).
10013                            #[expect(
10014                                clippy::match_same_arms,
10015                                reason = "each no-op patch keeps its own arm and the comment saying why it is one"
10016                            )]
10017                            NavPatch::Presentation(_) => {}
10018                            // Resident-page switch (docs/navigation.md): every page stays in the
10019                            // view hierarchy and only one is unhidden, so switching tabs keeps
10020                            // each page's scroll position and first responder exactly as left.
10021                            NavPatch::Select(i) => {
10022                                state.selected = *i;
10023                                match state.tabs.as_ref() {
10024                                    // The tab view shows exactly its selected item's page.
10025                                    Some(tabs) => {
10026                                        let n = unsafe { tabs.view.numberOfTabViewItems() };
10027                                        if (*i as isize) < n {
10028                                            TAB_PICK_SUPPRESS.with(|s| s.set(true));
10029                                            unsafe {
10030                                                tabs.view.selectTabViewItemAtIndex(*i as isize);
10031                                            };
10032                                            TAB_PICK_SUPPRESS.with(|s| s.set(false));
10033                                        }
10034                                    }
10035                                    None => {
10036                                        for (n, page) in state.pages.iter().enumerate() {
10037                                            page.setHidden(n != *i);
10038                                        }
10039                                    }
10040                                }
10041                            }
10042                            // Per-destination pane visibility (docs/navigation.md). Directly,
10043                            // not through the animator proxy: a screenshot must not catch a
10044                            // mid-animation pane (the sidebar-toggle rule), and settled now,
10045                            // like a re-present, so the detail's frame is right the instant
10046                            // the patch returns rather than one layout pass later.
10047                            NavPatch::ListVisible(v) => {
10048                                state.list_visible = *v;
10049                                if let Some(item) = state.list_item.as_ref() {
10050                                    item.setCollapsed(!*v);
10051                                    let split = unsafe { state.split_vc.splitView() };
10052                                    unsafe { split.layoutSubtreeIfNeeded() };
10053                                    // First time this pane is actually on screen: give it the
10054                                    // width the app asked for. The frame pass that would
10055                                    // otherwise do it has already run, back when there was no
10056                                    // pane to size.
10057                                    if let Some(w) = take_list_placement(state) {
10058                                        unsafe {
10059                                            split.setPosition_ofDividerAtIndex(
10060                                                day_spec::NAV_SIDEBAR_WIDTH + w,
10061                                                1,
10062                                            );
10063                                        }
10064                                    }
10065                                    // Re-frame the pane's page to the wrap it fills. A page
10066                                    // inserted while the pane was collapsed got a zero-width
10067                                    // frame, and `ViewWidthSizable` scales zero to zero however
10068                                    // wide the wrap becomes, so the list stayed invisible while
10069                                    // its rows were still there to click. An app opening on a
10070                                    // full-page section hits this on the first reveal.
10071                                    if *v
10072                                        && let Some(wrap) = state.list_wrap.as_ref()
10073                                        && let Some(page) = state.list_page.as_ref()
10074                                    {
10075                                        unsafe {
10076                                            wrap.layoutSubtreeIfNeeded();
10077                                            page.setFrame(wrap.bounds());
10078                                        }
10079                                    }
10080                                }
10081                            }
10082                            // Never arrives here: the pane persists through every presentation
10083                            // (`Cap::NavContentList` = Native), so the pieces layer never asks
10084                            // for the merged-stack shape.
10085                            NavPatch::ListInStack(_) => {}
10086                        }
10087                    });
10088                }
10089            }
10090            // Emulated cover (docs/cover.md): present = re-home onto the window's content view
10091            // at full bounds, topmost, autoresized with the window (the DayNavPage handle
10092            // reports FrameChanged on every resize). Dismiss = hide + report `CoverHidden`
10093            // immediately (no transition on this tier). Interactive dismissal doesn't exist on
10094            // this backend, so DismissDisabled has nothing to disable.
10095            kinds::COVER => {
10096                if let (Some(p), Ok(page)) = (
10097                    patch.downcast_ref::<CoverPatch>(),
10098                    h.clone().downcast::<DayNavPage>(),
10099                ) {
10100                    let node = page.ivars().node;
10101                    match p {
10102                        CoverPatch::Present { background, .. } => {
10103                            if page.ivars().sheet.get() {
10104                                if let Some(parent) =
10105                                    primary_content().and_then(|v| unsafe { v.window() })
10106                                {
10107                                    let bounds = parent.frame().size;
10108                                    let max = if page.ivars().large.get() {
10109                                        day_spec::props::LARGE_SHEET_MAX
10110                                    } else {
10111                                        day_spec::props::SHEET_MAX
10112                                    };
10113                                    let height = if page.ivars().half.get() {
10114                                        (bounds.height * 0.5).clamp(160.0, max.height)
10115                                    } else {
10116                                        (bounds.height - 80.0).clamp(300.0, max.height)
10117                                    };
10118                                    let size = NSSize::new(
10119                                        (bounds.width - 40.0).clamp(320.0, max.width),
10120                                        height,
10121                                    );
10122                                    let window = unsafe {
10123                                        NSWindow::initWithContentRect_styleMask_backing_defer(
10124                                            NSWindow::alloc(MainThreadMarker::new().unwrap()),
10125                                            NSRect::new(NSPoint::new(0.0, 0.0), size),
10126                                            NSWindowStyleMask::Titled,
10127                                            NSBackingStoreType::Buffered,
10128                                            false,
10129                                        )
10130                                    };
10131                                    unsafe {
10132                                        window.setReleasedWhenClosed(false);
10133                                        page.removeFromSuperview();
10134                                        page.setHidden(false);
10135                                        page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
10136                                        window.setContentView(Some(&page));
10137                                    }
10138                                    let key = ptr_of(h);
10139                                    SHEET_NODES.with(|t| {
10140                                        t.insert(Retained::as_ptr(&window) as usize, node)
10141                                    });
10142                                    install_sheet_escape_monitor();
10143                                    COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
10144                                    dispatch2::DispatchQueue::main().exec_async(move || {
10145                                        ffi_guard::contain((), || {
10146                                            let window =
10147                                                COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
10148                                            if let (Some(window), Some(parent)) = (
10149                                                window,
10150                                                primary_content()
10151                                                    .and_then(|v| unsafe { v.window() }),
10152                                            ) {
10153                                                unsafe {
10154                                                    parent.beginSheet_completionHandler(
10155                                                        &window, None,
10156                                                    );
10157                                                }
10158                                            }
10159                                        });
10160                                    });
10161                                    emit(
10162                                        node,
10163                                        Event::FrameChanged(Size::new(size.width, size.height)),
10164                                    );
10165                                }
10166                                return;
10167                            }
10168                            // A cover must occlude the window (the native tiers' modal surfaces
10169                            // are opaque): default to the window background when the app sets
10170                            // no explicit color.
10171                            unsafe {
10172                                page.setWantsLayer(true);
10173                                if let Some(layer) = page.layer() {
10174                                    let color = match background {
10175                                        Some(bg) => nscolor(*bg),
10176                                        None => NSColor::windowBackgroundColor(),
10177                                    };
10178                                    layer.setBackgroundColor(Some(&color.CGColor()));
10179                                }
10180                            }
10181                            // The primary window's content, specifically: firstObject()
10182                            // is arbitrary once secondary windows exist (docs/windows.md).
10183                            if let Some(content) = primary_content() {
10184                                if let Some(window) = unsafe { content.window() } {
10185                                    toolbar::cover_presented(ptr_of(h), &window);
10186                                }
10187                                // Edge to edge like the root's own background, laid out below
10188                                // the title bar like the root's content: the page starts at the
10189                                // top of the window (above the pinned content origin) and
10190                                // keeps the same strip above its own layout origin.
10191                                let top = title_bar_inset(&content);
10192                                let full = content.frame().size;
10193                                page.ivars().top_inset.set(top);
10194                                unsafe {
10195                                    page.removeFromSuperview();
10196                                    content.addSubview(&page);
10197                                    page.setFrame(NSRect::new(
10198                                        NSPoint::new(0.0, -top),
10199                                        NSSize::new(full.width, full.height),
10200                                    ));
10201                                    page.setBoundsOrigin(NSPoint::new(0.0, -top));
10202                                    page.setAutoresizingMask(
10203                                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10204                                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10205                                    );
10206                                    page.setHidden(false);
10207                                }
10208                                emit(
10209                                    node,
10210                                    Event::FrameChanged(Size::new(
10211                                        full.width,
10212                                        (full.height - top).max(0.0),
10213                                    )),
10214                                );
10215                            }
10216                        }
10217                        CoverPatch::DismissDisabled(_) => {}
10218                        CoverPatch::Dismiss => {
10219                            COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
10220                            toolbar::cover_dismissed(ptr_of(h));
10221                            unsafe {
10222                                page.setHidden(true);
10223                                page.removeFromSuperview();
10224                            }
10225                            emit(node, Event::CoverHidden);
10226                        }
10227                    }
10228                }
10229            }
10230            kinds::PICKER => picker::update_any(self, h, patch),
10231            kinds::TEXT_AREA => textarea::update_any(self, h, patch),
10232            kinds::TEXT_FIELD => {
10233                if let (Some(p), Ok(tf)) = (
10234                    patch.downcast_ref::<TextFieldPatch>(),
10235                    h.clone().downcast::<NSTextField>(),
10236                ) {
10237                    match p {
10238                        TextFieldPatch::Text { text, from_native } => {
10239                            // Origin-tagged echo suppression (§4.4).
10240                            if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
10241                                unsafe { tf.setStringValue(&NSString::from_str(text)) };
10242                            }
10243                        }
10244                        TextFieldPatch::Placeholder(t) => unsafe {
10245                            tf.setPlaceholderString(Some(&NSString::from_str(t)));
10246                        },
10247                        TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
10248                        // A selection lives in the field editor, which a field has only while
10249                        // it edits (docs/textfield.md "Selection"): an unfocused field has none
10250                        // to set, and taking focus selects the whole text anyway.
10251                        TextFieldPatch::Select(sel) => {
10252                            if let Some(editor) = tf.currentEditor() {
10253                                let (start, end) = sel.utf16(&editor.string().to_string());
10254                                editor.setSelectedRange(objc2_foundation::NSRange::new(
10255                                    start,
10256                                    end - start,
10257                                ));
10258                            }
10259                        }
10260                    }
10261                }
10262            }
10263            kinds::LIST => match patch.downcast_ref::<ListPatch>() {
10264                Some(ListPatch::Splice(deltas)) => {
10265                    // The set changed by exactly these deltas: animate each row in, out, or
10266                    // across, the thing a reload cannot express. Indexes are sequential, so
10267                    // each delta gets its own begin/endUpdates batch (NSTableView's combined
10268                    // batch semantics re-interpret indexes; one-at-a-time stays literal).
10269                    // Row realization stays deferred, as with Reload.
10270                    if let Some((table, data)) = list_entry(ptr_of(h)) {
10271                        use objc2_app_kit::NSTableViewAnimationOptions;
10272                        for d in deltas {
10273                            unsafe {
10274                                table.beginUpdates();
10275                                match d {
10276                                    day_spec::props::RowDelta::Insert(i) => table
10277                                        .insertRowsAtIndexes_withAnimation(
10278                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
10279                                            NSTableViewAnimationOptions::SlideDown,
10280                                        ),
10281                                    day_spec::props::RowDelta::Remove(i) => table
10282                                        .removeRowsAtIndexes_withAnimation(
10283                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
10284                                            NSTableViewAnimationOptions::SlideUp,
10285                                        ),
10286                                    day_spec::props::RowDelta::Move(from, to) => {
10287                                        table.moveRowAtIndex_toIndex(*from as isize, *to as isize);
10288                                    }
10289                                }
10290                                table.endUpdates();
10291                            }
10292                        }
10293                        // The displayed order matches the source again: refresh the cache a
10294                        // committed drag keeps in step and `permutation_moves` compares, or the
10295                        // next Reload finds a stale length and reloads flat instead of animating.
10296                        if let Some(source) = data.ivars().source.borrow().as_ref() {
10297                            let n = (source.len)();
10298                            *data.ivars().tokens.borrow_mut() =
10299                                (0..n).map(|i| (source.token_at)(i)).collect();
10300                        }
10301                    }
10302                    post_realize_visible_rows(ptr_of(h));
10303                }
10304                Some(ListPatch::Reload) => {
10305                    if let Some((table, data)) = list_entry(ptr_of(h)) {
10306                        // NSTableView reloadData clears selection for this view-based source.
10307                        // Preserve identities, not indexes, across refreshes/reorders; removed
10308                        // items disappear from the selection without selecting their successor.
10309                        let selected = unsafe { table.selectedRowIndexes() };
10310                        let tokens: Vec<u64> = data
10311                            .ivars()
10312                            .tokens
10313                            .borrow()
10314                            .iter()
10315                            .enumerate()
10316                            .filter(|(row, _)| selected.containsIndex(*row))
10317                            .map(|(_, token)| *token)
10318                            .collect();
10319                        data.ivars().suppress.set(true);
10320                        // A reload whose rows are the same set in a new order (a shuffle,
10321                        // a programmatic sort) animates as native row moves instead of a
10322                        // blink: a `moveRowAtIndex` batch, the same animation a drag commit
10323                        // gets. Anything else (insert/remove/content change) reloads flat.
10324                        // reloadData queries numberOfRows synchronously (snapshot only, no
10325                        // tree) and defers viewForRow, so both paths are safe in with_tree.
10326                        if let Some(moves) = data.permutation_moves(&table) {
10327                            unsafe {
10328                                table.beginUpdates();
10329                                for (from, to) in moves {
10330                                    table.moveRowAtIndex_toIndex(from as isize, to as isize);
10331                                }
10332                                table.endUpdates();
10333                            }
10334                        } else {
10335                            unsafe { table.reloadData() };
10336                        }
10337                        let restored = objc2_foundation::NSMutableIndexSet::new();
10338                        for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
10339                            if tokens.contains(token) {
10340                                restored.addIndex(row);
10341                            }
10342                        }
10343                        unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
10344                        data.ivars().suppress.set(false);
10345                    }
10346                    // Realize the visible rows on the next main-loop turn, outside this borrow.
10347                    // An occluded window (locked screen, covered, headless CI) gets no normal
10348                    // draw pass; NSTableView would first realize these rows inside a snapshot's
10349                    // `cacheDisplayInRect`, where `bind_row` must skip the held borrow and the
10350                    // table would cache permanently blank cells.
10351                    post_realize_visible_rows(ptr_of(h));
10352                }
10353                Some(ListPatch::ScrollToRow(row)) => {
10354                    // Same deferral discipline as ScrollToEnd: the scroll tiles target rows
10355                    // synchronously, which must happen outside this `with_tree` borrow.
10356                    let (key, row) = (ptr_of(h), *row);
10357                    <AppKit as Platform>::post(Box::new(move || {
10358                        if let Some((table, _)) = list_entry(key) {
10359                            let rows = unsafe { table.numberOfRows() };
10360                            if rows > 0 {
10361                                unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
10362                            }
10363                        }
10364                    }));
10365                    post_realize_visible_rows(ptr_of(h));
10366                }
10367                Some(ListPatch::ScrollToEnd) => {
10368                    // Deferred to the next main-loop turn: an actual scroll forces NSTableView
10369                    // to tile (realize) the target rows synchronously, and this patch arrives
10370                    // inside a `with_tree` borrow where `bind_row` must skip; the table would
10371                    // cache blank cells for every newly exposed row (see Reload above).
10372                    let key = ptr_of(h);
10373                    <AppKit as Platform>::post(Box::new(move || {
10374                        if let Some((table, _)) = list_entry(key) {
10375                            let rows = unsafe { table.numberOfRows() };
10376                            if rows > 0 {
10377                                unsafe { table.scrollRowToVisible(rows - 1) };
10378                            }
10379                        }
10380                    }));
10381                    // ...and realize whatever the scroll exposed, still outside the borrow.
10382                    post_realize_visible_rows(ptr_of(h));
10383                }
10384                Some(ListPatch::Selected(rows)) => {
10385                    // Programmatic selection sync (empty = clear), suppressed so the
10386                    // delegate does not echo it back as a selection event.
10387                    if let Some((table, data)) = list_entry(ptr_of(h)) {
10388                        data.ivars().suppress.set(true);
10389                        unsafe {
10390                            if rows.is_empty() {
10391                                table.deselectAll(None);
10392                            } else {
10393                                let set = objc2_foundation::NSMutableIndexSet::new();
10394                                let count = table.numberOfRows().max(0) as usize;
10395                                for r in rows.iter().copied().filter(|r| *r < count) {
10396                                    set.addIndex(r);
10397                                }
10398                                table.selectRowIndexes_byExtendingSelection(&set, false);
10399                            }
10400                        }
10401                        data.ivars().suppress.set(false);
10402                    }
10403                }
10404                Some(ListPatch::RowSizeInvalidated { cell, height }) => {
10405                    if let Some((table, data)) = list_entry(ptr_of(h)) {
10406                        data.row_resized(&table, *cell, *height);
10407                    }
10408                }
10409                // `None` = a patch for another kind's enum. A desktop table has no editing mode
10410                // (Cap::ListEditing is Unsupported).
10411                Some(ListPatch::Editing(_)) | None => {}
10412            },
10413            kinds::TREE => match patch.downcast_ref::<TreePatch>() {
10414                Some(TreePatch::Reload) => {
10415                    // Interned items keep their identity across reloadData, so NSOutlineView
10416                    // itself preserves expansion; the piece re-asserts it (and the selection)
10417                    // by token right after, belt and braces. reloadData queries the child
10418                    // counts synchronously (snapshot only, no tree) and defers viewForItem.
10419                    if let Some((outline, _)) = tree_entry(ptr_of(h)) {
10420                        unsafe { outline.reloadData() };
10421                    }
10422                    post_realize_visible_tree_rows(ptr_of(h));
10423                }
10424                Some(TreePatch::Expand(token, on)) => {
10425                    // Deferred: expandItem/collapseItem realize (or remove) the disclosed
10426                    // rows synchronously, and this patch arrives inside a `with_tree` borrow
10427                    // where `bind_row` must skip; the outline would cache permanently blank,
10428                    // id-less rows (the ScrollToEnd rule, one arm over).
10429                    let (key, token, on) = (ptr_of(h), *token, *on);
10430                    <AppKit as Platform>::post(Box::new(move || {
10431                        if let Some((outline, data)) = tree_entry(key) {
10432                            let item = data.intern(token);
10433                            // Suppressed: a programmatic disclosure must not echo back as
10434                            // `Event::TreeExpanded`. Redundant applications are AppKit no-ops.
10435                            data.ivars().suppress.set(true);
10436                            unsafe {
10437                                if on {
10438                                    outline.expandItem(Some(&item));
10439                                } else {
10440                                    outline.collapseItem(Some(&item));
10441                                }
10442                            }
10443                            data.ivars().suppress.set(false);
10444                        }
10445                        day_core::pump_events();
10446                    }));
10447                    post_realize_visible_tree_rows(ptr_of(h));
10448                }
10449                Some(TreePatch::Selected(tokens)) => {
10450                    if let Some((outline, data)) = tree_entry(ptr_of(h)) {
10451                        data.ivars().suppress.set(true);
10452                        unsafe {
10453                            if tokens.is_empty() {
10454                                outline.deselectAll(None);
10455                            } else {
10456                                let set = objc2_foundation::NSMutableIndexSet::new();
10457                                for t in tokens {
10458                                    // A token under a collapsed ancestor has no row, so it is
10459                                    // skipped; the piece re-applies after expansion changes.
10460                                    let row = outline.rowForItem(Some(&data.intern(*t)));
10461                                    if row >= 0 {
10462                                        set.addIndex(row as usize);
10463                                    }
10464                                }
10465                                outline.selectRowIndexes_byExtendingSelection(&set, false);
10466                            }
10467                        }
10468                        data.ivars().suppress.set(false);
10469                    }
10470                }
10471                Some(TreePatch::Reveal(token)) => {
10472                    // Deferred: the scroll tiles target rows synchronously, which must
10473                    // happen outside this `with_tree` borrow (the ScrollToRow rule).
10474                    let (key, token) = (ptr_of(h), *token);
10475                    <AppKit as Platform>::post(Box::new(move || {
10476                        if let Some((outline, data)) = tree_entry(key) {
10477                            let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
10478                            if row >= 0 {
10479                                unsafe { outline.scrollRowToVisible(row) };
10480                            }
10481                        }
10482                    }));
10483                    post_realize_visible_tree_rows(ptr_of(h));
10484                }
10485                None => {}
10486            },
10487            _ => {
10488                if let Some(update) = self.registry.get(kind).map(|r| r.update) {
10489                    update(self, h, patch);
10490                }
10491            }
10492        }
10493    }
10494
10495    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
10496    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
10497        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
10498        // the hook needs it mutably.
10499        let f = self.registry.get(kind).and_then(|r| r.release);
10500        if let Some(f) = f {
10501            f(self, h);
10502        }
10503    }
10504    fn release(&mut self, h: Handle) {
10505        LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
10506        // A released window content = that window is gone (docs/windows.md teardown):
10507        // drop the SecondaryWin (closing a straggler NSWindow) and its delegate with it.
10508        // (A re-fired windowWillClose emits to a torn-down node: dropped, harmless.)
10509        self.secondary.retain(|w| {
10510            if ptr_of(&w.content) == ptr_of(&h) {
10511                w.window.close();
10512                // The window's keyed state goes with it: its toolbar (toolbar.rs BARS,
10513                // keyed by the window pointer) used to survive a secondary close, and its
10514                // items, targets, retained NSToolbar and delegate all leaked.
10515                day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
10516                false
10517            } else {
10518                true
10519            }
10520        });
10521        TARGETS.with(|m| {
10522            m.borrow_mut().remove(&ptr_of(&h));
10523        });
10524        LIST_STATE.with(|m| {
10525            m.borrow_mut().remove(&ptr_of(&h));
10526        });
10527        TREE_STATE.with(|m| {
10528            m.borrow_mut().remove(&ptr_of(&h));
10529        });
10530        GESTURES.with(|m| {
10531            m.borrow_mut().remove(&ptr_of(&h));
10532        });
10533        NAV_STATE.with(|m| {
10534            if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
10535                // Unhook the split view controller from the responder chain before the drop
10536                // deallocs it. AppKit rewires these pointers behind day's back (mounting the
10537                // split resets its next to the superview; the controller's own view keeps
10538                // aiming at the controller), and a controller whose next responder is its own
10539                // view dies in dealloc's chain splice with the "next responder should never
10540                // be yourself" NSException, foreign to Rust, so it aborts the process
10541                // instead of unwinding (the Stack-page teardown crash, 2026-08).
10542                unsafe {
10543                    nav.split_vc.setNextResponder(None);
10544                    let split = nav.split_vc.splitView();
10545                    if split.nextResponder().is_some_and(|r| {
10546                        core::ptr::eq::<objc2::runtime::AnyObject>(
10547                            r.as_ref(),
10548                            nav.split_vc.as_ref(),
10549                        )
10550                    }) {
10551                        split.setNextResponder(None);
10552                    }
10553                }
10554            }
10555        });
10556        NAV_PAGES.with(|set| {
10557            set.borrow_mut().remove(&ptr_of(&h));
10558        });
10559        SPLIT_STATE.with(|m| {
10560            if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
10561                state.split.setDelegate(None);
10562            }
10563        });
10564        INSPECTOR_STATE.with(|m| {
10565            if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
10566                // The same dealloc-splice guard as the nav host above: never let the
10567                // controller (or its split) dealloc aiming at itself.
10568                unsafe {
10569                    insp.split_vc.setNextResponder(None);
10570                    let split = insp.split_vc.splitView();
10571                    if split.nextResponder().is_some_and(|r| {
10572                        core::ptr::eq::<objc2::runtime::AnyObject>(
10573                            r.as_ref(),
10574                            insp.split_vc.as_ref(),
10575                        )
10576                    }) {
10577                        split.setNextResponder(None);
10578                    }
10579                }
10580            }
10581        });
10582        NAV_MENUS.with(|m| {
10583            if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
10584                // The outline registers under its pointer (`menuForEvent:` resolves by
10585                // outline, not by this scroll handle): sweep that auxiliary key too, so
10586                // NAV_OUTLINE_MENUS, and any future outline-keyed table, drops it. A
10587                // surviving entry served the dead menu's rows once the address was recycled.
10588                day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
10589            }
10590        });
10591        // One call reclaims this handle's entry from every SideTable on this thread (canvas
10592        // OPS, PAGE_PANE, the picker/textarea state, and whatever lands later), running each
10593        // table's teardown hook (day-spec sidetable). The explicit removals above are the
10594        // older per-map checklist; new per-view maps should be SideTables so this sweep covers
10595        // them without another line here.
10596        day_spec::sidetable::sweep(ptr_of(&h));
10597        unsafe { h.removeFromSuperview() };
10598    }
10599
10600    fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
10601        // A nav menu that has just gained ancestors: if one of them is a tabs host, its rows
10602        // Are that host's tab labels (`adopt_menu_for_tabs`). The menu is built after its rows
10603        // page joined the host, so this is the first moment the host can see its rows.
10604        if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
10605            unsafe { content_of(parent).addSubview(child) };
10606            adopt_menu_for_tabs(self.mtm(), child);
10607            return;
10608        }
10609        // Nav host: pages land by their pane, not their position (docs/size-classes.md). Pages
10610        // fill their pane via autoresizing; the pane, not Day, owns their frames.
10611        let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
10612        let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
10613        let handled = NAV_STATE.with(|m| {
10614            let mut m = m.borrow_mut();
10615            let Some(state) = m.get_mut(&ptr_of(parent)) else {
10616                return false;
10617            };
10618            // The content-list page fills its pane at every presentation
10619            // (docs/navigation.md), never a member of the detail stack.
10620            if page_pane == Some(day_spec::props::Pane::List)
10621                && let Some(wrap) = state.list_wrap.as_ref()
10622            {
10623                state.list_page = Some(child.clone());
10624                unsafe {
10625                    child.setFrame(wrap.bounds());
10626                    child.setAutoresizingMask(
10627                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10628                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10629                    );
10630                    wrap.addSubview(child);
10631                }
10632                return true;
10633            }
10634            if is_sidebar_page {
10635                state.sidebar_page = Some(child.clone());
10636            }
10637            // Split (nav host Sidebar): the sidebar pane's page goes in the sidebar; the rest are
10638            // detail pages. Stack: every page, including the sidebar's, which is the stack's
10639            // root, lives in the detail pane so push/pop visibility covers them all.
10640            // The rows page goes to the sidebar pane in every presentation but `Stack`, where
10641            // it is the stack root and joins the detail pages instead.
10642            let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
10643            // A tabs host's detail page becomes an item of its tab view, which frames it (the
10644            // page's `setFrameSize:` reports the size to Day). Its label comes with the
10645            // menu's rows: already here when a page joins a live host, otherwise when the
10646            // menu is inserted (`adopt_menu_for_tabs`).
10647            if !to_pane && let Some(tabs) = state.tabs.as_ref() {
10648                state.pages.push(child.clone());
10649                let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
10650                unsafe {
10651                    child.setAutoresizingMask(
10652                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10653                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10654                    );
10655                    item.setView(Some(child));
10656                    tabs.view.addTabViewItem(&item);
10657                }
10658                if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
10659                    sync_tab_labels(tabs, &titles, state.selected);
10660                }
10661                return true;
10662            }
10663            let (wrap, frame) = if to_pane {
10664                (&state.sidebar_wrap, state.sidebar_wrap.bounds())
10665            } else {
10666                state.pages.push(child.clone());
10667                let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
10668                (
10669                    &state.detail_wrap,
10670                    nav_page_frame(&state.detail_wrap, visible),
10671                )
10672            };
10673            unsafe {
10674                child.setFrame(frame);
10675                child.setAutoresizingMask(
10676                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10677                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10678                );
10679                wrap.addSubview(child);
10680            }
10681            true
10682        });
10683        if handled {
10684            return;
10685        }
10686        // Split host (docs/split.md): each pane fills its wrap, an arranged subview the
10687        // splitter sizes; the pane's own `setFrameSize:` reports the size to Day.
10688        let split_pane = SPLIT_STATE.with(|m| {
10689            let m = m.borrow();
10690            let Some(state) = m.get(&ptr_of(parent)) else {
10691                return false;
10692            };
10693            let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
10694            let wrap = if second {
10695                &state.second_wrap
10696            } else {
10697                &state.first_wrap
10698            };
10699            unsafe {
10700                child.setFrame(wrap.bounds());
10701                child.setAutoresizingMask(
10702                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10703                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10704                );
10705                wrap.addSubview(child);
10706            }
10707            true
10708        });
10709        if split_pane {
10710            return;
10711        }
10712        // Inspector host: each pane fills its wrap via autoresizing, the nav-page contract;
10713        // the split, not Day, owns the pane frames (docs/inspector.md).
10714        let inspected = INSPECTOR_STATE.with(|m| {
10715            let m = m.borrow();
10716            let Some(state) = m.get(&ptr_of(parent)) else {
10717                return false;
10718            };
10719            let panel = INSPECTOR_PANES
10720                .with(|t| t.get(ptr_of(child)))
10721                .unwrap_or(false);
10722            let wrap = if panel {
10723                &state.panel_wrap
10724            } else {
10725                &state.content_wrap
10726            };
10727            unsafe {
10728                child.setFrame(wrap.bounds());
10729                child.setAutoresizingMask(
10730                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10731                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10732                );
10733                wrap.addSubview(child);
10734            }
10735            true
10736        });
10737        if !inspected {
10738            // Absolute positioning: z-order is build order; index is irrelevant for
10739            // non-overlapping frames (stack_z will need ordered insertion later).
10740            unsafe { content_of(parent).addSubview(child) };
10741        }
10742    }
10743
10744    fn remove(&mut self, parent: &Handle, child: &Handle) {
10745        PAGE_PANE.with(|t| t.remove(ptr_of(child)));
10746        let mtm = self.mtm();
10747        NAV_STATE.with(|m| {
10748            if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
10749                // A tabs host: the page leaves with its tab item.
10750                if let Some(tabs) = state.tabs.as_ref() {
10751                    unsafe {
10752                        let n = tabs.view.numberOfTabViewItems();
10753                        for i in 0..n {
10754                            let item = tabs.view.tabViewItemAtIndex(i);
10755                            if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
10756                                tabs.view.removeTabViewItem(&item);
10757                                break;
10758                            }
10759                        }
10760                    }
10761                }
10762                state.pages.retain(|p| ptr_of(p) != ptr_of(child));
10763                if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
10764                    state.sidebar_page = None;
10765                }
10766            }
10767        });
10768        unsafe { child.removeFromSuperview() };
10769    }
10770
10771    fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
10772        unsafe { content_of(parent).addSubview(child) };
10773    }
10774
10775    fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
10776        match kind {
10777            kinds::LABEL => {
10778                if let Some(tf) = h.downcast_ref::<NSTextField>() {
10779                    let w = p.width.unwrap_or(1.0e6);
10780                    // The field owns maximumNumberOfLines; measuring its cell bypasses it.
10781                    let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
10782                    let mut height = s.height.ceil();
10783                    // AppKit's truncating single-line mode still measures explicit newlines
10784                    // as multiple lines. Bound that case using AppKit's own font metrics.
10785                    if tf.maximumNumberOfLines() == 1 {
10786                        thread_local! {
10787                            static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
10788                        }
10789                        if let Some(font) = unsafe { tf.font() } {
10790                            height = height.min(
10791                                METRICS
10792                                    .with(|metrics| metrics.defaultLineHeightForFont(&font))
10793                                    .ceil(),
10794                            );
10795                        }
10796                    }
10797                    return Size::new(s.width.ceil().min(w), height);
10798                }
10799                Size::ZERO
10800            }
10801            kinds::BUTTON | kinds::TOGGLE => {
10802                let s = unsafe { h.fittingSize() };
10803                Size::new(s.width.ceil(), s.height.ceil())
10804            }
10805            kinds::SLIDER => {
10806                let s = unsafe { h.fittingSize() };
10807                Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
10808            }
10809            kinds::PICKER => picker::measure_any(self, h, p),
10810            kinds::TEXT_AREA => textarea::measure_any(self, h, p),
10811            kinds::TEXT_FIELD => {
10812                let s = unsafe { h.fittingSize() };
10813                Size::new(
10814                    p.width.unwrap_or(s.width.max(160.0)),
10815                    s.height.max(22.0).ceil(),
10816                )
10817            }
10818            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
10819            // The stack's own fitting size, at least a table row's 28pt; the words truncate to
10820            // the row's width.
10821            kinds::LIST_ITEM => {
10822                let s = h.fittingSize();
10823                Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
10824            }
10825            kinds::PROGRESS => {
10826                // Indeterminate spinner is a fixed square; determinate bar fills width.
10827                let indeterminate = h
10828                    .clone()
10829                    .downcast::<NSProgressIndicator>()
10830                    .is_ok_and(|pi| unsafe { pi.isIndeterminate() });
10831                if indeterminate {
10832                    let large = h
10833                        .downcast_ref::<NSProgressIndicator>()
10834                        .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
10835                    let side = if large { 32.0 } else { 20.0 };
10836                    Size::new(side, side)
10837                } else {
10838                    Size::new(p.width.unwrap_or(180.0), 20.0)
10839                }
10840            }
10841            kinds::NAV_MENU => {
10842                let rows = NAV_MENUS.with(|m| {
10843                    m.borrow()
10844                        .get(&ptr_of(h))
10845                        .map_or(0, |(_, d)| d.ivars().items.borrow().len())
10846                });
10847                Size::new(
10848                    p.width.unwrap_or(220.0),
10849                    p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
10850                )
10851            }
10852            // The recycling list fills the space it is offered (its native scroll owns overflow).
10853            kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
10854            _ => {
10855                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
10856                    measure(self, h, p)
10857                } else {
10858                    let s = unsafe { h.fittingSize() };
10859                    Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
10860                }
10861            }
10862        }
10863    }
10864
10865    fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
10866        unsafe {
10867            h.setWantsLayer(true);
10868        }
10869        let v = h.clone();
10870        with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
10871    }
10872
10873    fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
10874        // Expressed in the view's own geometry (see `TRANSFORMS`), so hit-testing follows the
10875        // drawing, as UIKit's does. Without a laid-out frame yet, `set_frame` applies it.
10876        TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
10877        let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
10878        let v = h.clone();
10879        with_appkit_anim(anim, move || {
10880            if let Some(base) = base {
10881                apply_geometry(&v, base, t);
10882            }
10883        });
10884    }
10885
10886    fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
10887        if let Some(label) = h.downcast_ref::<DayLabel>() {
10888            label.ivars().selectable.set(selectable);
10889            label.set_links(label.ivars().has_links.get());
10890        } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
10891            unsafe { tf.setSelectable(selectable) };
10892        }
10893        None
10894    }
10895
10896    fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
10897        let node = text_field_node(h)?;
10898        let old = h.downcast_ref::<NSTextField>()?;
10899        // Hidden characters are a class on AppKit. A field already of the right class is
10900        // dressed in place; otherwise its replacement is, and the node moves to it.
10901        let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
10902            .then(|| self.swap_text_field(h, old, node, traits.secure));
10903        let tf = swapped.as_deref().unwrap_or(old);
10904        unsafe {
10905            // Read-only keeps the bezel and the ordinary text color; the text stays
10906            // selectable, so it can still be copied.
10907            tf.setEditable(!traits.read_only);
10908            tf.setSelectable(true);
10909        }
10910        // The purpose is AutoFill's hint on the desktop: which saved credential or contact
10911        // detail the system offers. `Number` and `Decimal` have no content type. A constant
10912        // newer than the running system leaves the field untyped.
10913        let content_type = match traits.purpose {
10914            InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
10915            InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
10916            InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
10917            InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
10918            InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
10919            InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
10920            InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
10921            InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
10922            InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
10923        };
10924        unsafe {
10925            tf.setContentType(content_type);
10926            // Only free text wants the system finishing words; a name, an address or a code
10927            // is typed exactly.
10928            tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
10929        }
10930        // No on-screen keyboard, so no action key to label; and no native length limit:
10931        // day-pieces holds `max_length`.
10932        swapped.as_ref().map(view_of)
10933    }
10934
10935    fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
10936        let key = Retained::as_ptr(h) as usize;
10937        if cursor == Cursor::Default {
10938            // Release: drop the tracking area, and the hide if this owner holds one.
10939            if let Some((owner, area)) = self.cursors.remove(&key) {
10940                unsafe { h.removeTrackingArea(&area) };
10941                if owner.ivars().hiding.replace(false) {
10942                    NSCursor::unhide();
10943                }
10944            }
10945            return;
10946        }
10947        let hidden = cursor == Cursor::None;
10948        let shape = if hidden { None } else { ns_cursor(&cursor) };
10949        let mtm = self.mtm;
10950        let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
10951            let owner = DayCursorOwner::new(mtm);
10952            // InVisibleRect: the area follows the view's bounds, so no rect to keep in step
10953            // with layout. ActiveInKeyWindow: the shape belongs to the window taking input.
10954            let opts = NSTrackingAreaOptions::CursorUpdate
10955                | NSTrackingAreaOptions::MouseEnteredAndExited
10956                | NSTrackingAreaOptions::ActiveInKeyWindow
10957                | NSTrackingAreaOptions::InVisibleRect;
10958            let any: &objc2::runtime::AnyObject = &owner;
10959            let area = unsafe {
10960                NSTrackingArea::initWithRect_options_owner_userInfo(
10961                    NSTrackingArea::alloc(),
10962                    NSRect::ZERO,
10963                    opts,
10964                    Some(any),
10965                    None,
10966                )
10967            };
10968            unsafe { h.addTrackingArea(&area) };
10969            (owner, area)
10970        });
10971        let changed = {
10972            let iv = owner.ivars();
10973            let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10974                (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10975                (None, None) => true,
10976                _ => false,
10977            };
10978            *iv.cursor.borrow_mut() = shape;
10979            let was_hidden = iv.hidden.replace(hidden);
10980            !same || was_hidden != hidden
10981        };
10982        // A reactive change while the pointer is already inside: AppKit only asks on entry,
10983        // so ask it to re-evaluate now.
10984        if changed && let Some(w) = h.window() {
10985            unsafe { w.invalidateCursorRectsForView(h) };
10986        }
10987    }
10988
10989    /// Where the control actually draws its first line of text (docs/baseline.md).
10990    ///
10991    /// AppKit publishes `firstBaselineOffsetFromTop`, but it is measured from the top of the
10992    /// view's alignment rect and it is rounded to whole points, and that rounding is visible.
10993    /// An `NSDatePicker` in a 26pt frame insets its alignment rect 4pt and answers 15, i.e. 19
10994    /// in frame terms, while it paints at 19.9; a label beside it then sits a point high, which
10995    /// is exactly the drift baseline alignment exists to remove.
10996    ///
10997    /// So derive it from the metrics AppKit rounded: a single line of the control's own font,
10998    /// centered in its alignment rect, with the baseline an ascender below the line's top. That
10999    /// reproduces AppKit's own numbers for a plain label and a bezeled field (12.91 → its 13,
11000    /// 19.91 → its 20) while keeping the fractional part that makes a picker land on the line.
11001    /// Controls with no font of their own keep AppKit's answer.
11002    fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
11003        if !day_spec::kind_has_baseline(kind) {
11004            return None;
11005        }
11006        // The view has to be at the height the row settled on before it answers: a control
11007        // that centers its text vertically moves its baseline with its box.
11008        let current = unsafe { h.frame() };
11009        if (current.size.height - size.height).abs() > 0.5 {
11010            unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
11011        }
11012        let insets = unsafe { h.alignmentRectInsets() };
11013        let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
11014        let font = h
11015            .downcast_ref::<NSControl>()
11016            .and_then(|c| unsafe { c.font() });
11017        let offset = match font {
11018            // A multi-line editor's first line sits at the top of its text container, not
11019            // centered in it, so the centering model would put its baseline half a box too low.
11020            Some(_) if kind == kinds::TEXT_AREA => reported,
11021            Some(f) => {
11022                let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
11023                let line = ascender - descender;
11024                let align_h = (size.height - insets.top - insets.bottom).max(0.0);
11025                insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
11026            }
11027            None => reported,
11028        };
11029        // AppKit's documented "no baseline" answer is the view's own height.
11030        (offset > 0.0 && offset < size.height).then_some(offset)
11031    }
11032
11033    fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
11034        // Nav pages: the splitter pane / nav container owns the frame (autoresized).
11035        if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
11036            return;
11037        }
11038        // Every Day parent is flipped (DayFlipped containers, flipped scroll document views),
11039        // so top-left frames apply directly.
11040        let r = NSRect::new(
11041            NSPoint::new(frame.origin.x, frame.origin.y),
11042            NSSize::new(frame.size.width, frame.size.height),
11043        );
11044        // Nav host: the sidebar holds its width when the window resizes and the detail pane
11045        // absorbs the change. That is now the sidebar NSSplitViewItem's behavior, so the
11046        // only thing left to do here is give the split its frame and place the divider once;
11047        // re-placing it on every resize would fight the item and undo a user's drag.
11048        if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
11049            // A host at the top of a window's pinned content reaches up under the title bar,
11050            // where its controller expects to be (see `pane_under_title_bar`); its panes keep
11051            // their content below the strip, so nothing Day laid out moves.
11052            let strip = unsafe { split.superview() }
11053                .and_then(|sup| {
11054                    let content = unsafe { sup.window() }?.contentView()?;
11055                    // Layout wrappers (for example zstack with a reader cover) may sit
11056                    // between the window root and its navigation host. A direct-parent
11057                    // check misses them and puts AppKit's frosted pocket over page text.
11058                    let mut ancestor = Some(sup.clone());
11059                    while let Some(view) = ancestor {
11060                        if std::ptr::eq(&raw const *view, &raw const *content) {
11061                            break;
11062                        }
11063                        if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
11064                            return None; // nested navigation belongs to the outer pane
11065                        }
11066                        ancestor = unsafe { view.superview() };
11067                    }
11068                    let point = unsafe {
11069                        sup.convertPoint_toView(
11070                            NSPoint::new(frame.origin.x, frame.origin.y),
11071                            Some(&content),
11072                        )
11073                    };
11074                    (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
11075                })
11076                .unwrap_or(0.0);
11077            let r = NSRect::new(
11078                NSPoint::new(r.origin.x, r.origin.y - strip),
11079                NSSize::new(r.size.width, r.size.height + strip),
11080            );
11081            let wraps = NAV_STATE.with(|m| {
11082                m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
11083                    #[expect(
11084                        clippy::float_cmp,
11085                        reason = "unchanged-value check against the strip stored last time"
11086                    )]
11087                    let changed = s.title_strip != strip;
11088                    changed.then(|| {
11089                        s.title_strip = strip;
11090                        let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
11091                        w.extend(s.list_wrap.clone());
11092                        w
11093                    })
11094                })
11095            });
11096            let first = NAV_STATE.with(|m| {
11097                m.borrow_mut()
11098                    .get_mut(&ptr_of(h))
11099                    .map_or((false, None), |s| {
11100                        if !s.presentation.is_split() {
11101                            return (false, None);
11102                        }
11103                        let sidebar = !std::mem::replace(&mut s.positioned, true);
11104                        // The list's divider waits for the pane to be showing. Placing it while
11105                        // the pane is collapsed re-opens it (which is how an app whose first
11106                        // destination has no list opened with one beside it) and spends the one
11107                        // placement the pane gets, leaving it at the solver's width later on.
11108                        (sidebar, take_list_placement(s))
11109                    })
11110            });
11111            unsafe {
11112                split.setFrame(r);
11113                split.layoutSubtreeIfNeeded();
11114            }
11115            // After the panes have their new size, so each wrap is placed in the final pane;
11116            // autoresizing keeps the strip from then on.
11117            for wrap in wraps.iter().flatten() {
11118                place_below_strip(wrap, strip);
11119            }
11120            unsafe {
11121                if first.0 {
11122                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
11123                }
11124                // A triple split has a second divider, and nothing else places it: left alone,
11125                // the controller's initial constraint pass lands it wherever the solver liked, so
11126                // the content list opens at an arbitrary width and the detail pane gets the
11127                // leftovers until the first manual drag re-settles them.
11128                if let Some(w) = first.1 {
11129                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
11130                }
11131            }
11132        } else {
11133            BASE_FRAMES.with(|m| {
11134                m.insert(
11135                    ptr_of(h),
11136                    [
11137                        frame.origin.x,
11138                        frame.origin.y,
11139                        frame.size.width,
11140                        frame.size.height,
11141                    ],
11142                )
11143            });
11144            // A transform (`set_transform`) is applied to the frame Day laid out.
11145            match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
11146                Some(t) => apply_geometry(
11147                    h,
11148                    [
11149                        frame.origin.x,
11150                        frame.origin.y,
11151                        frame.size.width,
11152                        frame.size.height,
11153                    ],
11154                    t,
11155                ),
11156                None => unsafe { h.setFrame(r) },
11157            }
11158        }
11159    }
11160
11161    fn set_scroll_content(&mut self, h: &Handle, content: Size) {
11162        if let Some(sv) = h.downcast_ref::<NSScrollView>()
11163            && let Some(doc) = unsafe { sv.documentView() }
11164        {
11165            unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
11166        }
11167    }
11168
11169    /// A macOS table row: the dense rows of a Finder or Mail list, 28pt for an icon and a line of body text.
11170    fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
11171        day_spec::RowMetrics {
11172            insets: day_spec::Insets {
11173                top: 4.0,
11174                leading: 8.0,
11175                bottom: 4.0,
11176                trailing: 8.0,
11177            },
11178            min_height: 28.0,
11179        }
11180    }
11181
11182    fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
11183        if let Some(sv) = h.downcast_ref::<NSScrollView>()
11184            && let Some(doc) = unsafe { sv.documentView() }
11185        {
11186            unsafe {
11187                doc.scrollRectToVisible(NSRect::new(
11188                    NSPoint::new(target.origin.x, target.origin.y),
11189                    NSSize::new(target.size.width, target.size.height),
11190                ))
11191            };
11192        }
11193    }
11194
11195    fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
11196        let Some(window) = h.window() else { return };
11197        // A list's public handle is its scroll view; keyboard focus belongs to the table.
11198        let list = list_entry(ptr_of(h));
11199        let responder: &NSResponder = match &list {
11200            Some((table, _)) => table,
11201            None => h,
11202        };
11203        let responder_ptr = std::ptr::from_ref::<NSResponder>(responder) as usize;
11204        if focused {
11205            window.makeFirstResponder(Some(responder));
11206            return;
11207        }
11208        // Resign only while this view still owns focus, so a stale release can't blur a
11209        // sibling.
11210        let owns = window
11211            .firstResponder()
11212            .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
11213            || owns_first_responder(&window, h);
11214        if owns {
11215            window.makeFirstResponder(None);
11216        }
11217    }
11218
11219    fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
11220        // The overrides live on `DayFlipped` (the container view); registering any other
11221        // view is harmless but inert, the graceful silence the duty documents.
11222        if focusable {
11223            FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
11224        } else {
11225            FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
11226        }
11227    }
11228
11229    fn set_event_sink(&mut self, sink: EventSink) {
11230        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
11231    }
11232
11233    fn set_edit_state(&mut self, state: &day_spec::EditState) {
11234        EDIT_STATE.with(|s| s.set(*state));
11235    }
11236
11237    fn modifiers(&mut self) -> day_spec::Modifiers {
11238        let f = NSEvent::modifierFlags_class();
11239        day_spec::Modifiers {
11240            shift: f.contains(NSEventModifierFlags::Shift),
11241            primary: f.contains(NSEventModifierFlags::Command),
11242            alt: f.contains(NSEventModifierFlags::Option),
11243        }
11244    }
11245
11246    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
11247        let front = undo_front(self.mtm);
11248        *front.ivars().state.borrow_mut() = state.clone();
11249    }
11250
11251    fn attach_list(&mut self, host: &Handle, source: ListSource) {
11252        let key = ptr_of(host);
11253        if let Some((table, data)) = list_entry(key) {
11254            data.ivars().source.replace(Some(source));
11255            // Initial fill: numberOfRows reads the snapshot only; viewForRow is deferred.
11256            unsafe { table.reloadData() };
11257        }
11258        // Force the table to realize its visible row views on the next main-loop turn, outside
11259        // any `with_tree` borrow, so `viewForRow`/`bind_row` build the cells then. Otherwise a
11260        // headless CI window never lays the table out until a snapshot's `cacheDisplayInRect`
11261        // forces it *inside* the snapshot borrow, where `bind_row` must skip (blank rows).
11262        post_realize_visible_rows(key);
11263    }
11264
11265    fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
11266        let key = ptr_of(host);
11267        if let Some((outline, data)) = tree_entry(key) {
11268            data.ivars().source.replace(Some(source));
11269            // Initial fill: child counts read the snapshot only; viewForItem is deferred.
11270            unsafe { outline.reloadData() };
11271        }
11272        // Realize visible rows on the next main-loop turn, outside any borrow (the
11273        // attach_list comment has the occluded-window story).
11274        <AppKit as Platform>::post(Box::new(move || {
11275            if let Some((outline, _)) = tree_entry(key) {
11276                unsafe { outline.layoutSubtreeIfNeeded() };
11277            }
11278        }));
11279    }
11280
11281    fn adopt(&mut self, raw: RawHandle) -> Handle {
11282        // A recycling NSTableView cell view; Day builds/rebinds its row content in place.
11283        // Invariant, not app input: day-core only passes back the cell pointer this backend
11284        // itself vended through `bind_row`, so a null here is a framework bug worth stopping on.
11285        let ptr = raw.cast::<NSView>();
11286        unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
11287    }
11288
11289    fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
11290        self.edit_toolbar(h, ops)
11291    }
11292
11293    fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
11294        Self::patch_toolbar(h, patch);
11295    }
11296
11297    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
11298        let mtm = self.mtm;
11299        if self.menu_escape_monitor.is_none() {
11300            let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
11301                ffi_guard::contain(event.as_ptr(), || {
11302                    let event_ref = unsafe { event.as_ref() };
11303                    let app = NSApplication::sharedApplication(mtm);
11304                    // Native dialogs retain their cancellation behavior. Only an enabled
11305                    // menu key equivalent can consume Escape, never the general key stream.
11306                    if app.modalWindow().is_none()
11307                        && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
11308                        && unsafe { event_ref.charactersIgnoringModifiers() }
11309                            .is_some_and(|s| s.to_string() == "\u{1b}")
11310                        && app
11311                            .mainMenu()
11312                            .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
11313                    {
11314                        std::ptr::null_mut()
11315                    } else {
11316                        event.as_ptr()
11317                    }
11318                })
11319            });
11320            self.menu_escape_monitor = unsafe {
11321                NSEvent::addLocalMonitorForEventsMatchingMask_handler(
11322                    objc2_app_kit::NSEventMask::KeyDown,
11323                    &block,
11324                )
11325            }
11326            .map(MenuEscapeMonitor);
11327        }
11328        let app = NSApplication::sharedApplication(mtm);
11329        let menubar = NSMenu::new(mtm);
11330        // macOS owns the application menu; relocate app-level roles while preserving
11331        // their callbacks, shortcuts, and enabled state.
11332        let mut items = items.to_vec();
11333        let about = extract_app_role(&mut items, day_spec::MenuRole::About);
11334        let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
11335        let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
11336        let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
11337        let services =
11338            install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
11339        // Fill the standard slots the app did not claim, in the platform's bar order
11340        // (day-core owns that policy so every backend arranges its bar the same way).
11341        // Fill the standard slots the app left open, in macOS's bar order. The Window menu is
11342        // installed natively below, so the style deliberately supplies none.
11343        let items =
11344            day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
11345        let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
11346        // Each top-level entry becomes a menu-bar menu.
11347        for item in &items {
11348            match item {
11349                day_spec::MenuItem::Submenu { label, items, role } => {
11350                    let sub = build_ns_menu(mtm, label, items);
11351                    let it = NSMenuItem::new(mtm);
11352                    // Help is held back: the Window menu is installed natively after this loop
11353                    // (AppKit owns it so it can append the live window list), and Help sits
11354                    // last on every Mac menu bar.
11355                    if *role == Some(day_spec::MenuBarRole::Help)
11356                        || *label == day_localization::t(day_localization::key::day_help)
11357                    {
11358                        help_menu = Some((label.clone(), sub));
11359                        continue;
11360                    }
11361                    it.setTitle(&NSString::from_str(label));
11362                    it.setSubmenu(Some(&sub));
11363                    menubar.addItem(&it);
11364                }
11365                other => {
11366                    // A bare top-level action → wrap in a one-item menu so it has a submenu.
11367                    let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
11368                    let it = NSMenuItem::new(mtm);
11369                    it.setSubmenu(Some(&sub));
11370                    menubar.addItem(&it);
11371                }
11372            }
11373        }
11374        // The Window menu (docs/windows.md): auto-installed unless the app's model owns
11375        // `MenuRole::Minimize` (then the app is composing its own window management).
11376        if !model_has_role(&items, day_spec::MenuRole::Minimize) {
11377            install_windows_menu(mtm, &app, &menubar);
11378        }
11379        if let Some((label, help)) = help_menu {
11380            let it = NSMenuItem::new(mtm);
11381            it.setTitle(&NSString::from_str(&label));
11382            it.setSubmenu(Some(&help));
11383            menubar.addItem(&it);
11384            // Registering it makes AppKit add the Help search field and index the help book —
11385            // behavior no hand-built menu reproduces.
11386            unsafe { app.setHelpMenu(Some(&help)) };
11387        }
11388        app.setMainMenu(Some(&menubar));
11389        unsafe { app.setServicesMenu(Some(&services)) };
11390    }
11391
11392    fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
11393        fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
11394            for sub in v.subviews() {
11395                unsafe { sub.setMenu(Some(menu)) };
11396                apply_to_subviews(&sub, menu);
11397            }
11398        }
11399        let Some(view) = h.downcast_ref::<NSView>() else {
11400            return;
11401        };
11402        if items.is_empty() {
11403            unsafe { view.setMenu(None) };
11404            return;
11405        }
11406        let menu = build_ns_menu(self.mtm, "", items);
11407        // Attach to the view AND its current subviews: a right-click that hit-tests a child
11408        // control (the label inside a padded target) must find the menu on the view it hit —
11409        // AppKit does not walk ancestors for `.menu`, and controls swallow the event.
11410        // DayFlipped's `rightMouseDown:` pops the menu explicitly; native controls (labels)
11411        // show their `.menu` through their own default path.
11412        unsafe { view.setMenu(Some(&menu)) };
11413        apply_to_subviews(view, &menu);
11414    }
11415
11416    fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
11417        transfer::source(h, source);
11418    }
11419    fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
11420        transfer::target(h, target);
11421    }
11422    fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
11423        // Consulted by the classes that override `menuForEvent:` (the canvas; docs/menus.md
11424        // "Dynamic context menus" lists the covered surfaces per backend).
11425        CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
11426    }
11427
11428    fn set_button_menu(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
11429        let Some(btn) = h.downcast_ref::<NSButton>() else {
11430            return;
11431        };
11432        // A pull-down opens on the mouse going down, as `NSPopUpButton` does, so a press can
11433        // drag straight onto an item and release there. Space and the accessibility press
11434        // still arrive through `performClick:`, which sends the same action.
11435        unsafe { btn.sendActionOn(objc2_app_kit::NSEventMask::LeftMouseDown) };
11436        BUTTON_MENUS.with(|t| t.insert(ptr_of(h), f));
11437    }
11438
11439    fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
11440        let key = ptr_of(h);
11441        // Pan is not a recognizer on macOS: the two-finger idiom is the trackpad SCROLL, so
11442        // the canvas view's own `scrollWheel:` override reports it for registered nodes.
11443        // Containers use a horizontal-only monitor so nested vertical scrolling still works.
11444        if kind == day_spec::GestureKind::Pan {
11445            PAN_NODES.with(|t| t.insert(key, node));
11446            install_container_pan_monitor();
11447            return;
11448        }
11449        // Nor is rotation: `DayCanvas::rotateWithEvent:` reads the trackpad's rotate events, so
11450        // it runs alongside the magnification recognizer a pinch attaches. Like Pan and Hover,
11451        // a rotation enabled on another view emits nothing.
11452        if kind == day_spec::GestureKind::Rotate {
11453            ROTATE_NODES.with(|t| t.insert(key, node));
11454            return;
11455        }
11456        // Nor is hover: it is a tracking area plus `mouseEntered:`/`mouseMoved:`/`mouseExited:`,
11457        // which only `DayCanvas` overrides — a hover enabled on another view emits nothing, the
11458        // same limitation Pan has.
11459        if kind == day_spec::GestureKind::Hover {
11460            // Idempotent, and it has to be checked here rather than falling through to the
11461            // recognizer guard below: day-core re-enables a gesture on rebuild, and a second
11462            // tracking area on the same view means a second copy of every hover event.
11463            let first = HOVER_NODES.with(|t| t.get(key)).is_none();
11464            HOVER_NODES.with(|t| t.insert(key, node));
11465            if first {
11466                install_tracking_area(h);
11467            }
11468            return;
11469        }
11470        // Idempotent: attach each kind at most once per view.
11471        let already = GESTURES.with(|m| {
11472            m.borrow()
11473                .get(&key)
11474                .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
11475        });
11476        if already {
11477            return;
11478        }
11479        let mtm = self.mtm;
11480        let target = DayGesture::new(mtm, node, kind);
11481        let recognizer: Retained<NSGestureRecognizer> = unsafe {
11482            match kind {
11483                day_spec::GestureKind::Drag => {
11484                    Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
11485                        NSPanGestureRecognizer::alloc(mtm),
11486                        Some(&target),
11487                        Some(sel!(fire:)),
11488                    ))
11489                }
11490                day_spec::GestureKind::Pinch => Retained::into_super(
11491                    objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
11492                        objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
11493                        Some(&target),
11494                        Some(sel!(fire:)),
11495                    ),
11496                ),
11497                _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
11498                    NSClickGestureRecognizer::alloc(mtm),
11499                    Some(&target),
11500                    Some(sel!(fire:)),
11501                )),
11502            }
11503        };
11504        unsafe { h.addGestureRecognizer(&recognizer) };
11505        GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
11506    }
11507
11508    fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
11509        unsafe {
11510            if let Some(id) = &a11y.identifier {
11511                h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
11512            }
11513            if let Some(label) = &a11y.label {
11514                h.setAccessibilityLabel(Some(&NSString::from_str(label)));
11515                APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
11516            } else {
11517                APP_LABELED.with(|t| t.remove(ptr_of(h)));
11518            }
11519            if let Some(hint) = &a11y.hint {
11520                h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
11521            }
11522            if let Some(value) = &a11y.value {
11523                let ns = NSString::from_str(value);
11524                h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
11525            }
11526            // Only apply an EXPLICIT role (canvas/custom pieces, e.g. a Meter): native controls
11527            // already report the right role, so Day records but doesn't override theirs (§13).
11528            if let Some(role) = ns_role(a11y.role) {
11529                h.setAccessibilityRole(Some(role));
11530            }
11531            if a11y.role == day_spec::Role::Tab {
11532                h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
11533            }
11534            if let Some(on) = a11y.selected {
11535                h.setAccessibilitySelected(on);
11536            }
11537            // Decorative / hidden: drop from the AX tree entirely. An ignored view alone is
11538            // not enough — AppKit promotes an ignored element's children into its parent's
11539            // list — so the subtree is cut off too, which also covers subviews added later
11540            // (list rows, re-created children). Hidden never flips back, so the override is
11541            // never lifted.
11542            if a11y.hidden {
11543                h.setAccessibilityElement(false);
11544                h.setAccessibilityChildren(Some(&NSArray::new()));
11545            }
11546        }
11547    }
11548
11549    /// The announcement request goes out from the primary window (any live element will
11550    /// do; the app object stands in before the window exists). Without VoiceOver nothing
11551    /// observes the notification, so posting is free.
11552    fn announce(&mut self, text: &str, urgent: bool) {
11553        use objc2_app_kit::{
11554            NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
11555            NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
11556            NSAccessibilityPriorityLevel,
11557        };
11558        let app = NSApplication::sharedApplication(self.mtm());
11559        let window = primary_content().and_then(|content| content.window());
11560        let element: &objc2::runtime::AnyObject = match &window {
11561            Some(window) => window,
11562            None => &app,
11563        };
11564        // High priority interrupts the current sentence; medium waits its turn.
11565        let priority = if urgent {
11566            NSAccessibilityPriorityLevel::High
11567        } else {
11568            NSAccessibilityPriorityLevel::Medium
11569        };
11570        let announcement = NSString::from_str(text);
11571        let priority = NSNumber::new_isize(priority.0);
11572        let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
11573        // SAFETY: the keys are AppKit's constants and both values are the types the
11574        // announcement notification documents (an NSString and an NSNumber).
11575        unsafe {
11576            let user_info = NSDictionary::from_slices::<NSString>(
11577                &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
11578                &values,
11579            );
11580            NSAccessibilityPostNotificationWithUserInfo(
11581                element,
11582                NSAccessibilityAnnouncementRequestedNotification,
11583                Some(&user_info),
11584            );
11585        }
11586    }
11587
11588    fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
11589        unsafe {
11590            let role = h
11591                .accessibilityRole()
11592                .map_or(day_spec::Role::None, |r| day_role_from_ns(&r.to_string()));
11593            // A picker answers its displayed selection and its enabled state itself: the
11594            // inline style is a stack of radios, not one control.
11595            let picker = picker::read_native(h);
11596            day_spec::NativeSnapshot {
11597                found: true,
11598                role,
11599                label: h.accessibilityLabel().map(|s| s.to_string()),
11600                value: h.accessibilityValue().and_then(|v| {
11601                    v.downcast_ref::<NSString>()
11602                        .map(std::string::ToString::to_string)
11603                }),
11604                identifier: h
11605                    .accessibilityIdentifier()
11606                    .map(|s| s.to_string())
11607                    .filter(|s| !s.is_empty()),
11608                text: match &picker {
11609                    Some((text, _)) => text.clone(),
11610                    None => native_text(h),
11611                },
11612                number: native_number(h),
11613                checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
11614                    match sw.state() {
11615                        s if s == NSControlStateValueOn => Some(true),
11616                        s if s == NSControlStateValueOff => Some(false),
11617                        // Mixed is neither on nor off.
11618                        _ => None,
11619                    }
11620                } else if let Some(btn) = h.downcast_ref::<NSButton>() {
11621                    // A Day button's selected state (`ButtonProps::selected`): its own
11622                    // `state`, which a momentary button holds off at rest.
11623                    BUTTON_SELECTED
11624                        .with(|m| m.borrow().contains_key(&ptr_of(h)))
11625                        .then(|| btn.state() == NSControlStateValueOn)
11626                } else {
11627                    None
11628                },
11629                // A label is a non-editable NSTextField whose `isEnabled` says nothing about
11630                // input; every other control answers for itself.
11631                enabled: match (&picker, h.downcast_ref::<NSControl>()) {
11632                    (Some((_, on)), _) => *on,
11633                    (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
11634                    (None, Some(c)) => Some(c.isEnabled()),
11635                    (None, None) => None,
11636                },
11637                // Off-window counts as not shown: nothing of it reaches the screen.
11638                visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
11639                frame: native_frame(h),
11640            }
11641        }
11642    }
11643
11644    fn request_frame(
11645        &mut self,
11646        host: &Handle,
11647        cb: day_spec::FrameCallback,
11648    ) -> day_spec::CancelFrame {
11649        frame::request(host, cb)
11650    }
11651
11652    fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
11653        OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
11654        unsafe { h.setNeedsDisplay(true) };
11655    }
11656    fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
11657        NAV_STATE.with(|m| {
11658            let m = m.borrow();
11659            let Some(st) = m.get(&ptr_of(host)) else {
11660                return false;
11661            };
11662            // A pane to toggle exists in `Split` and `Rail`; a stack has none and a tab bar
11663            // keeps its rows in the chrome, where hiding them would strand the user.
11664            if !matches!(
11665                st.presentation,
11666                NavPresentation::Split | NavPresentation::Rail
11667            ) {
11668                return false;
11669            }
11670            let item = &st.sidebar_item;
11671            // Set directly, not through the `animator` proxy. The proxy defers the change to
11672            // an animation the dayscript screenshot step does not wait on, so a scripted
11673            // toggle captured a sidebar that had not moved yet. AppKit's own
11674            // NSToolbarToggleSidebarItem still animates — it runs `toggleSidebar:` on the
11675            // controller and never comes through here.
11676            let collapsed = unsafe { item.isCollapsed() };
11677            unsafe { item.setCollapsed(!collapsed) };
11678            true
11679        })
11680    }
11681
11682    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
11683        let content = self.content.as_ref().ok_or("no window content")?;
11684        match self.shown_document_content(content) {
11685            Some(shown) => snapshot_view(&shown),
11686            None => snapshot_view(content),
11687        }
11688    }
11689
11690    /// Decode bytes into an `NSImage` (docs/images.md).
11691    ///
11692    /// `NSBitmapImageRep` is asked first and kept: it is what actually reads the container, it
11693    /// answers in PIXELS (`NSImage.size` is in points and reports a 144-DPI photo at
11694    /// two-thirds its real width), and it is the only thing here that can re-encode later.
11695    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
11696        use objc2::AllocAnyThread as _;
11697        let data = NSData::with_bytes(bytes);
11698        let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
11699        else {
11700            emit(
11701                WINDOW_NODE,
11702                Event::ImageDecoded {
11703                    req,
11704                    result: Err(day_spec::ImageError::Decode),
11705                },
11706            );
11707            return;
11708        };
11709        let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
11710        let info = day_spec::BitmapInfo {
11711            pixels: Size::new(w, h),
11712            // Decoded bytes carry no density — a PNG is simply its pixels. Only a staged @2x
11713            // asset has a scale, and that arrives through the named path instead.
11714            scale: 1.0,
11715            format: day_spec::ImageFormat::sniff(bytes),
11716            has_alpha: unsafe { rep.hasAlpha() },
11717        };
11718        // Built AT the rep's pixel size so it draws 1:1 by default: an NSImage otherwise adopts
11719        // the rep's own `size`, which ImageIO derives from the file's DPI — that is what shrinks
11720        // a 144-DPI photo for no reason the app asked for.
11721        let image = unsafe {
11722            objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
11723        };
11724        unsafe { image.addRepresentation(&rep) };
11725        BITMAPS.with(|m| {
11726            m.borrow_mut().insert(
11727                id.0,
11728                AppKitBitmap {
11729                    image,
11730                    rep: Some(rep),
11731                    info,
11732                },
11733            )
11734        });
11735        emit(
11736            WINDOW_NODE,
11737            Event::ImageDecoded {
11738                req,
11739                result: Ok(info),
11740            },
11741        );
11742    }
11743
11744    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
11745        BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
11746    }
11747
11748    /// The container's own metadata (docs/images.md).
11749    ///
11750    /// DPI is DERIVED rather than read from a tag: AppKit has already resolved the file's
11751    /// resolution into the rep's point size, so pixels-per-point × 72 is the number the platform
11752    /// itself believes — and it is right for containers that record resolution in ways EXIF
11753    /// does not.
11754    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
11755        let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
11756        let mut out = day_spec::ImageProperties::default();
11757        let size = unsafe { rep.size() };
11758        if size.width > 0.0 {
11759            let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
11760            // 72 is "no resolution recorded" wearing a number; reporting it would read as a fact
11761            // the file never stated.
11762            if (dpi - 72.0).abs() > 0.5 {
11763                out.dpi = Some(dpi);
11764            }
11765        }
11766        // EXIF arrives as a dictionary of the format's own keys. It is walked through
11767        // `msg_send!` rather than a downcast because a generic `NSDictionary` is not a
11768        // `DowncastTarget`.
11769        if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
11770            let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
11771            for key in &keys {
11772                let value: Option<Retained<objc2::runtime::AnyObject>> =
11773                    unsafe { msg_send![&*exif, objectForKey: &*key] };
11774                let Some(value) = value else { continue };
11775                let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
11776                let (k, v) = (key.to_string(), text.to_string());
11777                match k.as_str() {
11778                    "Orientation" => out.orientation = v.parse().ok(),
11779                    "DateTimeOriginal" => out.created = Some(v.clone()),
11780                    _ => {}
11781                }
11782                // Keys stay in EXIF's own vocabulary, passed through rather than translated —
11783                // the doc for `extra` promises exactly that.
11784                out.extra.push((k, v));
11785            }
11786        }
11787        Some(out)
11788    }
11789
11790    /// What `NSBitmapImageRep` WRITES. It reads more than this — WebP and HEIF among them — and
11791    /// the asymmetry is the platform's own, which is exactly why this duty exists instead of
11792    /// letting `Cap::ImageEncode` imply every format round-trips.
11793    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
11794        use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
11795        vec![Png, Jpeg, Tiff, Bmp, Gif]
11796    }
11797
11798    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
11799        let result = encode_bitmap(id, spec);
11800        emit(WINDOW_NODE, Event::ImageEncoded { req, result });
11801    }
11802
11803    fn release_image(&mut self, id: day_spec::BitmapId) {
11804        release_bitmap(id);
11805    }
11806
11807    /// Replay `ops` offscreen through the canvas's own painter (docs/canvas.md "Exporting") and
11808    /// keep the result in the decode table, so `image`, `encode_image` and `DrawOp::Image` take
11809    /// it like any decoded bitmap.
11810    ///
11811    /// The paint runs on a `day_spec::offscreen` thread: CoreGraphics draws into a bitmap
11812    /// context from any thread, so a long replay (a map tile of a thousand paths) no longer
11813    /// holds a frame. The images and fonts the ops need are resolved here first, the painted
11814    /// `CGImage` comes back on the main queue, and the table insert and the answer happen
11815    /// there, in that order.
11816    fn render_bitmap(
11817        &mut self,
11818        req: u64,
11819        id: day_spec::BitmapId,
11820        ops: &[DrawOp],
11821        size: Size,
11822        scale: f64,
11823    ) {
11824        let resources = Sendable(OffscreenResources::collect(ops));
11825        let ops = ops.to_vec();
11826        day_spec::offscreen::spawn(move || {
11827            // Bound whole so the closure captures the `Send` wrapper, not its field.
11828            let resources = resources;
11829            let painted = day_spec::ffi_guard::contain(
11830                Err(day_spec::ExportError::Failed(
11831                    "the offscreen painter panicked".into(),
11832                )),
11833                || {
11834                    let started = std::time::Instant::now();
11835                    let painted = resources
11836                        .0
11837                        .with_installed(|| render_bitmap_cgimage(&ops, size, scale));
11838                    // The painter's own cost, apart from the queuing a caller's clock sees.
11839                    log::debug!(
11840                        "day-toolkit-appkit: bitmap {}x{} painted in {:.1} ms ({} ops)",
11841                        size.width * scale,
11842                        size.height * scale,
11843                        started.elapsed().as_secs_f64() * 1000.0,
11844                        ops.len()
11845                    );
11846                    painted
11847                },
11848            );
11849            let painted = Sendable(painted);
11850            <AppKit as Platform>::post(Box::new(move || {
11851                let painted = painted;
11852                let result = painted.0.map(|cg_image| {
11853                    let bitmap = bitmap_from_cgimage(&cg_image, scale);
11854                    let info = bitmap.info;
11855                    BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
11856                    info
11857                });
11858                emit(WINDOW_NODE, Event::BitmapRendered { req, result });
11859            }));
11860        });
11861    }
11862
11863    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
11864        let result = render_pdf_bytes(pages, info);
11865        emit(WINDOW_NODE, Event::PdfRendered { req, result });
11866    }
11867
11868    /// `NSFontManager.availableFontFamilies` + `availableMembersOfFontFamily:`, whose members
11869    /// are `[postscriptName, styleName, weight 0 … 15, traits]` (docs/fonts.md). The `.`-prefixed
11870    /// families are the system's private UI faces and are skipped, as Font Book skips them.
11871    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
11872        use day_spec::FontWeight as W;
11873        let mtm =
11874            objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
11875        let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
11876        let mut out = Vec::new();
11877        for family in &unsafe { manager.availableFontFamilies() } {
11878            let name = family.to_string();
11879            if name.starts_with('.') {
11880                continue;
11881            }
11882            let mut faces = Vec::new();
11883            if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
11884                for member in &members {
11885                    if member.count() < 4 {
11886                        continue;
11887                    }
11888                    let style = member
11889                        .objectAtIndex(1)
11890                        .downcast_ref::<NSString>()
11891                        .map_or_default(std::string::ToString::to_string);
11892                    let weight = member
11893                        .objectAtIndex(2)
11894                        .downcast_ref::<objc2_foundation::NSNumber>()
11895                        .map_or(5, objc2_foundation::NSNumber::integerValue);
11896                    let traits = member
11897                        .objectAtIndex(3)
11898                        .downcast_ref::<objc2_foundation::NSNumber>()
11899                        .map_or(0, objc2_foundation::NSNumber::integerValue);
11900                    let weight = match weight {
11901                        ..=2 => W::UltraLight,
11902                        3 => W::Thin,
11903                        4 => W::Light,
11904                        5 => W::Regular,
11905                        6 => W::Medium,
11906                        7 | 8 => W::Semibold,
11907                        9 => W::Bold,
11908                        10 | 11 => W::Heavy,
11909                        _ => W::Black,
11910                    };
11911                    let italic = traits & 0x1 != 0; // NSItalicFontMask
11912                    faces.push(day_spec::FontFace {
11913                        name: if style.is_empty() {
11914                            day_spec::FontFace::synthesized_name(weight, italic)
11915                        } else {
11916                            style
11917                        },
11918                        weight,
11919                        italic,
11920                    });
11921                }
11922            }
11923            out.push(day_spec::FontFamilyInfo {
11924                family: name,
11925                faces,
11926            });
11927        }
11928        out
11929    }
11930
11931    /// `sizeWithAttributes:` with the attributes `replay` draws with; the ascent is the
11932    /// font's own, so `at.y + ascent` is where the glyphs' baseline lands.
11933    fn measure_text(
11934        &mut self,
11935        text: &str,
11936        size: f64,
11937        font: &day_spec::CanvasFont,
11938    ) -> Option<day_spec::TextMetrics> {
11939        let nsfont = canvas_nsfont(size, font);
11940        let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
11941        let ns = NSString::from_str(text);
11942        let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
11943        // The INK box: `NSStringDrawingUsesDeviceMetrics` is what turns `boundingRectWithSize:`
11944        // from the layout box into the glyphs' own bounds, and it comes back baseline-relative
11945        // with y up — hence the flip. An unbounded size so nothing wraps: this measures one line.
11946        let unbounded = NSSize::new(f64::MAX, f64::MAX);
11947        let ink: NSRect = unsafe {
11948            msg_send![
11949                &ns,
11950                boundingRectWithSize: unbounded,
11951                options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
11952                attributes: &*attrs,
11953            ]
11954        };
11955        Some(day_spec::TextMetrics::from_baseline(
11956            sz.width,
11957            nsfont.ascender(),
11958            sz.height - nsfont.ascender(),
11959            nsfont.capHeight(),
11960            day_spec::Rect::new(
11961                ink.origin.x,
11962                -(ink.origin.y + ink.size.height),
11963                ink.size.width,
11964                ink.size.height,
11965            ),
11966        ))
11967    }
11968
11969    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
11970        let content = self.content.as_ref().ok_or("no window content")?;
11971        match self.shown_document_content(content) {
11972            Some(shown) => snapshot_view_chrome(&shown),
11973            None => snapshot_view_chrome(content),
11974        }
11975    }
11976
11977    fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
11978        snapshot_view(host)
11979    }
11980
11981    fn open_window(
11982        &mut self,
11983        id: NodeId,
11984        options: &WindowOptions,
11985        kind: day_spec::WindowKind,
11986    ) -> day_spec::WindowOpenReply<Handle> {
11987        let prefs = kind.is_panel();
11988        let (window, delegate, content) = self.make_window(options, prefs, Some(id));
11989        if prefs {
11990            // A settings panel is one-of-a-kind and centered, and it stays OUT of the Window
11991            // menu — the macOS convention every stock app follows (docs/windows.md).
11992            window.center();
11993            unsafe { window.setExcludedFromWindowsMenu(true) };
11994        } else {
11995            // Stagger, don't stack. Without this every window opens at the same centered frame
11996            // and the one underneath is invisible — which is exactly what two Day windows did.
11997            //
11998            // `cascadeTopLeftFromPoint:` puts the window AT the point it is given and answers
11999            // the point for the one after, so the series has to be primed from the primary
12000            // rather than seeded with its corner — seeding lands the first new window exactly
12001            // on top of the primary, which is the bug this replaces.
12002            let from = match self.cascade {
12003                Some(p) => p,
12004                None => self.window.as_ref().map_or(NSPoint::new(0.0, 0.0), |w| {
12005                    let f = w.frame();
12006                    let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
12007                    // Asking the primary to cascade from where it already is leaves it
12008                    // there and answers the next slot — the offset the first new window wants.
12009                    unsafe { w.cascadeTopLeftFromPoint(top_left) }
12010                }),
12011            };
12012            self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
12013        }
12014        window_chrome::place(&window, options.placement);
12015        // `center` (a settings panel's, or a `Centered` placement's) uses the main screen, the
12016        // one with the keyboard focus, which on a Mac with several displays need not be the
12017        // app's: such a window goes to the primary's screen instead. A scripted run on the
12018        // capture display relies on this to keep the window in its captures.
12019        if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
12020            center_on_screen_of(&window, self.window.as_deref());
12021        }
12022        // Secondary windows need the same initial client-coordinate pinning as the
12023        // primary. Native document pages may move here before any resize notification.
12024        let _ = pin_below_title_bar(&window);
12025        if !options.start_hidden {
12026            window.makeKeyAndOrderFront(None);
12027        }
12028        // Same macOS 26 quirk as the primary (`run`): a window ordered front before its
12029        // first turn drops pre-run layer displays — nudge every layer once.
12030        mark_tree_needs_display(&content);
12031        self.secondary.push(SecondaryWin {
12032            window,
12033            delegate,
12034            content: content.clone(),
12035        });
12036        day_spec::WindowOpenReply::Open(content)
12037    }
12038
12039    fn native_window_tabs(&self) -> bool {
12040        true
12041    }
12042    fn group_windows(&mut self, hosts: &[Handle]) {
12043        let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
12044        let Some(first) = windows.first() else {
12045            return;
12046        };
12047        unsafe {
12048            NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
12049        }
12050        // Explicit insertion respects the model even when system automatic tabbing is off.
12051        for window in windows.iter().skip(1) {
12052            unsafe {
12053                first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
12054            }
12055        }
12056        if let Some(group) = first.tabGroup() {
12057            if !group.isTabBarVisible() {
12058                unsafe {
12059                    first.toggleTabBar(None);
12060                }
12061            }
12062            for (i, window) in windows.iter().enumerate() {
12063                group.insertWindow_atIndex(window, i as isize);
12064            }
12065        }
12066        // Adding/showing a native tab strip changes contentLayoutRect without necessarily
12067        // resizing the window. Re-pin every member and tell the layout tree its usable size.
12068        for window in &windows {
12069            if let Some(size) = pin_below_title_bar(window) {
12070                let node = window
12071                    .delegate()
12072                    .and_then(|d| d.downcast::<DayWinDelegate>().ok())
12073                    .and_then(|d| d.ivars().node)
12074                    .unwrap_or(WINDOW_NODE);
12075                emit(node, Event::WindowResized(size));
12076            }
12077        }
12078    }
12079    fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
12080        let Some(window) = self.ns_window_for(host) else {
12081            return Vec::new();
12082        };
12083        let windows = window.tabGroup().map(|g| g.windows());
12084        let Some(windows) = windows else {
12085            return Vec::new();
12086        };
12087        windows
12088            .iter()
12089            .filter_map(|window| {
12090                self.secondary
12091                    .iter()
12092                    .find(|w| std::ptr::eq(&raw const *w.window, &raw const *window))
12093                    .and_then(|w| w.delegate.ivars().node)
12094            })
12095            .collect()
12096    }
12097
12098    fn close_window(&mut self, host: &Handle) {
12099        // `close()` runs the full native path — windowWillClose → `WindowClosed` →
12100        // day-core teardown — so programmatic and title-bar closes are one code path.
12101        if let Some(w) = self
12102            .secondary
12103            .iter()
12104            .find(|w| ptr_of(&w.content) == ptr_of(host))
12105        {
12106            w.window.close();
12107        }
12108    }
12109
12110    fn focus_window(&mut self, host: &Handle) {
12111        if let Some(w) = self
12112            .secondary
12113            .iter()
12114            .find(|w| ptr_of(&w.content) == ptr_of(host))
12115        {
12116            w.window.makeKeyAndOrderFront(None);
12117        }
12118    }
12119
12120    fn fit_window(&mut self, host: &Handle, size: Size) {
12121        let Some(w) = self
12122            .secondary
12123            .iter()
12124            .find(|w| ptr_of(&w.content) == ptr_of(host))
12125        else {
12126            return;
12127        };
12128        unsafe {
12129            // `setContentSize:` rather than `setFrame:`: Day measured the CONTENT, and AppKit
12130            // adds the title bar itself. Sizing the frame instead would eat the bar's height out
12131            // of the panel and clip the last row by exactly that much.
12132            w.window
12133                .setContentSize(NSSize::new(size.width, size.height));
12134            // A settings panel that fits its content has no reason to be resizable, and macOS
12135            // panels are not — dropping the mask also stops the user dragging it back to a size
12136            // the content does not fill.
12137            let mask = w.window.styleMask();
12138            w.window
12139                .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
12140            w.window.center();
12141        }
12142        center_on_screen_of(&w.window, self.window.as_deref());
12143    }
12144
12145    fn set_window_title(&mut self, host: &Handle, title: &str) {
12146        if let Some(w) = self
12147            .secondary
12148            .iter()
12149            .find(|w| ptr_of(&w.content) == ptr_of(host))
12150        {
12151            w.window.setTitle(&NSString::from_str(title));
12152            return;
12153        }
12154        // The PRIMARY window is retitlable too. It is an ordinary window (docs/windows.md), so
12155        // `window_title` in the first window's shell and `set_title` on `initial_window()` both
12156        // arrive here — and searching only the secondary list silently dropped them.
12157        if self
12158            .content
12159            .as_ref()
12160            .is_some_and(|c| ptr_of(c) == ptr_of(host))
12161            && let Some(w) = self.window.as_ref()
12162        {
12163            w.setTitle(&NSString::from_str(title));
12164        }
12165    }
12166
12167    fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
12168        use day_spec::WindowChange as C;
12169        let Some(window) = self.ns_window_for(host) else {
12170            return;
12171        };
12172        match change {
12173            C::State(state) => set_ns_window_state(&window, *state),
12174            // Screen capture, recording and sharing see an empty window; the user still does.
12175            C::ContentProtected(on) => window.setSharingType(if *on {
12176                objc2_app_kit::NSWindowSharingType::None
12177            } else {
12178                objc2_app_kit::NSWindowSharingType::ReadOnly
12179            }),
12180            other => window_chrome::apply_property(&window, other),
12181        }
12182    }
12183
12184    fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
12185        self.ns_window_for(host)
12186            .map(|w| window_chrome::frame_of(&w))
12187    }
12188
12189    fn monitors(&self) -> Vec<day_spec::Monitor> {
12190        window_chrome::monitors(self.mtm)
12191    }
12192
12193    /// The Dock menu lists them: day-core folds the run-time shortcuts into the model it sends
12194    /// through `set_dock_menu`, so there is nothing more to install here.
12195    fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
12196
12197    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
12198        dock::set_app_items(self.mtm, items);
12199    }
12200
12201    fn set_drag_region(&mut self, h: &Handle, drag: bool) {
12202        window_chrome::set_drag_region(h, drag);
12203    }
12204
12205    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
12206        status_item::set_items(self.mtm, items);
12207    }
12208
12209    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
12210        status_item::set_progress(self.mtm, progress);
12211    }
12212
12213    fn set_dock_visible(&mut self, visible: bool) {
12214        status_item::set_dock_visible(self.mtm, visible);
12215    }
12216
12217    fn set_keep_running(&mut self, keep: bool) {
12218        status_item::set_keep_running(keep);
12219    }
12220
12221    fn quit_app(&mut self) {
12222        let app = NSApplication::sharedApplication(self.mtm);
12223        unsafe { app.terminate(None) };
12224    }
12225
12226    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
12227        use present::PresentSpec;
12228        let mtm = self.mtm;
12229        // Sheets attach to the KEY window at present time (docs/windows.md) — a dialog
12230        // raised from a secondary/preferences window belongs on it; primary is the
12231        // fallback when no DAY window is key (a system panel may hold key status).
12232        let app = NSApplication::sharedApplication(mtm);
12233        let key = app.keyWindow().filter(|k| {
12234            let mut owner = k.clone();
12235            while let Some(parent) = owner.sheetParent() {
12236                owner = parent;
12237            }
12238            self.window
12239                .as_deref()
12240                .is_some_and(|w| std::ptr::eq(w, &raw const *owner))
12241                || self
12242                    .secondary
12243                    .iter()
12244                    .any(|s| std::ptr::eq(&raw const *s.window, &raw const *owner))
12245        });
12246        let Some(mut window) = key.or_else(|| self.window.clone()) else {
12247            emit(
12248                WINDOW_NODE,
12249                Event::PresentResult {
12250                    req,
12251                    result: present::PresentResult::Dismissed,
12252                },
12253            );
12254            return;
12255        };
12256        // A dialog opened from a modal cover belongs on the active sheet, not behind it.
12257        while let Some(sheet) = window.attachedSheet() {
12258            window = sheet;
12259        }
12260        // File pickers use a different native object (NSOpen/NSSavePanel), not an NSAlert.
12261        match spec {
12262            PresentSpec::OpenFile {
12263                filters, multiple, ..
12264            } => {
12265                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
12266                unsafe {
12267                    panel.setCanChooseFiles(true);
12268                    panel.setCanChooseDirectories(false);
12269                    panel.setAllowsMultipleSelection(*multiple);
12270                    panel.setMessage(Some(&NSString::from_str(spec.title())));
12271                }
12272                apply_allowed_file_types(&panel, filters);
12273                let p = panel.clone();
12274                // Completion blocks run inside a C ABI frame, so their bodies are contained
12275                // like every other trampoline (§8.5) — this one and the four below.
12276                let handler: block2::RcBlock<dyn Fn(isize)> =
12277                    block2::RcBlock::new(move |resp: isize| {
12278                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
12279                    });
12280                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12281                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
12282                return;
12283            }
12284            // The folder chooser is the same NSOpenPanel with files and directories swapped.
12285            PresentSpec::OpenFolder { .. } => {
12286                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
12287                unsafe {
12288                    panel.setCanChooseFiles(false);
12289                    panel.setCanChooseDirectories(true);
12290                    panel.setCanCreateDirectories(true);
12291                    panel.setAllowsMultipleSelection(false);
12292                    panel.setMessage(Some(&NSString::from_str(spec.title())));
12293                }
12294                let p = panel.clone();
12295                let handler: block2::RcBlock<dyn Fn(isize)> =
12296                    block2::RcBlock::new(move |resp: isize| {
12297                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
12298                    });
12299                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12300                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
12301                return;
12302            }
12303            PresentSpec::SaveFile { suggested_name, .. } => {
12304                let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
12305                unsafe {
12306                    panel.setMessage(Some(&NSString::from_str(spec.title())));
12307                    panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
12308                }
12309                apply_allowed_file_types(&panel, spec.filters());
12310                let p = panel.clone();
12311                let handler: block2::RcBlock<dyn Fn(isize)> =
12312                    block2::RcBlock::new(move |resp: isize| {
12313                        // The pieces layer copies the staged bytes to the chosen local path.
12314                        ffi_guard::contain((), || emit_panel_result(req, resp, &p));
12315                    });
12316                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12317                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
12318                return;
12319            }
12320            _ => {}
12321        }
12322        let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
12323        unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
12324        if let Some(msg) = spec.message() {
12325            unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
12326        }
12327        // The completion handler must outlive this call, so it's a heap (Rc) block.
12328        let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
12329            PresentSpec::Dialog { buttons, .. } => {
12330                if buttons
12331                    .iter()
12332                    .any(|b| b.role == present::ButtonRole::Destructive)
12333                {
12334                    unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
12335                }
12336                for b in buttons {
12337                    unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
12338                }
12339                block2::RcBlock::new(move |resp: isize| {
12340                    ffi_guard::contain((), || {
12341                        // NSAlertFirstButtonReturn = 1000; add order == spec order.
12342                        let idx = resp - 1000;
12343                        emit(
12344                            WINDOW_NODE,
12345                            Event::PresentResult {
12346                                req,
12347                                result: present::PresentResult::Button(idx as i64),
12348                            },
12349                        );
12350                        PRESENT_ALERTS.with(|m| {
12351                            m.borrow_mut().remove(&req);
12352                        });
12353                    });
12354                })
12355            }
12356            PresentSpec::Prompt {
12357                placeholder,
12358                initial,
12359                ok,
12360                cancel,
12361                ..
12362            } => {
12363                let tf = unsafe { NSTextField::new(mtm) };
12364                unsafe {
12365                    tf.setFrame(NSRect::new(
12366                        NSPoint::new(0.0, 0.0),
12367                        NSSize::new(260.0, 24.0),
12368                    ));
12369                    tf.setEditable(true);
12370                    tf.setBezeled(true);
12371                    tf.setStringValue(&NSString::from_str(initial));
12372                    tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
12373                    alert.setAccessoryView(Some(&tf));
12374                    alert.addButtonWithTitle(&NSString::from_str(ok)); // resp 1000
12375                    alert.addButtonWithTitle(&NSString::from_str(cancel)); // resp 1001
12376                }
12377                block2::RcBlock::new(move |resp: isize| {
12378                    ffi_guard::contain((), || {
12379                        let result = if resp == 1000 {
12380                            present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
12381                        } else {
12382                            present::PresentResult::Dismissed
12383                        };
12384                        emit(WINDOW_NODE, Event::PresentResult { req, result });
12385                        PRESENT_ALERTS.with(|m| {
12386                            m.borrow_mut().remove(&req);
12387                        });
12388                    });
12389                })
12390            }
12391            // File pickers returned early above.
12392            PresentSpec::OpenFile { .. }
12393            | PresentSpec::OpenFolder { .. }
12394            | PresentSpec::SaveFile { .. } => unreachable!(),
12395        };
12396        unsafe {
12397            alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
12398        }
12399        PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
12400    }
12401
12402    fn dismiss(&mut self, req: u64) {
12403        // Close the sheet; its completion handler fires but its (native) result is dropped
12404        // because day-core already removed the pending request when it resolved.
12405        let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
12406        if let Some(alert) = alert {
12407            let sheet = alert.window();
12408            if let Some(parent) = sheet.sheetParent() {
12409                unsafe { parent.endSheet(&sheet) };
12410            }
12411        }
12412        // File-picker sheets are their own NSWindow.
12413        let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
12414        if let Some(panel) = panel
12415            && let Some(parent) = panel.sheetParent()
12416        {
12417            unsafe { parent.endSheet(&panel) };
12418        }
12419    }
12420
12421    fn application_handlers(
12422        &mut self,
12423        query: &day_spec::applications::HandlerQuery,
12424    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
12425    {
12426        applications::handlers(query)
12427    }
12428
12429    fn open_url_with_application(
12430        &mut self,
12431        url: &str,
12432        application: &str,
12433        completion: day_spec::applications::OpenApplicationCompletion,
12434    ) {
12435        applications::open(url, application, completion);
12436    }
12437
12438    fn share_support(&self) -> day_spec::Support {
12439        day_spec::Support::Native
12440    }
12441    fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
12442        use objc2::{msg_send, runtime::AnyObject};
12443        use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
12444        let Some(mtm) = objc2::MainThreadMarker::new() else {
12445            return false;
12446        };
12447        let Some(url) = NSURL::URLWithString(&NSString::from_str(&spec.url)) else {
12448            return false;
12449        };
12450        let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
12451        let Some(window_view) = app.keyWindow().and_then(|w| w.contentView()) else {
12452            return false;
12453        };
12454        unsafe {
12455            let items = NSArray::from_retained_slice(&[url]);
12456            let picker: objc2::rc::Allocated<AnyObject> =
12457                msg_send![objc2::class!(NSSharingServicePicker), alloc];
12458            let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
12459            let delegate = DaySharePickerDelegate::alloc(mtm).set_ivars(SharePickerIvars {
12460                actions: spec.actions.clone(),
12461            });
12462            let delegate: Retained<DaySharePickerDelegate> = msg_send![super(delegate), init];
12463            let _: () = msg_send![&*picker, setDelegate: &*delegate];
12464            // Pointing at the control that asked, under it; without one, at the window's top
12465            // trailing corner.
12466            let (view, rect, edge) = if let Some(view) = anchor {
12467                (view.clone(), view.bounds(), 1usize)
12468            } else {
12469                let bounds = window_view.bounds();
12470                let y = if window_view.isFlipped() {
12471                    30.0
12472                } else {
12473                    bounds.size.height - 30.0
12474                };
12475                let rect = NSRect::new(
12476                    NSPoint::new(bounds.size.width - 30.0, y),
12477                    NSSize::new(1.0, 1.0),
12478                );
12479                (window_view, rect, 3usize)
12480            };
12481            let _: () =
12482                msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: edge];
12483            // The picker holds its delegate weakly: keep both until the next share.
12484            self.sharing = Some(picker);
12485            self.sharing_delegate = Some(delegate);
12486        }
12487        true
12488    }
12489    fn open_url(&mut self, url: &str) {
12490        // NSWorkspace opens the URL in the user's default handler (Safari for http(s), Mail for
12491        // mailto:, …). An unparseable string yields no NSURL and is silently ignored.
12492        let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
12493        if let Some(nsurl) = nsurl {
12494            unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
12495        }
12496    }
12497}
12498
12499/// Apply a file dialog's extension filters (`allowedFileTypes` — deprecated but still the simplest
12500/// extension-based API; `UTType` would pull in another framework crate for no benefit here).
12501#[allow(deprecated)]
12502fn apply_allowed_file_types(
12503    panel: &objc2_app_kit::NSSavePanel,
12504    filters: &[day_spec::present::FileFilter],
12505) {
12506    let exts: Vec<Retained<NSString>> = filters
12507        .iter()
12508        .flat_map(|f| f.extensions.iter())
12509        .map(|e| NSString::from_str(e))
12510        .collect();
12511    if !exts.is_empty() {
12512        let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
12513        let arr = objc2_foundation::NSArray::from_slice(&refs);
12514        unsafe { panel.setAllowedFileTypes(Some(&arr)) };
12515    }
12516}
12517
12518/// Turn an open panel completion into a `PresentResult` and enqueue it (`NSModalResponseOK` = 1):
12519/// every chosen URL, so a multiple-selection pick reports all of its files (and a folder
12520/// chooser its one directory).
12521fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
12522    let mut paths = Vec::new();
12523    if resp == 1 {
12524        for url in &unsafe { panel.URLs() } {
12525            if let Some(p) = unsafe { url.path() } {
12526                paths.push(p.to_string());
12527            }
12528        }
12529    }
12530    let result = if paths.is_empty() {
12531        present::PresentResult::Dismissed
12532    } else {
12533        present::PresentResult::Files(paths)
12534    };
12535    emit(WINDOW_NODE, Event::PresentResult { req, result });
12536    PRESENT_PANELS.with(|m| {
12537        m.borrow_mut().remove(&req);
12538    });
12539}
12540
12541/// Turn a save panel completion into a `PresentResult` and enqueue it (`NSModalResponseOK` = 1).
12542fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
12543    let result = if resp == 1 {
12544        unsafe { panel.URL() }
12545            .and_then(|url| unsafe { url.path() })
12546            .map_or(present::PresentResult::Dismissed, |p| {
12547                present::PresentResult::Files(vec![p.to_string()])
12548            })
12549    } else {
12550        present::PresentResult::Dismissed
12551    };
12552    emit(WINDOW_NODE, Event::PresentResult { req, result });
12553    PRESENT_PANELS.with(|m| {
12554        m.borrow_mut().remove(&req);
12555    });
12556}
12557
12558impl Platform for AppKit {
12559    const TARGET: &'static str = "macos-appkit";
12560    const TOOLKIT: &'static str = "appkit";
12561
12562    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
12563        let mtm = self.mtm;
12564        // The App menu / About use the app's display name. `app_name` overrides the (possibly
12565        // decorated) window title; setting the process name also makes the standard About panel and
12566        // the bold App-menu title show it (an unbundled binary otherwise shows the exe name).
12567        self.app_name = options
12568            .app_name
12569            .clone()
12570            .unwrap_or_else(|| options.title.clone());
12571        // The bold App-menu title, the About panel and Quit all show the app's NAME. Always set
12572        // it, not just when `app_name` was given explicitly — an app that only set `title` was
12573        // showing its kebab-case cargo target ("day-sheets") where its name belongs.
12574        //
12575        // Two sources, because AppKit consults them in order: the main bundle's CFBundleName
12576        // wins when there is one, and `day launch` runs the binary UNBUNDLED during development,
12577        // where the name falls back to the executable's file name. Writing the info dictionary
12578        // covers the bundled case; the process name covers the unbundled one.
12579        unsafe {
12580            objc2_foundation::NSProcessInfo::processInfo()
12581                .setProcessName(&NSString::from_str(&self.app_name));
12582            let bundle = objc2_foundation::NSBundle::mainBundle();
12583            let info: Option<Retained<objc2_foundation::NSDictionary>> =
12584                msg_send![&bundle, infoDictionary];
12585            if let Some(info) = info {
12586                let key = NSString::from_str("CFBundleName");
12587                let value = NSString::from_str(&self.app_name);
12588                // `infoDictionary` is documented immutable, but the instance backing an
12589                // unbundled process is a mutable dictionary; guard the send so a genuinely
12590                // immutable one is left alone instead of raising.
12591                if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
12592                    let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
12593                }
12594            }
12595        }
12596        // RTL locales (docs/localization): AppleTextDirection flips AppKit's app-wide
12597        // userInterfaceLayoutDirection (label alignment, slider fill, control mirroring) —
12598        // read at NSApplication init, so register before sharedApplication. Registration
12599        // domain only: volatile, never persisted to the app's defaults.
12600        if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
12601            unsafe {
12602                use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
12603                let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
12604                    .into_super()
12605                    .into_super()
12606                    .into_super();
12607                let dict = NSDictionary::from_retained_objects(
12608                    &[
12609                        &*NSString::from_str("AppleTextDirection"),
12610                        &*NSString::from_str("NSForceRightToLeftWritingDirection"),
12611                    ],
12612                    &[yes.clone(), yes],
12613                );
12614                NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
12615            }
12616        }
12617        let app = NSApplication::sharedApplication(mtm);
12618        // A menu-bar app keeps out of the Dock from the first frame (docs/status-item.md): its
12619        // bundle carries LSUIElement, and an unbundled `day launch` run hears DAY_MACOS_DOCK=0.
12620        let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
12621            || unsafe {
12622                let bundle = objc2_foundation::NSBundle::mainBundle();
12623                let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
12624                    &bundle,
12625                    objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
12626                ];
12627                value.is_some_and(|v| {
12628                    let on: bool = msg_send![&v, boolValue];
12629                    on
12630                })
12631            };
12632        app.setActivationPolicy(if menu_bar_app {
12633            NSApplicationActivationPolicy::Accessory
12634        } else {
12635            NSApplicationActivationPolicy::Regular
12636        });
12637        let document_delegate = documents::delegate(mtm);
12638        app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
12639        // DAY_THEME=light|dark forces the appearance app-wide (themed CI screenshot runs and
12640        // local theme checks); unset ⇒ follow the system.
12641        if let Ok(theme) = std::env::var("DAY_THEME") {
12642            let name = match theme.as_str() {
12643                "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
12644                "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
12645                _ => None,
12646            };
12647            if let Some(name) = name {
12648                let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
12649                unsafe { app.setAppearance(appearance.as_deref()) };
12650            }
12651        }
12652        // Bundled custom fonts (§18.4) must be registered before the first label realizes.
12653        register_bundled_fonts();
12654
12655        // Default menu bar (standard app menu + Edit) so ⌘Q / Cut-Copy-Paste work before the app
12656        // installs its own via `app_menu(...)`. Rebuilt after `ready` for the items that depend
12657        // on the app's registrations — see there.
12658        let app_name = self.app_name.clone();
12659        install_main_menu(mtm, &app, &app_name);
12660        // App activation / termination → day lifecycle events (docs/lifecycle.md).
12661        install_lifecycle_observers();
12662        install_appearance_observer();
12663        install_reduce_motion_observer();
12664
12665        let (window, delegate, content) = self.make_window(&options, false, None);
12666        // Optional window-appearance override (opt-in via env). An app with a fixed light/dark
12667        // palette sets `DAY_APPEARANCE=light|dark` so native controls (list, fields, editor) match
12668        // its own colors instead of following the system appearance. Unset = follow the system.
12669        let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
12670            Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
12671            Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
12672            _ => None,
12673        };
12674        if let Some(name) = appearance_name
12675            && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
12676        {
12677            window.setAppearance(Some(&appearance));
12678        }
12679        // The primary delegate lives for the process (this frame never returns); secondary
12680        // delegates are retained in `self.secondary`.
12681        std::mem::forget(delegate);
12682
12683        self.window = Some(window.clone());
12684        self.content = Some(content.clone());
12685        PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
12686
12687        // The root lays out below the title bar, not under it (§7.7).
12688        let layout = pin_below_title_bar(&window)
12689            .unwrap_or(Size::new(options.size.width, options.size.height));
12690        ready(self, content, layout);
12691
12692        // `ready` ran the app's root() — registrations are in. Without a new-window
12693        // builder only one Normal window can ever exist: turn automatic tabbing off so no
12694        // tab bar, "+" button, or dead tab menu items appear (docs/windows.md).
12695        if day_core::windows::new_window_action_id() == 0
12696            && options.tabbing == day_spec::WindowTabbing::Automatic
12697        {
12698            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
12699        }
12700        // The DEFAULT menu bar was built before `root()` ran, so its registration-dependent
12701        // items — Settings…/⌘, and File ▸ New Window — could not exist yet. Rebuild it now that
12702        // they can. An app with its own `app_menu` model already replaced the whole bar and
12703        // gets its items through the injection path instead.
12704        if !day_core::has_app_menu() {
12705            install_main_menu(mtm, &app, &app_name);
12706        }
12707
12708        // Reopen where the user left it (docs/windows.md). AppKit persists the frame under an
12709        // autosave name and hands it back on request; `setFrameUsingName` answers false the
12710        // first time, which is when centering is the right answer.
12711        //
12712        // NOT while a dayscript is driving or `DAY_WINDOW` has forced a size: a restored frame
12713        // would make every captured screenshot's dimensions depend on where the developer last
12714        // dragged the window, and the capture suites compare those across machines.
12715        let deterministic =
12716            std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
12717        let autosave = NSString::from_str("day.main");
12718        if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
12719            window.center();
12720            // An explicit placement wins over centering, but not over the frame the user left.
12721            window_chrome::place(&window, options.placement);
12722        }
12723        // A scripted run whose capture needs a display scale this host's displays lack opens on
12724        // the one `day launch` made for it (`DAY_WINDOW_SCREEN`, a CGDirectDisplayID): a
12725        // capture is the window server's pixels, so it has the scale of the display under it.
12726        if let Some(screen) = capture_screen(mtm) {
12727            let (visible, frame) = (screen.visibleFrame(), window.frame());
12728            window.setFrameOrigin(NSPoint::new(
12729                visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12730                visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
12731            ));
12732        }
12733        if !deterministic {
12734            unsafe { window.setFrameAutosaveName(&autosave) };
12735        }
12736        if !options.start_hidden {
12737            window.makeKeyAndOrderFront(None);
12738            app.activate();
12739        }
12740        // The root was mounted before the window was shown (ready() runs first), and on
12741        // macOS 26 layer displays requested pre-run are dropped for a window ordered front
12742        // before the app finishes launching — the window stays blank until the next real
12743        // event. Re-mark the whole tree so the first run-loop turn commits a full frame.
12744        if let Some(content) = window.contentView() {
12745            mark_tree_needs_display(&content);
12746        }
12747        if std::env::var_os("DAY_DUMP").is_some() {
12748            std::thread::spawn(|| {
12749                std::thread::sleep(std::time::Duration::from_millis(2000));
12750                Self::post(Box::new(|| {
12751                    // The primary's content specifically (docs/windows.md).
12752                    if let Some(content) = primary_content() {
12753                        let desc: Retained<NSString> =
12754                            unsafe { msg_send![&*content, _subtreeDescription] };
12755                        log::warn!("{desc}");
12756                    }
12757                }));
12758            });
12759        }
12760        app.run();
12761    }
12762
12763    fn post(f: Box<dyn FnOnce() + Send>) {
12764        // Posted-closure trampoline (§8.5): the closure runs inside dispatch's C frame, so a
12765        // panic is contained here rather than unwinding into libdispatch.
12766        dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
12767    }
12768
12769    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
12770        // The timer door behind `day::sleep` (docs/async.md): `dispatch_after` on the main
12771        // queue, so a sleep is a dispatch timer rather than a parked helper thread. Contained
12772        // like `post`. A delay too large for dispatch's clock runs at the far horizon instead.
12773        let when =
12774            dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
12775                .unwrap_or(dispatch2::DispatchTime::FOREVER);
12776        if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
12777            ffi_guard::contain((), f);
12778        }) {
12779            log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
12780        }
12781    }
12782
12783    fn locale_hints(&self) -> Vec<String> {
12784        // The user's ordered language preference from Settings ("fr-FR", "en-US", …), which is
12785        // the ambient locale Day negotiates its catalogs against (§12.2, docs/localization.md).
12786        objc2_foundation::NSLocale::preferredLanguages()
12787            .iter()
12788            .map(|s| s.to_string())
12789            .collect()
12790    }
12791}
12792
12793// `CGWindowListCreateImage` is obsoleted as of the macOS 15 SDK (ScreenCaptureKit is the
12794// sanctioned replacement) but still resolves and answers on macOS 26. It is declared here rather
12795// than taken from a binding because the availability attribute would refuse the call outright,
12796// and every use below treats a NULL return as "ask the offscreen path instead".
12797unsafe extern "C" {
12798    fn CGWindowListCreateImage(
12799        bounds: objc2_core_foundation::CGRect,
12800        list_option: u32,
12801        window_id: u32,
12802        image_option: u32,
12803    ) -> *mut objc2_core_graphics::CGImage;
12804}
12805
12806/// kCGWindowListOptionIncludingWindow — composite only this window, so whatever is stacked over
12807/// it (another app, a CI runner's stray window) cannot appear in the capture.
12808const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
12809/// kCGWindowImageBoundsIgnoreFraming — the window's own frame, without its drop shadow, which
12810/// makes the returned image exactly `window.frame()` at the backing scale.
12811const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
12812
12813/// Encode a captured rep as PNG, in sRGB.
12814///
12815/// A capture arrives in the color space of the display it was composited for, and a PNG of it
12816/// embeds that display's ICC profile: the same color then has different sample values on every
12817/// machine, and on every other Day target, which all capture sRGB. Converting first makes a
12818/// macOS capture's samples comparable with theirs and independent of the capturing display.
12819fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
12820    let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
12821        &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
12822        objc2_app_kit::NSColorRenderingIntent::Default,
12823    );
12824    let rep = srgb.as_deref().unwrap_or(rep);
12825    let data = unsafe {
12826        rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
12827    }
12828    .ok_or("png encode failed")?;
12829    Ok(data.to_vec())
12830}
12831
12832/// Capture `content` by asking the WINDOW SERVER for the composited window and cropping to it.
12833///
12834/// This exists because an offscreen render cannot draw macOS's own materials. As of macOS 26 a
12835/// sidebar `NSSplitViewItem` is a Liquid Glass surface the window server composites from what is
12836/// behind it; `cacheDisplayInRect` has no backdrop to sample, so it renders the sidebar as an
12837/// opaque white slab with none of its rows in it — every macos-appkit gallery shot had a blank
12838/// sidebar. The window server has the real pixels, including the rows.
12839///
12840/// It answers only while the window is actually on screen. A hidden, minimized or
12841/// never-composited window has no image to hand back (verified: hiding the app makes this return
12842/// NULL while the offscreen path still produces a frame), so this returns `Err` and the caller
12843/// falls back rather than failing the capture.
12844fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
12845    let window = content.window().ok_or("view is not in a window")?;
12846    // An attached sheet is the active modal surface and has its own composited window.
12847    // Capturing only the parent's window would show dimmed content without the modal UI.
12848    if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
12849        return snapshot_via_window_server(&sheet, chrome);
12850    }
12851    let number = window.windowNumber();
12852    if number <= 0 {
12853        return Err(format!("window {number} is not on screen"));
12854    }
12855    // The server hands back the frame it last COMPOSITED, which is the previous one whenever the
12856    // app has changed the view tree since. A capture taken right after a state change then shows
12857    // the state before it — a `when` whose outgoing arm is already gone from the tree and from the
12858    // view hierarchy still appears in the image, so a walkthrough asserting on pixels reads a
12859    // stale frame as "the change did not happen". Push the pending work out first: lay out, draw,
12860    // then commit the layer tree to the render server.
12861    unsafe { content.layoutSubtreeIfNeeded() };
12862    window.displayIfNeeded();
12863    CATransaction::flush();
12864    // CGRectNull asks for the window's own bounds rather than a screen region.
12865    let null_rect = objc2_core_foundation::CGRect::new(
12866        objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
12867        objc2_core_foundation::CGSize::new(0.0, 0.0),
12868    );
12869    let shot = unsafe {
12870        CGWindowListCreateImage(
12871            null_rect,
12872            CG_WINDOW_LIST_INCLUDING_WINDOW,
12873            number as u32,
12874            CG_WINDOW_IMAGE_IGNORE_FRAMING,
12875        )
12876    };
12877    if shot.is_null() {
12878        return Err("the window server has no image for this window".into());
12879    }
12880    // SAFETY: non-NULL CGImageRef owned by this call (Create rule); CFRetained takes that
12881    // ownership over, so it is released exactly once.
12882    let shot = unsafe {
12883        objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
12884    };
12885
12886    // A chrome capture is the window image as the server composited it — titlebar, toolbar and
12887    // rounded corners included — so it is done here, before the crop.
12888    if chrome {
12889        let rep = unsafe {
12890            objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12891                objc2_app_kit::NSBitmapImageRep::alloc(),
12892                &shot,
12893            )
12894        };
12895        return png_of_rep(&rep);
12896    }
12897
12898    // Crop the window frame down to the content view. Keeping the framing identical to the
12899    // offscreen path is the point: the titlebar has never been part of a Day capture, and every
12900    // published gallery shot would otherwise change size.
12901    let frame = window.frame();
12902    if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
12903        return Err("zero-size window".into());
12904    }
12905    let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
12906    // Cocoa rects are bottom-left origin; a CGImage's are top-left, so the content's distance
12907    // from the window top is what the crop needs.
12908    let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
12909    let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
12910    let crop = objc2_core_foundation::CGRect::new(
12911        objc2_core_foundation::CGPoint::new(
12912            (in_window.origin.x * scale).round(),
12913            (from_top * scale).round(),
12914        ),
12915        objc2_core_foundation::CGSize::new(
12916            (in_window.size.width * scale).round(),
12917            (in_window.size.height * scale).round(),
12918        ),
12919    );
12920    let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
12921        .ok_or("crop to the content view failed")?;
12922    let rep = unsafe {
12923        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12924            objc2_app_kit::NSBitmapImageRep::alloc(),
12925            &cropped,
12926        )
12927    };
12928    png_of_rep(&rep)
12929}
12930
12931/// Capture a window content view as PNG (the dayscript screenshot seam, §14).
12932///
12933/// The window server first, because it is the only one of the two that can show macOS's own
12934/// composited materials; the offscreen render when it declines, because it is the only one of the
12935/// two that works with no window on screen. See each for why.
12936/// Put a [`Transform`] on a view through its own geometry rather than its layer: the frame is
12937/// the laid-out `base` scaled about its center and moved by the translation, the bounds keep the
12938/// laid-out size (so the content draws at the scale), and the rotation is the frame's center
12939/// rotation (positive is clockwise on screen: Day's parents are flipped, y down).
12940fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
12941    let [x, y, w, h] = base;
12942    let (sw, sh) = (w * t.sx, h * t.sy);
12943    let frame = NSRect::new(
12944        NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
12945        NSSize::new(sw, sh),
12946    );
12947    unsafe {
12948        // The rotation goes first and comes back last: a rotated view's frame is its bounding
12949        // box, so setting the frame of a rotated view would scale it.
12950        v.setFrameCenterRotation(0.0);
12951        v.setFrame(frame);
12952        v.setBoundsSize(NSSize::new(w, h));
12953        if t.rotate_deg != 0.0 {
12954            v.setFrameCenterRotation(t.rotate_deg);
12955        }
12956    }
12957}
12958
12959fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
12960    let modal = content
12961        .window()
12962        .and_then(|w| w.attachedSheet())
12963        .and_then(|s| s.contentView());
12964    let content = modal.as_deref().unwrap_or(content);
12965    match snapshot_via_window_server(content, false) {
12966        Ok(bytes) => Ok(bytes),
12967        Err(_) => snapshot_view_cache(content),
12968    }
12969}
12970
12971/// Capture a window *with* its chrome — the titlebar and toolbar the content capture crops away
12972/// (`day::window_image().chrome()`, docs/window-image.md).
12973///
12974/// Only the window server can produce this: the offscreen path renders the content view's own
12975/// hierarchy, which the titlebar is not part of. When it declines (an offscreen or hidden window)
12976/// the content capture stands in — a smaller image beats no image, and it is what the caller
12977/// would have got from the plain duty.
12978fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
12979    let modal = content
12980        .window()
12981        .and_then(|w| w.attachedSheet())
12982        .and_then(|s| s.contentView());
12983    let content = modal.as_deref().unwrap_or(content);
12984    match snapshot_via_window_server(content, true) {
12985        Ok(bytes) => Ok(bytes),
12986        Err(_) => snapshot_view_cache(content),
12987    }
12988}
12989
12990/// The offscreen fallback: `cacheDisplayInRect` over a window-background pre-fill resolved for
12991/// the view's light/dark appearance. Renders the view hierarchy Day drew, and nothing the window
12992/// server composites (see `snapshot_via_window_server`).
12993fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
12994    let bounds = content.bounds();
12995    let rep =
12996        unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
12997    // Day containers are transparent (the window server paints the backdrop), so pre-fill
12998    // the rep with the window background — resolved for the window's light/dark appearance —
12999    // before compositing the view hierarchy over it (§14).
13000    let ctx =
13001        NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
13002    NSGraphicsContext::saveGraphicsState_class();
13003    NSGraphicsContext::setCurrentContext(Some(&ctx));
13004    content
13005        .effectiveAppearance()
13006        .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
13007            NSColor::windowBackgroundColor().setFill();
13008            objc2_app_kit::NSRectFill(bounds);
13009        }));
13010    NSGraphicsContext::restoreGraphicsState_class();
13011    unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
13012    png_of_rep(&rep)
13013}
13014
13015/// The screen a scripted run asked to open on: `DAY_WINDOW_SCREEN`, the `CGDirectDisplayID` of the
13016/// capture display `day launch --script` provides when no attached display has the capture's
13017/// scale. `None` when unset or when no screen has that id, which leaves the window where it was.
13018/// Center `window` on `primary`'s screen when `center` put it on another, as high as `center`
13019/// places a window (a third of the free height above it, two below).
13020fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
13021    let Some(screen) = primary.and_then(objc2_app_kit::NSWindow::screen) else {
13022        return;
13023    };
13024    if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
13025        return;
13026    }
13027    let (visible, frame) = (screen.visibleFrame(), window.frame());
13028    window.setFrameOrigin(NSPoint::new(
13029        visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
13030        visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
13031    ));
13032}
13033
13034fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
13035    let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
13036        .ok()?
13037        .trim()
13038        .parse()
13039        .ok()?;
13040    let key = NSString::from_str("NSScreenNumber");
13041    objc2_app_kit::NSScreen::screens(mtm)
13042        .into_iter()
13043        .find(|screen| {
13044            let number: Option<Retained<objc2_foundation::NSNumber>> =
13045                unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
13046            number.is_some_and(|n| n.unsignedIntValue() == wanted)
13047        })
13048}
13049
13050/// Recursively mark a view tree as needing display (startup first-frame fix, see `run`).
13051fn mark_tree_needs_display(view: &NSView) {
13052    view.setNeedsDisplay(true);
13053    for sub in view.subviews() {
13054        mark_tree_needs_display(&sub);
13055    }
13056}
13057
13058/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
13059/// macOS has no true background/foreground or memory-warning lifecycle. `const` so
13060/// `day::require_lifecycle!` can reject unsupported phases at compile time. Must agree with the
13061/// `Toolkit::supports_lifecycle` default (which also returns `is_universal`).
13062#[must_use]
13063pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
13064    phase.is_universal()
13065}
13066
13067/// Follow the SYSTEM appearance while the app runs: macOS posts the distributed
13068/// "`AppleInterfaceThemeChangedNotification`" on a theme switch, and AppKit updates
13069/// `effectiveAppearance` just after — so re-read on the next main-queue turn and refresh
13070/// day-core's reactive dark-mode signal (palette closures recolor live instead of going
13071/// stale until the next rebuild). The token is leaked to observe for the app's lifetime.
13072fn install_appearance_observer() {
13073    use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
13074    let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
13075    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13076        dispatch2::DispatchQueue::main()
13077            .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
13078    });
13079    let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
13080    let token = unsafe {
13081        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
13082    };
13083    std::mem::forget(token);
13084    // Accent and contrast changes can leave the appearance name unchanged.
13085    let center = objc2_foundation::NSNotificationCenter::defaultCenter();
13086    let name = NSString::from_str("NSSystemColorsDidChangeNotification");
13087    let token = unsafe {
13088        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
13089    };
13090    std::mem::forget(token);
13091}
13092
13093/// Follow the SYSTEM reduce-motion switch while the app runs: `NSWorkspace` posts
13094/// `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification` on its own notification
13095/// center when any Accessibility › Display option flips, and
13096/// `accessibilityDisplayShouldReduceMotion` already answers the new value by then. The
13097/// notification arrives on the main thread; the main-queue hop keeps the re-read off the
13098/// poster's stack, as the appearance observer does. The token is leaked to observe for the
13099/// app's lifetime.
13100fn install_reduce_motion_observer() {
13101    use objc2_foundation::NSNotification;
13102    let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
13103    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13104        dispatch2::DispatchQueue::main()
13105            .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
13106    });
13107    let token = unsafe {
13108        center.addObserverForName_object_queue_usingBlock(
13109            Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
13110            None,
13111            None,
13112            &block,
13113        )
13114    };
13115    std::mem::forget(token);
13116}
13117
13118/// Bridge the `NSApplication` activation/termination notifications to day lifecycle events
13119/// (docs/lifecycle.md). The observer tokens are leaked to live for the whole app.
13120fn install_lifecycle_observers() {
13121    use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
13122    let center = unsafe { NSNotificationCenter::defaultCenter() };
13123    let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
13124        let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13125            ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
13126        });
13127        let token = unsafe {
13128            center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
13129        };
13130        std::mem::forget(token); // observe for the app's lifetime
13131    };
13132    unsafe {
13133        observe(
13134            NSApplicationDidBecomeActiveNotification,
13135            day_spec::Lifecycle::DidBecomeActive,
13136        );
13137        observe(
13138            NSApplicationWillResignActiveNotification,
13139            day_spec::Lifecycle::WillResignActive,
13140        );
13141        observe(
13142            NSApplicationWillTerminateNotification,
13143            day_spec::Lifecycle::WillTerminate,
13144        );
13145        // `terminate:` exits the process from inside the run loop, so the loop never returns to
13146        // `launch_with`: the last Day code to run is this notification's second observer, which
13147        // NSNotificationCenter calls after the first (docs/lifecycle.md).
13148        observe(
13149            NSApplicationWillTerminateNotification,
13150            day_spec::Lifecycle::DidExit,
13151        );
13152    }
13153}
13154
13155day_localization_ui::locales!();
13156
13157/// Shared by the initial menu and every reactive replacement. AppKit owns Services
13158/// and the hide actions; these commands must not depend on a window or app callback.
13159fn install_application_menu(
13160    mtm: MainThreadMarker,
13161    menubar: &NSMenu,
13162    title: &str,
13163    about: Option<day_spec::MenuItem>,
13164    updates: Option<day_spec::MenuItem>,
13165    prefs: Option<day_spec::MenuItem>,
13166    quit: Option<day_spec::MenuItem>,
13167) -> Retained<NSMenu> {
13168    use day_spec::{MenuItem as M, MenuRole as R};
13169    let app = NSApplication::sharedApplication(mtm);
13170    let standard = |role, label| M::Action {
13171        id: None,
13172        action: 0,
13173        label,
13174        shortcut: None,
13175        enabled: true,
13176        checked: None,
13177        role: Some(role),
13178        icon: None,
13179    };
13180    let mut about =
13181        about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
13182    let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
13183    for (item, title) in [
13184        (&mut about, res::str::about_app(title).format()),
13185        (&mut quit, res::str::quit_app(title).format()),
13186    ] {
13187        if let M::Action { label, .. } = item {
13188            *label = title;
13189        }
13190    }
13191    // A registered Day About (docs/settings.md) replaces the stock Info.plist panel: the
13192    // item fires the dispatch action instead of `orderFrontStandardAboutPanel:`.
13193    if let M::Action { action, .. } = &mut about
13194        && *action == 0
13195    {
13196        *action = day_core::windows::about_action_id();
13197    }
13198    // Check for Updates… sits directly under About (the Sparkle convention), whether the app
13199    // placed the role itself or the updater only registered its action.
13200    let updates_id = day_core::windows::check_for_updates_action_id();
13201    let updates = updates.or_else(|| {
13202        (updates_id != 0).then(|| {
13203            standard(
13204                R::CheckForUpdates,
13205                day_localization::t(day_localization::key::day_check_for_updates),
13206            )
13207        })
13208    });
13209    let mut head = vec![about];
13210    if let Some(mut updates) = updates {
13211        if let M::Action { action, .. } = &mut updates
13212            && *action == 0
13213        {
13214            *action = updates_id;
13215        }
13216        head.push(updates);
13217    }
13218    head.push(M::Separator);
13219    let menu = build_ns_menu(mtm, title, &head);
13220    if let Some(mut prefs) = prefs {
13221        if let M::Action { label, .. } = &mut prefs {
13222            *label = res::str::settings().format();
13223        }
13224        let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
13225        for item in section.itemArray() {
13226            section.removeItem(&item);
13227            menu.addItem(&item);
13228        }
13229    }
13230    // AppKit keeps the registered Services menu across main-menu replacements.
13231    // Move that same menu to the new bar rather than abandoning its system-populated items.
13232    let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
13233    if let Some(parent) = unsafe { services.supermenu() } {
13234        let index = parent.indexOfItemWithSubmenu(Some(&services));
13235        if index >= 0 {
13236            parent.itemAtIndex(index).unwrap().setSubmenu(None);
13237        }
13238    }
13239    let services_item = NSMenuItem::new(mtm);
13240    services_item.setTitle(&NSString::from_str(&res::str::services().format()));
13241    services_item.setSubmenu(Some(&services));
13242    menu.addItem(&services_item);
13243    menu.addItem(&NSMenuItem::separatorItem(mtm));
13244    for (label, selector, shortcut) in [
13245        (
13246            res::str::hide_app(title).format(),
13247            sel!(hide:),
13248            Some(day_spec::Shortcut::primary("h")),
13249        ),
13250        (
13251            res::str::hide_others().format(),
13252            sel!(hideOtherApplications:),
13253            Some(day_spec::Shortcut::primary("h").alt()),
13254        ),
13255        (
13256            res::str::show_all().format(),
13257            sel!(unhideAllApplications:),
13258            None,
13259        ),
13260    ] {
13261        let item = unsafe {
13262            NSMenuItem::initWithTitle_action_keyEquivalent(
13263                NSMenuItem::alloc(mtm),
13264                &NSString::from_str(&label),
13265                Some(selector),
13266                &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
13267            )
13268        };
13269        if let Some(shortcut) = shortcut {
13270            item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
13271        }
13272        // Explicitly target the application so window responders cannot override Hide.
13273        unsafe { item.setTarget(Some(&app)) };
13274        menu.addItem(&item);
13275    }
13276    menu.addItem(&NSMenuItem::separatorItem(mtm));
13277    let section = build_ns_menu(mtm, title, &[quit]);
13278    let quit = section.itemAtIndex(0).unwrap();
13279    section.removeItem(&quit);
13280    menu.addItem(&quit);
13281    let item = NSMenuItem::new(mtm);
13282    item.setSubmenu(Some(&menu));
13283    menubar.addItem(&item);
13284    services
13285}
13286
13287/// The default main menu (§21.2 M2): standard application menu; Edit menu wired to the responder
13288/// chain so Cmd+C/V/X/A work in `NSTextFields`; Window menu basics.
13289fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
13290    let menubar = NSMenu::new(mtm);
13291
13292    let prefs_id = day_core::windows::preferences_action_id();
13293    let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
13294        id: None,
13295        action: prefs_id,
13296        label: res::str::settings().format(),
13297        shortcut: None,
13298        enabled: true,
13299        checked: None,
13300        role: Some(day_spec::MenuRole::Preferences),
13301        icon: None,
13302    });
13303    let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
13304
13305    // File ▸ New Window / Close, when the app registered a new-window builder — the same
13306    // zero-menu-code rule as Settings…/⌘, above (docs/windows.md). Without this an app that
13307    // never calls `app_menu` gets the tab-bar "+" and the Window menu's tab commands but no
13308    // File ▸ New Window, because the default menu bar has no File menu to put it in.
13309    let new_window_id = day_core::windows::new_window_action_id();
13310    if new_window_id != 0 {
13311        let file_item = NSMenuItem::new(mtm);
13312        let file_menu = unsafe {
13313            NSMenu::initWithTitle(
13314                NSMenu::alloc(mtm),
13315                &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
13316            )
13317        };
13318        let new_window = unsafe {
13319            NSMenuItem::initWithTitle_action_keyEquivalent(
13320                NSMenuItem::alloc(mtm),
13321                &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
13322                Some(sel!(fire:)),
13323                &NSString::from_str("n"),
13324            )
13325        };
13326        let target = menu_target(mtm);
13327        let tobj: &objc2::runtime::AnyObject = target.as_ref();
13328        unsafe { new_window.setTarget(Some(tobj)) };
13329        new_window.setTag(new_window_id as isize);
13330        file_menu.addItem(&new_window);
13331        file_menu.addItem(&NSMenuItem::separatorItem(mtm));
13332        // Nil-targeted, so it closes whatever window is key — the standard responder route.
13333        let close = unsafe {
13334            NSMenuItem::initWithTitle_action_keyEquivalent(
13335                NSMenuItem::alloc(mtm),
13336                &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
13337                Some(sel!(performClose:)),
13338                &NSString::from_str("w"),
13339            )
13340        };
13341        file_menu.addItem(&close);
13342        file_item.setSubmenu(Some(&file_menu));
13343        menubar.addItem(&file_item);
13344    }
13345
13346    let edit_item = NSMenuItem::new(mtm);
13347    let edit_menu = unsafe {
13348        NSMenu::initWithTitle(
13349            NSMenu::alloc(mtm),
13350            &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
13351        )
13352    };
13353    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
13354        let item = unsafe {
13355            NSMenuItem::initWithTitle_action_keyEquivalent(
13356                NSMenuItem::alloc(mtm),
13357                &NSString::from_str(&day_localization::t(key)),
13358                Some(action),
13359                &NSString::from_str(accel),
13360            )
13361        };
13362        edit_menu.addItem(&item);
13363    };
13364    add("day_undo", sel!(undo:), "z");
13365    add("day_redo", sel!(redo:), "Z");
13366    edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
13367    add("day_cut", sel!(cut:), "x");
13368    add("day_copy", sel!(copy:), "c");
13369    add("day_paste", sel!(paste:), "v");
13370    add("day_select_all", sel!(selectAll:), "a");
13371    edit_item.setSubmenu(Some(&edit_menu));
13372    menubar.addItem(&edit_item);
13373
13374    install_windows_menu(mtm, app, &menubar);
13375
13376    app.setMainMenu(Some(&menubar));
13377    unsafe { app.setServicesMenu(Some(&services)) };
13378}
13379
13380/// The standard Window menu (docs/windows.md): Minimize ⌘M / Zoom / Bring All to Front,
13381/// registered as `NSApp.windowsMenu` — AppKit then appends the open-window list and, with
13382/// tabbing live, the tab commands (Show Next/Previous Tab, Merge All Windows) itself. All
13383/// nav hosts are nil-targeted (responder chain), so they act on the key window.
13384fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
13385    let menu = unsafe {
13386        NSMenu::initWithTitle(
13387            NSMenu::alloc(mtm),
13388            &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
13389        )
13390    };
13391    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
13392        let item = unsafe {
13393            NSMenuItem::initWithTitle_action_keyEquivalent(
13394                NSMenuItem::alloc(mtm),
13395                &NSString::from_str(&day_localization::t(key)),
13396                Some(action),
13397                &NSString::from_str(accel),
13398            )
13399        };
13400        menu.addItem(&item);
13401    };
13402    add("day_minimize", sel!(performMiniaturize:), "m");
13403    add("day_zoom", sel!(performZoom:), "");
13404    menu.addItem(&NSMenuItem::separatorItem(mtm));
13405    add("day_bring_all_front", sel!(arrangeInFront:), "");
13406    let item = NSMenuItem::new(mtm);
13407    item.setTitle(&NSString::from_str(&day_localization::t(
13408        day_localization::key::day_window,
13409    )));
13410    item.setSubmenu(Some(&menu));
13411    menubar.addItem(&item);
13412    unsafe { app.setWindowsMenu(Some(&menu)) };
13413}
13414
13415/// Hoist application roles even from nested menus. First declaration wins; remove
13416/// duplicates and empty containers, then normalize separators left by the move.
13417fn extract_app_role(
13418    items: &mut Vec<day_spec::MenuItem>,
13419    role: day_spec::MenuRole,
13420) -> Option<day_spec::MenuItem> {
13421    use day_spec::MenuItem as M;
13422    let mut found = None;
13423    let mut remaining = Vec::new();
13424    for mut item in items.drain(..) {
13425        match &mut item {
13426            M::Action { role: Some(r), .. } if *r == role => {
13427                found.get_or_insert(item);
13428                continue;
13429            }
13430            M::Submenu { items, .. } => {
13431                let nested = extract_app_role(items, role);
13432                if found.is_none() {
13433                    found = nested;
13434                }
13435                if items.is_empty() {
13436                    continue;
13437                }
13438            }
13439            M::Separator
13440                if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
13441            {
13442                continue;
13443            }
13444            _ => {}
13445        }
13446        remaining.push(item);
13447    }
13448    while matches!(remaining.last(), Some(M::Separator)) {
13449        remaining.pop();
13450    }
13451    *items = remaining;
13452    found
13453}
13454
13455/// Whether any action in the model (recursively) carries `role`.
13456fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
13457    items.iter().any(|it| match it {
13458        day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
13459        day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
13460        day_spec::MenuItem::Separator => false,
13461    })
13462}
13463
13464// ---------------------------------------------------------------------------
13465// Menus (§ menus): render day's MenuItem model with NSMenu. Custom items route to a shared
13466// DayMenuTarget (id in the item's tag → Event::MenuAction); role items use the native selector.
13467// ---------------------------------------------------------------------------
13468
13469define_class!(
13470    #[unsafe(super(NSObject))]
13471    #[thread_kind = MainThreadOnly]
13472    #[name = "DayMenuTarget"]
13473    #[ivars = ()]
13474    struct DayMenuTarget;
13475
13476    unsafe impl NSObjectProtocol for DayMenuTarget {}
13477
13478    impl DayMenuTarget {
13479        #[unsafe(method(fire:))]
13480        fn fire(&self, sender: &NSMenuItem) {
13481            ffi_guard::contain((), || {
13482                let id = sender.tag() as u64;
13483                if id != 0 {
13484                    emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
13485                }
13486            });
13487        }
13488    }
13489);
13490
13491/// The primary window's content view (set once in `run`).
13492/// Pin the window's content coordinate space under its title bar and toolbar (§7.7). The
13493/// content view is full-size (`FullSizeContentView`, for the unified toolbar), so it runs
13494/// beneath the bar; moving its bounds origin up by that strip makes Day's root, laid out from
13495/// (0, 0), start below the bar — the way UIKit pins the root inside `safeAreaInsets` — while
13496/// the view's own background still paints edge to edge. Returns the size Day lays out at, the
13497/// window's `contentLayoutRect`. Called wherever that rect can change: window creation, every
13498/// resize, and a toolbar coming or going.
13499pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
13500    let content = window.contentView()?;
13501    let full = content.frame().size;
13502    let layout = unsafe { window.contentLayoutRect() }.size;
13503    let top = (full.height - layout.height).max(0.0);
13504    // An overlay title bar (docs/window-chrome.md) is the one place the content belongs under
13505    // the bar: it keeps the full height, and the bar's height goes to the app as a safe-area
13506    // inset so it can pad its own content.
13507    if window_chrome::is_overlay(window) {
13508        unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
13509        window_chrome::report_title_bar_inset(window, top);
13510        return Some(Size::new(full.width, full.height));
13511    }
13512    unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
13513    Some(Size::new(full.width, (full.height - top).max(0.0)))
13514}
13515
13516/// The text a widget displays, for `read_native`: a label's or text field's string, a
13517/// button's title, a text area's contents. `None` for a secure field (it masks its text), an
13518/// icon-only button (its title is a tooltip), and every other view.
13519fn native_text(h: &NSView) -> Option<String> {
13520    if h.downcast_ref::<NSSecureTextField>().is_some() {
13521        return None;
13522    }
13523    if let Some(tf) = h.downcast_ref::<NSTextField>() {
13524        // `stringValue` answers the field editor's live text while the field edits.
13525        return Some(tf.stringValue().to_string());
13526    }
13527    if let Some(btn) = h.downcast_ref::<NSButton>() {
13528        if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
13529            return None;
13530        }
13531        return Some(btn.title().to_string());
13532    }
13533    // A text area is an NSTextView inside the scroll view its handle names (textarea.rs).
13534    let sv = h.downcast_ref::<NSScrollView>()?;
13535    let doc = sv.documentView()?;
13536    let tv = doc.downcast_ref::<NSTextView>()?;
13537    Some(tv.string().to_string())
13538}
13539
13540/// A slider's value or a determinate progress bar's fraction, for `read_native`. Both native
13541/// ranges are the ones Day gave: the slider is built with Day's min and max, the bar runs 0–1.
13542fn native_number(h: &NSView) -> Option<f64> {
13543    if let Some(sl) = h.downcast_ref::<NSSlider>() {
13544        return Some(sl.doubleValue());
13545    }
13546    let pi = h.downcast_ref::<NSProgressIndicator>()?;
13547    (!pi.isIndeterminate()).then(|| pi.doubleValue())
13548}
13549
13550/// The view's frame in its window's content coordinates, origin top left, for `read_native`.
13551/// The content view is flipped and pinned below the title bar (`pin_below_title_bar`), so
13552/// converting into it gives Day's layout space; an unflipped content view is flipped here.
13553fn native_frame(h: &NSView) -> Option<Rect> {
13554    let content = h.window()?.contentView()?;
13555    let r = h.convertRect_toView(h.bounds(), Some(&content));
13556    let y = if content.isFlipped() {
13557        r.origin.y
13558    } else {
13559        let b = content.bounds();
13560        b.origin.y + b.size.height - (r.origin.y + r.size.height)
13561    };
13562    Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
13563}
13564
13565/// The strip a pinned content view keeps above its layout origin (see `pin_below_title_bar`).
13566fn title_bar_inset(content: &NSView) -> f64 {
13567    (-content.bounds().origin.y).max(0.0)
13568}
13569
13570fn primary_content() -> Option<Retained<NSView>> {
13571    PRIMARY_CONTENT.with(|c| c.borrow().clone())
13572}
13573
13574fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
13575    MENU_TARGET.with(|t| {
13576        t.borrow_mut()
13577            .get_or_insert_with(|| {
13578                let this = DayMenuTarget::alloc(mtm).set_ivars(());
13579                let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
13580                obj
13581            })
13582            .clone()
13583    })
13584}
13585
13586fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
13587    use objc2_app_kit::NSEventModifierFlags as F;
13588    let mut m = F::empty();
13589    if s.primary {
13590        m |= F::Command;
13591    }
13592    if s.shift {
13593        m |= F::Shift;
13594    }
13595    if s.alt {
13596        m |= F::Option;
13597    }
13598    if s.control {
13599        m |= F::Control;
13600    }
13601    m
13602}
13603
13604/// A shortcut's key-equivalent string. Single chars pass through (lowercased); a few named keys map
13605/// to their control characters. Modifiers ride separately via `setKeyEquivalentModifierMask`.
13606fn ns_key_equivalent(key: &str) -> String {
13607    match key {
13608        "Return" | "Enter" => "\r".into(),
13609        "Tab" => "\t".into(),
13610        "Delete" | "Backspace" => "\u{8}".into(),
13611        "Escape" => "\u{1b}".into(),
13612        "Space" => " ".into(),
13613        k if k.chars().count() == 1 => k.to_lowercase(),
13614        _ => String::new(), // named keys we don't map get no key-equivalent (still shown in menu)
13615    }
13616}
13617
13618/// A standard role → (default label, nav host, default shortcut). Nav host `None` = no native action
13619/// (the app should attach its own via a custom item); the role then only supplies label placement.
13620fn role_spec(
13621    role: day_spec::MenuRole,
13622) -> (
13623    &'static str,
13624    Option<objc2::runtime::Sel>,
13625    Option<day_spec::Shortcut>,
13626) {
13627    use day_spec::MenuRole as R;
13628    use day_spec::Shortcut as S;
13629    match role {
13630        R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
13631        R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
13632        R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
13633        R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
13634        R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
13635        R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
13636        R::Delete => ("Delete", Some(sel!(delete:)), None),
13637        R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
13638        R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
13639        R::Preferences => ("Settings…", None, Some(S::primary(","))),
13640        R::Minimize => (
13641            "Minimize",
13642            Some(sel!(performMiniaturize:)),
13643            Some(S::primary("m")),
13644        ),
13645        R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
13646        R::Fullscreen => (
13647            "Enter Full Screen",
13648            Some(sel!(toggleFullScreen:)),
13649            Some(S::primary("f").control()),
13650        ),
13651        // No native selector (docs/windows.md): the item dispatches the registered
13652        // new-window action through the ordinary custom-item path (`fire:`).
13653        R::NewWindow => ("New Window", None, Some(S::primary("n"))),
13654        // Likewise: no selector, the registered updater action fires through `fire:`.
13655        R::CheckForUpdates => ("Check for Updates…", None, None),
13656    }
13657}
13658
13659pub(crate) fn build_ns_menu(
13660    mtm: MainThreadMarker,
13661    title: &str,
13662    items: &[day_spec::MenuItem],
13663) -> Retained<NSMenu> {
13664    use day_spec::MenuItem as MI;
13665    let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
13666    let target = menu_target(mtm);
13667    for item in items {
13668        match item {
13669            MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
13670            MI::Submenu { label, items, .. } => {
13671                let sub = build_ns_menu(mtm, label, items);
13672                let it = NSMenuItem::new(mtm);
13673                it.setTitle(&NSString::from_str(label));
13674                it.setSubmenu(Some(&sub));
13675                menu.addItem(&it);
13676            }
13677            MI::Action {
13678                action,
13679                label,
13680                shortcut,
13681                enabled,
13682                checked,
13683                role,
13684                icon,
13685                ..
13686            } => {
13687                // Resolve label/nav host/shortcut, folding in the role's native defaults.
13688                let (mut lbl, sel, mut sc) = match role {
13689                    Some(r) => {
13690                        let (dl, ds, dsc) = role_spec(*r);
13691                        (dl.to_string(), ds, dsc)
13692                    }
13693                    None => (String::new(), None, None),
13694                };
13695                if !label.is_empty() {
13696                    lbl.clone_from(label);
13697                }
13698                if shortcut.is_some() {
13699                    sc.clone_from(shortcut);
13700                }
13701                // Custom action (nonzero id) overrides any role nav host and targets our
13702                // trampoline — except the responder-routed set (undo pair, clipboard trio),
13703                // whose nonzero ids are only the other platforms' fallback dispatchers: here
13704                // the nil-target nav hosts must stay, so the responder chain resolves the
13705                // acting object (a focused text field before the app's bridge).
13706                let responder_role = matches!(
13707                    role,
13708                    Some(
13709                        day_spec::MenuRole::Undo
13710                            | day_spec::MenuRole::Redo
13711                            | day_spec::MenuRole::Cut
13712                            | day_spec::MenuRole::Copy
13713                            | day_spec::MenuRole::Paste
13714                            | day_spec::MenuRole::SelectAll
13715                    )
13716                );
13717                let custom = *action != 0 && !responder_role;
13718                let key = sc.as_ref().map_or_default(|s| ns_key_equivalent(&s.key));
13719                let it = unsafe {
13720                    NSMenuItem::initWithTitle_action_keyEquivalent(
13721                        NSMenuItem::alloc(mtm),
13722                        &NSString::from_str(&lbl),
13723                        if custom { Some(sel!(fire:)) } else { sel },
13724                        &NSString::from_str(&key),
13725                    )
13726                };
13727                if let Some(s) = &sc {
13728                    it.setKeyEquivalentModifierMask(ns_modifiers(s));
13729                    // AppKit's own per-layout/per-language adjustments (macOS 12+): remap a
13730                    // key equivalent the current keyboard layout cannot type, and MIRROR
13731                    // directional pairs (⌘[ / ⌘]) under RTL languages — the system half of
13732                    // shortcut localization; the catalog half is the `.key` attribute
13733                    // (docs/localization.md).
13734                    it.setAllowsAutomaticKeyEquivalentLocalization(true);
13735                    it.setAllowsAutomaticKeyEquivalentMirroring(true);
13736                }
13737                if custom {
13738                    let tobj: &objc2::runtime::AnyObject = target.as_ref();
13739                    unsafe { it.setTarget(Some(tobj)) };
13740                    it.setTag(*action as isize);
13741                }
13742                it.setEnabled(*enabled);
13743                // A checkable item takes NSMenuItem's own state, so macOS draws the ✓ it draws
13744                // everywhere else and reserves the mark's column when it is off (docs/menus.md).
13745                if let Some(on) = checked {
13746                    it.setState(if *on {
13747                        NSControlStateValueOn
13748                    } else {
13749                        NSControlStateValueOff
13750                    });
13751                }
13752                // The item's glyph, drawn the way NSMenuItem draws its own (docs/menus.md):
13753                // template-tinted, sized to the menu's text.
13754                if let Some(icon) = icon
13755                    && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
13756                {
13757                    img.setSize(NSSize::new(16.0, 16.0));
13758                    it.setImage(Some(&img));
13759                }
13760                menu.addItem(&it);
13761            }
13762        }
13763    }
13764    menu
13765}
13766
13767// AppKit's TLS may be destroyed before the reactive arena drops its last Bitmap.
13768// The registry already released the native images in that case.
13769fn release_bitmap(id: day_spec::BitmapId) {
13770    let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
13771}
13772
13773#[cfg(test)]
13774mod bitmap_teardown_tests {
13775    use super::*;
13776
13777    #[test]
13778    fn releasing_after_bitmap_registry_teardown_does_not_abort() {
13779        // Isolate destructor panics: Rust aborts the process when a TLS destructor unwinds.
13780        const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
13781        if std::env::var_os(CHILD).is_some() {
13782            struct LateRelease;
13783            impl Drop for LateRelease {
13784                fn drop(&mut self) {
13785                    assert!(BITMAPS.try_with(|_| ()).is_err());
13786                    // Same duty called by Bitmap::drop; no NSApplication is needed.
13787                    release_bitmap(day_spec::BitmapId(1));
13788                }
13789            }
13790            std::thread_local! {
13791                static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
13792            }
13793            std::thread::spawn(|| {
13794                LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
13795                BITMAPS.with(|_| ()); // initialized last, destroyed first
13796            })
13797            .join()
13798            .unwrap();
13799            return;
13800        }
13801        let output = std::process::Command::new(std::env::current_exe().unwrap())
13802            .args([
13803                "--exact",
13804                "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
13805                "--nocapture",
13806            ])
13807            .env(CHILD, "1")
13808            .output()
13809            .unwrap();
13810        assert!(
13811            output.status.success(),
13812            "{}",
13813            String::from_utf8_lossy(&output.stderr)
13814        );
13815    }
13816}