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 color;
17mod nav_progress;
18
19use std::any::Any;
20use std::cell::{Cell, RefCell};
21use std::collections::HashMap;
22use std::rc::Rc;
23
24use linkme::distributed_slice;
25use objc2::Message as _;
26use objc2::rc::Retained;
27use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel};
28use objc2::{
29    AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
30};
31use objc2_app_kit::NSAccessibility as _;
32use objc2_app_kit::NSAppearanceCustomization as _;
33use objc2_app_kit::NSDraggingInfo as _;
34use objc2_app_kit::NSSplitViewDelegate;
35use objc2_app_kit::NSTextContent as _;
36use objc2_app_kit::NSTextInputClient;
37use objc2_app_kit::NSUserInterfaceItemIdentification as _;
38use objc2_app_kit::{
39    NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
40    NSGestureRecognizerDelegate, NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
41    NSPressGestureRecognizer,
42};
43use objc2_app_kit::{
44    NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
45    NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
46    NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
47    NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
48    NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
49    NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
50    NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
51    NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
52    NSWindowDelegate, NSWindowStyleMask,
53};
54use objc2_app_kit::{
55    NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
56    NSApplicationWillTerminateNotification,
57};
58use objc2_app_kit::{
59    NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
60};
61use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
62use objc2_core_foundation::CGAffineTransform;
63use objc2_foundation::{
64    NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
65    NSNumber, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString,
66};
67use objc2_quartz_core::CATransaction;
68
69use day_spec::ffi_guard;
70use day_spec::present;
71use day_spec::props::*;
72use day_spec::sidetable::SideTable;
73use day_spec::{
74    A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
75    InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
76    Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
77    WindowOptions, kinds, props_of,
78};
79
80pub type Handle = Retained<NSView>;
81
82/// Icon resolution for a piece renderer's own `NSToolbar` items (see `toolbar::image_for`).
83pub use toolbar::image_for as toolbar_image;
84
85// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
86mod dock;
87mod documents;
88mod frame;
89mod input;
90mod motion;
91mod picker;
92mod scroll;
93mod status_item;
94mod textarea;
95mod toolbar;
96mod transfer;
97mod window_chrome;
98use objc2_app_kit::NSDraggingSource;
99
100pub mod ext;
101pub use color::nsink;
102pub use ext::*;
103
104// ---------------------------------------------------------------------------
105// Event plumbing: node-id keyed sink, thread-local (single UI thread)
106// ---------------------------------------------------------------------------
107
108/// The day-core event sink (node-id keyed).
109type Sink = Rc<dyn Fn(NodeId, Event)>;
110
111day_core::tls_group! {
112    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
113    /// Keeps each control's `DayTarget` alive (target/action holds it weakly).
114    static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
115    /// The style each button currently carries, keyed by its view pointer.
116    ///
117    /// Needed because a tinted title is an attributed string (see `set_button_title`), and
118    /// `ButtonPatch::Title` would otherwise replace it with a plain one and lose the color.
119    static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
120        RefCell::new(HashMap::new());
121    /// Original template images, retained across tint changes and swept on view release.
122    static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
123    /// Each button's selected state (`ButtonProps::selected`), keyed by its view pointer: what
124    /// the `action:` handler restores after a click toggles a push-on/push-off button, and the
125    /// buttons whose `state` `read_native` reports as `checked`.
126    static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
127
128    /// Canvas ptr → its display list. A [`SideTable`], so the release sweep reclaims it
129    /// (replay inserted but nothing ever removed).
130    static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
131    /// Views the app gave an accessibility label (`set_a11y`): a button's title change must then
132    /// leave the label alone (`apply_button_content`). Swept on release like the other tables.
133    static APP_LABELED: SideTable<()> = SideTable::new();
134    /// How each image view renders its glyph (docs/vectors.md "Tint", "Template"): whether it
135    /// was realized as a template, and whether a tint is on it now. Template rendering is a
136    /// property of the NSImage, so a source swap has to re-apply it, and a tint patch of `None`
137    /// keeps a template in the neutral tint rather than returning to the authored art. Swept
138    /// on release.
139    static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
140    /// Each transformed view's `Transform` (`set_transform`). AppKit owns a layer-backed view's
141    /// layer geometry and re-syncs it from the view, so a transform written into the layer
142    /// never showed. It is expressed in the view's own geometry instead (`apply_geometry`).
143    static TRANSFORMS: SideTable<Transform> = SideTable::new();
144    /// Each view's frame as Day laid it out, before any translation, so a translation change can
145    /// move the view without waiting for the next layout.
146    static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
147    static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
148    /// A presented cover sheet's window → its cover node, for Escape (docs/cover.md).
149    static SHEET_NODES: SideTable<NodeId> = SideTable::new();
150    static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
151    /// View ptr → node for `GestureKind::Pan` (docs/shapes.md): macOS pans arrive as trackpad
152    /// scroll events, so `DayCanvas::scrollWheel:` reports them here instead of a recognizer.
153    static PAN_NODES: SideTable<NodeId> = SideTable::new();
154    static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
155    /// View ptr → node for `GestureKind::Hover` (docs/canvas.md "Interaction"). Hover is not a
156    /// recognizer on macOS either: it is an `NSTrackingArea` plus the three mouse methods, so
157    /// like [`PAN_NODES`] this holds the canvases that asked and `DayCanvas` reports for them.
158    static HOVER_NODES: SideTable<NodeId> = SideTable::new();
159    /// View ptr → node for `GestureKind::Rotate` (docs/canvas.md "Zoom and pan"). A trackpad
160    /// rotation arrives as `NSEventTypeRotate` events at the view under it, alongside the
161    /// magnify events the pinch recognizer reads, so `DayCanvas::rotateWithEvent:` reports
162    /// it and the two gestures run at once rather than competing as two recognizers would.
163    static ROTATE_NODES: SideTable<NodeId> = SideTable::new();
164    /// Canvas view ptr → the rotation accumulated since the trackpad gesture's `Began`, in
165    /// radians: the events carry per-event degrees, and Day's contract is cumulative.
166    static ROTATE_ANGLE: SideTable<f64> = SideTable::new();
167    /// Canvas view ptr → its node, so the view's own `keyDown:` knows who to report to. Every
168    /// canvas is registered at realize (unlike [`PAN_NODES`], which only holds the ones that
169    /// asked for a pan) because focus, not a gesture, is what decides who hears a key.
170    static KEY_NODES: SideTable<NodeId> = SideTable::new();
171    /// Focusable container view ptr → its node (docs/focus.md): `Decorate::focusable` opts a
172    /// `DayFlipped` into the canvas contract (accepts first responder, takes focus on a
173    /// press, reports both directions, hears the arrows). Empty for every container that
174    /// never asked, whose behavior is exactly as before.
175    static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
176    /// Canvas view ptr → the text an input method is still composing in it (docs/menus.md
177    /// "The full route"): a dead key's accent, a Japanese reading. Nothing reaches the app
178    /// until the input method commits; the entry is gone the moment it does or cancels.
179    static MARKED: SideTable<String> = SideTable::new();
180    /// The key press the text input system is interpreting right now: its unmodified name and
181    /// the modifier mask, so the text it commits is named by the key that typed it.
182    static INTERPRETING: RefCell<Option<Interpreting>> = const { RefCell::new(None) };
183
184    /// Keeps each view's gesture targets alive + records which gestures are attached (idempotent).
185    static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
186        RefCell::new(HashMap::new());
187
188    static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
189    /// Handles whose frames are native-owned (nav pages): set_frame skips them.
190    static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
191        RefCell::new(std::collections::HashSet::new());
192    /// Each nav page's pane, recorded at realize because `insert` sees only handles
193    /// (docs/size-classes.md). Identity rather than position: a re-present re-homes the pages
194    /// without changing their order, so "index 0 is the sidebar" stops being true the moment a
195    /// host can morph. A [`SideTable`]: `remove` clears it on the normal path, and the release
196    /// sweep catches a page released without one (a stale entry could mis-pane a recycled ptr).
197    static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
198
199    static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
200    /// INSPECTOR_PANE ptr → is-panel, recorded at realize because `insert` sees only handles.
201    /// A [`SideTable`]: the release sweep drops it with the view.
202    static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
203
204    /// Split host (the wrap around an `NSSplitView`, docs/split.md) ptr → its state.
205    static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
206    /// SPLIT_PANE ptr → is-second, recorded at realize because `insert` sees only handles.
207    static SPLIT_PANES: SideTable<bool> = SideTable::new();
208
209    /// Outline ptr → its data source, for [`DayNavOutlineView::menu_for_event`]'s row lookup.
210    /// A [`SideTable`], reclaimed by the outline-keyed auxiliary sweep in `release`: the entry
211    /// used to outlive its host, so a recycled outline address served the dead menu's rows.
212    static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
213
214    static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
215    /// Tree host scroll-view ptr → (outline, data source) (docs/tree.md).
216    static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
217
218    /// `BitmapId` → the decoded image (docs/images.md). Keyed by the id day-core minted, not by
219    /// a view pointer: a bitmap outlives any one view and may be drawn by several at once.
220    /// Entries leave only through `release_image`, which day-core calls when the app drops its
221    /// last `Bitmap` handle.
222    static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
223    /// The fonts a painting thread's text ops resolve to, keyed by (size bits, font): filled
224    /// by [`OffscreenResources`] for one export at a time (docs/canvas.md "Exporting"), since
225    /// `NSFontManager` belongs to the UI thread. Empty on the UI thread itself.
226    static OFFSCREEN_FONTS: RefCell<Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>> =
227        const { RefCell::new(Vec::new()) };
228    /// View ptr → its summon-time context-menu provider (docs/menus.md). Swept on release
229    /// via `day_spec::sidetable`.
230    static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
231    /// Menu button ptr → the provider its press opens (`set_button_menu`, docs/menus.md "Menu
232    /// buttons"). Swept on release like `CTX_MENU_FNS`.
233    static BUTTON_MENUS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
234
235    /// NAV_MENU scroll-view ptr → (outline, data source) for patches and measure.
236    static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
237
238    /// The app's edit-bridge state (`set_edit_state`), which validateMenuItem consults.
239    static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
240        const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
241    static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
242        const { std::cell::RefCell::new(None) };
243
244    /// Live modal sheets keyed by request id (for programmatic dismissal).
245    static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
246        RefCell::new(HashMap::new());
247    /// Live file-picker sheets (NSOpenPanel is stored via its NSSavePanel supertype).
248    static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
249        RefCell::new(HashMap::new());
250
251    // NSMenuItem does not retain its target, so one shared target is kept alive for the app's
252    // lifetime.
253    static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
254        const { std::cell::RefCell::new(None) };
255    /// The primary window's content view, for call sites without backend access that must
256    /// address the main window specifically (cover re-homing, DAY_DUMP). With secondary
257    /// windows open, `app.windows().firstObject()` is arbitrary (docs/windows.md).
258    static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
259        const { std::cell::RefCell::new(None) };
260
261}
262
263/// Emit an event into day-core's queue (public: external Day Piece renderers use this too).
264pub fn emit(id: NodeId, ev: Event) {
265    let sink = SINK.with(|s| s.borrow().clone());
266    if let Some(sink) = sink {
267        sink(id, ev);
268    }
269}
270
271fn ptr_of(v: &NSView) -> usize {
272    std::ptr::from_ref::<NSView>(v).cast::<()>() as usize
273}
274
275/// Open a menu button's menu under it (docs/menus.md "Menu buttons"): asks the provider now, so
276/// the entries are the current ones, and pops the `NSMenu` from the button's bottom-leading
277/// corner, the place a pull-down `NSPopUpButton` puts its menu. The button stays highlighted
278/// while the menu tracks, as a pressed pull-down does. Guarded: the provider is app code.
279fn pop_button_menu(btn: &NSButton, f: &day_spec::ContextMenuFn) {
280    ffi_guard::contain((), || {
281        // The provider may remove this button; then no menu opens (docs/menus.md).
282        let key = ptr_of(btn);
283        let Some(items) =
284            day_spec::resolve_button_menu(f, || BUTTON_MENUS.with(|t| t.get(key)).is_some())
285        else {
286            return;
287        };
288        let menu = build_ns_menu(btn.mtm(), "", &items);
289        let bounds = btn.bounds();
290        let y = if btn.isFlipped() {
291            bounds.size.height + 2.0
292        } else {
293            -2.0
294        };
295        unsafe {
296            btn.highlight(true);
297            // Modal until the menu closes; a chosen item has queued its `MenuAction` by then.
298            menu.popUpMenuPositioningItem_atLocation_inView(
299                None,
300                objc2_foundation::NSPoint::new(0.0, y),
301                Some(btn),
302            );
303            btn.highlight(false);
304        }
305    });
306}
307
308/// An image view's rendering (`IMAGE_MODES`).
309#[derive(Clone, Copy)]
310struct ImageMode {
311    template: bool,
312    tinted: bool,
313}
314
315impl ImageMode {
316    /// Template rendering: the glyph's alpha as a mask, filled with the tint or the neutral
317    /// template color.
318    fn renders_template(self) -> bool {
319        self.template || self.tinted
320    }
321}
322
323/// A decoded bitmap (docs/images.md), held until day-core drops its last handle.
324///
325/// The `NSBitmapImageRep` is kept beside the image rather than fetched on demand for two
326/// reasons: it is the only thing here that can re-encode to other formats, and it is the only
327/// accurate source of pixel dimensions, since `NSImage.size` is in points and reports a @2x
328/// asset at half its real width.
329struct AppKitBitmap {
330    image: Retained<objc2_app_kit::NSImage>,
331    rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
332    info: day_spec::BitmapInfo,
333}
334
335/// Draw a decoded image into a fresh bitmap `scale`× its pixel size, for [`day_spec::EncodeSpec`]'s
336/// `fit`.
337///
338/// 8 bits across 4 samples with alpha is the one layout every writer here accepts, and the only
339/// one that carries transparency through a PNG round-trip intact.
340fn scaled_rep(
341    image: &objc2_app_kit::NSImage,
342    pixels: Size,
343    scale: f64,
344) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
345    use objc2::AllocAnyThread as _;
346    let w = (pixels.width * scale).round().max(1.0);
347    let h = (pixels.height * scale).round().max(1.0);
348    let rep = unsafe {
349        objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
350            objc2_app_kit::NSBitmapImageRep::alloc(),
351            std::ptr::null_mut(),
352            w as isize,
353            h as isize,
354            8,
355            4,
356            true,
357            false,
358            objc2_app_kit::NSDeviceRGBColorSpace,
359            0,
360            0,
361        )
362    }?;
363    let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
364    NSGraphicsContext::saveGraphicsState_class();
365    objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
366    unsafe {
367        image.drawInRect_fromRect_operation_fraction(
368            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
369            NSRect::ZERO,
370            objc2_app_kit::NSCompositingOperation::SourceOver,
371            1.0,
372        );
373    }
374    NSGraphicsContext::restoreGraphicsState_class();
375    Some(rep)
376}
377
378/// Re-encode a decoded bitmap (docs/images.md).
379///
380/// A free function rather than the duty's body so each refusal reads as an early return instead
381/// of another copy of the same emit.
382fn encode_bitmap(
383    id: day_spec::BitmapId,
384    spec: &day_spec::EncodeSpec,
385) -> Result<Vec<u8>, day_spec::ImageError> {
386    use day_spec::ImageFormat as F;
387    use objc2_app_kit::NSBitmapImageFileType as T;
388    let file_type = match spec.format {
389        F::Png => T::PNG,
390        F::Jpeg => T::JPEG,
391        F::Tiff => T::TIFF,
392        F::Bmp => T::BMP,
393        F::Gif => T::GIF,
394        // Readable here but not writable: `NSBitmapImageRep` ships no WebP or HEIF writer. That
395        // asymmetry is why `encode_formats` exists instead of letting `Cap::ImageEncode` imply
396        // that everything decodable is also encodable.
397        _ => return Err(day_spec::ImageError::Encode),
398    };
399    let held = BITMAPS.with(|m| {
400        m.borrow()
401            .get(&id.0)
402            .map(|b| (b.rep.clone(), b.image.clone(), b.info))
403    });
404    let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
405    let rep = rep.ok_or(day_spec::ImageError::Encode)?;
406
407    // `fit` scales the longest side down first. A box larger than the original is ignored:
408    // upscaling on an export path inflates the bytes without adding any detail.
409    let rep = match spec.fit {
410        Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
411            let scale = (fit.width / info.pixels.width)
412                .min(fit.height / info.pixels.height)
413                .min(1.0);
414            if scale < 1.0 {
415                scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
416            } else {
417                rep
418            }
419        }
420        _ => rep,
421    };
422
423    let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
424        // AppKit's own compression-factor property; a lossless writer ignores it.
425        Some(q) => {
426            let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
427            let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
428            let value: &objc2::runtime::AnyObject = &number;
429            NSDictionary::from_slices::<NSString>(&[key], &[value])
430        }
431        None => NSDictionary::new(),
432    };
433    let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
434        .ok_or(day_spec::ImageError::Encode)?;
435    Ok(data.to_vec())
436}
437
438/// Replay a display list into the current graphics context. The one painter both the on-screen
439/// `DayCanvas` (its `drawRect:`) and the canvas exports run, so the two cannot drift apart
440/// (docs/canvas.md "Exporting").
441///
442/// `base_scale` is how many of the context's base units make a canvas point: `1` in a view
443/// and on a PDF page, the pixel scale in a bitmap export. A Core Graphics shadow is measured
444/// in that base space and not in the transformed one, so it is what turns a shadow's points
445/// into the numbers the context wants.
446fn paint_ops(ops: &[DrawOp], base_scale: f64) {
447    use objc2_core_graphics::CGContext;
448    // SAFETY: reading the current graphics context on the thread that set it.
449    let cg = unsafe { NSGraphicsContext::currentContext().map(|c| c.CGContext()) };
450    let mut replay = Replay::new(base_scale);
451    let Some(cg) = cg else {
452        for op in ops {
453            draw_op(op, &mut replay);
454        }
455        return;
456    };
457    cg_begin_replay(&cg);
458    // A canvas is its own compositing group (docs/canvas.md "Blend modes"): a list that blends
459    // is painted into a transparency layer, so a mode reads only what this canvas drew, and
460    // `Erase` leaves a hole in the canvas through which whatever the context already held (the
461    // views behind it, when they share a backing store) shows unchanged.
462    let grouped = ops
463        .iter()
464        .any(|op| matches!(op, DrawOp::Blend(mode) if *mode != day_spec::BlendMode::Normal));
465    if grouped {
466        CGContext::save_g_state(Some(&cg));
467        // SAFETY: no auxiliary dictionary, which the function documents as allowed.
468        unsafe { CGContext::begin_transparency_layer(Some(&cg), None) };
469    }
470    for op in ops {
471        if !cg_fast_op(&cg, op) {
472            draw_op(op, &mut replay);
473        }
474    }
475    // A list that saves more than it restores must not leave its states on the context (the
476    // layer above has to end in the state it began in).
477    while replay.restore() {
478        NSGraphicsContext::restoreGraphicsState_class();
479    }
480    if grouped {
481        CGContext::end_transparency_layer(Some(&cg));
482        CGContext::restore_g_state(Some(&cg));
483    }
484}
485
486/// The part of the canvas graphics state a replay has to know and Core Graphics will not
487/// report back: whether a shadow is set, and the blend mode (docs/canvas.md "Shadows", "Blend
488/// modes"). The context saves and restores the real state itself; this mirrors it.
489#[derive(Clone, Copy, Debug, Default, PartialEq)]
490struct Ink {
491    shadow: bool,
492    blend: day_spec::BlendMode,
493}
494
495/// One replay of a display list: the [`Ink`] in force and the ones `DrawOp::Save` put aside.
496struct Replay {
497    base_scale: f64,
498    ink: Ink,
499    saved: Vec<Ink>,
500}
501
502impl Replay {
503    fn new(base_scale: f64) -> Self {
504        Replay {
505            base_scale,
506            ink: Ink::default(),
507            saved: Vec::new(),
508        }
509    }
510
511    fn save(&mut self) {
512        self.saved.push(self.ink);
513    }
514
515    /// Put back the ink of the matching save, and say whether there was one. A restore with no
516    /// save is ignored: popping the context then would take away the state the view or the
517    /// export set up around the replay.
518    fn restore(&mut self) -> bool {
519        match self.saved.pop() {
520            Some(ink) => {
521                self.ink = ink;
522                true
523            }
524            None => false,
525        }
526    }
527}
528
529/// A display list as a PDF page can take it (docs/canvas.md "Exporting"). PDF has the
530/// separable blend modes and no Porter-Duff operators: Core Graphics writes `Add` as a normal
531/// paint, which is the nearest a page gets, but it writes `Erase` as a normal paint too, and
532/// that puts the eraser's own color where a hole was asked for. So what is drawn under `Erase`
533/// is left out of the page.
534fn pdf_ops(ops: &[DrawOp]) -> std::borrow::Cow<'_, [DrawOp]> {
535    use day_spec::BlendMode;
536    if !ops
537        .iter()
538        .any(|op| matches!(op, DrawOp::Blend(BlendMode::Erase)))
539    {
540        return std::borrow::Cow::Borrowed(ops);
541    }
542    let (mut blend, mut saved) = (BlendMode::Normal, Vec::new());
543    let mut kept = Vec::with_capacity(ops.len());
544    for op in ops {
545        match op {
546            DrawOp::Blend(mode) => blend = *mode,
547            DrawOp::Save => saved.push(blend),
548            DrawOp::Restore => blend = saved.pop().unwrap_or(blend),
549            DrawOp::Fill(..)
550            | DrawOp::Stroke(..)
551            | DrawOp::Text { .. }
552            | DrawOp::Stamp(_)
553            | DrawOp::Image { .. }
554                if blend == BlendMode::Erase =>
555            {
556                continue;
557            }
558            _ => {}
559        }
560        kept.push(op.clone());
561    }
562    std::borrow::Cow::Owned(kept)
563}
564
565/// The Core Graphics blend mode for a canvas [`day_spec::BlendMode`].
566fn cg_blend_mode(mode: day_spec::BlendMode) -> objc2_core_graphics::CGBlendMode {
567    use day_spec::BlendMode as B;
568    use objc2_core_graphics::CGBlendMode as M;
569    match mode {
570        B::Normal => M::Normal,
571        B::Multiply => M::Multiply,
572        B::Screen => M::Screen,
573        B::Overlay => M::Overlay,
574        B::Darken => M::Darken,
575        B::Lighten => M::Lighten,
576        B::Add => M::PlusLighter,
577        B::Erase => M::DestinationOut,
578    }
579}
580
581/// The same mode as AppKit's compositing operation, for the drawing that takes one per call.
582fn ns_compositing(mode: day_spec::BlendMode) -> objc2_app_kit::NSCompositingOperation {
583    use day_spec::BlendMode as B;
584    use objc2_app_kit::NSCompositingOperation as O;
585    match mode {
586        B::Normal => O::SourceOver,
587        B::Multiply => O::Multiply,
588        B::Screen => O::Screen,
589        B::Overlay => O::Overlay,
590        B::Darken => O::Darken,
591        B::Lighten => O::Lighten,
592        B::Add => O::PlusLighter,
593        B::Erase => O::DestinationOut,
594    }
595}
596
597/// Set or clear the context's shadow (docs/canvas.md "Shadows"). Core Graphics measures the
598/// offset and the blur in the context's base space, which no transform scales or rotates (the
599/// rule the spec states) and whose y axis points up whichever way the canvas is flipped: hence
600/// the negated `dy`, and `base_scale` for a bitmap whose base unit is a pixel. Its blur is the
601/// width of the soft edge, the spec's own measure.
602fn cg_set_shadow(
603    cg: &objc2_core_graphics::CGContext,
604    shadow: Option<&day_spec::Shadow>,
605    base_scale: f64,
606) {
607    use objc2_core_graphics::{CGColor, CGContext};
608    match shadow {
609        Some(s) => {
610            let c = s.color.resolved();
611            let color = CGColor::new_srgb(c.r, c.g, c.b, c.a);
612            CGContext::set_shadow_with_color(
613                Some(cg),
614                NSSize::new(s.dx * base_scale, -s.dy * base_scale),
615                s.blur.max(0.0) * base_scale,
616                Some(&color),
617            );
618        }
619        None => CGContext::set_shadow_with_color(Some(cg), NSSize::new(0.0, 0.0), 0.0, None),
620    }
621}
622
623/// Run `draw`, which shapes a gradient with a clip, inside a saved state, and so that a shadow
624/// in force is cast by the result: the clip that shapes the gradient would cut its shadow off
625/// with it. A transparency layer does that: it starts with no shadow, and is composited, shadow
626/// and blend mode and all, in the state it was begun in, outside the clip made within it.
627fn draw_grouped(replay: &Replay, draw: impl FnOnce()) {
628    use objc2_core_graphics::CGContext;
629    // SAFETY: reading the current graphics context on the thread that set it.
630    let cg = unsafe { NSGraphicsContext::currentContext().map(|c| c.CGContext()) };
631    let layer = cg.filter(|_| replay.ink.shadow);
632    NSGraphicsContext::saveGraphicsState_class();
633    if let Some(cg) = &layer {
634        // SAFETY: no auxiliary dictionary, which the function documents as allowed.
635        unsafe { CGContext::begin_transparency_layer(Some(cg), None) };
636    }
637    draw();
638    if let Some(cg) = &layer {
639        CGContext::end_transparency_layer(Some(cg));
640    }
641    NSGraphicsContext::restoreGraphicsState_class();
642}
643
644/// `CGContextDrawConicGradient`, where the running OS has it (macOS 14). Looked up by name
645/// rather than linked: Day deploys to macOS 11, and a linked symbol the OS lacks stops the
646/// app at launch.
647fn native_conic() -> Option<ConicFn> {
648    unsafe extern "C" {
649        fn dlsym(
650            handle: *mut std::ffi::c_void,
651            symbol: *const std::ffi::c_char,
652        ) -> *mut std::ffi::c_void;
653    }
654    static FOUND: std::sync::OnceLock<Option<ConicFn>> = std::sync::OnceLock::new();
655    *FOUND.get_or_init(|| {
656        // `RTLD_DEFAULT`: search every image the process has loaded.
657        let default = -2isize as *mut std::ffi::c_void;
658        // SAFETY: a NUL-terminated name and the documented pseudo-handle.
659        let symbol = unsafe { dlsym(default, c"CGContextDrawConicGradient".as_ptr()) };
660        // SAFETY: a non-null result is the address of the function of that name, whose C
661        // signature `ConicFn` spells out.
662        (!symbol.is_null())
663            .then(|| unsafe { std::mem::transmute::<*mut std::ffi::c_void, ConicFn>(symbol) })
664    })
665}
666
667/// `void CGContextDrawConicGradient(CGContextRef, CGGradientRef, CGPoint center, CGFloat angle)`.
668type ConicFn = unsafe extern "C-unwind" fn(
669    &objc2_core_graphics::CGContext,
670    Option<&objc2_core_graphics::CGGradient>,
671    NSPoint,
672    objc2_core_foundation::CGFloat,
673);
674
675/// A conic gradient as pixels, for an OS with no conic primitive: `width` by `height`
676/// premultiplied RGBA, row 0 at the top, where pixel (`i`, `j`) is the gradient's color
677/// ([`day_spec::ConicGradient::color_at`]) at the canvas point `origin + (i + ½, j + ½) × step`,
678/// by the angle of that point about `center`. Every pixel is computed from the gradient
679/// itself, so there is no fan of wedges to leave seams or bands.
680fn conic_pixels(
681    gradient: &day_spec::ConicGradient,
682    center: Point,
683    origin: Point,
684    step: f64,
685    width: usize,
686    height: usize,
687) -> Vec<u8> {
688    let mut pixels = Vec::with_capacity(width * height * 4);
689    let byte = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
690    for j in 0..height {
691        let dy = origin.y + (j as f64 + 0.5) * step - center.y;
692        for i in 0..width {
693            let dx = origin.x + (i as f64 + 0.5) * step - center.x;
694            // Canvas angles: 0 is +x and y points down, so `atan2` already turns clockwise.
695            let c = gradient.color_at(day_spec::Angle::rad(dy.atan2(dx)));
696            pixels.extend_from_slice(&[
697                byte(c.r * c.a),
698                byte(c.g * c.a),
699                byte(c.b * c.a),
700                byte(c.a),
701            ]);
702        }
703    }
704    pixels
705}
706
707/// The most pixels an emulated conic gradient is computed at; a larger area is computed more
708/// coarsely and scaled up, which a gradient takes well.
709const CONIC_PIXEL_BUDGET: f64 = 4_000_000.0;
710
711/// Draw a conic gradient through the clip that is installed: the OS's own conic gradient
712/// where it has one, computed pixels otherwise.
713fn draw_conic(
714    cg: &objc2_core_graphics::CGContext,
715    gradient: &day_spec::ConicGradient,
716    bounds: day_spec::Rect,
717) {
718    use objc2_core_graphics::{CGColorSpace, CGGradient};
719    if gradient.stops.is_empty() {
720        return;
721    }
722    let center = gradient.center.resolve(bounds);
723    if let Some(draw) = native_conic() {
724        let components: Vec<objc2_core_foundation::CGFloat> = stops_now(&gradient.stops)
725            .into_iter()
726            .flat_map(|(_, c)| [c.r, c.g, c.b, c.a])
727            .collect();
728        let locations: Vec<objc2_core_foundation::CGFloat> =
729            gradient.stops.iter().map(|(at, _)| *at).collect();
730        // SAFETY: `kCGColorSpaceSRGB` is an immutable CFString constant.
731        let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
732        // SAFETY: four components per stop and one location per stop, both alive for the call.
733        let native = unsafe {
734            CGGradient::with_color_components(
735                srgb.as_deref(),
736                components.as_ptr(),
737                locations.as_ptr(),
738                locations.len(),
739            )
740        };
741        if let Some(native) = native {
742            // SAFETY: the function `native_conic` found, called with its own signature. The
743            // canvas is y-down, where the function's growing angle turns clockwise.
744            unsafe {
745                draw(
746                    cg,
747                    Some(&native),
748                    NSPoint::new(center.x, center.y),
749                    gradient.start.radians(),
750                );
751            };
752            return;
753        }
754    }
755    draw_conic_pixels(cg, gradient, center);
756}
757
758/// The conic gradient of an OS with no conic primitive: [`conic_pixels`] over the area the
759/// installed clip lets through, at the context's own pixel density (and no less than two per
760/// point, which is what softens a hard stop's edge and gives a PDF page something to print),
761/// drawn through that clip as an image.
762fn draw_conic_pixels(
763    cg: &objc2_core_graphics::CGContext,
764    gradient: &day_spec::ConicGradient,
765    center: Point,
766) {
767    use objc2_core_graphics::{
768        CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGContext,
769        CGImageAlphaInfo,
770    };
771    let clip = CGContext::clip_bounding_box(Some(cg));
772    let (w, h) = (clip.size.width, clip.size.height);
773    if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
774        return;
775    }
776    let device = CGContext::user_space_to_device_space_transform(Some(cg));
777    let density = device
778        .a
779        .hypot(device.b)
780        .max(device.c.hypot(device.d))
781        .clamp(2.0, 16.0)
782        .min((CONIC_PIXEL_BUDGET / (w * h)).sqrt());
783    let (pw, ph) = (
784        ((w * density).ceil() as usize).max(1),
785        ((h * density).ceil() as usize).max(1),
786    );
787    let origin = Point::new(clip.origin.x, clip.origin.y);
788    let mut pixels = conic_pixels(gradient, center, origin, 1.0 / density, pw, ph);
789    // SAFETY: `kCGColorSpaceSRGB` is an immutable CFString constant.
790    let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
791    // SAFETY: `pixels` holds `ph` rows of `pw` RGBA pixels, the layout the arguments describe,
792    // and outlives the context, which is dropped at the end of this statement. The image is
793    // a copy of the buffer.
794    let image = unsafe {
795        CGBitmapContextCreate(
796            pixels.as_mut_ptr().cast(),
797            pw,
798            ph,
799            8,
800            pw * 4,
801            srgb.as_deref(),
802            CGImageAlphaInfo::PremultipliedLast.0,
803        )
804    }
805    .and_then(|bitmap| CGBitmapContextCreateImage(Some(&bitmap)));
806    let Some(image) = image else {
807        return;
808    };
809    // The canvas is y-down and `CGContextDrawImage` puts an image's first row at the top only
810    // in a y-up space, so the image is drawn through a local flip, as `DrawOp::Image` is.
811    CGContext::save_g_state(Some(cg));
812    CGContext::translate_ctm(Some(cg), origin.x, origin.y + ph as f64 / density);
813    CGContext::scale_ctm(Some(cg), 1.0, -1.0);
814    CGContext::draw_image(
815        Some(cg),
816        NSRect::new(
817            NSPoint::new(0.0, 0.0),
818            NSSize::new(pw as f64 / density, ph as f64 / density),
819        ),
820        Some(&image),
821    );
822    CGContext::restore_g_state(Some(cg));
823}
824
825/// Paint one op straight into the Core Graphics context when it is a solid fill, a solid
826/// stroke or a clip of a shape the context can take as path calls, and say whether it did.
827/// This is the hot path of a dense drawing (a map tile is a few thousand of these), and the
828/// path object route below it costs an order of magnitude more: every `NSBezierPath` is an
829/// allocation and a message per segment, and its fill or stroke re-derives the graphics state
830/// the context already holds. Everything else (text, images, gradients, stamps, rounded rects
831/// and arcs) keeps the full painter. The fill and stroke color spaces are set to sRGB once per
832/// replay by `cg_begin_replay`, so the components here read as the ones `nscolor` would make.
833fn cg_fast_op(cg: &objc2_core_graphics::CGContext, op: &DrawOp) -> bool {
834    use objc2_core_graphics::{CGContext, CGImage};
835    match op {
836        DrawOp::Fill(shape, day_spec::Paint::Solid(color)) => {
837            let Some(even_odd) = cg_add_shape(cg, shape) else {
838                return false;
839            };
840            let c = color.resolved();
841            let c = [c.r, c.g, c.b, c.a];
842            // SAFETY: four components for the sRGB fill space set at the start of the replay.
843            unsafe { CGContext::set_fill_color(Some(cg), c.as_ptr()) };
844            if even_odd {
845                CGContext::eo_fill_path(Some(cg));
846            } else {
847                CGContext::fill_path(Some(cg));
848            }
849            true
850        }
851        DrawOp::Stroke(shape, day_spec::Paint::Solid(color), style) => {
852            if cg_add_shape(cg, shape).is_none() {
853                return false;
854            }
855            let c = color.resolved();
856            let c = [c.r, c.g, c.b, c.a];
857            // SAFETY: four components for the sRGB stroke space set at the start of the replay.
858            unsafe { CGContext::set_stroke_color(Some(cg), c.as_ptr()) };
859            cg_stroke_style(cg, style);
860            CGContext::stroke_path(Some(cg));
861            true
862        }
863        DrawOp::Clip(shape) => {
864            let Some(even_odd) = cg_add_shape(cg, shape) else {
865                return false;
866            };
867            if even_odd {
868                CGContext::eo_clip(Some(cg));
869            } else {
870                CGContext::clip(Some(cg));
871            }
872            true
873        }
874        DrawOp::Image {
875            image,
876            rect,
877            opacity,
878            source,
879        } => {
880            // The bitmap's pixels straight to the context (`drawInRect:` on the image object
881            // costs tens of microseconds per call, and a pattern fill is hundreds of copies).
882            let Some((cg_image, pixels)) = BITMAPS.with(|m| {
883                m.borrow().get(&image.0).and_then(|b| {
884                    // SAFETY: reading the rep's immutable CGImage on the thread holding it.
885                    let cg = unsafe { b.rep.as_ref()?.CGImage() }?;
886                    Some((cg, b.info.pixels))
887                })
888            }) else {
889                return false;
890            };
891            // A region is in the bitmap's pixels with a top-left origin, which is also how
892            // `CGImageCreateWithImageInRect` counts; the shared clamp keeps its mapping into
893            // `rect` when it overhangs the bitmap.
894            let (cropped, dest) = match source {
895                None => (None, *rect),
896                Some(src) => {
897                    let Some((src, dest)) = day_spec::clamp_image_source(*src, *rect, pixels)
898                    else {
899                        return true;
900                    };
901                    let crop = CGImage::with_image_in_rect(
902                        Some(&cg_image),
903                        NSRect::new(
904                            NSPoint::new(src.origin.x, src.origin.y),
905                            NSSize::new(src.size.width, src.size.height),
906                        ),
907                    );
908                    let Some(crop) = crop else {
909                        return true;
910                    };
911                    (Some(crop), dest)
912                }
913            };
914            if dest.size.width <= 0.0 || dest.size.height <= 0.0 {
915                return true;
916            }
917            // The canvas is y-down and `CGContextDrawImage` puts the image's first row at the
918            // TOP of `rect` only in a y-up space, so the image is drawn through a local flip.
919            CGContext::save_g_state(Some(cg));
920            CGContext::set_alpha(Some(cg), opacity.clamp(0.0, 1.0));
921            CGContext::translate_ctm(Some(cg), dest.origin.x, dest.origin.y + dest.size.height);
922            CGContext::scale_ctm(Some(cg), 1.0, -1.0);
923            CGContext::draw_image(
924                Some(cg),
925                NSRect::new(
926                    NSPoint::new(0.0, 0.0),
927                    NSSize::new(dest.size.width, dest.size.height),
928                ),
929                Some(cropped.as_deref().unwrap_or(&cg_image)),
930            );
931            CGContext::restore_g_state(Some(cg));
932            true
933        }
934        _ => false,
935    }
936}
937
938/// Begin a replay on `cg`: fill and stroke colors are given as sRGB components from here on.
939fn cg_begin_replay(cg: &objc2_core_graphics::CGContext) {
940    use objc2_core_graphics::{CGColorSpace, CGContext};
941    // SAFETY: `kCGColorSpaceSRGB` is an immutable CFString constant.
942    let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
943    CGContext::set_fill_color_space(Some(cg), srgb.as_deref());
944    CGContext::set_stroke_color_space(Some(cg), srgb.as_deref());
945}
946
947/// Add `shape` as the context's current path and say whether it fills even-odd, or `None` for
948/// a shape that takes the path object route (a rounded rect or an arc).
949fn cg_add_shape(cg: &objc2_core_graphics::CGContext, shape: &day_spec::Shape) -> Option<bool> {
950    use day_spec::{PathSeg, Shape};
951    use objc2_core_graphics::CGContext;
952    CGContext::begin_path(Some(cg));
953    match shape {
954        Shape::Rect(r) => CGContext::add_rect(Some(cg), ns_rect(*r)),
955        Shape::Ellipse(r) => CGContext::add_ellipse_in_rect(Some(cg), ns_rect(*r)),
956        Shape::Line(a, b) => {
957            CGContext::move_to_point(Some(cg), a.x, a.y);
958            CGContext::add_line_to_point(Some(cg), b.x, b.y);
959        }
960        Shape::Polygon(pts) => {
961            let (first, rest) = pts.split_first()?;
962            if rest.is_empty() {
963                return None;
964            }
965            CGContext::move_to_point(Some(cg), first.x, first.y);
966            for p in rest {
967                CGContext::add_line_to_point(Some(cg), p.x, p.y);
968            }
969            CGContext::close_path(Some(cg));
970        }
971        Shape::Path(path) => {
972            if path.segs.is_empty() {
973                return None;
974            }
975            for seg in &path.segs {
976                match seg {
977                    PathSeg::Move(a) => CGContext::move_to_point(Some(cg), a.x, a.y),
978                    PathSeg::Line(a) => CGContext::add_line_to_point(Some(cg), a.x, a.y),
979                    PathSeg::Quad(c, a) => {
980                        CGContext::add_quad_curve_to_point(Some(cg), c.x, c.y, a.x, a.y);
981                    }
982                    PathSeg::Cubic(c1, c2, a) => {
983                        CGContext::add_curve_to_point(Some(cg), c1.x, c1.y, c2.x, c2.y, a.x, a.y);
984                    }
985                    PathSeg::Close => CGContext::close_path(Some(cg)),
986                }
987            }
988            return Some(path.rule == day_spec::FillRule::EvenOdd);
989        }
990        Shape::RoundedRect(..) | Shape::Arc { .. } => return None,
991    }
992    Some(false)
993}
994
995/// Put a [`day_spec::StrokeStyle`] on the context. Every field is set, because the graphics
996/// state keeps the previous stroke's cap, join and dash and a plain stroke must not inherit
997/// them.
998fn cg_stroke_style(cg: &objc2_core_graphics::CGContext, style: &day_spec::StrokeStyle) {
999    use day_spec::{LineCap, LineJoin};
1000    use objc2_core_graphics::{CGContext, CGLineCap, CGLineJoin};
1001    CGContext::set_line_width(Some(cg), style.width);
1002    CGContext::set_line_cap(
1003        Some(cg),
1004        match style.cap {
1005            LineCap::Butt => CGLineCap::Butt,
1006            LineCap::Round => CGLineCap::Round,
1007            LineCap::Square => CGLineCap::Square,
1008        },
1009    );
1010    CGContext::set_line_join(
1011        Some(cg),
1012        match style.join {
1013            LineJoin::Miter => CGLineJoin::Miter,
1014            LineJoin::Round => CGLineJoin::Round,
1015            LineJoin::Bevel => CGLineJoin::Bevel,
1016        },
1017    );
1018    CGContext::set_miter_limit(Some(cg), style.miter_limit);
1019    if style.dash.is_empty() {
1020        // SAFETY: a null pattern with a zero count clears the dash, per the CGContext docs.
1021        unsafe { CGContext::set_line_dash(Some(cg), 0.0, core::ptr::null(), 0) };
1022    } else {
1023        let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
1024        // SAFETY: `pattern` outlives the call, and `count` is its length.
1025        unsafe {
1026            CGContext::set_line_dash(Some(cg), style.dash_phase, pattern.as_ptr(), pattern.len());
1027        };
1028    }
1029}
1030
1031/// Paint `ops` into `cg` with a top-left origin and y down, as the flipped `DayCanvas` sees
1032/// them. `height` is the context's own height in its base units (pixels for a bitmap, points for
1033/// a PDF page) and `scale` its units per canvas point.
1034///
1035/// The CTM flip turns the geometry the right way up; wrapping the context as a FLIPPED
1036/// `NSGraphicsContext` is what tells AppKit's text and image drawing to keep glyphs and pictures
1037/// upright inside that flip, exactly as they are in a flipped view's `drawRect:`.
1038fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
1039    use objc2_core_graphics::CGContext;
1040    CGContext::save_g_state(Some(cg));
1041    CGContext::translate_ctm(Some(cg), 0.0, height);
1042    CGContext::scale_ctm(Some(cg), scale, -scale);
1043    let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
1044    NSGraphicsContext::saveGraphicsState_class();
1045    NSGraphicsContext::setCurrentContext(Some(&ns));
1046    paint_ops(ops, scale);
1047    NSGraphicsContext::restoreGraphicsState_class();
1048    CGContext::restore_g_state(Some(cg));
1049}
1050
1051/// A Cocoa object on its way to or from a painting thread (docs/canvas.md "Exporting").
1052struct Sendable<T>(T);
1053
1054// SAFETY: wrapped only around objects AppKit documents as usable from any thread while nothing
1055// mutates them — `NSImage` and `NSBitmapImageRep` for drawing, `NSFont`, and a `CGImage`,
1056// which is immutable — and a stored bitmap is never mutated after `BITMAPS` takes it. Each
1057// wrapped value is used by one thread at a time: the painter borrows it for one export, then
1058// the UI thread owns the result.
1059unsafe impl<T> Send for Sendable<T> {}
1060
1061/// Everything the painter would read from the UI thread's tables, resolved there before an
1062/// export leaves for a painting thread (docs/canvas.md "Exporting"): the decoded images its
1063/// image ops draw, and the font each of its text runs needs, which only the UI thread may ask
1064/// `NSFontManager` for.
1065struct OffscreenResources {
1066    images: Vec<(u64, AppKitBitmap)>,
1067    fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>,
1068}
1069
1070impl OffscreenResources {
1071    /// Walk `ops` on the UI thread. An image whose handle was already released is simply
1072    /// absent, and the painter draws nothing for it, as it does on screen.
1073    fn collect(ops: &[DrawOp]) -> Self {
1074        let mut images: Vec<(u64, AppKitBitmap)> = Vec::new();
1075        let mut fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)> = Vec::new();
1076        for op in ops {
1077            match op {
1078                DrawOp::Image { image, .. } => {
1079                    if images.iter().any(|(id, _)| *id == image.0) {
1080                        continue;
1081                    }
1082                    let held = BITMAPS.with(|m| {
1083                        m.borrow().get(&image.0).map(|b| AppKitBitmap {
1084                            image: b.image.clone(),
1085                            rep: b.rep.clone(),
1086                            info: b.info,
1087                        })
1088                    });
1089                    if let Some(bitmap) = held {
1090                        images.push((image.0, bitmap));
1091                    }
1092                }
1093                DrawOp::Text { size, font, .. } => {
1094                    let key = (size.to_bits(), font.clone());
1095                    if fonts.iter().any(|(k, _)| *k == key) {
1096                        continue;
1097                    }
1098                    let resolved = canvas_nsfont(*size, font);
1099                    fonts.push((key, resolved));
1100                }
1101                _ => {}
1102            }
1103        }
1104        Self { images, fonts }
1105    }
1106
1107    /// Run `paint` with these as the calling thread's own tables, then take them back out.
1108    /// Only entries this call added are removed afterwards, so a run on the UI thread itself
1109    /// (no painting thread could start) leaves its tables as they were.
1110    fn with_installed<R>(self, paint: impl FnOnce() -> R) -> R {
1111        let mut added_images = Vec::with_capacity(self.images.len());
1112        BITMAPS.with(|m| {
1113            let mut m = m.borrow_mut();
1114            for (id, bitmap) in self.images {
1115                if let std::collections::hash_map::Entry::Vacant(slot) = m.entry(id) {
1116                    slot.insert(bitmap);
1117                    added_images.push(id);
1118                }
1119            }
1120        });
1121        let added_fonts = self.fonts.len();
1122        OFFSCREEN_FONTS.with(|t| t.borrow_mut().extend(self.fonts));
1123        let out = paint();
1124        OFFSCREEN_FONTS.with(|t| {
1125            let mut t = t.borrow_mut();
1126            let keep = t.len().saturating_sub(added_fonts);
1127            t.truncate(keep);
1128        });
1129        BITMAPS.with(|m| {
1130            let mut m = m.borrow_mut();
1131            for id in added_images {
1132                m.remove(&id);
1133            }
1134        });
1135        out
1136    }
1137}
1138
1139/// Render a canvas display list offscreen (docs/canvas.md "Exporting"): `export_pixels` of
1140/// transparent sRGB, premultiplied RGBA, painted at `scale` pixels per point. The half of the
1141/// export that runs on a painting thread: CoreGraphics draws into a bitmap context from any
1142/// thread, and the painter's AppKit objects (paths, colors, gradients, fonts, string drawing,
1143/// image drawing) are documented safe off the main thread when nothing mutates them.
1144///
1145/// A `CGBitmapContext` rather than `NSGraphicsContext(bitmapImageRep:)`: it carries a real sRGB
1146/// color space, so the `NSBitmapImageRep` built from its image is tagged sRGB like every canvas
1147/// color, shows on the display through the same color matching the live canvas gets, and writes
1148/// that profile into a PNG.
1149fn render_bitmap_cgimage(
1150    ops: &[DrawOp],
1151    size: Size,
1152    scale: f64,
1153) -> Result<objc2_core_foundation::CFRetained<objc2_core_graphics::CGImage>, day_spec::ExportError>
1154{
1155    use objc2_core_graphics::{
1156        CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
1157    };
1158    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
1159    let (pw, ph) = day_spec::export_pixels(size, scale);
1160    // SAFETY: `kCGColorSpaceSRGB` is an immutable CoreGraphics constant, valid for the process.
1161    let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
1162        .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
1163    // SAFETY: a null data pointer asks CoreGraphics to allocate (and own) the buffer, and a zero
1164    // row stride lets it choose one; 8 bits × RGBA premultiplied is a supported layout.
1165    let cg = unsafe {
1166        CGBitmapContextCreate(
1167            std::ptr::null_mut(),
1168            pw as usize,
1169            ph as usize,
1170            8,
1171            0,
1172            Some(&space),
1173            CGImageAlphaInfo::PremultipliedLast.0,
1174        )
1175    }
1176    .ok_or_else(|| {
1177        day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
1178    })?;
1179    // A new bitmap context starts zeroed, which is the transparent background.
1180    paint_flipped(&cg, f64::from(ph), scale, ops);
1181    CGBitmapContextCreateImage(Some(&cg))
1182        .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))
1183}
1184
1185/// The UI-thread half of a bitmap export: the painted `CGImage` wrapped as the `NSBitmapImageRep`
1186/// and `NSImage` a decoded bitmap is stored as, so `image`, `encode_image` and `DrawOp::Image`
1187/// take it like one.
1188fn bitmap_from_cgimage(cg_image: &objc2_core_graphics::CGImage, scale: f64) -> AppKitBitmap {
1189    use objc2::AllocAnyThread as _;
1190    let rep = unsafe {
1191        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
1192            objc2_app_kit::NSBitmapImageRep::alloc(),
1193            cg_image,
1194        )
1195    };
1196    let (pw, ph) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
1197    // Sized in POINTS, pixels over scale, so the image draws at the drawing's size and stays
1198    // sharp at `scale`× — the same shape as a staged @2x asset.
1199    let points = NSSize::new(pw / scale, ph / scale);
1200    unsafe { rep.setSize(points) };
1201    let image =
1202        unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
1203    unsafe { image.addRepresentation(&rep) };
1204    AppKitBitmap {
1205        image,
1206        rep: Some(rep),
1207        info: day_spec::BitmapInfo {
1208            pixels: Size::new(pw, ph),
1209            scale,
1210            format: None,
1211            has_alpha: true,
1212        },
1213    }
1214}
1215
1216/// Write `pages` as one PDF document (docs/canvas.md "Exporting"): a `CGPDFContext` on a
1217/// `CGDataConsumer` over memory, one page per drawing with its own media box, the title and
1218/// author in the document info. Shapes and text stay vector: the same painter draws into the PDF
1219/// context, and AppKit's string drawing there emits real glyphs from embedded font subsets.
1220fn render_pdf_bytes(
1221    pages: &[day_spec::PdfPage],
1222    info: &day_spec::PdfInfo,
1223) -> Result<Vec<u8>, day_spec::ExportError> {
1224    use objc2_core_foundation::{
1225        CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
1226    };
1227    use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
1228    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
1229    let media =
1230        |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
1231    let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
1232    let data = CFMutableData::new(None, 0)
1233        .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
1234    let consumer = CGDataConsumer::with_cf_data(Some(&data))
1235        .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
1236
1237    let mut keys: Vec<&CFString> = Vec::new();
1238    let mut values: Vec<CFRetained<CFString>> = Vec::new();
1239    // SAFETY: the auxiliary-info keys are immutable CoreGraphics constants.
1240    let (title_key, author_key) = unsafe {
1241        (
1242            objc2_core_graphics::kCGPDFContextTitle,
1243            objc2_core_graphics::kCGPDFContextAuthor,
1244        )
1245    };
1246    for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
1247        if let Some(value) = value {
1248            keys.push(key);
1249            values.push(CFString::from_str(value));
1250        }
1251    }
1252    let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
1253    let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
1254
1255    let first_box = media(first.size);
1256    // SAFETY: `first_box` outlives the call, and the dictionary maps the documented
1257    // auxiliary-info string keys to strings, which is the type those keys take.
1258    let pdf =
1259        unsafe { CGPDFContextCreate(Some(&consumer), &raw const first_box, Some(aux.as_opaque())) }
1260            .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
1261    for page in pages {
1262        let page_box = media(page.size);
1263        // SAFETY: `page_box` outlives the call; in a PDF context it becomes the page's MediaBox.
1264        unsafe { CGContext::begin_page(Some(&pdf), &raw const page_box) };
1265        paint_flipped(&pdf, page.size.height, 1.0, &pdf_ops(&page.ops));
1266        CGContext::end_page(Some(&pdf));
1267    }
1268    // Closing flushes the trailer into the consumer; the bytes are complete only after it.
1269    CGPDFContextClose(Some(&pdf));
1270    drop(pdf);
1271    drop(consumer);
1272    Ok(data.to_vec())
1273}
1274
1275thread_local! {
1276    /// Each realized list item's current props, by its view: a patch updates one part and the
1277    /// item is re-dressed from the whole (docs/list.md "List items").
1278    static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
1279        std::cell::RefCell::new(std::collections::HashMap::new());
1280}
1281
1282/// A list row's standard content (docs/list.md "List items"), as an image-and-text table cell
1283/// draws it: a 16pt template image, the title in the system font with a smaller secondary
1284/// subtitle under it, a secondary trailing value, and the accent checkmark, in a horizontal
1285/// stack at least 28pt tall. Parts that are absent are hidden, and the stack closes up around
1286/// them.
1287///
1288/// The row's width is spoken for explicitly, as an image-and-text cell's is: the stack fills
1289/// its frame edge to edge, the words take every spare point and give way first, and the
1290/// trailing parts keep their own size. Left to the stack's default gravity areas, the spare
1291/// width had two equally weak claims, the words' column and the gap before the trailing parts,
1292/// so Auto Layout settled it from whatever the row's last layout had been: a checkmark landed
1293/// beside the title in one row and at the trailing edge in the next, and stayed put.
1294fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
1295    const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
1296        objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
1297    // Hugging: the words stretch (1), the trailing parts hold their size (750), and the stack
1298    // keeps its edges on its first and last parts (750), so exactly one part takes the slack.
1299    const STRETCH: f32 = 1.0;
1300    const HOLD: f32 = 750.0;
1301    use objc2_app_kit::{
1302        NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
1303    };
1304    let label = |text: &str, size: f64, secondary: bool| {
1305        let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
1306        unsafe {
1307            tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
1308            if secondary {
1309                tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
1310            }
1311            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
1312        }
1313        tf
1314    };
1315    let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
1316    let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
1317    let stack = NSStackView::new(mtm);
1318    stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
1319    stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
1320    stack.setAlignment(NSLayoutAttribute::CenterY);
1321    stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
1322    stack.setSpacing(6.0);
1323    // A table row's breathing room above and below; the list gives the sides.
1324    stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
1325        top: 4.0,
1326        left: 0.0,
1327        bottom: 4.0,
1328        right: 0.0,
1329    });
1330    let icon = unsafe { NSImageView::new(mtm) };
1331    unsafe {
1332        icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
1333        icon.widthAnchor()
1334            .constraintEqualToConstant(16.0)
1335            .setActive(true);
1336        icon.heightAnchor()
1337            .constraintEqualToConstant(16.0)
1338            .setActive(true);
1339    }
1340    stack.addArrangedSubview(&icon);
1341    // The title and subtitle span the words' column (Width alignment), so the column's width is
1342    // theirs and nothing is left over inside it.
1343    let texts = NSStackView::new(mtm);
1344    texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
1345    texts.setAlignment(NSLayoutAttribute::Width);
1346    texts.setSpacing(1.0);
1347    // Its height is its lines', centered in the row, not the row's height with the lines
1348    // floating somewhere inside it.
1349    texts.setHuggingPriority_forOrientation(
1350        HOLD,
1351        objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
1352    );
1353    let title = label("", size, false);
1354    let subtitle = label("", small, true);
1355    // The words take the width and give way first, truncating, before the trailing parts.
1356    for line in [&title, &subtitle] {
1357        line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
1358        line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
1359    }
1360    texts.addArrangedSubview(&title);
1361    texts.addArrangedSubview(&subtitle);
1362    stack.addArrangedSubview(&texts);
1363    let detail = label("", size, true);
1364    detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
1365    detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
1366    stack.addArrangedSubview(&detail);
1367    let check = unsafe { NSImageView::new(mtm) };
1368    unsafe {
1369        check.setImage(
1370            objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1371                &NSString::from_str("checkmark"),
1372                None,
1373            )
1374            .as_deref(),
1375        );
1376        check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
1377    }
1378    check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
1379    check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
1380    stack.addArrangedSubview(&check);
1381    let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
1382    LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
1383    dress_list_item(&view, p, mtm);
1384    view
1385}
1386
1387/// Show `p` on a list item's stack (see [`make_list_item`]), as one accessibility element.
1388fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
1389    use objc2_app_kit::{NSImageView, NSStackView};
1390    let Some(stack) = view.downcast_ref::<NSStackView>() else {
1391        return;
1392    };
1393    let parts = stack.arrangedSubviews();
1394    if parts.len() < 4 {
1395        return;
1396    }
1397    let icon = parts.objectAtIndex(0);
1398    if let Some(iv) = icon.downcast_ref::<NSImageView>() {
1399        let image = p
1400            .icon
1401            .as_ref()
1402            .and_then(|i| toolbar::image_for(i, &p.title, mtm));
1403        unsafe {
1404            iv.setImage(image.as_deref());
1405            iv.setContentTintColor(p.icon_tint.map(color::nsink).as_deref());
1406        }
1407    }
1408    icon.setHidden(p.icon.is_none());
1409    if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
1410        let lines = texts.arrangedSubviews();
1411        if lines.len() == 2 {
1412            if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
1413                tf.setStringValue(&NSString::from_str(&p.title));
1414            }
1415            let sub = lines.objectAtIndex(1);
1416            if let Some(tf) = sub.downcast_ref::<NSTextField>() {
1417                tf.setStringValue(&NSString::from_str(&p.subtitle));
1418            }
1419            sub.setHidden(p.subtitle.is_empty());
1420        }
1421    }
1422    let detail = parts.objectAtIndex(2);
1423    if let Some(tf) = detail.downcast_ref::<NSTextField>() {
1424        tf.setStringValue(&NSString::from_str(&p.detail));
1425    }
1426    detail.setHidden(p.detail.is_empty());
1427    parts.objectAtIndex(3).setHidden(!p.checked);
1428    let words = [&p.title, &p.subtitle, &p.detail]
1429        .into_iter()
1430        .filter(|w| !w.is_empty())
1431        .map(String::as_str)
1432        .collect::<Vec<_>>()
1433        .join(", ");
1434    unsafe {
1435        view.setAccessibilityElement(true);
1436        view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
1437        view.setAccessibilitySelected(p.checked);
1438    }
1439}
1440
1441/// The `NSImage` behind an [`day_spec::ImageSource`] (docs/images.md).
1442///
1443/// Shared by realize and the `Source` patch: a swapped source must load exactly what a fresh
1444/// realize would have, or a piece would show different pixels depending on whether it was
1445/// built or updated.
1446fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
1447    use objc2::AllocAnyThread as _;
1448    match source {
1449        // A vector glyph's SVG first (docs/vectors.md): NSImage renders SVG at display size
1450        // (macOS 11+), so vectors stay vector with no build-time raster resampling. Then the
1451        // shared image-file resolver (images/ then assets/ then bundle), which is macOS's native
1452        // path: a bundle file loaded straight into NSImage (§18.3).
1453        day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
1454            .or_else(|| day_spec::resource::resolve_image_file(name))
1455            .and_then(|path| unsafe {
1456                objc2_app_kit::NSImage::initWithContentsOfFile(
1457                    objc2_app_kit::NSImage::alloc(),
1458                    &NSString::from_str(&path.to_string_lossy()),
1459                )
1460            }),
1461        // Bytes the app already holds (a download, a picked file, a paste) with no staged
1462        // resource behind them.
1463        day_spec::ImageSource::Bytes(bytes) => unsafe {
1464            objc2_app_kit::NSImage::initWithData(
1465                objc2_app_kit::NSImage::alloc(),
1466                &NSData::with_bytes(bytes),
1467            )
1468        },
1469        // Already decoded: share the one NSImage rather than parsing the same bytes twice.
1470        day_spec::ImageSource::Decoded(id) => {
1471            BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
1472        }
1473    }
1474}
1475
1476/// `image` set to render as a template or as authored, for an image view to show
1477/// (docs/vectors.md "Tint", docs/images.md "Tinting"). Template rendering is a property of
1478/// the `NSImage`: it draws the image's alpha filled with the view's content tint, whether the
1479/// pixels came from a vector, a staged raster, encoded bytes or a decoded bitmap. An image that
1480/// already renders the right way comes back as it is; otherwise a copy is changed, because the
1481/// image may be the one a decoded bitmap shares with every other view and canvas drawing it.
1482fn image_rendered(
1483    image: Retained<objc2_app_kit::NSImage>,
1484    template: bool,
1485) -> Retained<objc2_app_kit::NSImage> {
1486    use objc2_foundation::NSCopying as _;
1487    if image.isTemplate() == template {
1488        return image;
1489    }
1490    let image = image.copy();
1491    image.setTemplate(template);
1492    image
1493}
1494
1495/// Day `Role` → the `NSAccessibilityRole` constant to apply (§13). `None` for `Role::None`:
1496/// Day leaves native controls' roles untouched and only applies explicit canvas/custom roles.
1497fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
1498    use day_spec::Role;
1499    use objc2_app_kit::{
1500        NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
1501        NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
1502        NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
1503        NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
1504    };
1505    unsafe {
1506        Some(match role {
1507            Role::Button => NSAccessibilityButtonRole,
1508            Role::Toggle => NSAccessibilityCheckBoxRole,
1509            // A tab is a radio button with the tab-button subrole (`set_a11y` adds it), which
1510            // is how NSTabView's own tabs read to VoiceOver; the strip is a tab group.
1511            Role::Tab => NSAccessibilityRadioButtonRole,
1512            Role::TabList => NSAccessibilityTabGroupRole,
1513            Role::Slider => NSAccessibilitySliderRole,
1514            Role::TextInput => NSAccessibilityTextFieldRole,
1515            // `AXHeading` lands the label in VoiceOver's headings rotor. The level has no
1516            // AppKit attribute of its own: the only convention (the level as `AXValue`) would
1517            // displace the text an NSTextField reports as its value, so the level stays
1518            // unspoken.
1519            Role::Heading(_) => NSAccessibilityHeadingRole,
1520            Role::Image => NSAccessibilityImageRole,
1521            Role::Meter => NSAccessibilityLevelIndicatorRole,
1522            Role::Group => NSAccessibilityGroupRole,
1523            // NSOutlineView already reports these itself; the mapping is for the audit's
1524            // expectation and for any composed stand-in (docs/tree.md).
1525            Role::Tree => NSAccessibilityOutlineRole,
1526            Role::TreeItem => NSAccessibilityRowRole,
1527            Role::None => return None,
1528        })
1529    }
1530}
1531
1532/// Native `AXRole` string → Day `Role` (best-effort, for `read_native`/`a11y_audit`).
1533fn day_role_from_ns(ax: &str) -> day_spec::Role {
1534    use day_spec::Role;
1535    match ax {
1536        "AXButton" => Role::Button,
1537        "AXCheckBox" => Role::Toggle,
1538        "AXSlider" => Role::Slider,
1539        "AXTextField" => Role::TextInput,
1540        // Plain text is ambiguous with a heading, and neither carries a level; the audit
1541        // ignores the level either way.
1542        "AXStaticText" | "AXHeading" => Role::Heading(0),
1543        "AXOutline" => Role::Tree,
1544        "AXImage" => Role::Image,
1545        "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
1546        "AXGroup" => Role::Group,
1547        "AXRadioButton" => Role::Tab,
1548        "AXTabGroup" => Role::TabList,
1549        _ => Role::None,
1550    }
1551}
1552
1553// ---------------------------------------------------------------------------
1554// DayTarget: target/action + text delegate trampoline
1555// ---------------------------------------------------------------------------
1556
1557struct TargetIvars {
1558    node: NodeId,
1559}
1560
1561define_class!(
1562    #[unsafe(super(NSObject))]
1563    #[thread_kind = MainThreadOnly]
1564    #[name = "DayTarget"]
1565    #[ivars = TargetIvars]
1566    struct DayTarget;
1567
1568    unsafe impl NSObjectProtocol for DayTarget {}
1569    unsafe impl NSTextFieldDelegate for DayTarget {}
1570
1571    /// A tabs host's `NSTabView` (docs/navigation.md). A pick emits against the NAV_MENU's
1572    /// node, exactly as the sidebar's outline view does, so as far as everything above this
1573    /// backend is concerned, picking a tab and clicking a sidebar row are the same event, and
1574    /// neither the pieces layer nor dayscript needs to know which chrome the window wears.
1575    unsafe impl NSTabViewDelegate for DayTarget {
1576        #[unsafe(method(tabView:didSelectTabViewItem:))]
1577        fn tab_view_did_select(
1578            &self,
1579            tab_view: &objc2_app_kit::NSTabView,
1580            item: Option<&objc2_app_kit::NSTabViewItem>,
1581        ) {
1582            ffi_guard::contain((), || {
1583                if TAB_PICK_SUPPRESS.with(std::cell::Cell::get) {
1584                    return;
1585                }
1586                if let Some(item) = item {
1587                    let idx = unsafe { tab_view.indexOfTabViewItem(item) };
1588                    if idx >= 0 {
1589                        emit(self.ivars().node, Event::SelectionChanged(idx as i64));
1590                    }
1591                }
1592            });
1593        }
1594    }
1595
1596    impl DayTarget {
1597        // Every trampoline that dispatches into the sink (and through it, app handlers) runs
1598        // its body through `ffi_guard::contain` (§8.5): a Rust panic unwinding out of an ObjC
1599        // frame is an abort, so it is caught, reported, and the reactive runtime recovered.
1600        // The same guard wraps every other target/delegate entry in this backend.
1601        #[unsafe(method(action:))]
1602        fn action(&self, sender: &NSControl) {
1603            ffi_guard::contain((), || {
1604                let node = self.ivars().node;
1605                if sender.downcast_ref::<NSSwitch>().is_some() {
1606                    emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
1607                } else if sender.downcast_ref::<NSSlider>().is_some() {
1608                    let value = unsafe { sender.doubleValue() };
1609                    // The live value first: bindings follow this, so the UI tracks the thumb.
1610                    emit(node, Event::ValueChanged(value));
1611                    // Then, once, the value the user settled on. The slider is `continuous`, so
1612                    // this action fires on every tick of a drag; AppKit's way to tell where in the
1613                    // gesture you are is the event that provoked it. A mouse-up ends a drag; a key
1614                    // press (arrow keys) moves the value by one discrete step and is already settled;
1615                    // anything else (mouse-down, mouse-dragged) is mid-gesture and commits nothing.
1616                    if slider_value_settled() {
1617                        emit(node, Event::ValueCommitted(value));
1618                    }
1619                } else if let (Some(f), Some(btn)) = (
1620                    BUTTON_MENUS.with(|t| t.get(ptr_of(sender))),
1621                    sender.downcast_ref::<NSButton>(),
1622                ) {
1623                    // A menu button's press opens its menu rather than reporting a press.
1624                    pop_button_menu(btn, &f);
1625                } else {
1626                    emit(node, Event::Pressed);
1627                    // A push-on/push-off button toggled its state on the click; Day owns the
1628                    // selected state (`set_button_selected`), so put back what it last asked.
1629                    let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
1630                    if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
1631                        unsafe {
1632                            btn.setState(if on {
1633                                NSControlStateValueOn
1634                            } else {
1635                                NSControlStateValueOff
1636                            });
1637                        };
1638                    }
1639                }
1640            });
1641        }
1642
1643        /// The stack-nav back header's button (docs/navigation.md): a day-initiated pop. The
1644        /// nav host's handler writes it into the path signal, which reconciles the pop.
1645        #[unsafe(method(navBack:))]
1646        fn nav_back(&self, _sender: &NSControl) {
1647            ffi_guard::contain((), || {
1648                emit(
1649                    self.ivars().node,
1650                    Event::NavBack {
1651                        already_popped: false,
1652                    },
1653                );
1654            });
1655        }
1656    }
1657
1658    unsafe impl NSControlTextEditingDelegate for DayTarget {
1659        #[unsafe(method(controlTextDidChange:))]
1660        fn control_text_did_change(&self, notification: &NSNotification) {
1661            ffi_guard::contain((), || {
1662                let node = self.ivars().node;
1663                if let Some(obj) = unsafe { notification.object() }
1664                    && let Ok(tf) = obj.downcast::<NSTextField>() {
1665                        emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
1666                    }
1667            });
1668        }
1669
1670        /// The field editor's commands for a text field with a key handler
1671        /// (docs/textfield.md "Keys"): the plain arrows and Escape arrive as `moveUp:`,
1672        /// `moveDown:` and `cancelOperation:`, which the field claims and reports as
1673        /// `Event::Key`, so the caret stays put and Escape does not open the completion list.
1674        /// Every other command, and these three on a field with no handler, is AppKit's.
1675        #[unsafe(method(control:textView:doCommandBySelector:))]
1676        fn control_do_command(
1677            &self,
1678            _control: &NSControl,
1679            _tv: &NSTextView,
1680            command: objc2::runtime::Sel,
1681        ) -> objc2::runtime::Bool {
1682            ffi_guard::contain(objc2::runtime::Bool::NO, || {
1683                let node = self.ivars().node;
1684                let key = if command == sel!(moveUp:) {
1685                    "ArrowUp"
1686                } else if command == sel!(moveDown:) {
1687                    "ArrowDown"
1688                } else if command == sel!(cancelOperation:) {
1689                    "Escape"
1690                } else {
1691                    return objc2::runtime::Bool::NO;
1692                };
1693                // The key press behind the command, for its phase (docs/menus.md "Keys"): a
1694                // repeat continues a press this field claimed, and a claimed press owes its
1695                // release, which the input monitor reports.
1696                let press = NSApplication::sharedApplication(self.mtm())
1697                    .currentEvent()
1698                    .filter(|e| e.r#type() == NSEventType::KeyDown);
1699                if let Some(press) = press.as_deref()
1700                    && press.isARepeat()
1701                {
1702                    if !input::owns_repeat(press) {
1703                        return objc2::runtime::Bool::NO;
1704                    }
1705                    emit(
1706                        node,
1707                        Event::Key(
1708                            day_spec::KeyEvent::named(key, 0)
1709                                .with_phase(day_spec::KeyPhase::Repeat),
1710                        ),
1711                    );
1712                    return objc2::runtime::Bool::YES;
1713                }
1714                if !day_spec::keys::field_claims(node, key, 0) {
1715                    return objc2::runtime::Bool::NO;
1716                }
1717                emit(node, Event::Key(day_spec::KeyEvent::named(key, 0)));
1718                if let Some(press) = press.as_deref() {
1719                    input::claim_key(press, node, key.to_string());
1720                }
1721                objc2::runtime::Bool::YES
1722            })
1723        }
1724
1725        /// End of an editing session (docs/focus.md). Return submits: AppKit keeps the field
1726        /// first responder and re-selects, so it is not a focus loss; every other movement
1727        /// (tab, click-away, cancel) reports `FocusChanged(false)`.
1728        #[unsafe(method(controlTextDidEndEditing:))]
1729        fn control_text_did_end_editing(&self, notification: &NSNotification) {
1730            ffi_guard::contain((), || {
1731                let node = self.ivars().node;
1732                let movement = unsafe { notification.userInfo() }
1733                    .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
1734                    .and_then(|n| n.downcast::<NSNumber>().ok())
1735                    .map_or(NSTextMovement::Other, |n| NSTextMovement(n.integerValue()));
1736                if movement == NSTextMovement::Return {
1737                    emit(node, Event::Submitted);
1738                } else {
1739                    input::forget_keys(node);
1740                    emit(node, Event::FocusChanged(false));
1741                }
1742            });
1743        }
1744    }
1745);
1746
1747impl DayTarget {
1748    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1749        let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
1750        unsafe { msg_send![super(this), init] }
1751    }
1752}
1753
1754// ---------------------------------------------------------------------------
1755// DayCursorOwner: the `.cursor()` decorator's tracking-area owner (docs/cursor.md)
1756// ---------------------------------------------------------------------------
1757
1758struct CursorIvars {
1759    /// The shape to set on `cursorUpdate:`; `None` leaves the platform's own choice.
1760    cursor: RefCell<Option<Retained<NSCursor>>>,
1761    /// `Cursor::None`: hide the pointer while it is inside, unhide on exit.
1762    hidden: Cell<bool>,
1763    /// Whether this owner is the one that hid the pointer (balanced by `unhide`).
1764    hiding: Cell<bool>,
1765}
1766
1767// AppKit only re-evaluates the pointer's shape on `cursorUpdate:`, which it sends to a
1768// tracking area's owner when the pointer enters the area (and on request through
1769// `invalidateCursorRectsForView:`). One owner per view keeps the view class untouched: a label,
1770// a button, or a plain container all get the same treatment without subclassing. Nested areas
1771// resolve by entry order: the innermost is entered last, so its shape is the one that stays.
1772define_class!(
1773    #[unsafe(super(NSObject))]
1774    #[thread_kind = MainThreadOnly]
1775    #[name = "DayCursorOwner"]
1776    #[ivars = CursorIvars]
1777    struct DayCursorOwner;
1778
1779    unsafe impl NSObjectProtocol for DayCursorOwner {}
1780
1781    impl DayCursorOwner {
1782        #[unsafe(method(cursorUpdate:))]
1783        fn cursor_update(&self, _event: &NSEvent) {
1784            let iv = self.ivars();
1785            if iv.hidden.get() {
1786                if !iv.hiding.replace(true) {
1787                    NSCursor::hide();
1788                }
1789                return;
1790            }
1791            if let Some(c) = iv.cursor.borrow().as_ref() {
1792                c.set();
1793            }
1794        }
1795
1796        #[unsafe(method(mouseExited:))]
1797        fn mouse_exited(&self, _event: &NSEvent) {
1798            if self.ivars().hiding.replace(false) {
1799                NSCursor::unhide();
1800            }
1801        }
1802    }
1803);
1804
1805impl DayCursorOwner {
1806    fn new(mtm: MainThreadMarker) -> Retained<Self> {
1807        let this = Self::alloc(mtm).set_ivars(CursorIvars {
1808            cursor: RefCell::new(None),
1809            hidden: Cell::new(false),
1810            hiding: Cell::new(false),
1811        });
1812        unsafe { msg_send![super(this), init] }
1813    }
1814}
1815
1816/// The `NSCursor` for a [`Cursor`], or `None` where the platform's own choice should stand
1817/// (`Cursor::None`, which the owner hides instead, and a native name AppKit does not have).
1818/// AppKit has no wait, progress, help, or move shape, so those take the arrow; the zoom, frame
1819/// (diagonal) resize, and column/row resize cursors arrived in macOS 15 and are probed by
1820/// nav host, with the nearest older shape below it.
1821// `resizeLeftRightCursor` and `resizeUpDownCursor` are deprecated in favor of the macOS 15
1822// column/row resize cursors, which are probed above them; below 15 they are the shape.
1823#[allow(deprecated)]
1824#[expect(
1825    clippy::match_same_arms,
1826    reason = "each macOS 15 cursor keeps its older fallback arm directly below its probe"
1827)]
1828fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1829    let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1830    Some(match c {
1831        Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1832        Cursor::Pointer => NSCursor::pointingHandCursor(),
1833        Cursor::Text => NSCursor::IBeamCursor(),
1834        Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1835        Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1836        Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1837        Cursor::Grabbing => NSCursor::closedHandCursor(),
1838        Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1839        Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1840        Cursor::Copy => NSCursor::dragCopyCursor(),
1841        Cursor::Alias => NSCursor::dragLinkCursor(),
1842        Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1843        Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1844        Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1845        Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1846        Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1847        Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1848            NSCursor::frameResizeCursorFromPosition_inDirections(
1849                NSCursorFrameResizePosition::TopRight,
1850                NSCursorFrameResizeDirections::All,
1851            )
1852        }
1853        Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1854            NSCursor::frameResizeCursorFromPosition_inDirections(
1855                NSCursorFrameResizePosition::TopLeft,
1856                NSCursorFrameResizeDirections::All,
1857            )
1858        }
1859        Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1860        Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1861        Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1862        Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1863        Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1864        Cursor::None => return None,
1865        Cursor::Native(name) => match &**name {
1866            "disappearingItem" => NSCursor::disappearingItemCursor(),
1867            "dragCopy" => NSCursor::dragCopyCursor(),
1868            "dragLink" => NSCursor::dragLinkCursor(),
1869            "contextualMenu" => NSCursor::contextualMenuCursor(),
1870            "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1871            _ => return None,
1872        },
1873    })
1874}
1875
1876/// Whether the `NSEvent` currently being dispatched ends a slider's interaction (see the
1877/// `ValueCommitted` emission in `DayTarget::action:`). AppKit gives a continuous slider no
1878/// "drag ended" callback, so the event that provoked the action is what says where in the gesture
1879/// we are: a mouse-up ends a drag, an arrow key moves one discrete step and is already settled,
1880/// and mouse-down/mouse-dragged are mid-gesture. No current event at all (a programmatic
1881/// `setDoubleValue:` that fires the action) is not a user commit either.
1882fn slider_value_settled() -> bool {
1883    let Some(mtm) = MainThreadMarker::new() else {
1884        return false;
1885    };
1886    let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1887        return false;
1888    };
1889    matches!(
1890        unsafe { event.r#type() },
1891        NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1892    )
1893}
1894
1895// ---------------------------------------------------------------------------
1896// DayTextField: NSTextField that reports focus gain (docs/focus.md)
1897// ---------------------------------------------------------------------------
1898
1899struct FieldIvars {
1900    node: NodeId,
1901}
1902
1903/// The share picker's delegate (docs/sharing.md): offers the app's own actions as sharing
1904/// services beside the system's, each reporting its choice as `Event::MenuAction`.
1905struct SharePickerIvars {
1906    actions: Vec<day_spec::share::ShareAction>,
1907}
1908
1909define_class!(
1910    #[unsafe(super(NSObject))]
1911    #[thread_kind = MainThreadOnly]
1912    #[name = "DaySharePickerDelegate"]
1913    #[ivars = SharePickerIvars]
1914    struct DaySharePickerDelegate;
1915
1916    unsafe impl NSObjectProtocol for DaySharePickerDelegate {}
1917
1918    impl DaySharePickerDelegate {
1919        #[unsafe(method_id(sharingServicePicker:sharingServicesForItems:proposedSharingServices:))]
1920        fn services(
1921            &self,
1922            _picker: &AnyObject,
1923            _items: &AnyObject,
1924            proposed: &objc2_foundation::NSArray<AnyObject>,
1925        ) -> Retained<objc2_foundation::NSArray<AnyObject>> {
1926            let mut services: Vec<Retained<AnyObject>> = Vec::new();
1927            for action in &self.ivars().actions {
1928                let id = action.id;
1929                let handler = block2::RcBlock::new(move || {
1930                    ffi_guard::contain((), || emit(WINDOW_NODE, Event::MenuAction(id)));
1931                });
1932                let image = action.symbol.and_then(|s| {
1933                    objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1934                        &NSString::from_str(day_spec::sf_symbol_name(s)),
1935                        None,
1936                    )
1937                });
1938                // SAFETY: NSSharingService's documented initializer for a custom service; the
1939                // handler block is copied by the service.
1940                let service: Option<Retained<AnyObject>> = unsafe {
1941                    let alloc: objc2::rc::Allocated<AnyObject> =
1942                        msg_send![objc2::class!(NSSharingService), alloc];
1943                    msg_send![
1944                        alloc,
1945                        initWithTitle: &*NSString::from_str(&action.title),
1946                        image: image.as_deref(),
1947                        alternateImage: None::<&AnyObject>,
1948                        handler: &*handler
1949                    ]
1950                };
1951                services.extend(service);
1952            }
1953            // The system's targets first, then the app's own, as Safari lists Add Bookmark
1954            // after them.
1955            let mut all: Vec<Retained<AnyObject>> = proposed.to_vec();
1956            all.extend(services);
1957            objc2_foundation::NSArray::from_retained_slice(&all)
1958        }
1959    }
1960);
1961
1962define_class!(
1963    #[unsafe(super(NSTextField))]
1964    #[thread_kind = MainThreadOnly]
1965    #[name = "DayTextField"]
1966    #[ivars = FieldIvars]
1967    struct DayTextField;
1968
1969    impl DayTextField {
1970        /// Focus gain. Key events go to the shared field editor, but the field itself receives
1971        /// `becomeFirstResponder` first, the reliable gain hook (`controlTextDidBeginEditing:`
1972        /// waits for the first keystroke). Loss comes from `controlTextDidEndEditing:` on the
1973        /// delegate.
1974        #[unsafe(method(becomeFirstResponder))]
1975        fn become_first_responder(&self) -> bool {
1976            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1977            if ok {
1978                field_gained_focus(self.ivars().node);
1979            }
1980            ok
1981        }
1982    }
1983);
1984
1985impl DayTextField {
1986    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1987        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1988        unsafe { msg_send![super(this), init] }
1989    }
1990}
1991
1992// The secure twin (docs/textfield.md). AppKit hides characters with a class, not a property:
1993// `NSSecureTextField` brings its own cell and field editor, which keep the text out of the
1994// pasteboard, the spelling checker and the accessibility value. A `text_field` that turns
1995// `secure` is rebuilt as this class (`set_input_traits`), with the same focus hook.
1996define_class!(
1997    #[unsafe(super(NSSecureTextField))]
1998    #[thread_kind = MainThreadOnly]
1999    #[name = "DaySecureTextField"]
2000    #[ivars = FieldIvars]
2001    struct DaySecureTextField;
2002
2003    impl DaySecureTextField {
2004        /// Focus gain, as on `DayTextField`.
2005        #[unsafe(method(becomeFirstResponder))]
2006        fn become_first_responder(&self) -> bool {
2007            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
2008            if ok {
2009                field_gained_focus(self.ivars().node);
2010            }
2011            ok
2012        }
2013    }
2014);
2015
2016impl DaySecureTextField {
2017    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2018        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
2019        unsafe { msg_send![super(this), init] }
2020    }
2021}
2022
2023thread_local! {
2024    /// A plain/secure class swap in flight (`set_input_traits`): focus moves from the old
2025    /// field to its replacement, which the app must not see as a focus change.
2026    static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
2027}
2028
2029/// Report a text field's focus gain, unless it is a class swap handing focus to the
2030/// replacement of a field that already had it.
2031fn field_gained_focus(node: NodeId) {
2032    if FIELD_SWAP.with(std::cell::Cell::get) {
2033        return;
2034    }
2035    // Guard only the sink dispatch: the responder change already happened, so a contained
2036    // panic must not flip the answer AppKit acts on.
2037    ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2038}
2039
2040/// The node a `text_field`'s view reports against, or `None` when the view is not one
2041/// (a label is an `NSTextField` too).
2042fn text_field_node(v: &NSView) -> Option<NodeId> {
2043    v.downcast_ref::<DayTextField>()
2044        .map(|f| f.ivars().node)
2045        .or_else(|| {
2046            v.downcast_ref::<DaySecureTextField>()
2047                .map(|f| f.ivars().node)
2048        })
2049}
2050
2051/// Build a `text_field`'s view, plain or secure, with its delegate wired and registered.
2052/// `realize` and the class swap in `set_input_traits` both come through here, so both classes
2053/// report text, submit and focus the same way against the same node.
2054fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
2055    let target = DayTarget::new(mtm, node);
2056    // Up to `NSTextField` (the declared superclass of both), so the AsRef<NSView> bound on
2057    // `view_of` resolves and every `NSTextField` downcast sees either class.
2058    let tf: Retained<NSTextField> = if secure {
2059        Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
2060    } else {
2061        Retained::into_super(DayTextField::new(mtm, node))
2062    };
2063    unsafe {
2064        tf.setEditable(true);
2065        tf.setBezeled(true);
2066        tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
2067    }
2068    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
2069    tf
2070}
2071
2072/// Whether `h` (a text field, or the field editor's client) holds its window's focus. A
2073/// focused `NSTextField`'s first responder is the shared field editor, so unwrap it back to
2074/// the field via its delegate.
2075fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
2076    window.firstResponder().is_some_and(|fr| {
2077        if Retained::as_ptr(&fr).cast::<()>() as usize == ptr_of(h) {
2078            return true;
2079        }
2080        fr.downcast::<NSText>().is_ok_and(|text| {
2081            unsafe { text.delegate() }
2082                .is_some_and(|d| Retained::as_ptr(&d).cast::<()>() as usize == ptr_of(h))
2083        })
2084    })
2085}
2086
2087/// An `NSTextContentType` constant by symbol name, or `None` on a system that predates it.
2088/// Looked up at run time because most of the vocabulary arrived in macOS 14: a direct
2089/// reference binds at launch, and one missing symbol would keep the whole app from starting
2090/// on an older system.
2091fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
2092    unsafe extern "C" {
2093        fn dlsym(
2094            handle: *mut std::ffi::c_void,
2095            symbol: *const std::ffi::c_char,
2096        ) -> *mut std::ffi::c_void;
2097    }
2098    // <dlfcn.h>: search every image loaded in the process.
2099    const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
2100    // SAFETY: `symbol` is NUL-terminated. Each name passed here is an AppKit
2101    // `NSString * const`, so a non-null result is the address of a pointer to an immortal
2102    // constant string.
2103    unsafe {
2104        let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
2105        if slot.is_null() {
2106            None
2107        } else {
2108            (*slot).as_ref()
2109        }
2110    }
2111}
2112
2113/// Move a view-keyed entry to the view that replaces it.
2114fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
2115    if let Some(v) = table.take(old) {
2116        table.insert(new, v);
2117    }
2118}
2119
2120/// A label is the shared field editor's delegate. AppKit does not forward
2121/// `textView:clickedOnLink:atIndex:` to an `NSTextField`'s separate control delegate, so the
2122/// label itself must handle it to prevent the field editor from opening the target externally.
2123/// See Apple's "Working With the Field Editor" and docs/text-runs.md.
2124struct LabelIvars {
2125    node: NodeId,
2126    has_links: Cell<bool>,
2127    has_runs: Cell<bool>,
2128    selectable: Cell<bool>,
2129    /// `LabelProps::wraps`: `false` holds the label to one line whatever the limit says.
2130    wraps: Cell<bool>,
2131    /// The paragraph attributes in force (`LabelProps::paragraph`, `LabelPatch::Paragraph`),
2132    /// kept so a text, font or color patch can stamp them again.
2133    paragraph: Cell<day_spec::props::LabelParagraph>,
2134    align: Cell<day_spec::props::TextAlign>,
2135    /// The reading direction `set_layout_direction` gave this label; `None` follows the app.
2136    direction: Cell<Option<day_spec::LayoutDirection>>,
2137    /// The label shows an attributed string Day stamped for letter spacing or line height
2138    /// although it has no runs; every later text, font or color change stamps it again.
2139    stamped: Cell<bool>,
2140    /// `LabelProps::reports_selection`, and the last nonempty byte range reported.
2141    reports_selection: Cell<bool>,
2142    selection: Cell<Option<(usize, usize)>>,
2143    /// The label's own color and role (`LabelProps::color`, `role`, `LabelPatch::Color`):
2144    /// what a `LabelPatch::Runs` rebuild lays under the runs, as the plain label shows it.
2145    color: Cell<Option<day_spec::Ink>>,
2146    role: Cell<TextRole>,
2147}
2148
2149define_class!(
2150    #[unsafe(super(NSTextField))]
2151    #[thread_kind = MainThreadOnly]
2152    #[name = "DayLabel"]
2153    #[ivars = LabelIvars]
2154    struct DayLabel;
2155
2156    impl DayLabel {
2157        /// Pass-through (docs/gestures.md): a label takes the pointer only when it is
2158        /// selectable (links make it so) or has something attached; otherwise a press goes to
2159        /// whatever is behind it.
2160        #[unsafe(method_id(hitTest:))]
2161        fn hit_test(&self, point: NSPoint) -> Option<Retained<NSView>> {
2162            let hit: Option<Retained<NSView>> = unsafe { msg_send![super(self), hitTest: point] };
2163            ffi_guard::contain(None, || {
2164                let takes = self.isSelectable() || input::takes_pointer(self);
2165                input::leaf_hit_test(self, hit, takes)
2166            })
2167        }
2168
2169        /// Hover, as on a container (`input::report_hover`); the field's own tracking (a
2170        /// link's cursor) still runs.
2171        #[unsafe(method(mouseEntered:))]
2172        fn mouse_entered(&self, event: &NSEvent) {
2173            ffi_guard::contain(false, || {
2174                input::report_hover(self, event, day_spec::DragPhase::Began)
2175            });
2176            let _: () = unsafe { msg_send![super(self), mouseEntered: event] };
2177        }
2178
2179        #[unsafe(method(mouseMoved:))]
2180        fn mouse_moved(&self, event: &NSEvent) {
2181            ffi_guard::contain(false, || {
2182                input::report_hover(self, event, day_spec::DragPhase::Changed)
2183            });
2184            let _: () = unsafe { msg_send![super(self), mouseMoved: event] };
2185        }
2186
2187        #[unsafe(method(mouseExited:))]
2188        fn mouse_exited(&self, event: &NSEvent) {
2189            ffi_guard::contain(false, || {
2190                input::report_hover(self, event, day_spec::DragPhase::Ended)
2191            });
2192            let _: () = unsafe { msg_send![super(self), mouseExited: event] };
2193        }
2194
2195        #[unsafe(method(updateTrackingAreas))]
2196        fn update_tracking_areas(&self) {
2197            let _: () = unsafe { msg_send![super(self), updateTrackingAreas] };
2198            ffi_guard::contain((), || input::refresh_hover_area(self));
2199        }
2200
2201        #[unsafe(method_id(menuForEvent:))]
2202        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
2203            ffi_guard::contain(None, || {
2204                if !self.isSelectable()
2205                    && let Some(menu) = inherited_context_menu(self, event)
2206                {
2207                    return menu;
2208                }
2209                unsafe { msg_send![super(self), menuForEvent: event] }
2210            })
2211        }
2212
2213        #[unsafe(method(drawRect:))]
2214        fn draw_rect(&self, dirty: NSRect) {
2215            // AppKit cannot propagate a table cell's background style through arbitrary
2216            // Day containers. Resolve selection at paint time so keyboard focus, window
2217            // activation, and cell reuse all use the actual native row state.
2218            let mut ancestor = unsafe { self.superview() };
2219            let mut selection_color = None;
2220            if !self.ivars().has_runs.get() {
2221                while let Some(view) = ancestor {
2222                    if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
2223                        if unsafe { row.isSelected() } {
2224                            selection_color = Some(unsafe {
2225                                if row.isEmphasized() {
2226                                    objc2_app_kit::NSColor::alternateSelectedControlTextColor()
2227                                } else {
2228                                    objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
2229                                }
2230                            });
2231                        }
2232                        break;
2233                    }
2234                    ancestor = unsafe { view.superview() };
2235                }
2236            }
2237            let cell = unsafe { self.cell() }
2238                .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
2239            if let (Some(color), Some(cell)) = (selection_color, cell) {
2240                let original = unsafe { cell.textColor() };
2241                // Mutate the cell only for this paint; changing the field would invalidate
2242                // the view again. Keep the app's normal color for deselection and reuse.
2243                unsafe {
2244                    cell.setTextColor(Some(&color));
2245                    let _: () = msg_send![super(self), drawRect: dirty];
2246                    cell.setTextColor(original.as_deref());
2247                }
2248            } else {
2249                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
2250            }
2251        }
2252    }
2253
2254    unsafe impl NSObjectProtocol for DayLabel {}
2255    unsafe impl NSTextDelegate for DayLabel {
2256        /// The field editor left the label: the reader's selection is gone with it
2257        /// (`Event::TextSelected` with `start == end`). `NSTextField` ends its editing session
2258        /// here, so the call goes to it first.
2259        #[unsafe(method(textDidEndEditing:))]
2260        fn text_did_end_editing(&self, notification: &NSNotification) {
2261            let _: () = unsafe { msg_send![super(self), textDidEndEditing: notification] };
2262            ffi_guard::contain((), || self.clear_selection());
2263        }
2264    }
2265
2266    unsafe impl NSTextViewDelegate for DayLabel {
2267        /// The field editor's selection moved while the reader selects in this label
2268        /// (`NSTextViewDidChangeSelectionNotification`, docs/text.md "Hearing about the
2269        /// selection"). The editor holds the label's whole string, so its UTF-16 range maps
2270        /// straight onto the displayed text.
2271        #[unsafe(method(textViewDidChangeSelection:))]
2272        fn text_view_did_change_selection(&self, notification: &NSNotification) {
2273            if <NSTextField as objc2::ClassType>::class()
2274                .instance_method(sel!(textViewDidChangeSelection:))
2275                .is_some()
2276            {
2277                let _: () =
2278                    unsafe { msg_send![super(self), textViewDidChangeSelection: notification] };
2279            }
2280            ffi_guard::contain((), || self.report_selection(notification));
2281        }
2282
2283        #[unsafe(method(textView:clickedOnLink:atIndex:))]
2284        fn clicked_on_link(
2285            &self,
2286            _tv: &NSTextView,
2287            link: &objc2::runtime::AnyObject,
2288            _index: usize,
2289        ) -> bool {
2290            ffi_guard::contain(true, || {
2291                // NSString targets stay verbatim (including #route); accept NSURL too.
2292                let url: Retained<NSString> = unsafe { msg_send![link, description] };
2293                emit(self.ivars().node, Event::LinkActivated(url.to_string()));
2294                true // Handled: AppKit must never also open the target itself.
2295            })
2296        }
2297    }
2298);
2299
2300impl DayLabel {
2301    fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
2302        let this = Self::alloc(mtm).set_ivars(LabelIvars {
2303            node,
2304            has_links: Cell::new(false),
2305            has_runs: Cell::new(false),
2306            selectable: Cell::new(false),
2307            wraps: Cell::new(true),
2308            paragraph: Cell::new(day_spec::props::LabelParagraph::default()),
2309            align: Cell::new(day_spec::props::TextAlign::Leading),
2310            direction: Cell::new(None),
2311            stamped: Cell::new(false),
2312            reports_selection: Cell::new(false),
2313            selection: Cell::new(None),
2314            color: Cell::new(None),
2315            role: Cell::new(TextRole::default()),
2316        });
2317        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
2318        unsafe {
2319            this.setStringValue(&NSString::from_str(text));
2320            this.setEditable(false);
2321            this.setSelectable(false);
2322            this.setBordered(false);
2323            this.setBezeled(false);
2324            this.setDrawsBackground(false);
2325        }
2326        this
2327    }
2328
2329    fn set_links(&self, has_links: bool) {
2330        self.ivars().has_links.set(has_links);
2331        unsafe {
2332            self.setSelectable(has_links || self.ivars().selectable.get());
2333            self.setAllowsEditingTextAttributes(has_links);
2334        }
2335    }
2336
2337    /// Report the field editor's selection as byte offsets into the displayed text, once per
2338    /// change (`LabelProps::reports_selection`).
2339    fn report_selection(&self, notification: &NSNotification) {
2340        if !self.ivars().reports_selection.get() {
2341            return;
2342        }
2343        let Some(editor) = notification
2344            .object()
2345            .and_then(|o| o.downcast::<NSTextView>().ok())
2346        else {
2347            return;
2348        };
2349        let range = unsafe { editor.selectedRange() };
2350        let text = self.stringValue().to_string();
2351        let now = utf16_span_to_bytes(&text, range.location, range.location + range.length);
2352        if let Some((last, (start, end))) = selection_change(self.ivars().selection.get(), now) {
2353            self.ivars().selection.set(last);
2354            emit(self.ivars().node, Event::TextSelected { start, end });
2355        }
2356    }
2357
2358    /// The selection is gone (editing ended, or a text patch replaced the string): report it
2359    /// cleared if a range was showing.
2360    fn clear_selection(&self) {
2361        if let Some((_, end)) = self.ivars().selection.take()
2362            && self.ivars().reports_selection.get()
2363        {
2364            let at = end.min(self.stringValue().len());
2365            emit(
2366                self.ivars().node,
2367                Event::TextSelected { start: at, end: at },
2368            );
2369        }
2370    }
2371}
2372
2373/// A UTF-16 span of `text` as byte offsets, each on a character boundary: a start inside a
2374/// surrogate pair moves back to the character's start, an end inside one forward to its end,
2375/// and offsets past the end clamp to the text's length.
2376fn utf16_span_to_bytes(text: &str, start16: usize, end16: usize) -> ByteSpan {
2377    let (start16, end16) = (start16.min(end16), start16.max(end16));
2378    let mut start = text.len();
2379    let mut end = text.len();
2380    let mut at16 = 0;
2381    let mut found_start = false;
2382    for (byte, ch) in text.char_indices() {
2383        let next16 = at16 + ch.len_utf16();
2384        if !found_start && next16 > start16 {
2385            start = byte;
2386            found_start = true;
2387        }
2388        if next16 > end16 {
2389            end = if at16 >= end16 {
2390                byte
2391            } else {
2392                byte + ch.len_utf8()
2393            };
2394            break;
2395        }
2396        at16 = next16;
2397    }
2398    (start.min(end), end)
2399}
2400
2401/// A byte range in a label's text, `(start, end)`.
2402type ByteSpan = (usize, usize);
2403
2404/// The next selection report, if any: `last` is the nonempty range last reported (`None`
2405/// when nothing is selected) and `now` the range the editor holds. A collapsed range is "no
2406/// selection", so moving the caret alone reports nothing; clearing a shown range reports
2407/// `start == end` at the caret. Returns the new `last` and the range to emit.
2408fn selection_change(last: Option<ByteSpan>, now: ByteSpan) -> Option<(Option<ByteSpan>, ByteSpan)> {
2409    let now_set = (now.0 != now.1).then_some(now);
2410    if now_set == last {
2411        return None;
2412    }
2413    match now_set {
2414        Some(range) => Some((Some(range), range)),
2415        None => Some((None, (now.0, now.0))),
2416    }
2417}
2418
2419#[cfg(test)]
2420mod label_text_tests {
2421    use super::{
2422        label_line_break, label_line_limit, label_line_points, nstextalign, selection_change,
2423        utf16_span_to_bytes,
2424    };
2425    use day_spec::props::{TextAlign, Truncation};
2426    use objc2_app_kit::{NSLineBreakMode, NSTextAlignment};
2427
2428    #[test]
2429    fn utf16_spans_land_on_character_boundaries() {
2430        let text = "Say déjà vu 🌅 now";
2431        let deja = text.find("déjà").unwrap();
2432        assert_eq!(utf16_span_to_bytes(text, 4, 8), (deja, deja + "déjà".len()));
2433        let sun = text.find('🌅').unwrap();
2434        assert_eq!(utf16_span_to_bytes(text, 12, 14), (sun, sun + 4));
2435        // Half a surrogate pair widens to the whole character, from either side.
2436        assert_eq!(utf16_span_to_bytes(text, 13, 14), (sun, sun + 4));
2437        assert_eq!(utf16_span_to_bytes(text, 12, 13), (sun, sun + 4));
2438        // Reversed, collapsed and out-of-range spans.
2439        assert_eq!(utf16_span_to_bytes(text, 8, 4), (deja, deja + "déjà".len()));
2440        assert_eq!(utf16_span_to_bytes(text, 2, 2), (2, 2));
2441        assert_eq!(utf16_span_to_bytes(text, 99, 120), (text.len(), text.len()));
2442        assert_eq!(utf16_span_to_bytes("", 0, 0), (0, 0));
2443    }
2444
2445    #[test]
2446    fn selection_reports_once_per_change() {
2447        // Caret moves with nothing selected report nothing.
2448        assert_eq!(selection_change(None, (3, 3)), None);
2449        // A range appears, stays, changes, then clears at the caret.
2450        assert_eq!(selection_change(None, (2, 5)), Some((Some((2, 5)), (2, 5))));
2451        assert_eq!(selection_change(Some((2, 5)), (2, 5)), None);
2452        assert_eq!(
2453            selection_change(Some((2, 5)), (2, 6)),
2454            Some((Some((2, 6)), (2, 6)))
2455        );
2456        assert_eq!(selection_change(Some((2, 6)), (4, 4)), Some((None, (4, 4))));
2457    }
2458
2459    #[test]
2460    fn paragraph_rules() {
2461        assert_eq!(label_line_limit(false, 3), 1);
2462        assert_eq!(label_line_limit(true, 3), 3);
2463        assert_eq!(label_line_limit(true, 0), 0);
2464        assert_eq!(
2465            label_line_break(1, Truncation::Middle),
2466            NSLineBreakMode::ByTruncatingMiddle
2467        );
2468        assert_eq!(
2469            label_line_break(1, Truncation::Head),
2470            NSLineBreakMode::ByTruncatingHead
2471        );
2472        // Several lines wrap (the last one ends at the tail), unlimited wraps.
2473        assert_eq!(
2474            label_line_break(2, Truncation::Head),
2475            NSLineBreakMode::ByWordWrapping
2476        );
2477        assert_eq!(
2478            label_line_break(0, Truncation::Tail),
2479            NSLineBreakMode::ByWordWrapping
2480        );
2481        assert_eq!(label_line_points(2.0, 20.0), Some(40.0));
2482        assert_eq!(label_line_points(0.0, 20.0), None);
2483        assert_eq!(label_line_points(-1.0, 20.0), None);
2484        assert_eq!(label_line_points(f64::NAN, 20.0), None);
2485        assert_eq!(
2486            nstextalign(TextAlign::Trailing, false),
2487            NSTextAlignment::Right
2488        );
2489        assert_eq!(
2490            nstextalign(TextAlign::Trailing, true),
2491            NSTextAlignment::Left
2492        );
2493        assert_eq!(
2494            nstextalign(TextAlign::Leading, true),
2495            NSTextAlignment::Natural
2496        );
2497        assert_eq!(
2498            nstextalign(TextAlign::Justified, false),
2499            NSTextAlignment::Justified
2500        );
2501    }
2502}
2503
2504struct PanMonitor(Retained<objc2::runtime::AnyObject>);
2505impl Drop for PanMonitor {
2506    fn drop(&mut self) {
2507        unsafe { NSEvent::removeMonitor(&self.0) };
2508    }
2509}
2510
2511// Escape closes a cover's window sheet, as it cancels any sheet on macOS (docs/cover.md
2512// "Modal sheet"): the cover hears it as its back request. A local monitor, because the key
2513// window's first responder may be a web view or a field that keeps Escape to itself. A sheet
2514// with its own sheet or alert over it, and app-modal panels, keep their Escape.
2515fn install_sheet_escape_monitor() {
2516    SHEET_ESCAPE_MONITOR.with(|slot| {
2517        if slot.borrow().is_some() {
2518            return;
2519        }
2520        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
2521            let event = unsafe { raw.as_ref() };
2522            ffi_guard::contain(raw.as_ptr(), || {
2523                let Some(mtm) = MainThreadMarker::new() else {
2524                    return raw.as_ptr();
2525                };
2526                let escape = unsafe { event.charactersIgnoringModifiers() }
2527                    .is_some_and(|s| s.to_string() == "\u{1b}");
2528                let Some(window) = event.window(mtm).filter(|_| escape) else {
2529                    return raw.as_ptr();
2530                };
2531                let app = NSApplication::sharedApplication(mtm);
2532                if app.modalWindow().is_some() || window.attachedSheet().is_some() {
2533                    return raw.as_ptr();
2534                }
2535                match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
2536                    Some(node) => {
2537                        emit(
2538                            node,
2539                            Event::NavBack {
2540                                already_popped: false,
2541                            },
2542                        );
2543                        std::ptr::null_mut()
2544                    }
2545                    None => raw.as_ptr(),
2546                }
2547            })
2548        });
2549        let monitor = unsafe {
2550            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
2551                objc2_app_kit::NSEventMask::KeyDown,
2552                &block,
2553            )
2554        };
2555        *slot.borrow_mut() = monitor.map(PanMonitor);
2556    });
2557}
2558
2559// A container pan observes horizontal wheel events over its descendants, including native
2560// scroll views. Leave vertical scrolling and canvas 2D pans to their existing handlers.
2561fn install_container_pan_monitor() {
2562    PAN_MONITOR.with(|slot| {
2563        if slot.borrow().is_some() {
2564            return;
2565        }
2566        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
2567            let event = unsafe { raw.as_ref() };
2568            ffi_guard::contain(raw.as_ptr(), || {
2569                let dx = unsafe { event.scrollingDeltaX() };
2570                let dy = unsafe { event.scrollingDeltaY() };
2571                if dx.abs() <= dy.abs() {
2572                    return raw.as_ptr();
2573                }
2574                let Some(mtm) = MainThreadMarker::new() else {
2575                    return raw.as_ptr();
2576                };
2577                let Some(window) = event.window(mtm) else {
2578                    return raw.as_ptr();
2579                };
2580                let Some(content) = window.contentView() else {
2581                    return raw.as_ptr();
2582                };
2583                let point =
2584                    content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2585                let mut view = content.hitTest(point);
2586                while let Some(v) = view {
2587                    if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
2588                        if v.downcast_ref::<DayCanvas>().is_some() {
2589                            return raw.as_ptr();
2590                        }
2591                        let raw_phase = unsafe { event.phase() };
2592                        let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
2593                            day_spec::DragPhase::Began
2594                        } else if raw_phase.intersects(
2595                            objc2_app_kit::NSEventPhase::Ended
2596                                | objc2_app_kit::NSEventPhase::Cancelled,
2597                        ) {
2598                            day_spec::DragPhase::Ended
2599                        } else {
2600                            day_spec::DragPhase::Changed
2601                        };
2602                        let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2603                        emit(
2604                            node,
2605                            Event::Pan {
2606                                phase,
2607                                delta: Point::new(dx, dy),
2608                                location: Point::new(p.x, p.y),
2609                            },
2610                        );
2611                        return std::ptr::null_mut();
2612                    }
2613                    view = unsafe { v.superview() };
2614                }
2615                raw.as_ptr()
2616            })
2617        });
2618        *slot.borrow_mut() = unsafe {
2619            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
2620                objc2_app_kit::NSEventMask::ScrollWheel,
2621                &block,
2622            )
2623        }
2624        .map(PanMonitor);
2625    });
2626}
2627
2628// ---------------------------------------------------------------------------
2629// DayFlipped: top-left-origin container view
2630// ---------------------------------------------------------------------------
2631
2632/// A decorated container's surface (docs/surfaces.md). The fill (a solid ink or a linear,
2633/// radial or conic gradient) is painted in `drawRect` with `NSColor`, `NSGradient` and Core
2634/// Graphics' conic gradient, clipped to the outline the radius and corners give, so it is
2635/// redrawn at whatever size the view has and resolves its inks for the appearance it is drawn
2636/// in. The border is the layer's own (`borderWidth`, `borderColor`), which Core Animation draws
2637/// over the layer's sublayers, the children, as the rules ask. The shadow is the view's own
2638/// `NSShadow`, cast by this outline.
2639#[derive(Clone, Default)]
2640struct SurfaceStyle {
2641    fill: Option<day_spec::Paint>,
2642    radius: f64,
2643    corners: day_spec::Corners,
2644    border: Option<day_spec::Border>,
2645    shadow: Option<day_spec::Shadow>,
2646    clips: bool,
2647}
2648
2649impl SurfaceStyle {
2650    /// The solid ink of the fill; `None` for a gradient or no fill.
2651    fn solid(&self) -> Option<day_spec::Ink> {
2652        match self.fill {
2653            Some(day_spec::Paint::Solid(ink)) => Some(ink),
2654            _ => None,
2655        }
2656    }
2657
2658    /// Whether the layer cuts the children to the outline. A shadow lies outside the bounds a
2659    /// mask would cut to, so a shadowed surface never masks (it arrives with `clips: false`).
2660    fn masks(&self) -> bool {
2661        (self.clips || self.radius > 0.0) && self.shadow.is_none()
2662    }
2663
2664    /// The surface's outline in `rect`, inset by `inset` on every side with the corner radius
2665    /// shrunk to match (a border's center line, half its width in). All four corners is
2666    /// AppKit's own rounded rectangle, as it was before corners could be picked.
2667    fn outline(&self, rect: NSRect, inset: f64) -> Retained<objc2_app_kit::NSBezierPath> {
2668        use objc2_app_kit::NSBezierPath;
2669        let rect = NSRect::new(
2670            NSPoint::new(rect.origin.x + inset, rect.origin.y + inset),
2671            NSSize::new(
2672                (rect.size.width - 2.0 * inset).max(0.0),
2673                (rect.size.height - 2.0 * inset).max(0.0),
2674            ),
2675        );
2676        let radius = (self.radius - inset).max(0.0);
2677        if radius <= 0.0 || self.corners == day_spec::Corners::NONE {
2678            return NSBezierPath::bezierPathWithRect(rect);
2679        }
2680        if self.corners == day_spec::Corners::ALL {
2681            return NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(rect, radius, radius);
2682        }
2683        // The view is flipped, so the top-left of the spec's radii is the top-left here.
2684        let shape = day_spec::Shape::rounded_rect(
2685            day_spec::Rect::new(
2686                rect.origin.x,
2687                rect.origin.y,
2688                rect.size.width,
2689                rect.size.height,
2690            ),
2691            self.corners.radii(radius),
2692        );
2693        bezier(&shape).unwrap_or_else(|| NSBezierPath::bezierPathWithRect(rect))
2694    }
2695}
2696
2697#[derive(Default)]
2698struct FlippedIvars {
2699    surface: RefCell<Option<SurfaceStyle>>,
2700    /// `SurfaceRole::SectionCard`: `(radius,)`, drawn with a dynamic system fill resolved at
2701    /// draw time, so the card tracks light/dark appearance changes automatically.
2702    section_card: Cell<Option<f64>>,
2703    /// Paint the whole view with the dynamic window background before anything else: the
2704    /// inspector panel wrap (docs/inspector.md). The inspector `NSSplitViewItem` backs its pane
2705    /// with a vibrancy material, and the section cards' thin quaternary fill composites over
2706    /// it into near-black in dark mode (and the material itself captures black offscreen; see
2707    /// the sidebar-screenshot rule, docs/navigation.md). An opaque appearance-resolved
2708    /// backdrop gives the cards the same ground System Settings draws them on.
2709    pane_backdrop: Cell<bool>,
2710    /// A focusable container holds focus that came from the keyboard (Tab): the one case the
2711    /// focus ring shows (docs/focus.md). A press or a programmatic focus draws none.
2712    keyboard_focus: Cell<bool>,
2713    /// An animated fill change is playing on the layer's `backgroundColor`, so `drawRect`
2714    /// leaves the plain fill out (see `motion`).
2715    layer_fill: Cell<bool>,
2716    /// The latest fill run, so the completion of one that was replaced or stopped does not
2717    /// hand the fill back while another plays.
2718    fill_run: Cell<u64>,
2719}
2720
2721define_class!(
2722    #[unsafe(super(NSView))]
2723    #[thread_kind = MainThreadOnly]
2724    #[name = "DayFlipped"]
2725    #[ivars = FlippedIvars]
2726    struct DayFlipped;
2727
2728    impl DayFlipped {
2729        #[unsafe(method_id(menuForEvent:))]
2730        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
2731            ffi_guard::contain(None, || {
2732                inherited_context_menu(self, event)
2733                    .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
2734            })
2735        }
2736
2737        #[unsafe(method(isFlipped))]
2738        fn is_flipped(&self) -> bool {
2739            true
2740        }
2741
2742        // Focus, and with it the keyboard (docs/focus.md): the canvas contract, opted into by
2743        // `Decorate::focusable`. A container never in FOCUSABLE_NODES behaves exactly as
2744        // before (refuses first responder, forwards every key).
2745        #[unsafe(method(acceptsFirstResponder))]
2746        fn accepts_first_responder(&self) -> bool {
2747            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2748            FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2749                && !ffi_guard::contain(true, || input::subtree_disabled(self))
2750        }
2751
2752        /// The key view loop (Tab, Shift-Tab; the window recalculates it): a focusable
2753        /// container joins it at its place in the tree, unless a disabled group holds it.
2754        #[unsafe(method(canBecomeKeyView))]
2755        fn can_become_key_view(&self) -> bool {
2756            self.acceptsFirstResponder() && !self.isHiddenOrHasHiddenAncestor()
2757        }
2758
2759        /// Pass-through and hit slop (docs/gestures.md): the children answer front to back,
2760        /// each inside its slop, and the container itself takes a press only when something
2761        /// is attached to it. A plain stack, a background or a decoration lets the press
2762        /// through to whatever is behind it.
2763        #[unsafe(method_id(hitTest:))]
2764        fn hit_test(&self, point: NSPoint) -> Option<Retained<NSView>> {
2765            ffi_guard::contain(None, || input::container_hit_test(self, point))
2766        }
2767
2768        /// Hover (docs/gestures.md "State styling"): the tracking area `enable_gesture`
2769        /// installs reports here, as on a canvas.
2770        #[unsafe(method(mouseEntered:))]
2771        fn mouse_entered(&self, event: &NSEvent) {
2772            if !ffi_guard::contain(true, || {
2773                input::report_hover(self, event, day_spec::DragPhase::Began)
2774            }) {
2775                let _: () = unsafe { msg_send![super(self), mouseEntered: event] };
2776            }
2777        }
2778
2779        #[unsafe(method(mouseMoved:))]
2780        fn mouse_moved(&self, event: &NSEvent) {
2781            if !ffi_guard::contain(true, || {
2782                input::report_hover(self, event, day_spec::DragPhase::Changed)
2783            }) {
2784                let _: () = unsafe { msg_send![super(self), mouseMoved: event] };
2785            }
2786        }
2787
2788        #[unsafe(method(mouseExited:))]
2789        fn mouse_exited(&self, event: &NSEvent) {
2790            if !ffi_guard::contain(true, || {
2791                input::report_hover(self, event, day_spec::DragPhase::Ended)
2792            }) {
2793                let _: () = unsafe { msg_send![super(self), mouseExited: event] };
2794            }
2795        }
2796
2797        #[unsafe(method(updateTrackingAreas))]
2798        fn update_tracking_areas(&self) {
2799            let _: () = unsafe { msg_send![super(self), updateTrackingAreas] };
2800            ffi_guard::contain((), || input::refresh_hover_area(self));
2801        }
2802
2803        /// The focus ring's shape: the surface's outline, only while focus came from the
2804        /// keyboard (`focusRingMaskBounds` is empty otherwise, which draws no ring).
2805        #[unsafe(method(drawFocusRingMask))]
2806        fn draw_focus_ring_mask(&self) {
2807            let bounds = self.bounds();
2808            let outline = match self.ivars().surface.borrow().as_ref() {
2809                Some(surface) => surface.outline(bounds, 0.0),
2810                None => objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds),
2811            };
2812            outline.fill();
2813        }
2814
2815        #[unsafe(method(focusRingMaskBounds))]
2816        fn focus_ring_mask_bounds(&self) -> NSRect {
2817            if self.ivars().keyboard_focus.get() {
2818                self.bounds()
2819            } else {
2820                NSRect::ZERO
2821            }
2822        }
2823
2824        // Clicking a focusable container focuses it, the way clicking a table does. The
2825        // gesture recognizers still see the press: this runs before `super`, which is what
2826        // forwards it to them.
2827        #[unsafe(method(mouseDown:))]
2828        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2829            if transfer::pressed(self, event) { return; }
2830            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2831            if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2832                && let Some(window) = self.window()
2833            {
2834                window.makeFirstResponder(Some(self));
2835            }
2836            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2837        }
2838
2839        #[unsafe(method(becomeFirstResponder))]
2840        fn become_first_responder(&self) -> bool {
2841            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2842            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2843                // Focus that arrived by Tab shows the ring; a press or a request does not.
2844                let by_key = NSApplication::sharedApplication(self.mtm())
2845                    .currentEvent()
2846                    .is_some_and(|e| e.r#type() == NSEventType::KeyDown);
2847                self.ivars().keyboard_focus.set(by_key);
2848                self.noteFocusRingMaskChanged();
2849                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2850            }
2851            true
2852        }
2853
2854        #[unsafe(method(resignFirstResponder))]
2855        fn resign_first_responder(&self) -> bool {
2856            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2857            if self.ivars().keyboard_focus.replace(false) {
2858                self.noteFocusRingMaskChanged();
2859            }
2860            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2861                ffi_guard::contain((), || {
2862                    input::forget_keys(node);
2863                    emit(node, Event::FocusChanged(false));
2864                });
2865            }
2866            true
2867        }
2868
2869        /// The arrows and digits, delivered here while this container is the first
2870        /// responder, with their repeats (docs/menus.md "Keys"); the input monitor reports
2871        /// the release. Anything else (and every key when the app registered no key handler
2872        /// for the node) goes to `super`, which walks the responder chain exactly as it would
2873        /// have without us.
2874        #[unsafe(method(keyDown:))]
2875        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2876            let ptr = std::ptr::from_ref::<DayFlipped>(self).cast::<NSView>() as usize;
2877            let handled = ffi_guard::contain(false, || {
2878                let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
2879                    return false;
2880                };
2881                short_route_key_down(node, event)
2882            });
2883            if !handled {
2884                let _: () = unsafe { msg_send![super(self), keyDown: event] };
2885            }
2886        }
2887
2888        /// Show the attached context menu (docs/menus.md) explicitly rather than relying on
2889        /// `NSResponder`'s default `.menu` display: popping it ourselves is deterministic
2890        /// regardless of how the click threads through Day's container hierarchy.
2891        #[unsafe(method(rightMouseDown:))]
2892        fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2893            if let Some(menu) = self.menuForEvent(event) {
2894                unsafe {
2895                    objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self);
2896                };
2897            } else {
2898                let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
2899            }
2900        }
2901
2902        #[unsafe(method(drawRect:))]
2903        fn draw_rect(&self, _dirty: NSRect) {
2904            let paint = || {
2905                if self.ivars().pane_backdrop.get() {
2906                    let bounds = self.bounds();
2907                    unsafe {
2908                        // Resolved at draw time, like the section fill below, so the backdrop
2909                        // follows light/dark appearance changes automatically.
2910                        NSColor::windowBackgroundColor().setFill();
2911                        objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
2912                    }
2913                }
2914                if let Some(radius) = self.ivars().section_card.get() {
2915                    let bounds = self.bounds();
2916                    unsafe {
2917                        // quaternarySystemFill (macOS 14+) is the grouped-card material System
2918                        // Settings uses; older systems fall back to the control background.
2919                        let cls = objc2::class!(NSColor);
2920                        let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
2921                        let color: objc2::rc::Retained<NSColor> = if has {
2922                            msg_send![cls, quaternarySystemFillColor]
2923                        } else {
2924                            msg_send![cls, controlBackgroundColor]
2925                        };
2926                        color.setFill();
2927                        let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2928                            bounds, radius, radius,
2929                        );
2930                        path.fill();
2931                    }
2932                }
2933                if let Some(surface) = self.ivars().surface.borrow().as_ref() {
2934                    let bounds = self.bounds();
2935                    let outline = surface.outline(bounds, 0.0);
2936                    match &surface.fill {
2937                        // The dynamic color resolves for the appearance performed below.
2938                        Some(day_spec::Paint::Solid(ink)) => {
2939                            if !self.ivars().layer_fill.get() {
2940                                color::nsink(*ink).setFill();
2941                                outline.fill();
2942                            }
2943                        }
2944                        Some(paint) => {
2945                            // The unit points resolve against the bounds of this draw, which
2946                            // is how the gradient follows the frame.
2947                            let area = day_spec::Rect::new(
2948                                bounds.origin.x,
2949                                bounds.origin.y,
2950                                bounds.size.width,
2951                                bounds.size.height,
2952                            );
2953                            NSGraphicsContext::saveGraphicsState_class();
2954                            outline.addClip();
2955                            draw_gradient_in(paint, area);
2956                            NSGraphicsContext::restoreGraphicsState_class();
2957                        }
2958                        None => {}
2959                    }
2960                }
2961            };
2962            // Paint under the standard counterpart of this view's appearance. Inside an
2963            // NSVisualEffectView subtree (the inspector pane) the effective appearance is
2964            // a vibrant one (NSAppearanceNameVibrantDark/-Light), and the system fills'
2965            // vibrant variants are opaque blend colors that only composite correctly in an
2966            // `allowsVibrancy` view: drawn plainly, dark-mode quaternary fill comes out
2967            // near-black instead of lightening. Resolving under aqua/darkAqua gives exactly
2968            // the fills System Settings draws with, and re-resolves on every theme change
2969            // (this runs per draw, and appearance flips redraw).
2970            match color::standard_appearance(&self.effectiveAppearance()) {
2971                Some(appearance) => {
2972                    let block = block2::StackBlock::new(paint);
2973                    appearance.performAsCurrentDrawingAppearance(&block);
2974                }
2975                None => paint(),
2976            }
2977        }
2978
2979        /// A light/dark switch (the app's, the window's or the system's): `drawRect` resolves
2980        /// the fill again by itself, and the colors the layer holds (the border, the shadow)
2981        /// are set again for the new appearance.
2982        #[unsafe(method(viewDidChangeEffectiveAppearance))]
2983        fn view_did_change_effective_appearance(&self) {
2984            let _: () = unsafe { msg_send![super(self), viewDidChangeEffectiveAppearance] };
2985            ffi_guard::contain((), || {
2986                self.sync_layer();
2987                NSView::setNeedsDisplay(self, true);
2988            });
2989        }
2990    }
2991    unsafe impl NSObjectProtocol for DayFlipped {}
2992    unsafe impl NSDraggingSource for DayFlipped {
2993        #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
2994        fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
2995    }
2996    impl DayFlipped {
2997        #[unsafe(method(mouseDragged:))]
2998        fn transfer_dragged(&self, event: &NSEvent) {
2999            if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
3000        }
3001        #[unsafe(method(draggingEntered:))]
3002        fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
3003        #[unsafe(method(draggingUpdated:))]
3004        fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
3005        #[unsafe(method(performDragOperation:))]
3006        fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
3007        /// The session left this view without dropping: the target's hover ends.
3008        #[unsafe(method(draggingExited:))]
3009        fn transfer_exited(&self, _info: Option<&ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>>) {
3010            ffi_guard::contain((), || transfer::leave(self));
3011        }
3012        /// The session ended (a drop, Escape, a drop elsewhere) while this view was its
3013        /// destination: idempotent after a drop, which already ended the hover.
3014        #[unsafe(method(draggingEnded:))]
3015        fn transfer_ended(&self, _info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) {
3016            ffi_guard::contain((), || transfer::leave(self));
3017        }
3018
3019        /// A surface is drawn for the size it has: repaint it, and move its shadow's outline,
3020        /// when that changes (docs/surfaces.md). An undecorated container does neither.
3021        #[unsafe(method(setFrameSize:))]
3022        fn set_frame_size(&self, size: NSSize) {
3023            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
3024            if self.ivars().surface.borrow().is_some() {
3025                NSView::setNeedsDisplay(self, true);
3026                self.sync_layer();
3027            }
3028        }
3029
3030        /// A scaled view keeps its laid-out size as its bounds (`apply_geometry`), and the
3031        /// shadow's outline is in bounds.
3032        #[unsafe(method(setBoundsSize:))]
3033        fn set_bounds_size(&self, size: NSSize) {
3034            let _: () = unsafe { msg_send![super(self), setBoundsSize: size] };
3035            self.sync_layer();
3036        }
3037    }
3038
3039);
3040
3041impl DayFlipped {
3042    fn new(mtm: MainThreadMarker) -> Retained<Self> {
3043        let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
3044        unsafe { msg_send![super(this), init] }
3045    }
3046
3047    /// `SurfaceRole::SectionCard`: the fill resolves dynamically in drawRect (theme-adaptive).
3048    fn set_section_card(&self, corner_radius: f64) {
3049        self.ivars().section_card.set(Some(corner_radius));
3050        unsafe {
3051            let _: () = msg_send![self, setNeedsDisplay: true];
3052        }
3053    }
3054
3055    /// Opaque window-background backdrop (the inspector panel wrap; see `FlippedIvars`).
3056    fn set_pane_backdrop(&self) {
3057        self.ivars().pane_backdrop.set(true);
3058        unsafe {
3059            let _: () = msg_send![self, setNeedsDisplay: true];
3060        }
3061    }
3062
3063    /// Apply a decorated container's surface (docs/surfaces.md), at realize and again for
3064    /// every `ContainerPatch::Surface`: the whole style is replaced, so a radius, a border, a
3065    /// shadow or the clip can come and go. The fill is `drawRect` content; the child clip
3066    /// (`cornerRadius`, `maskedCorners`, `masksToBounds`), the border and the shadow are the
3067    /// layer's (`sync_layer`).
3068    fn set_surface(&self, p: &ContainerProps) {
3069        // A shadow that cannot show casts nothing (and so does not stop the clip).
3070        let shadow = p
3071            .shadow
3072            .filter(|s| !matches!(s.color, day_spec::Ink::Fixed(c) if c.a <= 0.0));
3073        *self.ivars().surface.borrow_mut() = Some(SurfaceStyle {
3074            fill: p.fill.clone(),
3075            radius: p.corner_radius,
3076            corners: p.corners,
3077            border: p.border,
3078            shadow,
3079            clips: p.clips,
3080        });
3081        NSView::setNeedsDisplay(self, true);
3082        self.sync_layer();
3083    }
3084
3085    /// Put the layer half of the surface on the layer, for the size and the appearance the
3086    /// view has now: the child clip, the border and the shadow. Runs on every surface change,
3087    /// resize and appearance change. A view with no layer gets one only when the surface needs
3088    /// it.
3089    ///
3090    /// The border is the layer's: inside the frame, following the corners, and drawn by Core
3091    /// Animation over the sublayers, which are the children's layers, so a child that reaches
3092    /// the edge never covers it. A border wider than half the surface fills it, as a radius
3093    /// larger than half rounds it fully. Its color is a `CGColor`, resolved here for the
3094    /// view's appearance.
3095    ///
3096    /// The shadow is the view's `NSShadow`, which AppKit carries to the layer as they are: the
3097    /// blur radius becomes `shadowRadius`, the Gaussian's standard deviation, which is half the
3098    /// spec's blur; the offset is in the flipped layer's space, so positive y is down. It is
3099    /// cast by an explicit `shadowPath` (the surface's outline) whatever the fill and the
3100    /// children are.
3101    fn sync_layer(&self) {
3102        let Some(s) = self.ivars().surface.borrow().clone() else {
3103            return;
3104        };
3105        let border = s.border.filter(|b| b.width > 0.0);
3106        let masks = s.masks();
3107        if self.layer().is_none() {
3108            if !masks && border.is_none() && s.shadow.is_none() {
3109                return;
3110            }
3111            self.setWantsLayer(true);
3112        }
3113        let Some(layer) = self.layer() else {
3114            return;
3115        };
3116        let size = layer.bounds().size;
3117        let half = (size.width.min(size.height) / 2.0).max(0.0);
3118        layer.setCornerRadius(s.radius.min(half));
3119        layer.setMaskedCorners(corner_mask(s.corners));
3120        layer.setMasksToBounds(masks);
3121        if let Some(b) = border {
3122            layer.setBorderWidth(b.width.min(half));
3123            layer.setBorderColor(Some(&color::cg_for(self, b.color)));
3124        } else {
3125            layer.setBorderWidth(0.0);
3126            layer.setBorderColor(None);
3127        }
3128        match s.shadow {
3129            Some(sh) => {
3130                let native = objc2_app_kit::NSShadow::new();
3131                native.setShadowColor(Some(&nscolor(color::color_for(self, sh.color))));
3132                native.setShadowOffset(NSSize::new(sh.dx, sh.dy));
3133                native.setShadowBlurRadius(sh.blur.max(0.0) / 2.0);
3134                self.setShadow(Some(&native));
3135                let outline = s.outline(self.bounds(), 0.0);
3136                // SAFETY: an immutable snapshot of the path's geometry.
3137                layer.setShadowPath(Some(&*unsafe { outline.CGPath() }));
3138            }
3139            None => {
3140                if self.shadow().is_some() {
3141                    self.setShadow(None);
3142                    layer.setShadowPath(None);
3143                }
3144            }
3145        }
3146    }
3147
3148    /// A `background(..)` bound to a signal: the fill changes and everything else the surface
3149    /// was realized with (corners, border, shadow) stays.
3150    fn set_background(&self, fill: Option<day_spec::Paint>) {
3151        self.ivars()
3152            .surface
3153            .borrow_mut()
3154            .get_or_insert_default()
3155            .fill = fill;
3156        NSView::setNeedsDisplay(self, true);
3157    }
3158}
3159
3160/// The layer corners a surface's `corners` round. The layer of a flipped view counts y downward
3161/// like the view, so the layer's "min Y" corners are the top ones.
3162fn corner_mask(corners: day_spec::Corners) -> objc2_quartz_core::CACornerMask {
3163    use objc2_quartz_core::CACornerMask;
3164    let mut mask = CACornerMask::empty();
3165    for (corner, layer_corner) in [
3166        (
3167            day_spec::Corners::TOP_LEFT,
3168            CACornerMask::LayerMinXMinYCorner,
3169        ),
3170        (
3171            day_spec::Corners::TOP_RIGHT,
3172            CACornerMask::LayerMaxXMinYCorner,
3173        ),
3174        (
3175            day_spec::Corners::BOTTOM_RIGHT,
3176            CACornerMask::LayerMaxXMaxYCorner,
3177        ),
3178        (
3179            day_spec::Corners::BOTTOM_LEFT,
3180            CACornerMask::LayerMinXMaxYCorner,
3181        ),
3182    ] {
3183        if corners.contains(corner) {
3184            mask |= layer_corner;
3185        }
3186    }
3187    mask
3188}
3189
3190// ---------------------------------------------------------------------------
3191// DayCanvas — a flipped view replaying the Day display list in drawRect (§11)
3192// ---------------------------------------------------------------------------
3193
3194struct CanvasIvars;
3195
3196define_class!(
3197    #[unsafe(super(NSView))]
3198    #[thread_kind = MainThreadOnly]
3199    #[name = "DayCanvas"]
3200    #[ivars = CanvasIvars]
3201    struct DayCanvas;
3202
3203    impl DayCanvas {
3204        #[unsafe(method(isFlipped))]
3205        fn is_flipped(&self) -> bool {
3206            true
3207        }
3208
3209        /// A summon-time context menu (docs/menus.md): built when the right-click lands,
3210        /// from the provider `set_context_menu_fn` registered — so a canvas can select what
3211        /// is under the pointer and offer commands for that selection.
3212        #[unsafe(method_id(menuForEvent:))]
3213        fn menu_for_event(
3214            &self,
3215            event: &objc2_app_kit::NSEvent,
3216        ) -> Option<Retained<NSMenu>> {
3217            let f = CTX_MENU_FNS.with(|t| t.get(std::ptr::from_ref::<Self>(self) as usize));
3218            let Some(f) = f else {
3219                return unsafe { msg_send![super(self), menuForEvent: event] };
3220            };
3221            // Guarded: the provider is app code (it usually re-selects, then builds).
3222            ffi_guard::contain(None, || {
3223                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3224                let items = f(day_spec::Point::new(p.x, p.y));
3225                if items.is_empty() {
3226                    return None;
3227                }
3228                Some(build_ns_menu(self.mtm(), "", &items))
3229            })
3230        }
3231
3232        // Focus, and with it the keyboard (docs/focus.md, docs/menus.md). A canvas is the one
3233        // built-in piece with no native control under it, so nothing else would ever make it
3234        // the first responder — and without that, arrow keys aimed at what it draws could only
3235        // be caught by watching the whole app.
3236        #[unsafe(method(acceptsFirstResponder))]
3237        fn accepts_first_responder(&self) -> bool {
3238            !ffi_guard::contain(true, || input::subtree_disabled(self))
3239        }
3240
3241        /// Pass-through (docs/gestures.md): a canvas with nothing attached (no gesture, menu,
3242        /// drag, drop, focus or key handler) is decoration, and a press on it reaches whatever
3243        /// is behind it. One with a key handler keeps the canvas contract: a press focuses it.
3244        #[unsafe(method_id(hitTest:))]
3245        fn hit_test(&self, point: NSPoint) -> Option<Retained<NSView>> {
3246            let hit: Option<Retained<NSView>> = unsafe { msg_send![super(self), hitTest: point] };
3247            ffi_guard::contain(None, || {
3248                let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3249                let keys = KEY_NODES
3250                    .with(|t| t.get(ptr))
3251                    .is_some_and(day_spec::keys::handled);
3252                input::leaf_hit_test(self, hit, keys || input::takes_pointer(self))
3253            })
3254        }
3255
3256        /// A hover area grown by a hit slop follows the view's bounds by hand (an area over
3257        /// the visible rect follows them on its own).
3258        #[unsafe(method(updateTrackingAreas))]
3259        fn update_tracking_areas(&self) {
3260            let _: () = unsafe { msg_send![super(self), updateTrackingAreas] };
3261            ffi_guard::contain((), || input::refresh_hover_area(self));
3262        }
3263
3264        // Clicking a canvas focuses it, the way clicking a table or a text field does. The
3265        // gesture recognizers (tap/drag) still see the press — this runs before `super`, which
3266        // is what forwards it to them.
3267        #[unsafe(method(mouseDown:))]
3268        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
3269            if let Some(window) = self.window() {
3270                window.makeFirstResponder(Some(self));
3271            }
3272            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
3273        }
3274
3275        // Report focus both ways, so `.focused(signal)` binds two-way and dayscript's
3276        // `assert_focused` can see it.
3277        #[unsafe(method(becomeFirstResponder))]
3278        fn become_first_responder(&self) -> bool {
3279            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3280            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
3281                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
3282            }
3283            true
3284        }
3285
3286        #[unsafe(method(resignFirstResponder))]
3287        fn resign_first_responder(&self) -> bool {
3288            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3289            // A composition in progress goes with the focus: the input method is told, so it
3290            // does not commit into whatever is focused next.
3291            if MARKED.with(|t| t.remove(ptr)).is_some()
3292                && let Some(context) = self.inputContext()
3293            {
3294                context.discardMarkedText();
3295            }
3296            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
3297                ffi_guard::contain((), || {
3298                    input::forget_keys(node);
3299                    emit(node, Event::FocusChanged(false));
3300                });
3301            }
3302            true
3303        }
3304
3305        /// The keys, delivered to this canvas because it is the first responder. On the short
3306        /// route the arrows and digits; on the full route (docs/menus.md "The full route")
3307        /// every key, through the text input system for the ones that type. Anything
3308        /// unclaimed — and every key when the app registered no handler for this node — goes
3309        /// to `super`, which walks the responder chain exactly as it would have without us.
3310        #[unsafe(method(keyDown:))]
3311        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
3312            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3313            let handled = ffi_guard::contain(false, || {
3314                let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
3315                    return false;
3316                };
3317                // A canvas nobody asked keys from does not get to keep them: an enclosing
3318                // scroll view still scrolls, and an unclaimed key still beeps the way the
3319                // platform means it to.
3320                if !day_spec::keys::handled(node) {
3321                    return false;
3322                }
3323                if day_spec::keys::text(node) {
3324                    return full_route_key_down(self, node, event);
3325                }
3326                short_route_key_down(node, event)
3327            });
3328            if !handled {
3329                let _: () = unsafe { msg_send![super(self), keyDown: event] };
3330            }
3331        }
3332
3333        /// The text input context, only for a canvas on the full route: an input context is
3334        /// what makes the input method (and the keyboard layout's dead keys) address this
3335        /// view, and a drawing canvas that hears the arrows alone must not look like a text
3336        /// field to it.
3337        #[unsafe(method_id(inputContext))]
3338        fn input_context(&self) -> Option<Retained<objc2_app_kit::NSTextInputContext>> {
3339            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3340            let takes_keyboard = KEY_NODES
3341                .with(|t| t.get(ptr))
3342                .is_some_and(|node| ffi_guard::contain(false, || day_spec::keys::text(node)));
3343            if takes_keyboard {
3344                unsafe { msg_send![super(self), inputContext] }
3345            } else {
3346                None
3347            }
3348        }
3349
3350        #[unsafe(method(drawRect:))]
3351        fn draw_rect(&self, _dirty: NSRect) {
3352            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3353            let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
3354            paint_ops(&ops, 1.0);
3355        }
3356
3357        /// Hover entry/motion/exit (docs/canvas.md "Interaction"). The tracking area is installed
3358        /// by `enable_gesture`; `updateTrackingAreas` below keeps it the size of the view.
3359        #[unsafe(method(mouseEntered:))]
3360        fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
3361            self.report_hover(event, day_spec::DragPhase::Began);
3362        }
3363
3364        #[unsafe(method(mouseMoved:))]
3365        fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
3366            self.report_hover(event, day_spec::DragPhase::Changed);
3367        }
3368
3369        #[unsafe(method(mouseExited:))]
3370        fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
3371            self.report_hover(event, day_spec::DragPhase::Ended);
3372        }
3373
3374        /// A trackpad rotation (docs/canvas.md "Zoom and pan"). Each event's `rotation` is that
3375        /// event's own angle in degrees, counterclockwise positive; Day wants radians, clockwise
3376        /// positive, cumulative since `Began`. A gesture is bracketed by the event phases; an
3377        /// event with no phase is a lone `Changed` carrying its own angle.
3378        #[unsafe(method(rotateWithEvent:))]
3379        fn rotate_with_event(&self, event: &objc2_app_kit::NSEvent) {
3380            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3381            let Some(node) = ROTATE_NODES.with(|t| t.get(ptr)) else {
3382                let _: () = unsafe { msg_send![super(self), rotateWithEvent: event] };
3383                return;
3384            };
3385            ffi_guard::contain((), || {
3386                let tick = -f64::from(event.rotation()).to_radians();
3387                let raw = event.phase();
3388                let (phase, rotation) = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
3389                    ROTATE_ANGLE.with(|t| t.insert(ptr, tick));
3390                    (day_spec::DragPhase::Began, tick)
3391                } else if raw.intersects(
3392                    objc2_app_kit::NSEventPhase::Ended | objc2_app_kit::NSEventPhase::Cancelled,
3393                ) {
3394                    let total = ROTATE_ANGLE.with(|t| t.remove(ptr)).unwrap_or(0.0) + tick;
3395                    (day_spec::DragPhase::Ended, total)
3396                } else if raw.contains(objc2_app_kit::NSEventPhase::Changed) {
3397                    let total = ROTATE_ANGLE
3398                        .with(|t| {
3399                            t.with(ptr, |a| {
3400                                *a += tick;
3401                                *a
3402                            })
3403                        })
3404                        .unwrap_or(tick);
3405                    (day_spec::DragPhase::Changed, total)
3406                } else {
3407                    (day_spec::DragPhase::Changed, tick)
3408                };
3409                let win = event.locationInWindow();
3410                let loc = self.convertPoint_fromView(win, None);
3411                emit(
3412                    node,
3413                    Event::Rotate {
3414                        phase,
3415                        rotation,
3416                        location: Point::new(loc.x, loc.y),
3417                    },
3418                );
3419            });
3420        }
3421
3422        #[unsafe(method(scrollWheel:))]
3423        fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
3424            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3425            let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
3426                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
3427                return;
3428            };
3429            ffi_guard::contain((), || {
3430                // Trackpads bracket a pan with phases; a discrete wheel tick has none and
3431                // arrives as a lone Changed — exactly the Event::Pan contract.
3432                let raw = unsafe { event.phase() };
3433                let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
3434                    day_spec::DragPhase::Began
3435                } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
3436                    || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
3437                {
3438                    day_spec::DragPhase::Ended
3439                } else {
3440                    day_spec::DragPhase::Changed
3441                };
3442                let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
3443                    event.scrollingDeltaY()
3444                });
3445                let win = unsafe { event.locationInWindow() };
3446                let loc = self.convertPoint_fromView(win, None);
3447                emit(
3448                    node,
3449                    Event::Pan {
3450                        phase,
3451                        delta,
3452                        location: Point::new(loc.x, loc.y),
3453                    },
3454                );
3455            });
3456        }
3457    }
3458
3459    unsafe impl NSObjectProtocol for DayCanvas {}
3460
3461    /// The text input system's client (docs/menus.md "The full route"): the view a dead key
3462    /// or an input method composes into. A canvas has no document, so the marked text is
3463    /// held here and never shown; what the input method commits is the key event's text.
3464    unsafe impl NSTextInputClient for DayCanvas {
3465        #[unsafe(method(insertText:replacementRange:))]
3466        unsafe fn insert_text(&self, string: &AnyObject, _replacement: NSRange) {
3467            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3468            MARKED.with(|t| t.remove(ptr));
3469            let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
3470                return;
3471            };
3472            let text = text_of_input_string(string);
3473            if text.is_empty() {
3474                return;
3475            }
3476            ffi_guard::contain((), || {
3477                let interpreting = INTERPRETING.with(|i| {
3478                    i.borrow()
3479                        .as_ref()
3480                        .map(|i| (i.key.clone(), i.mods, i.phase, i.event.clone()))
3481                });
3482                let event = match interpreting {
3483                    // One character typed by the key being interpreted: named by that key, and
3484                    // that key's release is owed here.
3485                    Some((key, mods, phase, press)) if text.chars().count() == 1 => {
3486                        if phase == day_spec::KeyPhase::Down {
3487                            input::claim_key(&press, node, key.clone());
3488                        }
3489                        day_spec::KeyEvent::typed_by(key, text, mods).with_phase(phase)
3490                    }
3491                    // An input method's commit: no single key is behind it, so no phases.
3492                    Some((_, mods, _, _)) => day_spec::KeyEvent::typed_text(text, mods),
3493                    // Committed outside any key press (the Character Viewer, dictation).
3494                    None => day_spec::KeyEvent::typed_text(text, 0),
3495                };
3496                emit(node, Event::Key(event));
3497            });
3498        }
3499
3500        /// A key the text input system turned into an editing command (`insertNewline:`,
3501        /// `moveLeft:`, …). `keyDown:` already named every key the route carries before it
3502        /// asked the input system, so nothing is left to do here; anything else (a `noop:`
3503        /// for a function key the vocabulary lacks) types nothing, by design.
3504        #[unsafe(method(doCommandBySelector:))]
3505        unsafe fn do_command_by_selector(&self, _selector: Sel) {}
3506
3507        #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
3508        unsafe fn set_marked_text(&self, string: &AnyObject, _selected: NSRange, _replacement: NSRange) {
3509            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3510            let text = text_of_input_string(string);
3511            if text.is_empty() {
3512                MARKED.with(|t| t.remove(ptr));
3513            } else {
3514                MARKED.with(|t| t.insert(ptr, text));
3515            }
3516        }
3517
3518        #[unsafe(method(unmarkText))]
3519        fn unmark_text(&self) {
3520            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3521            MARKED.with(|t| t.remove(ptr));
3522        }
3523
3524        #[unsafe(method(selectedRange))]
3525        fn selected_range(&self) -> NSRange {
3526            NSRange::new(objc2_foundation::NSNotFound as usize, 0)
3527        }
3528
3529        #[unsafe(method(markedRange))]
3530        fn marked_range(&self) -> NSRange {
3531            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3532            match MARKED.with(|t| t.get(ptr)) {
3533                Some(marked) => NSRange::new(0, marked.encode_utf16().count()),
3534                None => NSRange::new(objc2_foundation::NSNotFound as usize, 0),
3535            }
3536        }
3537
3538        #[unsafe(method(hasMarkedText))]
3539        fn has_marked_text(&self) -> bool {
3540            let ptr = std::ptr::from_ref::<DayCanvas>(self).cast::<NSView>() as usize;
3541            MARKED.with(|t| t.contains(ptr))
3542        }
3543
3544        #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
3545        unsafe fn attributed_substring(
3546            &self,
3547            _range: NSRange,
3548            _actual: objc2_foundation::NSRangePointer,
3549        ) -> Option<Retained<objc2_foundation::NSAttributedString>> {
3550            None
3551        }
3552
3553        #[unsafe(method_id(validAttributesForMarkedText))]
3554        fn valid_attributes(&self) -> Retained<NSArray<objc2_foundation::NSAttributedStringKey>> {
3555            NSArray::new()
3556        }
3557
3558        /// Where the input method puts its candidate window: under the canvas, since the
3559        /// canvas does not say where its caret is.
3560        #[unsafe(method(firstRectForCharacterRange:actualRange:))]
3561        unsafe fn first_rect(&self, _range: NSRange, _actual: objc2_foundation::NSRangePointer) -> NSRect {
3562            let bounds = self.bounds();
3563            let in_window = self.convertRect_toView(bounds, None);
3564            match self.window() {
3565                Some(window) => window.convertRectToScreen(in_window),
3566                None => in_window,
3567            }
3568        }
3569
3570        #[unsafe(method(characterIndexForPoint:))]
3571        fn character_index_for_point(&self, _point: NSPoint) -> objc2_foundation::NSUInteger {
3572            objc2_foundation::NSNotFound as objc2_foundation::NSUInteger
3573        }
3574    }
3575);
3576
3577impl DayCanvas {
3578    fn new(mtm: MainThreadMarker) -> Retained<Self> {
3579        let this = Self::alloc(mtm).set_ivars(CanvasIvars);
3580        unsafe { msg_send![super(this), init] }
3581    }
3582
3583    /// One hover phase, reported to whichever node asked for it (docs/canvas.md "Interaction").
3584    ///
3585    /// `mouseEntered:`/`mouseExited:` are scoped by the tracking area, but **`mouseMoved:` is
3586    /// not**: it walks the responder chain, so a focused canvas hears about motion anywhere in
3587    /// its window — including outside itself. Hence the bounds test, without which a canvas
3588    /// reports a hover for a pointer that is nowhere near it (measured: a pointer parked outside
3589    /// the window entirely still produced hover positions).
3590    fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
3591        ffi_guard::contain(false, || input::report_hover(self, event, phase));
3592    }
3593}
3594
3595// ---------------------------------------------------------------------------
3596// DayGesture — tap/drag recognizer target, node-id keyed (docs/shapes.md)
3597// ---------------------------------------------------------------------------
3598
3599struct GestureIvars {
3600    node: NodeId,
3601    kind: day_spec::GestureKind,
3602}
3603
3604define_class!(
3605    #[unsafe(super(NSObject))]
3606    #[thread_kind = MainThreadOnly]
3607    #[name = "DayGesture"]
3608    #[ivars = GestureIvars]
3609    struct DayGesture;
3610
3611    unsafe impl NSObjectProtocol for DayGesture {}
3612
3613    /// The arbitration AppKit's recognizers lack a property for (docs/gestures.md
3614    /// "Recognizers"). Set on the tap, double-tap and long-press recognizers only.
3615    unsafe impl NSGestureRecognizerDelegate for DayGesture {
3616        /// A Control-click is the context-menu click: the menu keeps it, so a long press
3617        /// does not start under it.
3618        #[unsafe(method(gestureRecognizer:shouldAttemptToRecognizeWithEvent:))]
3619        fn should_attempt(&self, _g: &NSGestureRecognizer, event: &NSEvent) -> bool {
3620            !(self.ivars().kind == day_spec::GestureKind::LongPress
3621                && event.modifierFlags().contains(NSEventModifierFlags::Control))
3622        }
3623
3624        /// A view's single and double click run side by side: the second click of a double
3625        /// must reach the double recognizer whichever of the two AppKit asks first. Which
3626        /// one reports is decided in `fire:` (`input::tap_disposition`).
3627        #[unsafe(method(gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:))]
3628        fn simultaneous(&self, _g: &NSGestureRecognizer, other: &NSGestureRecognizer) -> bool {
3629            use day_spec::GestureKind::{DoubleTap, Tap};
3630            let mine = self.ivars().kind;
3631            let theirs = unsafe { other.delegate() }.and_then(|d| {
3632                let obj: &AnyObject = d.as_ref();
3633                obj.downcast_ref::<DayGesture>().map(|g| g.ivars().kind)
3634            });
3635            matches!((mine, theirs), (Tap, Some(DoubleTap)) | (DoubleTap, Some(Tap)))
3636        }
3637    }
3638
3639    impl DayGesture {
3640        #[unsafe(method(fire:))]
3641        fn fire(&self, g: &NSGestureRecognizer) {
3642            ffi_guard::contain((), || {
3643                let node = self.ivars().node;
3644                let view = g.view();
3645                let loc = g.locationInView(view.as_deref());
3646                // Node-local, origin top left, on a flipped view or not.
3647                let at = match view.as_deref() {
3648                    Some(v) => input::top_left(v, loc),
3649                    None => Point::new(loc.x, loc.y),
3650                };
3651                let up = view.as_deref().is_some_and(|v| !v.isFlipped());
3652                let phase = match g.state() {
3653                    NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
3654                    NSGestureRecognizerState::Ended
3655                    | NSGestureRecognizerState::Cancelled
3656                    | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
3657                    _ => day_spec::DragPhase::Changed,
3658                };
3659                let obj: &objc2::runtime::AnyObject = g.as_ref();
3660                match self.ivars().kind {
3661                    day_spec::GestureKind::Drag => {
3662                        let pan = obj.downcast_ref::<NSPanGestureRecognizer>();
3663                        let flip = |p: NSPoint| Point::new(p.x, if up { -p.y } else { p.y });
3664                        let translation = pan.map_or(Point::ZERO, |pan| {
3665                            flip(unsafe { pan.translationInView(view.as_deref()) })
3666                        });
3667                        // The recognizer's own release velocity (docs/gestures.md "Velocity"),
3668                        // just before the release, and only for a gesture that ended rather
3669                        // than being cancelled.
3670                        if g.state() == NSGestureRecognizerState::Ended
3671                            && let Some(pan) = pan
3672                        {
3673                            let velocity = flip(unsafe { pan.velocityInView(view.as_deref()) });
3674                            emit(
3675                                node,
3676                                Event::GestureVelocity {
3677                                    kind: day_spec::GestureKind::Drag,
3678                                    velocity,
3679                                },
3680                            );
3681                        }
3682                        emit(node, Event::Drag { phase, location: at, translation });
3683                    }
3684                    day_spec::GestureKind::LongPress => {
3685                        // Fires once, while the button is still down; the click that ends
3686                        // this sequence is not a tap.
3687                        let key = view.as_deref().map_or(0, ptr_of);
3688                        match g.state() {
3689                            NSGestureRecognizerState::Began => {
3690                                input::LONG_HELD.with(|t| t.insert(key, ()));
3691                                emit(node, Event::LongPress(at));
3692                            }
3693                            NSGestureRecognizerState::Ended
3694                            | NSGestureRecognizerState::Cancelled
3695                            | NSGestureRecognizerState::Failed => {
3696                                // After the click recognizers had their say on this release.
3697                                <AppKit as Platform>::post(Box::new(move || {
3698                                    input::LONG_HELD.with(|t| t.take(key));
3699                                }));
3700                            }
3701                            _ => {}
3702                        }
3703                    }
3704                    day_spec::GestureKind::DoubleTap => {
3705                        if let Some(v) = view.as_deref() {
3706                            input::cancel_held_tap(v);
3707                        }
3708                        emit(node, Event::DoubleTap(at));
3709                    }
3710                    day_spec::GestureKind::Pinch => {
3711                        // Cumulative since Began: `magnification` is the total delta (0 =
3712                        // unchanged), and Day's contract wants a factor.
3713                        let scale = if let Some(m) =
3714                            obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
3715                        {
3716                            1.0 + unsafe { m.magnification() }
3717                        } else {
3718                            1.0
3719                        };
3720                        emit(node, Event::Pinch { phase, scale, location: at });
3721                    }
3722                    _ => {
3723                        let Some(v) = view.as_deref() else {
3724                            emit(node, Event::Tap(at));
3725                            return;
3726                        };
3727                        if input::LONG_HELD.with(|t| t.take(ptr_of(v))).is_some() {
3728                            return;
3729                        }
3730                        let double = GESTURES.with(|m| {
3731                            m.borrow().get(&ptr_of(v)).is_some_and(|targets| {
3732                                targets
3733                                    .iter()
3734                                    .any(|t| t.ivars().kind == day_spec::GestureKind::DoubleTap)
3735                            })
3736                        });
3737                        let clicks = NSApplication::sharedApplication(self.mtm())
3738                            .currentEvent()
3739                            .map_or(1, |e| {
3740                                if matches!(
3741                                    e.r#type(),
3742                                    NSEventType::LeftMouseUp | NSEventType::LeftMouseDown
3743                                ) {
3744                                    e.clickCount()
3745                                } else {
3746                                    1
3747                                }
3748                            });
3749                        match input::tap_disposition(double, clicks) {
3750                            input::TapDisposition::Immediate => emit(node, Event::Tap(at)),
3751                            input::TapDisposition::Pending => input::hold_tap(v, node, at),
3752                            input::TapDisposition::Drop => {}
3753                        }
3754                    }
3755                }
3756            });
3757        }
3758    }
3759);
3760
3761impl DayGesture {
3762    fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
3763        let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
3764        unsafe { msg_send![super(this), init] }
3765    }
3766}
3767
3768// ---------------------------------------------------------------------------
3769// Navigation (docs/navigation.md): NSSplitView host, sidebar + detail panes.
3770// Page FRAMES are pane-owned (autoresized); Day lays content inside the size each
3771// page reports from setFrameSize:. Day's set_frame on pages is skipped.
3772// ---------------------------------------------------------------------------
3773
3774/// The stack presentation's back header (desktop has no system back affordance — this bar
3775/// gives a pushed page its way out, like `AdwNavigationView`'s header on GTK). Hidden at root.
3776struct NavHeader {
3777    bar: Retained<NSView>,
3778    title: Retained<NSTextField>,
3779    /// Title per stack level (index 0 = root); the field shows the last.
3780    titles: Vec<String>,
3781    _target: Retained<DayTarget>,
3782}
3783
3784/// Height of the stack-nav back header while a pushed page is showing.
3785const NAV_HEADER_H: f64 = 34.0;
3786
3787// Drag limits for both draggable panes come from day-spec (`NAV_SIDEBAR_MIN_W` and friends): a
3788// sidebar NSSplitViewItem enforces them itself, which is why the divider no longer needs
3789// restoring by hand after every window resize.
3790use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
3791
3792/// The content-list width to place divider 1 at, once, the first time the pane is showing —
3793/// `None` when the pane is collapsed or has already been placed. Latches on the way out, so the
3794/// two callers (the first frame pass, and the patch that reveals the pane) cannot both spend it.
3795fn take_list_placement(state: &mut NavState) -> Option<f64> {
3796    if !state.list_visible || state.list_positioned {
3797        return None;
3798    }
3799    state.list_positioned = true;
3800    state.list_width
3801}
3802
3803/// A tabs host's `NSTabView` margins inside its pane: the sides and the foot, and the top —
3804/// deeper, since the tabs themselves stand about a segment's height above the bezel.
3805const NAV_TABVIEW_INSET: f64 = 12.0;
3806const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
3807
3808/// The `NavPresentation::Tabs` container: a real `NSTabView` — the Mac's own tab control, top
3809/// tabs on a bezel — whose items own the detail pages. The page frames stay native-owned
3810/// exactly as in a split: the tab view frames the selected item's view, and the page's
3811/// `setFrameSize:` reports it. The labels come from the `NAV_MENU`'s rows, which arrive after
3812/// the pages' host (day-core mounts top-down: the rows page joins the host before its menu is
3813/// built), so `adopt_menu_for_tabs` runs when the menu is inserted and whenever its rows are
3814/// rebuilt.
3815///
3816/// Until 2026-09-12 this was an `NSSegmentedControl` docked at the foot, built from the rows
3817/// page's menu at the moment that page was inserted — before the menu existed — so no bar was
3818/// ever built and a tabs host showed its first page alone.
3819struct TabHost {
3820    view: Retained<objc2_app_kit::NSTabView>,
3821    /// The delegate reporting a native tab pick against the `NAV_MENU`'s node; set once the menu
3822    /// is known.
3823    target: Option<Retained<DayTarget>>,
3824}
3825
3826thread_local! {
3827    /// A Day-driven tab selection in flight (`NavPatch::Select`, a label sync): the tab view's
3828    /// delegate must not echo it back as `SelectionChanged`.
3829    static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3830}
3831
3832/// Give the tab view its labels from the rows, and its selection. Rows and items are
3833/// index-aligned (destination `i` is item `i`); a count mismatch mid-rebuild labels what both
3834/// have.
3835fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
3836    unsafe {
3837        let n = tabs.view.numberOfTabViewItems().max(0) as usize;
3838        for (i, title) in titles.iter().enumerate().take(n) {
3839            tabs.view
3840                .tabViewItemAtIndex(i as isize)
3841                .setLabel(&NSString::from_str(title));
3842        }
3843        if n > 0 {
3844            TAB_PICK_SUPPRESS.with(|s| s.set(true));
3845            tabs.view
3846                .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
3847            TAB_PICK_SUPPRESS.with(|s| s.set(false));
3848        }
3849    }
3850}
3851
3852/// A `NAV_MENU` reached a tabs host (its rows page sits in the host's collapsed sidebar pane):
3853/// the menu's rows become the tab labels and its node the delegate's target. Walks up from the
3854/// menu, so the innermost host — the one whose rows these are — is the one that takes them.
3855fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
3856    let Some((titles, node)) = NAV_MENUS.with(|m| {
3857        m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
3858            let ivars = d.ivars();
3859            (
3860                ivars
3861                    .items
3862                    .borrow()
3863                    .iter()
3864                    .map(std::string::ToString::to_string)
3865                    .collect::<Vec<String>>(),
3866                ivars.node,
3867            )
3868        })
3869    }) else {
3870        return;
3871    };
3872    let mut up = unsafe { menu.superview() };
3873    while let Some(v) = up {
3874        let reached = NAV_STATE.with(|m| {
3875            let mut m = m.borrow_mut();
3876            let Some(s) = m.get_mut(&ptr_of(&v)) else {
3877                return false;
3878            };
3879            let selected = s.selected;
3880            if let Some(tabs) = s.tabs.as_mut() {
3881                if tabs.target.is_none() {
3882                    let target = DayTarget::new(mtm, node);
3883                    unsafe {
3884                        tabs.view
3885                            .setDelegate(Some(ProtocolObject::from_ref(&*target)));
3886                    };
3887                    tabs.target = Some(target);
3888                }
3889                sync_tab_labels(tabs, &titles, selected);
3890            }
3891            true
3892        });
3893        if reached {
3894            return;
3895        }
3896        up = unsafe { v.superview() };
3897    }
3898}
3899
3900struct NavState {
3901    sidebar_wrap: Retained<NSView>,
3902    detail_wrap: Retained<NSView>,
3903    /// The container behind the host view. A view holds NO strong reference to its controller,
3904    /// and the split view controller is what owns the items, their holding priorities, the
3905    /// sidebar's material and the split's delegate duties — so it has to be retained here or
3906    /// the sidebar loses its treatment the moment this realize returns.
3907    split_vc: Retained<objc2_app_kit::NSSplitViewController>,
3908    /// The sidebar item, for the `SidebarToggle` duty (docs/toolbars.md). AppKit's own
3909    /// `NSToolbarToggleSidebarItem` reaches the controller through the responder chain; this is
3910    /// the path dayscript and any non-toolbar caller take.
3911    sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
3912    /// The content-list pane (docs/navigation.md), `Some` only on a host whose
3913    /// `NavProps::list_width` was set: the wrap its `Pane::List` page fills, and the
3914    /// `contentList` split item `NavPatch::ListVisible` collapses. The pane PERSISTS through
3915    /// every presentation (`Cap::NavContentList` = Native) — a narrow window collapses the
3916    /// sidebar and keeps the list, exactly as a narrow Mail.app does.
3917    list_wrap: Option<Retained<NSView>>,
3918    list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
3919    /// The app's requested content-list width (`NavProps::list_width`) — applied once, at the
3920    /// first frame pass, by placing divider 1 (see `set_frame`).
3921    list_width: Option<f64>,
3922    /// Whether the content-list pane is showing (`NavProps::list_visible`, then
3923    /// `NavPatch::ListVisible`). Placing divider 1 for a pane that is collapsed is what re-opens
3924    /// it, so both placement paths ask first.
3925    list_visible: bool,
3926    /// Whether divider 1 has been placed at the app's requested width yet. Separate from
3927    /// `positioned` because the pane may not exist on screen when the first frame pass runs: an
3928    /// app opening on a full-width destination has nothing to size then, and spending the
3929    /// one-time placement there is what left the list at the solver's own width when it did
3930    /// appear.
3931    list_positioned: bool,
3932    /// Detail pages in stack order (the sidebar page is not in here in split mode; in stack
3933    /// mode `split == false`, the root page is here too, so push/pop visibility covers it).
3934    pages: Vec<Retained<NSView>>,
3935    /// The host's sidebar page, once it has one — what a re-present moves between the sidebar
3936    /// pane and the head of `pages` (docs/size-classes.md).
3937    sidebar_page: Option<Retained<NSView>>,
3938    /// The content-list pane's page, re-framed when the pane is first revealed: it was inserted
3939    /// into a collapsed wrap, where autoresizing can only keep it at zero.
3940    list_page: Option<Retained<NSView>>,
3941    positioned: bool,
3942    /// Which of the four presentations is drawn right now (docs/size-classes.md). All of them are
3943    /// the same `NSSplitViewController`: a stack is that split with its sidebar collapsed, a rail
3944    /// is it with a narrow one, and a tab bar is a collapsed sidebar plus the bottom bar below.
3945    presentation: NavPresentation,
3946    /// The detail page on screen, as an index into `pages`. Maintained by every patch that
3947    /// changes it — push, pop and select alike — so a re-present can carry it across.
3948    selected: usize,
3949    /// The tab view (`NavPresentation::Tabs` only), holding the detail pages as its items and
3950    /// labeled from the same rows the sidebar's outline view shows; a pick emits
3951    /// `SelectionChanged` against the same `NAV_MENU` node.
3952    tabs: Option<TabHost>,
3953    /// Back header (stack presentation only).
3954    header: Option<NavHeader>,
3955    /// The host's own title, kept so a re-present into a stack can seed a fresh back header
3956    /// with the same root title the initial build would have used.
3957    root_title: String,
3958    /// The host's node, for the same reason — a back header's button targets it.
3959    node: NodeId,
3960    /// How far the host reaches up under the window's title bar (see `pane_under_title_bar`):
3961    /// the strip each pane's wrap is kept below. Zero for a host that does not start at the top
3962    /// of a pinned window.
3963    title_strip: f64,
3964}
3965
3966/// A split item's view: a transparent pane that runs the item's full height, with `wrap` (the
3967/// view Day's pages and the rest of this backend frame themselves against) inside it.
3968///
3969/// `NSSplitViewController` expects its split view to reach the top of a full-size-content window
3970/// and lays its title-bar treatment over the top of every item: a title-bar background, and on
3971/// macOS 26 and later the frosted scroll pocket. Day pins its content below the title bar
3972/// (`pin_below_title_bar`), so a split framed where Day lays it out put that treatment over the
3973/// first strip of every page instead, blurring a detail page's heading. The host is framed up
3974/// under the bar instead (`set_frame`), and each wrap is held below the strip inside its pane, so
3975/// the treatment lands on the bar, the sidebar's material runs to the top of the window as
3976/// `allowsFullHeightLayout` intends, and every page still starts where Day laid it out.
3977fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
3978    let pane = view_of(&DayFlipped::new(mtm));
3979    unsafe {
3980        wrap.setFrame(pane.bounds());
3981        wrap.setAutoresizingMask(
3982            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
3983                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
3984        );
3985        pane.addSubview(wrap);
3986    }
3987    pane
3988}
3989
3990/// Hold `wrap` `strip` points below the top of the pane that holds it.
3991fn place_below_strip(wrap: &NSView, strip: f64) {
3992    let Some(pane) = (unsafe { wrap.superview() }) else {
3993        return;
3994    };
3995    let b = pane.bounds();
3996    unsafe {
3997        wrap.setFrame(NSRect::new(
3998            NSPoint::new(0.0, strip),
3999            NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
4000        ));
4001    };
4002}
4003
4004/// The stack presentation's back header: a chevron + centered title docked above the pages,
4005/// hidden at the root. Desktop has no system back affordance, so a pushed page carries its own
4006/// way out (docs/navigation.md).
4007///
4008/// Built here rather than inline because a host that RE-PRESENTS into a stack needs one at that
4009/// moment (docs/size-classes.md), and a header that differed from the one a stack-at-launch host
4010/// gets would be a second shape to keep in step.
4011fn build_nav_header(
4012    mtm: MainThreadMarker,
4013    id: NodeId,
4014    detail_wrap: &NSView,
4015    root_title: &str,
4016) -> NavHeader {
4017    let bar = view_of(&DayFlipped::new(mtm));
4018    let target = DayTarget::new(mtm, id);
4019    let back = unsafe {
4020        // Invariant: NSImageNameGoBackTemplate is one of AppKit's own named images, present
4021        // on every macOS release this backend builds for.
4022        let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
4023            .expect("NSGoBackTemplate");
4024        let tobj: &objc2::runtime::AnyObject = target.as_ref();
4025        objc2_app_kit::NSButton::buttonWithImage_target_action(
4026            &img,
4027            Some(tobj),
4028            Some(sel!(navBack:)),
4029            mtm,
4030        )
4031    };
4032    let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
4033    unsafe {
4034        back.setFrame(NSRect::new(
4035            NSPoint::new(6.0, 4.0),
4036            NSSize::new(30.0, NAV_HEADER_H - 8.0),
4037        ));
4038        title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
4039        title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
4040        title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
4041        title.setFrame(NSRect::new(
4042            NSPoint::new(44.0, 9.0),
4043            NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
4044        ));
4045        title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
4046        bar.setFrame(NSRect::new(
4047            NSPoint::new(0.0, 0.0),
4048            NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
4049        ));
4050        bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
4051        bar.addSubview(&back);
4052        bar.addSubview(&title);
4053        bar.setHidden(true);
4054        detail_wrap.addSubview(&bar);
4055    }
4056    NavHeader {
4057        bar,
4058        title,
4059        titles: vec![root_title.to_string()],
4060        _target: target,
4061    }
4062}
4063
4064/// The frame a stack page occupies inside the detail wrap: full bounds at the root, inset below
4065/// the back header while a pushed page is showing. (A tabs host's pages are framed by its
4066/// `NSTabView`, never through here.)
4067fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
4068    let b = wrap.bounds();
4069    let top = if header_visible { NAV_HEADER_H } else { 0.0 };
4070    NSRect::new(
4071        NSPoint::new(0.0, top),
4072        NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
4073    )
4074}
4075
4076/// The row titles and the `NAV_MENU` node of the menu inside `page`, if it has one.
4077///
4078/// The tab bar needs the same rows the sidebar shows, and they arrive at the `NAV_MENU` rather
4079/// than at the host. Rather than plumb a second copy through the props, this walks down to the
4080/// menu that is already there — the sidebar page is Day-built and shallow, so the search is a
4081/// handful of views — and reads the titles it has stored for its own outline view.
4082fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
4083    fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
4084        if out.is_some() {
4085            return;
4086        }
4087        let found = NAV_MENUS.with(|m| {
4088            m.borrow()
4089                .get(&(std::ptr::from_ref::<NSView>(v) as usize))
4090                .map(|(_, d)| {
4091                    let ivars = d.ivars();
4092                    (
4093                        ivars
4094                            .items
4095                            .borrow()
4096                            .iter()
4097                            .map(std::string::ToString::to_string)
4098                            .collect(),
4099                        ivars.node,
4100                    )
4101                })
4102        });
4103        if found.is_some() {
4104            *out = found;
4105            return;
4106        }
4107        for sub in &unsafe { v.subviews() } {
4108            walk(&sub, out);
4109        }
4110    }
4111    let mut out = None;
4112    walk(page, &mut out);
4113    out
4114}
4115
4116/// Apply a presentation to the sidebar split item. All four are the same item at a different
4117/// thickness or collapsed outright, which is why a morph never rebuilds the split.
4118fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
4119    let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
4120    unsafe {
4121        item.setCanCollapse(shown);
4122        item.setCollapsed(!shown);
4123        match pres {
4124            // macOS has no rail: nothing in AppKit is a vertical strip of icon-only
4125            // destinations, and a source list pinned to icon width just truncates every row to an
4126            // ellipsis. `NavPresentation::Rail` is explicitly ROUNDABLE for exactly this case, so
4127            // it lands on the neighbor a Mac does have — an ordinary sidebar. Windows rounds the
4128            // other way (`PaneDisplayMode = LeftCompact` is a real rail there).
4129            NavPresentation::Split | NavPresentation::Rail => {
4130                item.setAllowsFullHeightLayout(true);
4131                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
4132                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
4133            }
4134            // Zero the thickness bounds before collapsing takes effect, or the pane keeps a
4135            // minimum width and the detail never reaches the window edge.
4136            NavPresentation::Stack | NavPresentation::Tabs => {
4137                item.setMinimumThickness(0.0);
4138                item.setMaximumThickness(0.0);
4139            }
4140        }
4141    }
4142}
4143
4144/// Show/hide the stack-nav back header for the given page stack and re-frame the pages under
4145/// it. The header shows exactly while a pushed page (depth ≥ 1 above the root) is on top; each
4146/// page's `DayNavPage::setFrameSize` reports the new size so Day re-lays its content.
4147/// The split view of the navigation host in `window` that has a content-list pane, for the
4148/// tracking separator pinned to its second divider (docs/toolbars.md).
4149pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
4150    NAV_STATE.with(|m| {
4151        m.borrow()
4152            .values()
4153            .find(|st| {
4154                st.list_item.is_some()
4155                    && st
4156                        .sidebar_wrap
4157                        .window()
4158                        .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
4159            })
4160            .map(|st| unsafe { st.split_vc.splitView() })
4161    })
4162}
4163
4164fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
4165    let visible = pages.len() >= 2;
4166    hdr.bar.setHidden(!visible);
4167    unsafe {
4168        hdr.title.setStringValue(&NSString::from_str(
4169            hdr.titles.last().map_or("", String::as_str),
4170        ));
4171    }
4172    let frame = nav_page_frame(wrap, visible);
4173    for page in pages {
4174        unsafe { page.setFrame(frame) };
4175    }
4176}
4177
4178/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
4179/// chrome changes but the pages do not.
4180///
4181/// Both presentations already share one `NSSplitViewController` — a stack is the same split with
4182/// its sidebar item collapsed to zero thickness — so the morph is three moves, and none of them
4183/// touches a page's CONTENT:
4184///
4185/// 1. the sidebar item collapses or expands (AppKit animates it and re-runs the titlebar
4186///    separator on its own),
4187/// 2. the sidebar PAGE moves between the sidebar wrap and the head of the detail stack,
4188/// 3. the back header appears or hides, since only a stack has one.
4189///
4190/// `addSubview` re-parents a view rather than rebuilding it, so every page keeps its subtree,
4191/// its scroll position, and its first responder across the move.
4192fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
4193    let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
4194        NAV_STATE.with(|m| {
4195            let st = m.borrow();
4196            let s = st.get(&ptr_of(host))?;
4197            Some((
4198                s.sidebar_page.clone(),
4199                s.detail_wrap.clone(),
4200                s.sidebar_wrap.clone(),
4201                s.sidebar_item.clone(),
4202                s.presentation,
4203                s.root_title.clone(),
4204                s.node,
4205                s.selected,
4206            ))
4207        })
4208    else {
4209        return;
4210    };
4211    if was == next {
4212        return;
4213    }
4214    apply_sidebar_item(&sidebar_item, next);
4215    // Settle the split now rather than at the next natural layout pass. `setCollapsed` marks the
4216    // split view as needing layout; without this the pane keeps its old width for one more frame,
4217    // which the dayscript screenshot seam captures (it renders the window offscreen the instant
4218    // the patch returns) and which a user crossing a breakpoint sees as a stutter.
4219    NAV_STATE.with(|m| {
4220        if let Some(s) = m.borrow().get(&ptr_of(host)) {
4221            unsafe { s.split_vc.splitView().layoutSubtreeIfNeeded() };
4222        }
4223    });
4224    // A stack needs a back header; nothing else may show one. Built on demand and kept
4225    // afterwards — rebuilding it on every morph would leak a target per crossing.
4226    let stacked = next == NavPresentation::Stack;
4227    let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
4228    if stacked && header.is_none() {
4229        header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
4230    }
4231    if let Some(hdr) = header.as_ref() {
4232        hdr.bar.setHidden(true);
4233    }
4234    // No tab view here: `Tabs` is a PINNED style on this backend (`Cap::NavTabsAdaptive` is
4235    // off), resolved the same at every width, so a host never morphs into or out of it — its
4236    // `NSTabView` is built at realize and lives for the host.
4237    // Which page is on screen, by IDENTITY: moving the sidebar page in or out of the detail list
4238    // shifts every index past it, so an index captured now would name the wrong page after.
4239    let mut pages = NAV_STATE.with(|m| {
4240        m.borrow()
4241            .get(&ptr_of(host))
4242            .map_or_default(|s| s.pages.clone())
4243    });
4244    let shown_page = pages.get(sel).cloned();
4245    // The sidebar page is a stack ROOT only while stacked; otherwise it lives in its own pane,
4246    // which is the sidebar in `Split`/`Rail` and a collapsed one behind a tab bar in `Tabs`.
4247    if let Some(page) = sidebar_page {
4248        pages.retain(|p| ptr_of(p) != ptr_of(&page));
4249        unsafe {
4250            if stacked {
4251                detail_wrap.addSubview(&page);
4252                pages.insert(0, page.clone());
4253            } else {
4254                page.setFrame(sidebar_wrap.bounds());
4255                sidebar_wrap.addSubview(&page);
4256            }
4257        }
4258        // A pane always shows its page; as a stack root it may have been hidden under a push.
4259        page.setHidden(false);
4260    }
4261    let shown = shown_page
4262        .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
4263        .unwrap_or_else(|| pages.len().saturating_sub(1));
4264    for (i, page) in pages.iter().enumerate() {
4265        page.setHidden(i != shown);
4266    }
4267    NAV_STATE.with(|m| {
4268        let mut m = m.borrow_mut();
4269        if let Some(s) = m.get_mut(&ptr_of(host)) {
4270            s.presentation = next;
4271            s.pages = pages;
4272            s.selected = shown;
4273            s.header = header;
4274            if let Some(hdr) = s.header.as_ref() {
4275                // Depth drives visibility, and the header is meaningless anywhere but a stack.
4276                if stacked {
4277                    sync_nav_header(hdr, &s.detail_wrap, &s.pages);
4278                } else {
4279                    hdr.bar.setHidden(true);
4280                }
4281            }
4282            if !stacked {
4283                // Leaving the stack: the pages were inset below the header, so give them the
4284                // pane back.
4285                let frame = nav_page_frame(&s.detail_wrap, false);
4286                for page in &s.pages {
4287                    unsafe { page.setFrame(frame) };
4288                }
4289            }
4290        }
4291    });
4292}
4293
4294// ---------------------------------------------------------------------------
4295// The sidebar pane holds its width through NSSplitViewController's own holding priorities
4296// (docs/navigation.md) — a sidebar NSSplitViewItem pins its thickness and lets the detail
4297// absorb a window resize, which is exactly the Finder/Mail behavior the hand-rolled
4298// `splitView:shouldAdjustSizeOfSubview:` delegate used to approximate. The controller IS the
4299// split's delegate, so Day must not install one of its own.
4300// ---------------------------------------------------------------------------
4301
4302struct CoverSheet(Retained<NSWindow>);
4303impl Drop for CoverSheet {
4304    fn drop(&mut self) {
4305        // try_with: the table may already be gone when the thread's locals tear down.
4306        let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
4307        // Sheet transitions may run a nested AppKit update cycle. Defer them until the
4308        // core's tree borrow has ended; this retained pointer travels only to the main queue.
4309        let raw = Retained::into_raw(self.0.clone()) as usize;
4310        dispatch2::DispatchQueue::main().exec_async(move || {
4311            ffi_guard::contain((), || unsafe {
4312                let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
4313                if let Some(parent) = window.sheetParent() {
4314                    parent.endSheet(&window);
4315                }
4316                window.orderOut(None);
4317                window.setContentView(None);
4318            });
4319        });
4320    }
4321}
4322struct NavPageIvars {
4323    node: NodeId,
4324    /// A presented cover's strip under the window's title bar: the page paints it (its frame
4325    /// starts above the layout area) but lays its content out below it, and reports the
4326    /// remaining height (see `pin_below_title_bar`).
4327    top_inset: Cell<f64>,
4328    sheet: Cell<bool>,
4329    /// A half sheet (docs/cover.md): the window sheet stands half the parent's height.
4330    half: Cell<bool>,
4331    /// A large sheet (docs/cover.md "Large sheet"): the window sheet grows to
4332    /// `LARGE_SHEET_MAX`.
4333    large: Cell<bool>,
4334    /// A presented cover's opaque fill on the layer, set again for each appearance.
4335    fill: Cell<Option<day_spec::Ink>>,
4336}
4337
4338define_class!(
4339    #[unsafe(super(NSView))]
4340    #[thread_kind = MainThreadOnly]
4341    #[name = "DayNavPage"]
4342    #[ivars = NavPageIvars]
4343    struct DayNavPage;
4344
4345    impl DayNavPage {
4346        #[unsafe(method(isFlipped))]
4347        fn is_flipped(&self) -> bool {
4348            true
4349        }
4350
4351        #[unsafe(method(setFrameSize:))]
4352        fn set_frame_size(&self, size: NSSize) {
4353            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
4354            // Pane-driven resize (splitter drag, window resize): report the usable size
4355            // so NavLayout re-lays this page's content (enqueue-only, §8.3).
4356            ffi_guard::contain((), || {
4357                let inset = self.ivars().top_inset.get();
4358                emit(
4359                    self.ivars().node,
4360                    Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
4361                );
4362            });
4363        }
4364
4365        /// A cover's fill is a layer color, which holds one appearance: set it again.
4366        #[unsafe(method(viewDidChangeEffectiveAppearance))]
4367        fn view_did_change_effective_appearance(&self) {
4368            let _: () = unsafe { msg_send![super(self), viewDidChangeEffectiveAppearance] };
4369            ffi_guard::contain((), || self.paint_fill());
4370        }
4371    }
4372);
4373
4374impl DayNavPage {
4375    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
4376        let this = Self::alloc(mtm).set_ivars(NavPageIvars {
4377            node,
4378            top_inset: Cell::new(0.0),
4379            sheet: Cell::new(false),
4380            half: Cell::new(false),
4381            large: Cell::new(false),
4382            fill: Cell::new(None),
4383        });
4384        unsafe { msg_send![super(this), init] }
4385    }
4386
4387    /// Fill a presented cover with `ink` (docs/cover.md): the page's layer background, opaque
4388    /// over the window, resolved for the appearance the page is shown in.
4389    fn set_fill(&self, ink: day_spec::Ink) {
4390        self.ivars().fill.set(Some(ink));
4391        self.setWantsLayer(true);
4392        self.paint_fill();
4393    }
4394
4395    fn paint_fill(&self) {
4396        if let (Some(ink), Some(layer)) = (self.ivars().fill.get(), self.layer()) {
4397            layer.setBackgroundColor(Some(&color::cg_for(self, ink)));
4398        }
4399    }
4400}
4401
4402// ---------------------------------------------------------------------------
4403// Inspector (docs/inspector.md): an NSSplitViewController whose trailing pane is a REAL
4404// inspector item (`inspectorWithViewController:`) — the system treatment for exactly this
4405// surface: its own backing material, the standard thickness handling, full-height layout
4406// under the titlebar. Day's bound signal is the only visibility driver (the item cannot be
4407// user-collapsed), so this backend never emits `Event::InspectorChanged`.
4408// ---------------------------------------------------------------------------
4409
4410struct InspectorState {
4411    content_wrap: Handle,
4412    panel_wrap: Handle,
4413    /// Retained so the controller (the split's delegate) lives as long as its split.
4414    split_vc: Retained<objc2_app_kit::NSSplitViewController>,
4415    panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
4416}
4417
4418// ---------------------------------------------------------------------------
4419// Split (docs/split.md): a plain `NSSplitView` inside a flipped wrap (the wrap is the handle,
4420// so `set_frame`'s nav-host treatment of split views never sees it), two arranged flipped
4421// subviews as the panes, and a delegate that places the divider by the bound share, keeps
4422// both panes above the minimum, and reports a drag back as the new share.
4423// ---------------------------------------------------------------------------
4424
4425struct SplitState {
4426    split: Retained<objc2_app_kit::NSSplitView>,
4427    first_wrap: Handle,
4428    second_wrap: Handle,
4429    delegate: Retained<DaySplitDelegate>,
4430}
4431
4432struct SplitDelegateIvars {
4433    node: NodeId,
4434    min_pane: f64,
4435    /// The share as last patched or reported: what a report is compared against, and where
4436    /// the divider goes when the split first has a size or turns.
4437    share: Cell<f64>,
4438    /// The divider has been placed once; before that the split has no size to place it in.
4439    positioned: Cell<bool>,
4440    /// Day is moving the divider itself: the resize that follows is not a report.
4441    suppress: Cell<bool>,
4442}
4443
4444define_class!(
4445    #[unsafe(super(NSObject))]
4446    #[thread_kind = MainThreadOnly]
4447    #[name = "DaySplitDelegate"]
4448    #[ivars = SplitDelegateIvars]
4449    struct DaySplitDelegate;
4450
4451    unsafe impl NSObjectProtocol for DaySplitDelegate {}
4452
4453    unsafe impl NSSplitViewDelegate for DaySplitDelegate {
4454        #[unsafe(method(splitViewDidResizeSubviews:))]
4455        fn did_resize(&self, notification: &NSNotification) {
4456            ffi_guard::contain((), || {
4457                let Some(obj) = notification.object() else {
4458                    return;
4459                };
4460                let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
4461                    return;
4462                };
4463                let iv = self.ivars();
4464                let usable = split_usable(&sv);
4465                if usable <= 0.0 {
4466                    return;
4467                }
4468                // The first resize with a size: place the divider by the share, once.
4469                if !iv.positioned.replace(true) {
4470                    split_place(&sv, iv);
4471                    return;
4472                }
4473                if iv.suppress.get() {
4474                    return;
4475                }
4476                let Some(first) = sv.subviews().iter().next() else {
4477                    return;
4478                };
4479                let f = first.frame();
4480                let a = if sv.isVertical() {
4481                    f.size.width
4482                } else {
4483                    f.size.height
4484                };
4485                let share = (a / usable).clamp(0.0, 1.0);
4486                if (share - iv.share.get()).abs() > 1e-4 {
4487                    iv.share.set(share);
4488                    emit(iv.node, Event::ValueChanged(share));
4489                }
4490            });
4491        }
4492
4493        #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
4494        fn constrain_min(
4495            &self,
4496            _sv: &objc2_app_kit::NSSplitView,
4497            proposed: f64,
4498            _index: isize,
4499        ) -> f64 {
4500            proposed.max(self.ivars().min_pane)
4501        }
4502
4503        #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
4504        fn constrain_max(
4505            &self,
4506            sv: &objc2_app_kit::NSSplitView,
4507            proposed: f64,
4508            _index: isize,
4509        ) -> f64 {
4510            proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
4511        }
4512    }
4513);
4514
4515impl DaySplitDelegate {
4516    fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
4517        let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
4518            node,
4519            min_pane,
4520            share: Cell::new(share.clamp(0.0, 1.0)),
4521            positioned: Cell::new(false),
4522            suppress: Cell::new(false),
4523        });
4524        unsafe { msg_send![super(this), init] }
4525    }
4526}
4527
4528/// The length the two panes share along the split's axis: the frame minus the divider.
4529fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
4530    let frame = sv.frame();
4531    let len = if sv.isVertical() {
4532        frame.size.width
4533    } else {
4534        frame.size.height
4535    };
4536    (len - sv.dividerThickness()).max(0.0)
4537}
4538
4539/// Move the divider so the first pane takes the share, silently (Day's own write, not a drag).
4540fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
4541    let usable = split_usable(sv);
4542    if usable <= 0.0 {
4543        return;
4544    }
4545    iv.suppress.set(true);
4546    unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
4547    iv.suppress.set(false);
4548}
4549
4550// ---------------------------------------------------------------------------
4551
4552// ---------------------------------------------------------------------------
4553// DayNavMenuData — flat NSOutlineView source list for nav_menu() (docs/navigation.md)
4554// ---------------------------------------------------------------------------
4555
4556struct NavMenuIvars {
4557    node: NodeId,
4558    items: RefCell<Vec<Retained<NSString>>>,
4559    /// Pre-resolved template icons per row (docs/navigation.md), `None` where a row has no icon.
4560    /// Template images tint with the source-list's selection/appearance, so they read in light,
4561    /// dark, and while selected — the macOS-idiomatic sidebar look (Finder/Mail).
4562    icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
4563    /// How much of each icon's box its drawing spans (`nav_icon_fill`), index-aligned with
4564    /// `icons`: the cell sizes the icon so the drawing matches a system sidebar glyph.
4565    icon_fills: RefCell<Vec<f64>>,
4566    /// Per-row icon tint (docs/vectors.md): recolors the template glyph via contentTintColor;
4567    /// `None` keeps the source-list's neutral template tint.
4568    tints: RefCell<Vec<Option<day_spec::Ink>>>,
4569    /// Trailing accessory per item row (an unread count), `None` where a row has none.
4570    badges: RefCell<Vec<Option<Retained<NSString>>>>,
4571    /// Trailing accessory GLYPH per row, in the same slot as `badges` and drawn after it —
4572    /// a starred page's star. Resolved to images once per rebuild, like `icons`.
4573    icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
4574    badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
4575    /// Tint for `badge_icons`; `None` keeps the neutral template tint.
4576    badge_tints: RefCell<Vec<Option<day_spec::Ink>>>,
4577    /// Per-row context menu (docs/menus.md), empty = none. Built into an `NSMenu` and attached
4578    /// to the row's cell view, so a secondary click pops it like any native sidebar menu.
4579    menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
4580    /// Which items drag to reorder (`NavMenuProps::movable`); empty when none do.
4581    movable: RefCell<Vec<bool>>,
4582    /// Movable rows may cross section headers (`NavMenuProps::regroup`); set at creation.
4583    regroup: std::cell::Cell<bool>,
4584    /// Which movable items keep their section's sorted order (`NavMenuProps::sorted`).
4585    sorted: RefCell<Vec<bool>>,
4586    /// The outline's rows, in display order: `Some(i)` is item `i`, `None` is a section
4587    /// header. Day addresses rows by ITEM index, so every selection crossing the boundary
4588    /// goes through this map — a header must never shift what index 3 means.
4589    rows: RefCell<Vec<Option<usize>>>,
4590    /// One retained `NSString` per outline row: the row's text (a header's or an item's).
4591    row_objects: RefCell<Vec<Retained<NSString>>>,
4592    /// One `NSNumber` per outline row, holding the row's index: the outline's item IDENTITY.
4593    /// `NSOutlineView` matches items with `isEqual:`, so an `NSString` cannot be the identity —
4594    /// a section header titled "Controls" and an item titled "Controls" would collapse into one
4595    /// row, and the header would wear the item's icon. Row indexes are unique by construction.
4596    row_ids: RefCell<Vec<Retained<NSNumber>>>,
4597    /// Programmatic selection in flight: don't re-emit `SelectionChanged`.
4598    suppress: std::cell::Cell<bool>,
4599}
4600
4601struct NavCellIvars {
4602    /// The trailing accessories (an unread count, a status glyph), when the row has any: the
4603    /// label ends before them.
4604    accessory: RefCell<Option<Retained<NSView>>>,
4605    /// The unread count among them, sized to follow the row's text.
4606    count: RefCell<Option<Retained<NSTextField>>>,
4607    /// How much of the icon's box its drawing spans (`nav_icon_fill`).
4608    icon_fill: std::cell::Cell<f64>,
4609}
4610
4611define_class!(
4612    /// A sidebar row's cell. `NSTableCellView` lays out its icon and label itself, at the
4613    /// size the outline's row size style gives them: the system's Sidebar icon size setting,
4614    /// followed live (docs/navigation.md). This only makes room for the trailing accessories,
4615    /// which AppKit knows nothing about.
4616    #[unsafe(super(objc2_app_kit::NSTableCellView))]
4617    #[thread_kind = MainThreadOnly]
4618    #[name = "DayNavCell"]
4619    #[ivars = NavCellIvars]
4620    struct DayNavCell;
4621
4622    unsafe impl NSObjectProtocol for DayNavCell {}
4623
4624    impl DayNavCell {
4625        #[unsafe(method(layout))]
4626        fn layout(&self) {
4627            let _: () = unsafe { msg_send![super(self), layout] };
4628            ffi_guard::contain((), || self.fit_accessories());
4629        }
4630    }
4631);
4632
4633impl DayNavCell {
4634    fn new(mtm: MainThreadMarker) -> Retained<Self> {
4635        let this = Self::alloc(mtm).set_ivars(NavCellIvars {
4636            accessory: RefCell::new(None),
4637            count: RefCell::new(None),
4638            icon_fill: std::cell::Cell::new(1.0),
4639        });
4640        unsafe { msg_send![super(this), init] }
4641    }
4642
4643    /// After AppKit's layout: the count takes a size two points under the label's, and the
4644    /// label, which AppKit stretches to the cell's trailing edge, ends 6pt before the
4645    /// accessories so a long title truncates instead of running under its count. A showing
4646    /// progress ring re-fits the icon AppKit just sized.
4647    fn fit_accessories(&self) {
4648        let label = unsafe { self.textField() };
4649        if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
4650            let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
4651                (f.pointSize() - 2.0).max(9.0)
4652            });
4653            #[expect(
4654                clippy::float_cmp,
4655                reason = "unchanged-value check against the exact size set below"
4656            )]
4657            let resize = unsafe { count.font() }.is_none_or(|f| f.pointSize() != size);
4658            if resize {
4659                unsafe {
4660                    count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
4661                        size,
4662                        objc2_app_kit::NSFontWeightRegular,
4663                    )));
4664                }
4665                self.layoutSubtreeIfNeeded();
4666            }
4667        }
4668        if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
4669            let mut frame = label.frame();
4670            let end = accessory.frame().origin.x - 6.0;
4671            if frame.origin.x + frame.size.width > end {
4672                frame.size.width = (end - frame.origin.x).max(0.0);
4673                label.setFrame(frame);
4674            }
4675        }
4676        if let Some(icon) = unsafe { self.imageView() } {
4677            fit_nav_icon(&icon, self.ivars().icon_fill.get());
4678            nav_progress::fit(&icon);
4679        }
4680    }
4681}
4682
4683thread_local! {
4684    /// The side of a system sidebar glyph per symbol configuration (see `fit_nav_icon`).
4685    static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
4686}
4687
4688/// Draw a sidebar row's icon so its drawing is the size a system sidebar draws its SF Symbol,
4689/// centered in the slot AppKit lays out for it; `fill` is how much of the image's box the
4690/// drawing spans (`nav_icon_fill`). The slot is wider than the glyph AppKit puts there (22pt for a
4691/// 16pt glyph at Medium), and Day's icons are artwork that fills whatever frame it gets, so
4692/// left at the slot's size they read a third larger and heavier than Finder's or Mail's.
4693/// The side is measured, not tabled: a square symbol (`gearshape`) drawn with the symbol
4694/// configuration the row size style gave this image view, so it tracks the Sidebar icon size
4695/// setting and whatever a later macOS draws.
4696fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
4697    let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
4698        return;
4699    };
4700    let slot = icon.frame();
4701    // Configurations compare by value, and AppKit gives every cell of a row size style an
4702    // equal one, so the hash names the style.
4703    let key = config.hash() as u64;
4704    let side = NAV_GLYPH_SIDES
4705        .with(|m| m.borrow().get(&key).copied())
4706        .or_else(|| {
4707            let symbol =
4708                objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
4709                    &NSString::from_str("gearshape"),
4710                    None,
4711                )?;
4712            let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
4713            NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
4714            Some(side)
4715        });
4716    // The box that puts the drawing itself at the glyph's size: a Material Symbols icon keeps
4717    // the margin of its grid inside the box, so its box is that much larger.
4718    let Some(side) = side
4719        .filter(|s| *s > 0.0)
4720        .map(|s| (s / fill.clamp(0.25, 1.0)).round())
4721    else {
4722        return;
4723    };
4724    if slot.size.width <= side && slot.size.height <= side {
4725        return;
4726    }
4727    icon.setFrame(NSRect::new(
4728        NSPoint::new(
4729            (slot.origin.x + (slot.size.width - side) / 2.0).round(),
4730            (slot.origin.y + (slot.size.height - side) / 2.0).round(),
4731        ),
4732        NSSize::new(side, side),
4733    ));
4734}
4735
4736define_class!(
4737    #[unsafe(super(objc2_app_kit::NSTableRowView))]
4738    #[thread_kind = MainThreadOnly]
4739    #[name = "DayNavRowView"]
4740    struct DayNavRowView;
4741
4742    unsafe impl NSObjectProtocol for DayNavRowView {}
4743
4744    impl DayNavRowView {
4745        /// Always report the emphasized (key-window) state, so the selected sidebar row draws
4746        /// the accent pill with auto-whitened label/icon in both themes. Without this, a run
4747        /// whose window never becomes key (scripted screenshot captures) falls back to the
4748        /// unemphasized selection fill, which under a forced appearance rendered as a
4749        /// near-black pill that swallowed the row's label.
4750        #[unsafe(method(isEmphasized))]
4751        fn is_emphasized(&self) -> bool {
4752            true
4753        }
4754    }
4755);
4756
4757define_class!(
4758    #[unsafe(super(objc2_app_kit::NSOutlineView))]
4759    #[thread_kind = MainThreadOnly]
4760    #[name = "DayNavOutlineView"]
4761    struct DayNavOutlineView;
4762
4763    unsafe impl NSObjectProtocol for DayNavOutlineView {}
4764
4765    impl DayNavOutlineView {
4766        /// The clicked row's context menu (docs/menus.md): NSTableView-family views consume
4767        /// right-clicks themselves, so per-row menus are served here — resolve the row under
4768        /// the click, then build the same NSMenu the piece decorator would.
4769        #[unsafe(method_id(menuForEvent:))]
4770        fn menu_for_event(
4771            &self,
4772            event: &objc2_app_kit::NSEvent,
4773        ) -> Option<Retained<NSMenu>> {
4774            ffi_guard::contain(None, || {
4775                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4776                let row = unsafe { self.rowAtPoint(point) };
4777                let data = NAV_OUTLINE_MENUS.with(|t| t.get(std::ptr::from_ref(self) as usize));
4778                // `define_class!` rewrites the return, so no early `return` — one expression.
4779                match data {
4780                    None => None,
4781                    Some(d) => {
4782                        let items = d
4783                            .item_of_row(row)
4784                            .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
4785                            .unwrap_or_default();
4786                        if items.is_empty() {
4787                            None
4788                        } else {
4789                            Some(build_ns_menu(d.mtm(), "", &items))
4790                        }
4791                    }
4792                }
4793            })
4794        }
4795    }
4796);
4797
4798define_class!(
4799    #[unsafe(super(NSObject))]
4800    #[thread_kind = MainThreadOnly]
4801    #[name = "DayNavMenuData"]
4802    #[ivars = NavMenuIvars]
4803    struct DayNavMenuData;
4804
4805    unsafe impl NSObjectProtocol for DayNavMenuData {}
4806
4807    unsafe impl NSOutlineViewDataSource for DayNavMenuData {
4808        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
4809        fn number_of_children(
4810            &self,
4811            _ov: &objc2_app_kit::NSOutlineView,
4812            item: Option<&objc2::runtime::AnyObject>,
4813        ) -> isize {
4814            if item.is_none() {
4815                self.ivars().row_objects.borrow().len() as isize
4816            } else {
4817                0
4818            }
4819        }
4820
4821        #[unsafe(method_id(outlineView:child:ofItem:))]
4822        fn child_of_item(
4823            &self,
4824            _ov: &objc2_app_kit::NSOutlineView,
4825            index: isize,
4826            _item: Option<&objc2::runtime::AnyObject>,
4827        ) -> Retained<objc2::runtime::AnyObject> {
4828            let ids = self.ivars().row_ids.borrow();
4829            // AppKit only asks for children it was told exist, but a stale query racing a
4830            // reload must degrade (an unmatched identity) rather than index out of bounds —
4831            // a panic here unwinds into an ObjC frame and aborts.
4832            let id = ids
4833                .get(index as usize)
4834                .cloned()
4835                .unwrap_or_else(|| NSNumber::new_isize(-1));
4836            unsafe { objc2::rc::Retained::cast_unchecked(id) }
4837        }
4838
4839        #[unsafe(method(outlineView:isItemExpandable:))]
4840        fn is_expandable(
4841            &self,
4842            _ov: &objc2_app_kit::NSOutlineView,
4843            _item: &objc2::runtime::AnyObject,
4844        ) -> bool {
4845            false
4846        }
4847
4848        // --- drag-to-reorder (docs/navigation.md "Reordering sidebar destinations"): the
4849        // outline's own drag pipeline, with the Gap placeholder Finder's sidebar shows. A row
4850        // moves within the run of movable rows around it, or, regrouping, into any section of
4851        // movable rows (`regroup_gap`); the app's data change brings the new order back as
4852        // `NavMenuPatch::Items`.
4853
4854        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
4855        fn pasteboard_writer_for_item(
4856            &self,
4857            _ov: &objc2_app_kit::NSOutlineView,
4858            item: &objc2::runtime::AnyObject,
4859        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4860            let make = || {
4861                let row = Self::outline_row(item);
4862                let index = self.item_of_row(row)?;
4863                if !self.is_movable(index) {
4864                    return None;
4865                }
4866                let pbitem = objc2_app_kit::NSPasteboardItem::new();
4867                unsafe {
4868                    pbitem.setString_forType(
4869                        &NSString::from_str(&row.to_string()),
4870                        &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
4871                    );
4872                }
4873                Some(ProtocolObject::from_retained(pbitem))
4874            };
4875            ffi_guard::contain(None, make)
4876        }
4877
4878        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
4879        fn validate_drop(
4880            &self,
4881            ov: &objc2_app_kit::NSOutlineView,
4882            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4883            item: Option<&objc2::runtime::AnyObject>,
4884            child_index: isize,
4885        ) -> objc2_app_kit::NSDragOperation {
4886            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4887                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
4888                    return objc2_app_kit::NSDragOperation::None;
4889                };
4890                // A drop past the run's end lands at that end: move the gap there.
4891                if drop.retarget {
4892                    unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
4893                }
4894                objc2_app_kit::NSDragOperation::Move
4895            })
4896        }
4897
4898        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
4899        fn accept_drop(
4900            &self,
4901            ov: &objc2_app_kit::NSOutlineView,
4902            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4903            item: Option<&objc2::runtime::AnyObject>,
4904            child_index: isize,
4905        ) -> bool {
4906            ffi_guard::contain(false, || {
4907                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
4908                    return false;
4909                };
4910                // Deferred through the event queue: the app's callback never runs inside
4911                // AppKit's drop, and its data change reloads the rows in the new order.
4912                match drop.moves {
4913                    Some(NavMove::Reorder { from, to }) => {
4914                        emit(self.ivars().node, Event::ListReorder { from, to });
4915                    }
4916                    Some(NavMove::Regroup {
4917                        from,
4918                        section,
4919                        before,
4920                    }) => emit(
4921                        self.ivars().node,
4922                        Event::NavRegroup {
4923                            from,
4924                            section,
4925                            before,
4926                        },
4927                    ),
4928                    None => {}
4929                }
4930                true
4931            })
4932        }
4933    }
4934
4935    unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
4936
4937    unsafe impl NSOutlineViewDelegate for DayNavMenuData {
4938        /// Section headers are AppKit group rows: the source-list treatment (small, bold,
4939        /// secondary) comes free, and they are excluded from selection below.
4940        #[unsafe(method(outlineView:isGroupItem:))]
4941        fn is_group_item(
4942            &self,
4943            _ov: &objc2_app_kit::NSOutlineView,
4944            item: &objc2::runtime::AnyObject,
4945        ) -> bool {
4946            let row = Self::outline_row(item);
4947            row >= 0 && self.item_of_row(row).is_none()
4948        }
4949
4950        #[unsafe(method(outlineView:shouldSelectItem:))]
4951        fn should_select(
4952            &self,
4953            _ov: &objc2_app_kit::NSOutlineView,
4954            item: &objc2::runtime::AnyObject,
4955        ) -> bool {
4956            self.item_of_row(Self::outline_row(item)).is_some()
4957        }
4958
4959        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
4960        fn view_for(
4961            &self,
4962            ov: &objc2_app_kit::NSOutlineView,
4963            _col: Option<&objc2_app_kit::NSTableColumn>,
4964            item: &objc2::runtime::AnyObject,
4965        ) -> Option<Retained<NSView>> {
4966            let mtm = self.mtm();
4967            let row = Self::outline_row(item);
4968            let text = self
4969                .ivars()
4970                .row_objects
4971                .borrow()
4972                .get(usize::try_from(row).unwrap_or(usize::MAX))
4973                .cloned();
4974            // No early returns: the method_id macro owns the return conversion.
4975            text.map(|text| {
4976                let text: &NSString = &text;
4977                let Some(index) = self.item_of_row(row) else {
4978                    // A section header: a plain label. AppKit gives group rows their own
4979                    // typography and places the text, so this only supplies it.
4980                    let cell = DayNavCell::new(mtm);
4981                    let label = unsafe { NSTextField::labelWithString(text, mtm) };
4982                    unsafe {
4983                        label.cell().inspect(|c| {
4984                            c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
4985                        });
4986                        cell.addSubview(&label);
4987                        cell.setTextField(Some(&label));
4988                    }
4989                    return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
4990                };
4991                let icon = self
4992                    .ivars()
4993                    .icons
4994                    .borrow()
4995                    .get(index)
4996                    .and_then(std::clone::Clone::clone);
4997                let badge = self
4998                    .ivars()
4999                    .badges
5000                    .borrow()
5001                    .get(index)
5002                    .and_then(std::clone::Clone::clone);
5003                let badge_icon = self
5004                    .ivars()
5005                    .badge_icons
5006                    .borrow()
5007                    .get(index)
5008                    .and_then(std::clone::Clone::clone);
5009                let badge_tint = self
5010                    .ivars()
5011                    .badge_tints
5012                    .borrow()
5013                    .get(index)
5014                    .copied()
5015                    .flatten();
5016                // The cell places the icon and the label itself, at the row size style's size
5017                // (the system's Sidebar icon size); `DayNavCell` keeps the label clear of the
5018                // trailing accessories.
5019                let cell = DayNavCell::new(mtm);
5020                let label = unsafe { NSTextField::labelWithString(text, mtm) };
5021                unsafe {
5022                    // Feed titles are arbitrarily long, so the label truncates with an
5023                    // ellipsis within the frame the cell gives it.
5024                    label.cell().inspect(|c| {
5025                        c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
5026                    });
5027                    cell.addSubview(&label);
5028                    cell.setTextField(Some(&label));
5029                    // The badge sits at the trailing edge and keeps its intrinsic width; the
5030                    // label truncates into whatever is left, so a long feed name never pushes
5031                    // its own unread count off the pane.
5032                    // Both accessories share the trailing slot: the count (if any) and then
5033                    // the status glyph (if any), in a stack so a row can carry either or both
5034                    // without the constraints below caring which it got.
5035                    let accessory = objc2_app_kit::NSStackView::new(mtm);
5036                    accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
5037                    accessory.setOrientation(
5038                        objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
5039                    );
5040                    accessory.setSpacing(4.0);
5041                    let mut has_accessory = false;
5042                    let trailing: Retained<NSView> = match &badge {
5043                        Some(text) => {
5044                            let b = NSTextField::labelWithString(text, mtm);
5045                            b.setTranslatesAutoresizingMaskIntoConstraints(false);
5046                            b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
5047                            b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
5048                            b.setFont(Some(
5049                                &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
5050                                    objc2_app_kit::NSFont::smallSystemFontSize(),
5051                                    objc2_app_kit::NSFontWeightRegular,
5052                                ),
5053                            ));
5054                            b.setContentCompressionResistancePriority_forOrientation(
5055                                objc2_app_kit::NSLayoutPriorityRequired,
5056                                objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
5057                            );
5058                            *cell.ivars().count.borrow_mut() = Some(b.clone());
5059                            accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
5060                                objc2::rc::Retained::into_super(b),
5061                            ));
5062                            has_accessory = true;
5063                            let v: Retained<NSView> =
5064                                objc2::rc::Retained::into_super(accessory.clone());
5065                            v
5066                        }
5067                        None => objc2::rc::Retained::into_super(accessory.clone()),
5068                    };
5069                    // The status glyph, tinted where the app gave it a meaning-bearing color
5070                    // (a star is yellow because that is what a star IS, not because the theme
5071                    // says so). Template images take contentTintColor exactly as the row's
5072                    // leading icon does.
5073                    if let Some(img) = &badge_icon {
5074                        let iv = objc2_app_kit::NSImageView::new(mtm);
5075                        iv.setImage(Some(img));
5076                        iv.setTranslatesAutoresizingMaskIntoConstraints(false);
5077                        if let Some(c) = badge_tint {
5078                            iv.setContentTintColor(Some(&color::nsink(c)));
5079                        }
5080                        iv.setContentCompressionResistancePriority_forOrientation(
5081                            objc2_app_kit::NSLayoutPriorityRequired,
5082                            objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
5083                        );
5084                        accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
5085                        has_accessory = true;
5086                    }
5087                    cell.addSubview(&trailing);
5088                    if has_accessory {
5089                        *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
5090                    }
5091                    objc2_app_kit::NSLayoutConstraint::activateConstraints(
5092                        &objc2_foundation::NSArray::from_retained_slice(&[
5093                            trailing
5094                                .trailingAnchor()
5095                                .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
5096                            trailing
5097                                .centerYAnchor()
5098                                .constraintEqualToAnchor(&cell.centerYAnchor()),
5099                        ]),
5100                    );
5101                }
5102                if let Some(img) = icon {
5103                    let fill = self.ivars().icon_fills.borrow().get(index).copied();
5104                    cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
5105                    let tint = self.ivars().tints.borrow().get(index).copied().flatten();
5106                    let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
5107                    unsafe {
5108                        iv.setImage(Some(&img));
5109                        // Per-row tint (docs/vectors.md): the icons are template images, so
5110                        // contentTintColor recolors the alpha mask; None keeps the neutral look.
5111                        if let Some(t) = tint {
5112                            iv.setContentTintColor(Some(&color::nsink(t)));
5113                        }
5114                        iv.setImageScaling(
5115                            objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
5116                        );
5117                        cell.addSubview(&iv);
5118                        cell.setImageView(Some(&iv));
5119                        let progress = self
5120                            .ivars()
5121                            .icon_progress
5122                            .borrow()
5123                            .iter()
5124                            .find(|(row, _)| *row == index)
5125                            .map(|(_, f)| *f);
5126                        nav_progress::update(&iv, progress);
5127                    }
5128                }
5129                objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
5130            })
5131        }
5132
5133        #[unsafe(method_id(outlineView:rowViewForItem:))]
5134        fn row_view_for(
5135            &self,
5136            _ov: &objc2_app_kit::NSOutlineView,
5137            _item: &objc2::runtime::AnyObject,
5138        ) -> Retained<objc2_app_kit::NSTableRowView> {
5139            let row: Retained<DayNavRowView> =
5140                unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
5141            objc2::rc::Retained::into_super(row)
5142        }
5143
5144        #[unsafe(method(outlineViewSelectionDidChange:))]
5145        fn selection_did_change(&self, notification: &NSNotification) {
5146            ffi_guard::contain((), || {
5147                if self.ivars().suppress.get() {
5148                    return;
5149                }
5150                let Some(obj) = (unsafe { notification.object() }) else {
5151                    return;
5152                };
5153                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5154                    return;
5155                };
5156                let row = unsafe { ov.selectedRow() };
5157                if let Some(item) = self.item_of_row(row) {
5158                    emit(self.ivars().node, Event::SelectionChanged(item as i64));
5159                }
5160            });
5161        }
5162    }
5163);
5164
5165thread_local! {
5166    /// `nav_icon_fill` per icon name: a sidebar rebuilds its rows on every count change, and an
5167    /// icon's drawing does not change with them.
5168    static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
5169}
5170
5171/// `nav_icon_fill` for each resolved icon, by name; 1 where a row has none.
5172fn nav_icon_fills(
5173    names: &[Option<String>],
5174    images: &[Option<Retained<objc2_app_kit::NSImage>>],
5175) -> Vec<f64> {
5176    names
5177        .iter()
5178        .zip(images)
5179        .map(|(name, image)| match (name, image) {
5180            (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
5181                *m.borrow_mut()
5182                    .entry(name.clone())
5183                    .or_insert_with(|| nav_icon_fill(image))
5184            }),
5185            _ => 1.0,
5186        })
5187        .collect()
5188}
5189
5190/// How much of an icon's box its drawing spans along its longer side, in (0, 1]: a Material
5191/// Symbols glyph keeps the 80-unit margin of its 960-unit grid (about 0.83), an SF Symbol export
5192/// is boxed to its content (1), and artwork usually fills its square. Measured from the alpha of
5193/// one small render, since a plain SVG says nothing about where its drawing sits.
5194fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
5195    const PX: f64 = 64.0;
5196    let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
5197        return 1.0;
5198    };
5199    let (w, h) = (
5200        rep.pixelsWide().max(0) as usize,
5201        rep.pixelsHigh().max(0) as usize,
5202    );
5203    let stride = rep.bytesPerRow().max(0) as usize;
5204    let data = unsafe { rep.bitmapData() };
5205    if data.is_null() || stride < w * 4 {
5206        return 1.0;
5207    }
5208    // SAFETY: `scaled_rep` made a meshed 8-bit RGBA bitmap of `h` rows of `stride` bytes, which
5209    // `rep` owns and keeps alive for this borrow.
5210    let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
5211    let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
5212    for y in 0..h {
5213        for x in 0..w {
5214            if bytes[y * stride + x * 4 + 3] > 24 {
5215                (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
5216            }
5217        }
5218    }
5219    if x1 <= x0 || y1 <= y0 {
5220        return 1.0;
5221    }
5222    // The render stretched the image to a square; back in the image's own proportions, the
5223    // drawing's longer extent over the image's longer side is what proportional scaling keeps.
5224    let size = image.size();
5225    let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
5226    let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
5227    ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
5228}
5229
5230fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
5231    // A bundled icon name → a template NSImage (tinted by the source list); `None` per iconless row.
5232    icons
5233        .iter()
5234        .map(|ic| {
5235            use objc2::AllocAnyThread as _;
5236            let name = ic.as_deref()?;
5237            // Prefer the glyph SVG (docs/vectors.md): NSImage renders it at display size.
5238            let path = day_spec::resource::resolve_vector_svg(name)
5239                .or_else(|| day_spec::resource::resolve_image_file(name))?;
5240            let img = unsafe {
5241                objc2_app_kit::NSImage::initWithContentsOfFile(
5242                    objc2_app_kit::NSImage::alloc(),
5243                    &NSString::from_str(&path.to_string_lossy()),
5244                )
5245            }?;
5246            // Downloaded/user-file icons are artwork; bundled glyphs remain templates.
5247            unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
5248            Some(img)
5249        })
5250        .collect()
5251}
5252
5253impl DayNavMenuData {
5254    #[allow(clippy::too_many_arguments)]
5255    fn new(
5256        mtm: MainThreadMarker,
5257        node: NodeId,
5258        items: &[String],
5259        icons: &[Option<String>],
5260        badges: &[Option<String>],
5261        badge_icons: &[Option<String>],
5262        badge_tints: &[Option<day_spec::Ink>],
5263        sections: &[Option<String>],
5264        tints: &[Option<day_spec::Ink>],
5265        menus: &[Vec<day_spec::MenuItem>],
5266    ) -> Retained<Self> {
5267        let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
5268            node,
5269            items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
5270            icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
5271            icons: RefCell::new(resolve_nav_icons(icons)),
5272            tints: RefCell::new(tints.to_vec()),
5273            menus: RefCell::new(menus.to_vec()),
5274            movable: RefCell::new(Vec::new()),
5275            regroup: std::cell::Cell::new(false),
5276            sorted: RefCell::new(Vec::new()),
5277            badges: RefCell::new(ns_badges(badges)),
5278            icon_progress: RefCell::new(Vec::new()),
5279            badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
5280            badge_tints: RefCell::new(badge_tints.to_vec()),
5281            rows: RefCell::new(Vec::new()),
5282            row_objects: RefCell::new(Vec::new()),
5283            row_ids: RefCell::new(Vec::new()),
5284            suppress: std::cell::Cell::new(false),
5285        });
5286        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
5287        this.rebuild_rows(items, sections);
5288        this
5289    }
5290
5291    /// Data-driven rows changed (`NavMenuPatch::Items`): swap the stored decorations in place.
5292    // The parameters are the patch's payload: index-aligned per-row decoration arrays, each
5293    // landing in its own ivar. Bundling them would just move the same eight fields.
5294    #[allow(clippy::too_many_arguments)]
5295    fn set_items(
5296        &self,
5297        items: &[String],
5298        icons: &[Option<String>],
5299        badges: &[Option<String>],
5300        badge_icons: &[Option<String>],
5301        badge_tints: &[Option<day_spec::Ink>],
5302        sections: &[Option<String>],
5303        tints: &[Option<day_spec::Ink>],
5304        menus: &[Vec<day_spec::MenuItem>],
5305    ) {
5306        *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
5307        let resolved = resolve_nav_icons(icons);
5308        *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
5309        *self.ivars().icons.borrow_mut() = resolved;
5310        *self.ivars().tints.borrow_mut() = tints.to_vec();
5311        *self.ivars().menus.borrow_mut() = menus.to_vec();
5312        *self.ivars().badges.borrow_mut() = ns_badges(badges);
5313        self.ivars().icon_progress.borrow_mut().clear();
5314        *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
5315        *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
5316        self.rebuild_rows(items, sections);
5317    }
5318
5319    /// Flatten items + section headers into the outline's display rows. Each row gets its own
5320    /// retained `NSString` so the outline can tell two rows apart by identity even when their
5321    /// labels match (two feeds legitimately share a title).
5322    fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
5323        let mut rows = Vec::with_capacity(items.len());
5324        let mut objects = Vec::with_capacity(items.len());
5325        for (i, label) in items.iter().enumerate() {
5326            if let Some(Some(header)) = sections.get(i) {
5327                rows.push(None);
5328                objects.push(NSString::from_str(header));
5329            }
5330            rows.push(Some(i));
5331            objects.push(NSString::from_str(label));
5332        }
5333        let ids = (0..objects.len())
5334            .map(|i| NSNumber::new_isize(i as isize))
5335            .collect();
5336        *self.ivars().rows.borrow_mut() = rows;
5337        *self.ivars().row_objects.borrow_mut() = objects;
5338        *self.ivars().row_ids.borrow_mut() = ids;
5339    }
5340
5341    /// The outline row an item object names — the index its `NSNumber` identity carries — or
5342    /// `-1` for anything that is not one of ours (a stale query racing a reload).
5343    fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
5344        item.downcast_ref::<NSNumber>()
5345            .map_or(-1, objc2_foundation::NSNumber::integerValue)
5346    }
5347
5348    /// Outline row → day item index.
5349    fn item_of_row(&self, row: isize) -> Option<usize> {
5350        if row < 0 {
5351            return None;
5352        }
5353        self.ivars()
5354            .rows
5355            .borrow()
5356            .get(row as usize)
5357            .copied()
5358            .flatten()
5359    }
5360
5361    /// Day item index → outline row.
5362    fn row_of_item(&self, item: usize) -> Option<usize> {
5363        self.ivars()
5364            .rows
5365            .borrow()
5366            .iter()
5367            .position(|r| *r == Some(item))
5368    }
5369
5370    fn is_movable(&self, item: usize) -> bool {
5371        self.ivars()
5372            .movable
5373            .borrow()
5374            .get(item)
5375            .copied()
5376            .unwrap_or(false)
5377    }
5378
5379    /// What a drop proposal means for a reorder, or `None` when it is no drop of ours: a drag
5380    /// from another view, of a row that cannot move, or (regrouping) to a gap no rule allows.
5381    /// Reordering, the gap clamps to the run of movable rows around the dragged one, which
5382    /// section headers and fixed rows end ([`reorder_gap`]); regrouping, see [`regroup_gap`].
5383    fn nav_drop(
5384        &self,
5385        ov: &objc2_app_kit::NSOutlineView,
5386        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5387        item: Option<&objc2::runtime::AnyObject>,
5388        child_index: isize,
5389    ) -> Option<NavDrop> {
5390        let src = unsafe { info.draggingSource() }?;
5391        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
5392            != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
5393        {
5394            return None;
5395        }
5396        let pb = unsafe { info.draggingPasteboard() };
5397        let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
5398            .to_string()
5399            .parse::<usize>()
5400            .ok()?;
5401        let rows = self.ivars().rows.borrow();
5402        // The flat outline proposes a gap among the root's children, or a row itself (a drop
5403        // ONTO it, index -1).
5404        let proposed = match item {
5405            Some(item) => Self::outline_row(item),
5406            None => child_index,
5407        };
5408        let proposed = usize::try_from(proposed).unwrap_or(rows.len());
5409        if self.ivars().regroup.get() {
5410            regroup_gap(
5411                &rows,
5412                &self.ivars().movable.borrow(),
5413                &self.ivars().sorted.borrow(),
5414                from_row,
5415                proposed,
5416                item.is_some(),
5417            )
5418        } else {
5419            reorder_gap(
5420                &rows,
5421                &self.ivars().movable.borrow(),
5422                from_row,
5423                proposed,
5424                item.is_some(),
5425            )
5426        }
5427    }
5428}
5429
5430/// A drop in a sidebar outline (`DayNavMenuData::nav_drop`).
5431#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5432struct NavDrop {
5433    /// The gap the row drops into, among the outline's rows.
5434    gap: usize,
5435    /// The proposal named some other place, and the gap moves here.
5436    retarget: bool,
5437    /// What the drop reports, or `None` for a drop back in place.
5438    moves: Option<NavMove>,
5439}
5440
5441/// What a sidebar drop reports, in item indices (the rows before the move).
5442#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5443enum NavMove {
5444    /// `Event::ListReorder`: `from` takes `to`'s place.
5445    Reorder { from: usize, to: usize },
5446    /// `Event::NavRegroup`: `from` joins the section whose first row is `section`, before
5447    /// `before` or at the section's end.
5448    Regroup {
5449        from: usize,
5450        section: usize,
5451        before: Option<usize>,
5452    },
5453}
5454
5455/// A reorder drop at `proposed`, a gap among the outline's `rows` (`None` a header, `Some(i)`
5456/// item `i`), for the row at `from_row`; `onto` when the proposal named a row itself, which
5457/// reads as the gap above it. The gap clamps to the run of movable rows around the dragged
5458/// one, which section headers and fixed rows end. `None` when that row cannot move.
5459fn reorder_gap(
5460    rows: &[Option<usize>],
5461    movable: &[bool],
5462    from_row: usize,
5463    proposed: usize,
5464    onto: bool,
5465) -> Option<NavDrop> {
5466    let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
5467    let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
5468    let in_run = |r: usize| rows[r].is_some_and(is_movable);
5469    let first = (0..from_row)
5470        .rev()
5471        .take_while(|r| in_run(*r))
5472        .last()
5473        .unwrap_or(from_row);
5474    let last = (from_row + 1..rows.len())
5475        .take_while(|r| in_run(*r))
5476        .last()
5477        .unwrap_or(from_row);
5478    let gap = proposed.clamp(first, last + 1);
5479    // The row's place once it has left its own: the row whose position it takes.
5480    let target_row = if gap > from_row { gap - 1 } else { gap };
5481    let moves = (target_row != from_row)
5482        .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
5483        .flatten();
5484    Some(NavDrop {
5485        gap,
5486        retarget: gap != proposed || onto,
5487        moves,
5488    })
5489}
5490
5491/// A regroup drop at `proposed`, a gap among the outline's `rows` (as [`reorder_gap`]'s), for
5492/// the row at `from_row` (docs/navigation.md "Moving rows between sections"). The gap's section
5493/// is the nearest header above it, or the rows above the first header; `before` is the item
5494/// right below the gap when that row is in the same section. A drop ONTO a header reads as
5495/// that section's first gap, onto an item as the gap above it. `None` when the row cannot
5496/// move, the gap is above the first header with no rows there, the section holds a fixed row,
5497/// or the gap is in the row's own section and the row is sorted. Gaps are never clamped.
5498fn regroup_gap(
5499    rows: &[Option<usize>],
5500    movable: &[bool],
5501    sorted: &[bool],
5502    from_row: usize,
5503    proposed: usize,
5504    onto: bool,
5505) -> Option<NavDrop> {
5506    let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
5507    let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
5508    let gap = match rows.get(proposed) {
5509        Some(None) if onto => proposed + 1,
5510        _ => proposed.min(rows.len()),
5511    };
5512    // The first outline row of the section a gap (or a row, as the gap above it) sits in.
5513    let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
5514        Some(header) => Some(header + 1),
5515        None => rows.first().copied().flatten().map(|_| 0),
5516    };
5517    let first = section_start(gap)?;
5518    let end = (first..rows.len())
5519        .find(|r| rows[*r].is_none())
5520        .unwrap_or(rows.len());
5521    let section = rows.get(first).copied().flatten()?;
5522    if !rows[first..end]
5523        .iter()
5524        .all(|r| r.is_some_and(|i| flag(movable, i)))
5525    {
5526        return None;
5527    }
5528    let own = section_start(from_row) == Some(first);
5529    if own && flag(sorted, from) {
5530        return None;
5531    }
5532    let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
5533        from,
5534        section,
5535        before: rows.get(gap).copied().flatten(),
5536    });
5537    Some(NavDrop {
5538        gap,
5539        retarget: gap != proposed || onto,
5540        moves,
5541    })
5542}
5543
5544#[cfg(test)]
5545mod nav_gap_tests {
5546    use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
5547
5548    /// 0 today, 1 [news], 2 a, 3 b, 4 e, 5 [tech], 6 c, 7 d, 8 [smart], 9 starred: items 0..=6.
5549    const ROWS: [Option<usize>; 10] = [
5550        Some(0),
5551        None,
5552        Some(1),
5553        Some(2),
5554        Some(3),
5555        None,
5556        Some(4),
5557        Some(5),
5558        None,
5559        Some(6),
5560    ];
5561    /// The feeds move; today and starred are fixed.
5562    const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
5563    const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
5564    const UNSORTED: [bool; 7] = [false; 7];
5565
5566    fn regroup(from: usize, section: usize, before: Option<usize>) -> NavMove {
5567        NavMove::Regroup {
5568            from,
5569            section,
5570            before,
5571        }
5572    }
5573
5574    #[test]
5575    fn regroup_gaps_name_the_section_above_and_the_row_below() {
5576        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
5577        // a, into tech's first gap: before c.
5578        assert_eq!(
5579            at(2, 6),
5580            Some(NavDrop {
5581                gap: 6,
5582                retarget: false,
5583                moves: Some(regroup(1, 4, Some(4))),
5584            })
5585        );
5586        // c, into the gap above tech's header: the end of news.
5587        assert_eq!(at(6, 5).and_then(|d| d.moves), Some(regroup(4, 1, None)));
5588        // a, between c and d, and at tech's end above smart's header.
5589        assert_eq!(at(2, 7).and_then(|d| d.moves), Some(regroup(1, 4, Some(5))));
5590        assert_eq!(at(2, 8).and_then(|d| d.moves), Some(regroup(1, 4, None)));
5591    }
5592
5593    #[test]
5594    fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
5595        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
5596        // Smart holds starred, and the rows above the first header hold today.
5597        for gap in [0, 1, 9, 10] {
5598            assert_eq!(at(2, gap), None, "gap {gap}");
5599        }
5600        // A sorted row's own section offers no gap, its own place included.
5601        for gap in [2, 3, 4, 5] {
5602            assert_eq!(at(2, gap), None, "gap {gap}");
5603        }
5604        // Fixed rows and headers never drag.
5605        assert_eq!(at(0, 6), None);
5606        assert_eq!(at(1, 6), None);
5607        assert_eq!(at(9, 6), None);
5608    }
5609
5610    #[test]
5611    fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
5612        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
5613        // a, between b and e.
5614        assert_eq!(at(2, 4).and_then(|d| d.moves), Some(regroup(1, 1, Some(3))));
5615        // a, at news's end above tech's header.
5616        assert_eq!(at(2, 5).and_then(|d| d.moves), Some(regroup(1, 1, None)));
5617        // Back in place, either side of itself: a drop that reports nothing.
5618        for gap in [2, 3] {
5619            let drop = at(2, gap).expect("offered");
5620            assert_eq!(drop.moves, None, "gap {gap}");
5621        }
5622    }
5623
5624    #[test]
5625    fn regroup_drops_onto_a_row_move_to_a_gap() {
5626        // Onto tech's header: its first gap. Onto d: the gap above d.
5627        assert_eq!(
5628            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
5629            Some(NavDrop {
5630                gap: 6,
5631                retarget: true,
5632                moves: Some(regroup(1, 4, Some(4))),
5633            })
5634        );
5635        assert_eq!(
5636            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
5637            Some(NavDrop {
5638                gap: 7,
5639                retarget: true,
5640                moves: Some(regroup(1, 4, Some(5))),
5641            })
5642        );
5643    }
5644
5645    #[test]
5646    fn regroup_offers_nothing_above_a_leading_header() {
5647        // 0 [news], 1 a, 2 [tech], 3 b.
5648        let rows = [None, Some(0), None, Some(1)];
5649        let movable = [true, true];
5650        let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
5651        assert_eq!(at(0), None);
5652        assert_eq!(at(1).map(|d| d.moves), Some(None));
5653        assert_eq!(at(2).map(|d| d.moves), Some(None));
5654        assert_eq!(at(3).and_then(|d| d.moves), Some(regroup(0, 1, Some(1))));
5655        assert_eq!(at(4).and_then(|d| d.moves), Some(regroup(0, 1, None)));
5656    }
5657
5658    #[test]
5659    fn reorder_gaps_clamp_to_the_run() {
5660        // a past the run's end lands at its end: e's place.
5661        assert_eq!(
5662            reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
5663            Some(NavDrop {
5664                gap: 5,
5665                retarget: true,
5666                moves: Some(NavMove::Reorder { from: 1, to: 3 }),
5667            })
5668        );
5669        // Back in place.
5670        assert_eq!(
5671            reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
5672            Some(None)
5673        );
5674        // b above the run's start lands at a's place; a fixed row offers nothing.
5675        assert_eq!(
5676            reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
5677            Some(NavMove::Reorder { from: 2, to: 1 })
5678        );
5679        assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
5680    }
5681}
5682
5683/// The private pasteboard type carrying a dragged sidebar row (local reorder only).
5684const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
5685
5686/// Badge strings, retained once per rebuild rather than per cell.
5687fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
5688    badges
5689        .iter()
5690        .map(|b| b.as_deref().map(NSString::from_str))
5691        .collect()
5692}
5693
5694// ---------------------------------------------------------------------------
5695/// Force the table's visible rows to exist on the next main-loop turn — outside any `with_tree`
5696/// borrow, so `bind_row` may build them. `layoutSubtreeIfNeeded` is not enough: an occluded
5697/// window's table skips row tiling entirely, so `viewAtColumn:row:makeIfNecessary:` is the only
5698/// reliable way to realize rows without a draw pass (§10; see the Reload patch for why).
5699fn post_realize_visible_rows(key: usize) {
5700    <AppKit as Platform>::post(Box::new(move || {
5701        if let Some((table, data)) = list_entry(key) {
5702            // A change held through a pass lands first: the rows below are the source's.
5703            data.apply_held(&table);
5704            {
5705                // The binds below flush Day's pending work, as a pass's do: hold what it
5706                // changes, so the rows walked stay the rows shown.
5707                let _pass = RowPass::enter();
5708                unsafe { table.layoutSubtreeIfNeeded() };
5709                let range = unsafe { table.rowsInRect(table.visibleRect()) };
5710                for row in range.location..range.location + range.length {
5711                    let cell =
5712                        unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
5713                    // A snapshot, a splice or a layout can have requested this cell while
5714                    // day-core held its tree borrow. The bind was skipped then: the delegate
5715                    // returned an empty container, or a pooled cell still showing the row it
5716                    // held before (an inserted row reusing a removed one's cell). AppKit caches
5717                    // either and will not ask viewForRow again. Complete that skipped bind here,
5718                    // for the source row the table's row stands for (a change held by an
5719                    // earlier bind of this pass maps them).
5720                    if let Some(cell) = cell {
5721                        let raw = Retained::as_ptr(&cell) as RawHandle;
5722                        let skipped = data.ivars().unbound.borrow_mut().remove(&(raw as usize));
5723                        if (skipped || cell.subviews().is_empty())
5724                            && let Some(source) = data.ivars().source.borrow().clone()
5725                            && let Some(index) = data.source_row(row as isize)
5726                        {
5727                            (source.bind_row)(index, raw);
5728                            data.note_row_height(&table, &source, row as isize, raw);
5729                        }
5730                    }
5731                }
5732            }
5733            data.report_viewport(&table);
5734        }
5735        // The builds above queued their styling effects; drain them now — outside the pump, no
5736        // event may arrive for a while (idle app), and a snapshot would capture bare rows.
5737        day_core::pump_events();
5738    }));
5739}
5740
5741/// A native drop changes the snapshot synchronously and suppresses the app's echo Reload.
5742/// Once AppKit has unwound its drop/gap tracking, reconcile the table with that snapshot:
5743/// the incremental move alone can leave its row tiling and scroll extent out of sync.
5744/// Preserve the user's viewport and selection; never force a jump to the moved row.
5745fn post_settle_list_drop(key: usize) {
5746    <AppKit as Platform>::post(Box::new(move || {
5747        // Publish the deferred on_reorder before reading the final row set. App code may
5748        // remove rows or close the list, so resolve the native handles only after the drain.
5749        day_core::pump_events();
5750        let Some((table, data)) = list_entry(key) else {
5751            return;
5752        };
5753        data.apply_held(&table);
5754        let Some(scroll) = table.enclosingScrollView() else {
5755            return;
5756        };
5757        let clip = scroll.contentView();
5758        let origin = clip.bounds().origin;
5759        let selected = table.selectedRowIndexes();
5760        let suppressed = data.ivars().suppress.replace(true);
5761        table.reloadData();
5762        // Outside with_tree: tiling is allowed to bind/rebind Day's cell contents here.
5763        table.layoutSubtreeIfNeeded();
5764        let restored = objc2_foundation::NSMutableIndexSet::new();
5765        for row in 0..table.numberOfRows().max(0) as usize {
5766            if selected.containsIndex(row) {
5767                restored.addIndex(row);
5768            }
5769        }
5770        table.selectRowIndexes_byExtendingSelection(&restored, false);
5771        let mut bounds = clip.bounds();
5772        bounds.origin = origin;
5773        clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
5774        scroll.reflectScrolledClipView(&clip);
5775        data.ivars().suppress.set(suppressed);
5776        post_realize_visible_rows(key);
5777    }));
5778}
5779
5780// DayListData — NSTableView data-source + delegate for the recycling list (docs/list.md, §10)
5781//
5782// No custom NSTableRowView: the table runs the PLAIN style, whose standard row view lays cell
5783// views out at the full row bounds — no inset to pin away — and whose cell-frame slide is what
5784// animates a row-action swipe. (A `layout`-override pin lived here under FullWidth until
5785// 2026-08; it also froze row content mid-swipe, revealing actions behind a motionless row.)
5786// ---------------------------------------------------------------------------
5787
5788define_class!(
5789    #[unsafe(super(NSTableView))]
5790    #[thread_kind = MainThreadOnly]
5791    #[name = "DayListView"]
5792    struct DayListView;
5793    unsafe impl NSObjectProtocol for DayListView {}
5794    impl DayListView {
5795        /// NSTableView consumes right-clicks before the row's container sees them. Resolve
5796        /// its summon-time provider from the visible cell, never from the selected row.
5797        #[unsafe(method_id(menuForEvent:))]
5798        fn menu_for_event(
5799            &self,
5800            event: &objc2_app_kit::NSEvent,
5801        ) -> Option<Retained<NSMenu>> {
5802            ffi_guard::contain(None, || {
5803                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
5804                let row = unsafe { self.rowAtPoint(point) };
5805                let provider = if row >= 0 {
5806                    unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
5807                        .and_then(|cell| list_row_menu_provider(&cell))
5808                } else {
5809                    None
5810                };
5811                match provider {
5812                    Some((view, provider)) => {
5813                        let point = view.convertPoint_fromView(
5814                            unsafe { event.locationInWindow() }, None,
5815                        );
5816                        let items = provider(day_spec::Point::new(point.x, point.y));
5817                        if items.is_empty() {
5818                            None
5819                        } else {
5820                            Some(build_ns_menu(self.mtm(), "", &items))
5821                        }
5822                    }
5823                    None => unsafe { msg_send![super(self), menuForEvent: event] },
5824                }
5825            })
5826        }
5827
5828        /// Host-drawn separators (`ListProps::separators`) skip supplementary rows: no line
5829        /// above or below a list's header, footer, empty state or padding (docs/list.md).
5830        #[unsafe(method(drawGridInClipRect:))]
5831        fn draw_grid_in_clip_rect(&self, clip: NSRect) {
5832            ffi_guard::contain((), || {
5833                let data = unsafe { self.target() }
5834                    .and_then(|t| t.downcast::<DayListData>().ok())
5835                    .filter(|d| d.ivars().supplements.get());
5836                let Some(data) = data else {
5837                    let _: () = unsafe { msg_send![super(self), drawGridInClipRect: clip] };
5838                    return;
5839                };
5840                if unsafe { self.gridStyleMask() }.is_empty() {
5841                    return;
5842                }
5843                let rows = unsafe { self.numberOfRows() };
5844                let shown = unsafe { self.rowsInRect(clip) };
5845                unsafe { self.gridColor() }.setFill();
5846                for row in shown.location..shown.location + shown.length {
5847                    let row = row as isize;
5848                    if data.is_supplement(row) || (row + 1 < rows && data.is_supplement(row + 1)) {
5849                        continue;
5850                    }
5851                    let rect = unsafe { self.rectOfRow(row) };
5852                    objc2_app_kit::NSBezierPath::fillRect(NSRect::new(
5853                        NSPoint::new(clip.origin.x, rect.origin.y + rect.size.height - 1.0),
5854                        NSSize::new(clip.size.width, 1.0),
5855                    ));
5856                }
5857            });
5858        }
5859
5860        #[unsafe(method(becomeFirstResponder))]
5861        fn become_first_responder(&self) -> bool {
5862            let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
5863            if accepted {
5864                self.report_focus(true);
5865            }
5866            accepted
5867        }
5868
5869        #[unsafe(method(resignFirstResponder))]
5870        fn resign_first_responder(&self) -> bool {
5871            let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
5872            if accepted {
5873                self.report_focus(false);
5874            }
5875            accepted
5876        }
5877
5878        #[unsafe(method(keyDown:))]
5879        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
5880            ffi_guard::contain((), || {
5881                let key = unsafe { event.keyCode() };
5882                if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
5883                    let row = unsafe { self.selectedRow() };
5884                    if row >= 0 && let Some(target) = unsafe { self.target() } {
5885                        let _: () = unsafe { msg_send![&*target, activateRow: self] };
5886                        return;
5887                    }
5888                }
5889                // What a key scrolls is the reader's scroll (docs/list.md "Following the
5890                // end"); a page key or Home/End also stops a scroll the app asked for.
5891                let data = unsafe { self.target() }
5892                    .and_then(|t| t.downcast::<DayListData>().ok());
5893                if let Some(data) = &data {
5894                    if PAGE_KEYS.contains(&key)
5895                        && let Some(scroll) = self.enclosingScrollView()
5896                    {
5897                        scroll::stop_clip_animation(&scroll);
5898                    }
5899                    data.ivars().input.set(true);
5900                }
5901                let _: () = unsafe { msg_send![super(self), keyDown: event] };
5902                if let Some(data) = &data {
5903                    data.ivars().input.set(false);
5904                }
5905            });
5906        }
5907
5908        /// AppKit updates the visible rows here (`NSTableRowData updateVisibleRowViews`): a
5909        /// change of rows that arrives meanwhile, from a bind or an event pumped from inside
5910        /// the pass, is held until it is over (`RowPass`).
5911        #[unsafe(method(layout))]
5912        fn layout(&self) {
5913            let _pass = RowPass::enter();
5914            let _: () = unsafe { msg_send![super(self), layout] };
5915        }
5916
5917        /// A scroll updates the visible rows here, before the next layout (see `layout`).
5918        #[unsafe(method(prepareContentInRect:))]
5919        fn prepare_content_in_rect(&self, rect: NSRect) {
5920            let _pass = RowPass::enter();
5921            let _: () = unsafe { msg_send![super(self), prepareContentInRect: rect] };
5922        }
5923    }
5924);
5925
5926/// The key codes of Home, Page Up, End and Page Down: keys that only scroll a list.
5927const PAGE_KEYS: [u16; 4] = [115, 116, 119, 121];
5928
5929define_class!(
5930    /// A list's scroll view (docs/list.md "Following the end"): what a wheel event scrolls is
5931    /// the reader's scroll, and a notch or the start of a gesture stops a scroll the app asked
5932    /// for. It only watches the events go by, so it asks to keep AppKit's responsive scrolling,
5933    /// which overriding `scrollWheel:` would otherwise turn off.
5934    #[unsafe(super(NSScrollView))]
5935    #[thread_kind = MainThreadOnly]
5936    #[name = "DayListScrollView"]
5937    struct DayListScrollView;
5938    unsafe impl NSObjectProtocol for DayListScrollView {}
5939    impl DayListScrollView {
5940        #[unsafe(method(isCompatibleWithResponsiveScrolling))]
5941        fn compatible_with_responsive_scrolling() -> bool {
5942            true
5943        }
5944
5945        #[unsafe(method(scrollWheel:))]
5946        fn scroll_wheel(&self, event: &NSEvent) {
5947            ffi_guard::contain((), || {
5948                let entry = list_entry(ptr_of(self));
5949                if let Some((table, data)) = &entry {
5950                    let phase = unsafe { event.phase() };
5951                    let notch = phase.is_empty() && unsafe { event.momentumPhase() }.is_empty();
5952                    if notch || phase.contains(objc2_app_kit::NSEventPhase::Began) {
5953                        scroll::stop_clip_animation(self);
5954                    }
5955                    // A notch or a gesture toward the top takes the list from its end, whenever
5956                    // AppKit moves it: responsive scrolling can land a notch on a later turn,
5957                    // after this call, where the move would no longer read as the reader's.
5958                    // Said first, so the viewport report of a move made now comes after it.
5959                    if unsafe { event.scrollingDeltaY() } > 0.0
5960                        && unsafe { self.contentView() }.bounds().origin.y > 0.0
5961                    {
5962                        data.report_reader_leaving(table);
5963                    }
5964                    data.ivars().input.set(true);
5965                    data.ivars().wheel.set(true);
5966                }
5967                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
5968                if let Some((_, data)) = &entry {
5969                    data.ivars().input.set(false);
5970                    data.ivars().wheel.set(false);
5971                }
5972            });
5973        }
5974    }
5975);
5976
5977/// The cell can wrap its decorated row in layout containers. Search only this visible
5978/// cell, not other rows; cloning the provider releases the registry borrow before app code.
5979fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
5980    if let Some(provider) =
5981        CTX_MENU_FNS.with(|t| t.get(std::ptr::from_ref::<NSView>(view) as usize))
5982    {
5983        return Some((view.retain(), provider));
5984    }
5985    view.subviews()
5986        .iter()
5987        .find_map(|view| list_row_menu_provider(&view))
5988}
5989
5990/// Plain labels receive the mouse event before their row does. Resolve the nearest dynamic
5991/// owner without copying providers onto descendants (which would go stale on recycling).
5992/// `Some(None)` means an owner deliberately returned no menu; do not fall through to a parent.
5993#[expect(
5994    clippy::option_option,
5995    reason = "`None` defers to AppKit's own menu while `Some(None)` is an owner's deliberate no-menu answer"
5996)]
5997fn inherited_context_menu(
5998    view: &NSView,
5999    event: &objc2_app_kit::NSEvent,
6000) -> Option<Option<Retained<NSMenu>>> {
6001    let mut current = Some(view.retain());
6002    while let Some(view) = current {
6003        if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
6004            let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
6005            let items = provider(day_spec::Point::new(point.x, point.y));
6006            return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
6007        }
6008        current = unsafe { view.superview() };
6009    }
6010    None
6011}
6012
6013impl DayListView {
6014    fn report_focus(&self, focused: bool) {
6015        ffi_guard::contain((), || {
6016            if let Some(target) = unsafe { self.target() }
6017                && let Some(data) = target.downcast_ref::<DayListData>()
6018            {
6019                emit(data.ivars().node, Event::FocusChanged(focused));
6020            }
6021        });
6022    }
6023}
6024
6025struct ListIvars {
6026    node: NodeId,
6027    /// Injected by `attach_list` once day-core wires the driver.
6028    source: RefCell<Option<ListSource>>,
6029    selectable: std::cell::Cell<bool>,
6030    /// Multi-select mode (docs/list.md): every change reports the FULL selected set.
6031    multi: std::cell::Cell<bool>,
6032    /// Programmatic selection in flight: don't re-emit `SelectionChanged`.
6033    suppress: std::cell::Cell<bool>,
6034    /// The row-token order this table currently displays — the baseline `permutation_moves`
6035    /// diffs a Reload against (docs/list.md: a same-set reorder animates as row moves).
6036    tokens: RefCell<Vec<u64>>,
6037    /// `RowHeight::Automatic` (docs/list.md "Row heights"): each row is as tall as Day laid
6038    /// it, through `tableView:heightOfRow:`. A uniform list never answers that selector, so
6039    /// `NSTableView` keeps its fixed-pitch fast path.
6040    automatic: bool,
6041    /// The list has section headers (docs/list.md "Sections"): AppKit group rows, which float
6042    /// at the top as their section scrolls under them. A header sizes to its content in any
6043    /// list, so a sectioned list answers `tableView:heightOfRow:` even when it is uniform.
6044    sections: bool,
6045    /// The height a header nobody has bound yet is given, like `estimate` for rows.
6046    header_estimate: std::cell::Cell<f64>,
6047    /// Each self-sizing row's height by row token, as Day last laid it. By token, not row: a
6048    /// splice or a drag moves rows without rebinding them.
6049    heights: RefCell<std::collections::HashMap<u64, f64>>,
6050    /// The row token each bound cell shows, so `RowSizeInvalidated` (which names the cell)
6051    /// finds the height it corrects.
6052    cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
6053    /// The height a row nobody has bound yet is given: the last one Day measured, so a list
6054    /// of like rows scrolls without its rows jumping as they arrive.
6055    estimate: std::cell::Cell<f64>,
6056    /// A height pass is posted and not yet run (`post_row_heights` coalesces).
6057    heights_pending: std::cell::Cell<bool>,
6058    /// The list has supplementary rows (docs/list.md "Header, footer and empty state"), which
6059    /// size to their content in any list, so a uniform list with them answers
6060    /// `tableView:heightOfRow:` too. Known once `attach_list` brings the source.
6061    supplements: std::cell::Cell<bool>,
6062    /// Cells AppKit asked for while day-core held its tree borrow, whose bind was skipped;
6063    /// `post_realize_visible_rows` binds them.
6064    unbound: RefCell<std::collections::HashSet<usize>>,
6065    /// A `ListPatch::Splice` being applied: the source row behind each row the table shows
6066    /// between two deltas ([`SpliceRows`]).
6067    splice: RefCell<Option<SpliceRows>>,
6068    /// The reader is scrolling the list live (docs/list.md "Following the end"): between the
6069    /// scroll view's will-start and did-end live scroll notifications for a trackpad or Magic
6070    /// Mouse gesture (its momentum included) or a drag of the scroller. AppKit also starts a
6071    /// live scroll for an animated `pageUp:`/`pageDown:`, but never ends that one, so it is
6072    /// reported once and not held.
6073    live: std::cell::Cell<bool>,
6074    /// A wheel or key event of the reader's is being handled: what it scrolls is theirs.
6075    input: std::cell::Cell<bool>,
6076    /// The scroll view's `scrollWheel:` is handling an event: a live scroll AppKit starts
6077    /// now is a gesture's.
6078    wheel: std::cell::Cell<bool>,
6079    /// A change of rows that arrived while a table was updating its visible rows, held until
6080    /// that pass is over ([`HeldRows`], `DayListData::change_rows`).
6081    held: RefCell<Option<HeldRows>>,
6082    /// The apply of a held change is posted and has not run yet.
6083    held_posted: std::cell::Cell<bool>,
6084    /// A splice or a reload is being applied to the table: a change arriving now is held, and
6085    /// the rows keep the in-flight splice's mapping until it is done.
6086    applying: std::cell::Cell<bool>,
6087}
6088
6089thread_local! {
6090    /// How deep this thread is inside a pass of a list's `NSTableView` over its visible rows:
6091    /// its `layout` or `prepareContentInRect:` (both run `NSTableRowData`'s
6092    /// `updateVisibleRowViews`), a row bind from `tableView:viewForTableColumn:row:`, or the
6093    /// realize pass. A bind flushes Day's pending reactive work, which can change any list's
6094    /// rows; AppKit throws ("can not happen while updating visible rows!") if a row is
6095    /// inserted, removed or moved then, so a change arriving inside a pass is held
6096    /// ([`HeldRows`]).
6097    static LIST_ROW_PASS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
6098}
6099
6100/// One level of [`LIST_ROW_PASS`], left when dropped (a contained panic's unwind included).
6101struct RowPass;
6102
6103impl RowPass {
6104    fn enter() -> Self {
6105        LIST_ROW_PASS.with(|depth| depth.set(depth.get() + 1));
6106        Self
6107    }
6108
6109    /// Whether a list is updating its visible rows on this thread now.
6110    fn active() -> bool {
6111        LIST_ROW_PASS.with(|depth| depth.get() > 0)
6112    }
6113}
6114
6115impl Drop for RowPass {
6116    fn drop(&mut self) {
6117        LIST_ROW_PASS.with(|depth| depth.set(depth.get().saturating_sub(1)));
6118    }
6119}
6120
6121/// The changes of a list's rows that arrived during a pass over its visible rows ([`RowPass`]),
6122/// applied together on the next main-loop turn, or as soon as another patch for the list
6123/// arrives outside a pass, whichever is first. Until then the table shows the rows it had, and
6124/// the delegate answers for each through the held splice's [`SpliceRows`], as it does part way
6125/// through an applied one.
6126struct HeldRows {
6127    /// The sequential deltas of every splice held, in the order they arrived, which apply to the
6128    /// rows the table shows as one splice. `None` once a reload is held: it covers every change
6129    /// before and after it.
6130    deltas: Option<Vec<day_spec::props::RowDelta>>,
6131    /// The tokens of the rows selected last while the change was held, selected after it.
6132    selected: Option<Vec<u64>>,
6133}
6134
6135/// The rows of a table part way through a `ListPatch::Splice`. The source already answers in
6136/// the final state, but `NSTableView` asks about rows as each delta lands (an inserted row's
6137/// height, whether it is a group row, its view), by the index the row has at that moment. A
6138/// sectioned list answered from the final state then sizes and styles a row as whatever row
6139/// ends up at that index: an item row gets a header's height and clips its content.
6140///
6141/// Each row shown is an entry: the rows shown before the splice are entries `0..shown`, and
6142/// each insert adds the next one. Replaying the deltas once up front gives every entry its
6143/// final index, so `source_row` maps a row of any in-between state to the source's row.
6144struct SpliceRows {
6145    /// The entry of each row the table shows now.
6146    entries: Vec<usize>,
6147    /// The source row each entry ends at; `None` for an entry a later delta removes.
6148    finals: Vec<Option<usize>>,
6149    /// The entry the next insert adds.
6150    next: usize,
6151}
6152
6153impl SpliceRows {
6154    /// The rows of a table showing `shown` rows that is about to apply `deltas`, which must
6155    /// fit it ([`splice_fits`]).
6156    fn new(shown: usize, deltas: &[day_spec::props::RowDelta]) -> Self {
6157        let mut replay = Self {
6158            entries: (0..shown).collect(),
6159            finals: Vec::new(),
6160            next: shown,
6161        };
6162        for delta in deltas {
6163            replay.apply(*delta);
6164        }
6165        let mut finals = vec![None; replay.next];
6166        for (row, entry) in replay.entries.iter().enumerate() {
6167            finals[*entry] = Some(row);
6168        }
6169        Self {
6170            entries: (0..shown).collect(),
6171            finals,
6172            next: shown,
6173        }
6174    }
6175
6176    /// Apply one delta, as the table is about to. A delta that does not fit is ignored
6177    /// ([`splice_fits`] has already turned such a splice into a reload).
6178    fn apply(&mut self, delta: day_spec::props::RowDelta) {
6179        use day_spec::props::RowDelta;
6180        let len = self.entries.len();
6181        match delta {
6182            RowDelta::Insert(i) if i <= len => {
6183                self.entries.insert(i, self.next);
6184                self.next += 1;
6185            }
6186            RowDelta::Remove(i) if i < len => {
6187                self.entries.remove(i);
6188            }
6189            RowDelta::Move(from, to) if from < len && to < len => {
6190                let entry = self.entries.remove(from);
6191                self.entries.insert(to, entry);
6192            }
6193            _ => {}
6194        }
6195    }
6196
6197    /// The source row behind the table's row `row` now, `None` for a row the splice removes.
6198    fn source_row(&self, row: usize) -> Option<usize> {
6199        self.entries
6200            .get(row)
6201            .and_then(|entry| self.finals.get(*entry).copied().flatten())
6202    }
6203}
6204
6205define_class!(
6206    #[unsafe(super(NSObject))]
6207    #[thread_kind = MainThreadOnly]
6208    #[name = "DayListData"]
6209    #[ivars = ListIvars]
6210    struct DayListData;
6211
6212    unsafe impl NSObjectProtocol for DayListData {}
6213    unsafe impl NSControlTextEditingDelegate for DayListData {}
6214
6215    impl DayListData {
6216        /// Only a self-sizing list answers `tableView:heightOfRow:`: NSTableView asks that
6217        /// of every row on each reload, and a uniform list's fixed `rowHeight` is the fast
6218        /// path. NSTableView reads this once, at `setDelegate:`, after `automatic` is set.
6219        #[unsafe(method(respondsToSelector:))]
6220        fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
6221            if selector == objc2::sel!(tableView:heightOfRow:)
6222                && !self.ivars().automatic
6223                && !self.ivars().sections
6224                && !self.ivars().supplements.get()
6225            {
6226                false
6227            } else {
6228                unsafe { msg_send![super(self), respondsToSelector: selector] }
6229            }
6230        }
6231
6232        /// The clip view scrolled (the user's scroll or a programmatic one, each step of an
6233        /// animated one) or was resized. A scroll the reader is making is reported as theirs
6234        /// first, so the viewport report that follows tells where they took the list.
6235        #[unsafe(method(listViewportChanged:))]
6236        fn list_viewport_changed(&self, notification: &NSNotification) {
6237            ffi_guard::contain((), || {
6238                if let Some(object) = notification.object()
6239                    && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
6240                    && let Some(document) = clip.documentView()
6241                    && let Some(table) = document.downcast_ref::<NSTableView>() {
6242                    if &*notification.name()
6243                        == unsafe { objc2_app_kit::NSViewBoundsDidChangeNotification }
6244                    {
6245                        self.note_reader_scroll(table);
6246                    }
6247                    self.report_viewport(table);
6248                }
6249            });
6250        }
6251
6252        /// The reader started a live scroll. A scroll the app asked for that is still on its
6253        /// way stops where it is. A gesture or a drag of the scroller (the event AppKit is
6254        /// handling is a gesture's wheel event or a mouse event) holds the list until AppKit
6255        /// ends it; any other live scroll (`pageUp:`, the animation AppKit sometimes runs for a
6256        /// wheel notch on a later turn, neither of which it ever ends) is the reader's from
6257        /// where it starts.
6258        #[unsafe(method(listLiveScrollStarted:))]
6259        fn list_live_scroll_started(&self, notification: &NSNotification) {
6260            ffi_guard::contain((), || {
6261                let Some(object) = notification.object() else { return };
6262                let Some(scroll) = object.downcast_ref::<NSScrollView>() else { return };
6263                scroll::stop_clip_animation(scroll);
6264                let app = NSApplication::sharedApplication(self.mtm());
6265                let held = self.ivars().wheel.get()
6266                    || app.currentEvent().is_some_and(|event| match unsafe { event.r#type() } {
6267                        NSEventType::ScrollWheel => {
6268                            !unsafe { event.phase() }.is_empty()
6269                                || !unsafe { event.momentumPhase() }.is_empty()
6270                        }
6271                        NSEventType::LeftMouseDown | NSEventType::LeftMouseDragged => true,
6272                        _ => false,
6273                    });
6274                if held {
6275                    self.ivars().live.set(true);
6276                } else if let Some(document) = unsafe { scroll.documentView() }
6277                    && let Some(table) = document.downcast_ref::<NSTableView>()
6278                {
6279                    self.report_reader_scroll(table);
6280                }
6281            });
6282        }
6283
6284        /// The live scroll is over, momentum included.
6285        #[unsafe(method(listLiveScrollEnded:))]
6286        fn list_live_scroll_ended(&self, _notification: &NSNotification) {
6287            ffi_guard::contain((), || self.ivars().live.set(false));
6288        }
6289
6290        #[unsafe(method(activateRow:))]
6291        fn activate_row(&self, table: &NSTableView) {
6292            ffi_guard::contain((), || {
6293                let row = unsafe { table.selectedRow() };
6294                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
6295            });
6296        }
6297        #[unsafe(method(doubleClickRow:))]
6298        fn double_click_row(&self, table: &NSTableView) {
6299            ffi_guard::contain((), || {
6300                let row = unsafe { table.clickedRow() };
6301                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
6302            });
6303        }
6304    }
6305
6306    unsafe impl NSTableViewDataSource for DayListData {
6307        #[unsafe(method(numberOfRowsInTableView:))]
6308        fn number_of_rows(&self, _tv: &NSTableView) -> isize {
6309            // Reads the piece's snapshot only (no tree access) — safe even when called
6310            // synchronously from reloadData inside a with_tree borrow. Guarded because
6311            // `len` is a day-core closure.
6312            ffi_guard::contain(0, || {
6313                // Part way through a splice the table shows the rows the deltas so far left.
6314                if let Some(splice) = self.ivars().splice.borrow().as_ref() {
6315                    return splice.entries.len() as isize;
6316                }
6317                self.ivars()
6318                    .source
6319                    .borrow()
6320                    .as_ref()
6321                    .map_or(0, |s| (s.len)() as isize)
6322            })
6323        }
6324
6325        // --- drag-to-reorder (docs/list.md): NSTableView's native drag pipeline. The dragged
6326        // row rides the pasteboard as a private-typed string; `validateDrop` consults the app's
6327        // guard live (the `.gap` feedback style opens the placeholder gap only where the guard
6328        // allows), and `acceptDrop` commits through the sync seam, then animates the native move.
6329
6330        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
6331        fn pasteboard_writer_for_row(
6332            &self,
6333            _tv: &NSTableView,
6334            row: isize,
6335        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
6336            // (Closure body: define_class converts only the TAIL expression, so early `return`s
6337            // must not escape the method itself.)
6338            let make = || {
6339                // Only reorderable lists write drag items — no seam, no drag.
6340                let reorderable = self
6341                    .ivars()
6342                    .source
6343                    .borrow()
6344                    .as_ref()
6345                    .is_some_and(|s| s.reorder.is_some());
6346                // A group row (a section header) never lifts (docs/list.md "Sections").
6347                if !reorderable || row < 0 || self.is_header(row) || self.is_supplement(row) {
6348                    return None;
6349                }
6350                let item = objc2_app_kit::NSPasteboardItem::new();
6351                unsafe {
6352                    item.setString_forType(
6353                        &NSString::from_str(&row.to_string()),
6354                        &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
6355                    );
6356                }
6357                Some(ProtocolObject::from_retained(item))
6358            };
6359            ffi_guard::contain(None, make)
6360        }
6361
6362        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
6363        fn validate_drop(
6364            &self,
6365            tv: &NSTableView,
6366            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
6367            row: isize,
6368            _op: objc2_app_kit::NSTableViewDropOperation,
6369        ) -> objc2_app_kit::NSDragOperation {
6370            // Guarded: `can_move` consults the app's reorder guard closure.
6371            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
6372                let Some((from, len)) = self.drag_context(tv, info) else {
6373                    return objc2_app_kit::NSDragOperation::None;
6374                };
6375                // Normalize to an above insertion point (the gap style's semantics), convert to
6376                // the post-removal target index, and ask the guard.
6377                let ins = row.clamp(0, len as isize) as usize;
6378                let to = insertion_to_target(from, ins, len);
6379                let accepted = self.can_move(from, to);
6380                if accepted < 0 {
6381                    return objc2_app_kit::NSDragOperation::None;
6382                }
6383                let accepted = (accepted as usize).min(len.saturating_sub(1));
6384                if accepted != to {
6385                    // The guard retargeted: move the gap to where the drop would actually land.
6386                    unsafe {
6387                        tv.setDropRow_dropOperation(
6388                            target_to_insertion(from, accepted) as isize,
6389                            objc2_app_kit::NSTableViewDropOperation::Above,
6390                        );
6391                    }
6392                }
6393                objc2_app_kit::NSDragOperation::Move
6394            })
6395        }
6396
6397        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
6398        fn accept_drop(
6399            &self,
6400            tv: &NSTableView,
6401            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
6402            row: isize,
6403            _op: objc2_app_kit::NSTableViewDropOperation,
6404        ) -> bool {
6405            // (Closure body: early `return`s must not escape the define_class method itself.)
6406            let drop = || {
6407                let Some((from, len)) = self.drag_context(tv, info) else {
6408                    return false;
6409                };
6410                let ins = row.clamp(0, len as isize) as usize;
6411                let to = insertion_to_target(from, ins, len);
6412                let accepted = self.can_move(from, to);
6413                if accepted < 0 {
6414                    return false;
6415                }
6416                let accepted = (accepted as usize).min(len.saturating_sub(1));
6417                if accepted == from {
6418                    return true; // dropped back home — nothing to commit
6419                }
6420                // Commit through the sync seam (rotates Day's snapshot, defers the app
6421                // callback), THEN animate the native move — the data source already answers in
6422                // the new order.
6423                let mv = self
6424                    .ivars()
6425                    .source
6426                    .borrow()
6427                    .as_ref()
6428                    .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
6429                let Some(mv) = mv else { return false };
6430                mv(from, accepted);
6431                // Keep the displayed-order cache in step (the commit's echo skips the Reload
6432                // that would otherwise refresh it — see `permutation_moves`).
6433                {
6434                    let mut toks = self.ivars().tokens.borrow_mut();
6435                    if from < toks.len() && accepted < toks.len() {
6436                        let t = toks.remove(from);
6437                        toks.insert(accepted, t);
6438                    }
6439                }
6440                unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
6441                if let Some(scroll) = tv.enclosingScrollView() {
6442                    post_settle_list_drop(ptr_of(&scroll));
6443                }
6444                true
6445            };
6446            // Guarded: the commit runs the seam's move closure into day-core and the app.
6447            ffi_guard::contain(false, drop)
6448        }
6449    }
6450
6451    unsafe impl NSTableViewDelegate for DayListData {
6452        /// A self-sizing row's height (docs/list.md "Row heights"): the height Day laid it at
6453        /// once it has been bound, the running estimate until then. Asked before the row's view
6454        /// exists, often from inside `reloadData` under a day-core borrow, so it reads only this
6455        /// table's own record and the source's token snapshot.
6456        #[unsafe(method(tableView:heightOfRow:))]
6457        fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
6458            ffi_guard::contain(44.0, || {
6459                let ivars = self.ivars();
6460                let header = self.is_header(row);
6461                let supplement = self.is_supplement(row);
6462                // A uniform list: rows keep the fixed pitch, headers and supplementary rows
6463                // size themselves.
6464                if !header && !supplement && !ivars.automatic {
6465                    return unsafe { tv.rowHeight() };
6466                }
6467                let token = self.source_row(row).and_then(|row| {
6468                    ivars
6469                        .source
6470                        .borrow()
6471                        .as_ref()
6472                        .filter(|s| row < (s.len)())
6473                        .map(|s| (s.token_at)(row))
6474                });
6475                token
6476                    .and_then(|t| ivars.heights.borrow().get(&t).copied())
6477                    .unwrap_or_else(|| {
6478                        if header {
6479                            ivars.header_estimate.get()
6480                        } else if supplement && !ivars.automatic {
6481                            unsafe { tv.rowHeight() }
6482                        } else {
6483                            ivars.estimate.get()
6484                        }
6485                    })
6486            })
6487        }
6488
6489        /// Section headers are AppKit group rows (docs/list.md "Sections"): drawn in the
6490        /// group style, spanning the row, and floated over their section by
6491        /// `floatsGroupRows`.
6492        #[unsafe(method(tableView:isGroupRow:))]
6493        fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
6494            ffi_guard::contain(false, || self.is_header(row))
6495        }
6496
6497        /// A header or a supplementary row is not an item: clicks and arrow keys pass over it,
6498        /// and it never shows a selection.
6499        #[unsafe(method(tableView:shouldSelectRow:))]
6500        fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
6501            ffi_guard::contain(true, || !self.is_header(row) && !self.is_supplement(row))
6502        }
6503
6504        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
6505        fn view_for_row(
6506            &self,
6507            tv: &NSTableView,
6508            _col: Option<&NSTableColumn>,
6509            row: isize,
6510        ) -> Option<Retained<NSView>> {
6511            // Guarded: `bind_row` builds the app's row content.
6512            ffi_guard::contain(None, || {
6513                // The table is updating its visible rows, and the bind below flushes Day's
6514                // pending reactive work: a change of rows it makes is held (`RowPass`).
6515                let _pass = RowPass::enter();
6516                let mtm = self.mtm();
6517                // Headers and supplementary rows pool apart from rows, so a recycled cell keeps
6518                // its kind and rebinds.
6519                let ident = NSString::from_str(if self.is_header(row) {
6520                    DAY_HEADER_CELL
6521                } else if self.is_supplement(row) {
6522                    DAY_EXTRA_CELL
6523                } else {
6524                    DAY_ROW_CELL
6525                });
6526                // Recycle a cell view if one is free; else make a fresh flipped container.
6527                let cell: Retained<NSView> =
6528                    unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
6529                        let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
6530                        unsafe { v.setIdentifier(Some(&ident)) };
6531                        v
6532                    });
6533                // Day builds row content the first time it sees this cell, and rebinds
6534                // (slot-write) when the cell is recycled. NSTableView calls this outside
6535                // reloadData's stack, so the re-entry into with_tree is safe.
6536                let source = self.ivars().source.borrow().clone();
6537                // A row a splice in flight is about to remove keeps the cell it has.
6538                if let Some(source) = source
6539                    && let Some(index) = self.source_row(row)
6540                {
6541                    let raw = Retained::as_ptr(&cell) as RawHandle;
6542                    // Under day-core's borrow (a splice's insert, a snapshot) the bind is
6543                    // skipped; remember the cell so the realize pass binds it.
6544                    let busy = day_core::try_with_tree(|_| ()).is_none();
6545                    (source.bind_row)(index, raw);
6546                    if busy {
6547                        self.ivars().unbound.borrow_mut().insert(raw as usize);
6548                    } else {
6549                        self.ivars().unbound.borrow_mut().remove(&(raw as usize));
6550                        self.note_row_height(tv, &source, row, raw);
6551                    }
6552                }
6553                Some(cell)
6554            })
6555        }
6556
6557        #[unsafe(method(tableView:didRemoveRowView:forRow:))]
6558        fn did_remove_row_view(
6559            &self,
6560            _tv: &NSTableView,
6561            row_view: &objc2_app_kit::NSTableRowView,
6562            _row: isize,
6563        ) {
6564            // The row went back to the reuse pool (a reload dropping it past a shrunk source, a
6565            // scroll): clear its day element ids so it stops answering lookups, as the tree's
6566            // `outlineView:didRemoveRowView:forRow:` does. Deferred, since this fires inside
6567            // reload stacks that hold the day-core borrow, and re-checked: a cell the same
6568            // turn's reload already reused has a window again, and its fresh ids must survive.
6569            ffi_guard::contain((), || {
6570                let Some(cell) = row_view.subviews().iter().find(|sub| {
6571                    sub.identifier()
6572                        .is_some_and(|i| {
6573                            let i = i.to_string();
6574                            i == DAY_ROW_CELL || i == DAY_HEADER_CELL || i == DAY_EXTRA_CELL
6575                        })
6576                }) else {
6577                    return;
6578                };
6579                // Raw +1 pointers across the post (the closure must be Send, which Retained is
6580                // not; everything stays on the main thread). AppKit may free a removed row view.
6581                let cell = Retained::into_raw(cell) as usize;
6582                let Some(this) = (unsafe {
6583                    Retained::retain(std::ptr::from_ref::<DayListData>(self).cast_mut())
6584                }) else {
6585                    return;
6586                };
6587                let this = Retained::into_raw(this) as usize;
6588                <AppKit as Platform>::post(Box::new(move || {
6589                    // Reclaim both +1s first, so every early return balances them.
6590                    let this = unsafe { Retained::from_raw(this as *mut DayListData) };
6591                    let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
6592                    let (Some(this), Some(cell)) = (this, cell) else {
6593                        return;
6594                    };
6595                    if cell.window().is_some() {
6596                        return; // reused already: its ids are the live row's
6597                    }
6598                    let recycle = this
6599                        .ivars()
6600                        .source
6601                        .borrow()
6602                        .as_ref()
6603                        .map(|s| s.recycle.clone());
6604                    if let Some(recycle) = recycle {
6605                        recycle(Retained::as_ptr(&cell) as RawHandle);
6606                    }
6607                }));
6608            });
6609        }
6610
6611        #[unsafe(method(tableViewSelectionDidChange:))]
6612        fn selection_did_change(&self, notification: &NSNotification) {
6613            ffi_guard::contain((), || {
6614                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
6615                    return;
6616                }
6617                let Some(obj) = (unsafe { notification.object() }) else {
6618                    return;
6619                };
6620                let Ok(tv) = obj.downcast::<NSTableView>() else {
6621                    return;
6622                };
6623                if self.ivars().multi.get() {
6624                    // Multi-select: report the FULL set (ascending; empty = cleared).
6625                    let idx = unsafe { tv.selectedRowIndexes() };
6626                    let mut rows = Vec::with_capacity(idx.count());
6627                    let mut i = idx.firstIndex();
6628                    while i != objc2_foundation::NSNotFound as usize {
6629                        rows.push(i as i64);
6630                        i = unsafe { idx.indexGreaterThanIndex(i) };
6631                    }
6632                    emit(self.ivars().node, Event::SelectionSet(rows));
6633                } else {
6634                    let row = unsafe { tv.selectedRow() };
6635                    if row >= 0 {
6636                        emit(self.ivars().node, Event::SelectionChanged(row as i64));
6637                    } else {
6638                        // CLEARED. `selectedRow()` answers -1, which is not a row, so there is
6639                        // nothing for `SelectionChanged` to carry and nothing for `on_select` to
6640                        // be called with — but the app still has to hear about it, or a detail
6641                        // pane goes on showing the row the user just deselected. The empty set is
6642                        // how that is said (`on_selection`, docs/list.md); reporting nothing was
6643                        // a silent contract break, since single-selection backends are documented
6644                        // as firing it with a one-element OR EMPTY set.
6645                        emit(self.ivars().node, Event::SelectionSet(Vec::new()));
6646                    }
6647                }
6648            });
6649        }
6650
6651        // --- swipe actions (docs/list.md): NSTableView's row-action pipeline. AppKit calls
6652        // this as the two-finger swipe starts, so the offer reflects the row's state at
6653        // GESTURE time; a full swipe across activates the first action (AppKit's own
6654        // full-slide behavior). The handler commits through the seam, which defers the app's
6655        // callback to the event drain.
6656        #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
6657        fn row_actions_for_row(
6658            &self,
6659            tv: &NSTableView,
6660            row: isize,
6661            edge: objc2_app_kit::NSTableRowActionEdge,
6662        ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
6663            // Guarded: `actions_at` runs the app's provider closure.
6664            ffi_guard::contain(NSArray::new(), || {
6665                let sw = self
6666                    .ivars()
6667                    .source
6668                    .borrow()
6669                    .as_ref()
6670                    .and_then(|s| s.swipe.clone());
6671                let Some(sw) = sw else {
6672                    return NSArray::new();
6673                };
6674                if row < 0 {
6675                    return NSArray::new();
6676                }
6677                // AppKit's Leading/Trailing already speak reading direction, same as ours.
6678                let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
6679                    day_spec::SwipeEdge::Leading
6680                } else {
6681                    day_spec::SwipeEdge::Trailing
6682                };
6683                let offer = (sw.actions_at)(row as usize, day_edge);
6684                let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
6685                    .iter()
6686                    .enumerate()
6687                    .map(|(i, a)| {
6688                        let style = if a.destructive {
6689                            objc2_app_kit::NSTableViewRowActionStyle::Destructive
6690                        } else {
6691                            objc2_app_kit::NSTableViewRowActionStyle::Regular
6692                        };
6693                        let perform = sw.perform.clone();
6694                        // Retained only for the swipe session: AppKit releases the actions
6695                        // (and this block) when the revealed buttons close.
6696                        let table = tv.retain();
6697                        let handler = block2::RcBlock::new(
6698                            move |_action: std::ptr::NonNull<
6699                                objc2_app_kit::NSTableViewRowAction,
6700                            >,
6701                                  row: isize| {
6702                                ffi_guard::contain((), || {
6703                                    perform(row as usize, day_edge, i);
6704                                    // A button press leaves the buttons revealed; close
6705                                    // them (a full slide already closed itself).
6706                                    unsafe { table.setRowActionsVisible(false) };
6707                                });
6708                            },
6709                        );
6710                        let action =
6711                            objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
6712                                style,
6713                                &NSString::from_str(&a.label),
6714                                &handler,
6715                            );
6716                        if let Some(t) = a.tint {
6717                            unsafe { action.setBackgroundColor(Some(&color::nsink(t))) };
6718                        }
6719                        // Glyph above the label — the Mail row-action look. The SF symbol
6720                        // resolves per OS release; an unknown name yields no image and the
6721                        // button keeps its label alone.
6722                        if let Some(sym) = a.symbol {
6723                            let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
6724                                &NSString::from_str(day_spec::sf_symbol_name(sym)),
6725                                None,
6726                            );
6727                            if let Some(img) = img {
6728                                unsafe { action.setImage(Some(&img)) };
6729                            }
6730                        }
6731                        action
6732                    })
6733                    .collect();
6734                NSArray::from_retained_slice(&actions)
6735            })
6736        }
6737    }
6738);
6739
6740impl DayListData {
6741    fn new(
6742        mtm: MainThreadMarker,
6743        node: NodeId,
6744        selectable: bool,
6745        multi: bool,
6746        automatic: bool,
6747        sections: bool,
6748    ) -> Retained<Self> {
6749        let this = Self::alloc(mtm).set_ivars(ListIvars {
6750            node,
6751            source: RefCell::new(None),
6752            selectable: std::cell::Cell::new(selectable),
6753            multi: std::cell::Cell::new(multi),
6754            suppress: std::cell::Cell::new(false),
6755            tokens: RefCell::new(Vec::new()),
6756            automatic,
6757            sections,
6758            header_estimate: std::cell::Cell::new(28.0),
6759            heights: RefCell::new(std::collections::HashMap::new()),
6760            cell_tokens: RefCell::new(std::collections::HashMap::new()),
6761            estimate: std::cell::Cell::new(44.0),
6762            heights_pending: std::cell::Cell::new(false),
6763            supplements: std::cell::Cell::new(false),
6764            unbound: RefCell::new(std::collections::HashSet::new()),
6765            splice: RefCell::new(None),
6766            live: std::cell::Cell::new(false),
6767            input: std::cell::Cell::new(false),
6768            wheel: std::cell::Cell::new(false),
6769            held: RefCell::new(None),
6770            held_posted: std::cell::Cell::new(false),
6771            applying: std::cell::Cell::new(false),
6772        });
6773        unsafe { msg_send![super(this), init] }
6774    }
6775
6776    /// A row was just bound to `cell`: when it sizes itself (a self-sizing list's row, a
6777    /// header, a supplementary row), record the height Day laid it at, and if the table drew
6778    /// the row at another height (the estimate, or the row's old content), correct it on the
6779    /// next turn. Not here: this runs inside `NSTableView`'s own tiling.
6780    fn note_row_height(
6781        &self,
6782        table: &NSTableView,
6783        source: &ListSource,
6784        row: isize,
6785        cell: RawHandle,
6786    ) {
6787        let header = self.is_header(row);
6788        let supplement = self.is_supplement(row);
6789        if !self.ivars().automatic && !header && !supplement {
6790            return;
6791        }
6792        let height = (source.cell_height)(cell);
6793        let Some(index) = self.source_row(row).filter(|_| height > 0.0) else {
6794            return;
6795        };
6796        let token = (source.token_at)(index);
6797        self.ivars()
6798            .cell_tokens
6799            .borrow_mut()
6800            .insert(cell as usize, token);
6801        self.ivars().heights.borrow_mut().insert(token, height);
6802        // A supplementary row is one of a kind: its height says nothing about the rows'.
6803        if header {
6804            self.ivars().header_estimate.set(height);
6805        } else if !supplement {
6806            self.ivars().estimate.set(height);
6807        }
6808        let drawn = unsafe { table.rectOfRow(row) }.size.height;
6809        if (drawn - height).abs() > 0.5 {
6810            self.post_row_heights(table);
6811        }
6812    }
6813
6814    /// The source's row behind the table's row `row`: the same index, except part way through a
6815    /// splice ([`SpliceRows`]). `None` for no row, or one the splice in flight removes.
6816    fn source_row(&self, row: isize) -> Option<usize> {
6817        let row = usize::try_from(row).ok()?;
6818        match self.ivars().splice.borrow().as_ref() {
6819            Some(splice) => splice.source_row(row),
6820            None => Some(row),
6821        }
6822    }
6823
6824    /// Whether display row `row` is a section header (docs/list.md "Sections").
6825    fn is_header(&self, row: isize) -> bool {
6826        self.source_row(row).is_some_and(|row| {
6827            self.ivars()
6828                .source
6829                .borrow()
6830                .as_ref()
6831                .and_then(|s| s.is_header.clone())
6832                .is_some_and(|is_header| is_header(row))
6833        })
6834    }
6835
6836    /// Whether `deltas` apply to the rows `table` shows and leave the source's row count
6837    /// ([`splice_fits`]).
6838    fn splice_fits(&self, table: &NSTableView, deltas: &[day_spec::props::RowDelta]) -> bool {
6839        let shown = unsafe { table.numberOfRows() }.max(0) as usize;
6840        let now = self
6841            .ivars()
6842            .source
6843            .borrow()
6844            .as_ref()
6845            .map_or(0, |s| (s.len)());
6846        splice_fits(shown, deltas, now)
6847    }
6848
6849    /// Reload every row in place of a splice that cannot apply: the selection follows its rows
6850    /// by token and the viewport stays where it was (clamped to the new content).
6851    fn reload_keeping_offset(&self, table: &NSTableView) {
6852        let selected = unsafe { table.selectedRowIndexes() };
6853        let tokens: Vec<u64> = self
6854            .ivars()
6855            .tokens
6856            .borrow()
6857            .iter()
6858            .enumerate()
6859            .filter(|(row, _)| selected.containsIndex(*row))
6860            .map(|(_, token)| *token)
6861            .collect();
6862        let scroll = table.enclosingScrollView();
6863        let origin = scroll
6864            .as_ref()
6865            .map(|s| unsafe { s.contentView() }.bounds().origin);
6866        self.ivars().suppress.set(true);
6867        unsafe { table.reloadData() };
6868        if let Some(source) = self.ivars().source.borrow().as_ref() {
6869            let n = (source.len)();
6870            *self.ivars().tokens.borrow_mut() = (0..n).map(|i| (source.token_at)(i)).collect();
6871        }
6872        let restored = objc2_foundation::NSMutableIndexSet::new();
6873        for (row, token) in self.ivars().tokens.borrow().iter().enumerate() {
6874            if tokens.contains(token) {
6875                restored.addIndex(row);
6876            }
6877        }
6878        unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
6879        self.ivars().suppress.set(false);
6880        if let (Some(scroll), Some(origin)) = (scroll, origin) {
6881            let clip = unsafe { scroll.contentView() };
6882            if clip.bounds().origin != origin {
6883                scroll::scroll_clip_to(&scroll, origin, false, None);
6884            }
6885        }
6886    }
6887
6888    /// Apply a change the source made to its rows: `deltas` for a `ListPatch::Splice`, `None`
6889    /// for a `Reload`. Held instead ([`HeldRows`]) while a list is updating its visible rows
6890    /// ([`RowPass`]), where AppKit throws on a row inserted, removed or moved, or while this
6891    /// table is applying another change, whose row indexes the new one would shift. Held
6892    /// changes apply on the next main-loop turn (`key` is the list's handle), in order.
6893    fn change_rows(
6894        &self,
6895        key: usize,
6896        table: &NSTableView,
6897        deltas: Option<&[day_spec::props::RowDelta]>,
6898    ) {
6899        let applying = self.ivars().applying.get();
6900        if !RowPass::active() && !applying {
6901            match deltas {
6902                Some(deltas) => self.splice_rows(table, deltas),
6903                None => self.reload_rows(table),
6904            }
6905            return;
6906        }
6907        {
6908            let mut held = self.ivars().held.borrow_mut();
6909            let held = held.get_or_insert_with(|| HeldRows {
6910                deltas: Some(Vec::new()),
6911                selected: None,
6912            });
6913            // Sequential deltas compose by concatenation; a reload covers everything.
6914            match (deltas, held.deltas.as_mut()) {
6915                (Some(deltas), Some(all)) => all.extend_from_slice(deltas),
6916                _ => held.deltas = None,
6917            }
6918        }
6919        // Part way through a splice its own mapping answers; the held one is mapped once the
6920        // splice is done.
6921        if !applying {
6922            self.map_held(table);
6923        }
6924        self.post_held(key);
6925    }
6926
6927    /// `ListPatch::Selected`: select `rows` now, or, while a change of rows is held, once it
6928    /// has landed. A held selection is kept by row token, since the rows it names may move
6929    /// with a change held after it.
6930    fn select(&self, table: &NSTableView, rows: &[usize]) {
6931        if self.ivars().held.borrow().is_none() {
6932            self.select_rows(table, rows);
6933            return;
6934        }
6935        let tokens: Vec<u64> =
6936            self.ivars()
6937                .source
6938                .borrow()
6939                .as_ref()
6940                .map_or_else(Vec::new, |source| {
6941                    let n = (source.len)();
6942                    rows.iter()
6943                        .filter(|row| **row < n)
6944                        .map(|row| (source.token_at)(*row))
6945                        .collect()
6946                });
6947        if let Some(held) = self.ivars().held.borrow_mut().as_mut() {
6948            held.selected = Some(tokens);
6949        }
6950    }
6951
6952    /// Point the rows the table shows at the source's while a change is held: through the held
6953    /// splice ([`SpliceRows`], as part way through an applied one), or each at its own index
6954    /// while a reload is held.
6955    fn map_held(&self, table: &NSTableView) {
6956        let shown = unsafe { table.numberOfRows() }.max(0) as usize;
6957        let map = self
6958            .ivars()
6959            .held
6960            .borrow()
6961            .as_ref()
6962            .and_then(|held| held.deltas.as_ref())
6963            .map(|deltas| SpliceRows::new(shown, deltas));
6964        *self.ivars().splice.borrow_mut() = map;
6965    }
6966
6967    /// Apply the held change on the next main-loop turn, once (coalesced).
6968    fn post_held(&self, key: usize) {
6969        if self.ivars().held_posted.replace(true) {
6970            return;
6971        }
6972        <AppKit as Platform>::post(Box::new(move || {
6973            let Some((table, data)) = list_entry(key) else {
6974                return;
6975            };
6976            data.ivars().held_posted.set(false);
6977            if RowPass::active() || data.ivars().applying.get() {
6978                // A main loop run from inside a pass: come back once it is over.
6979                data.post_held(key);
6980            } else {
6981                data.apply_held(&table);
6982            }
6983        }));
6984    }
6985
6986    /// Apply the change held through a pass over the rows ([`HeldRows`]), then the selection
6987    /// asked for meanwhile. Nothing while a pass or another change is under way: the posted
6988    /// apply comes back for it.
6989    fn apply_held(&self, table: &NSTableView) {
6990        if RowPass::active() || self.ivars().applying.get() {
6991            return;
6992        }
6993        let Some(held) = self.ivars().held.borrow_mut().take() else {
6994            return;
6995        };
6996        // The table answers for its own rows again, then takes the change.
6997        self.ivars().splice.borrow_mut().take();
6998        match &held.deltas {
6999            Some(deltas) => self.splice_rows(table, deltas),
7000            None => self.reload_rows(table),
7001        }
7002        if let Some(tokens) = held.selected {
7003            let rows: Vec<usize> =
7004                self.ivars()
7005                    .source
7006                    .borrow()
7007                    .as_ref()
7008                    .map_or_else(Vec::new, |source| {
7009                        (0..(source.len)())
7010                            .filter(|row| tokens.contains(&(source.token_at)(*row)))
7011                            .collect()
7012                    });
7013            self.select_rows(table, &rows);
7014        }
7015        if let Some(scroll) = table.enclosingScrollView() {
7016            post_realize_visible_rows(ptr_of(&scroll));
7017        }
7018    }
7019
7020    /// `ListPatch::Splice`: the set changed by exactly these deltas, so animate each row in,
7021    /// out, or across, the thing a reload cannot express. Indexes are sequential, so each delta
7022    /// gets its own begin/endUpdates batch (`NSTableView`'s combined batch semantics
7023    /// re-interpret indexes; one-at-a-time stays literal).
7024    fn splice_rows(&self, table: &NSTableView, deltas: &[day_spec::props::RowDelta]) {
7025        use objc2_app_kit::NSTableViewAnimationOptions;
7026        if !self.splice_fits(table, deltas) {
7027            // The deltas do not start from the rows the table shows (a change the table
7028            // missed): a batch would index rows that are not there. Reload, keeping the
7029            // viewport where it is.
7030            log::warn!(
7031                "day-toolkit-appkit: a list splice of {} rows does not fit the {} rows shown; reloading",
7032                deltas.len(),
7033                unsafe { table.numberOfRows() }
7034            );
7035            let applying = self.ivars().applying.replace(true);
7036            self.reload_keeping_offset(table);
7037            self.ivars().applying.set(applying);
7038            self.map_held(table);
7039            return;
7040        }
7041        // Past a few dozen rows a splice is a bulk change (an append of a page, a filter):
7042        // applied without animation, in one zero-length group.
7043        let quiet = deltas.len() > SPLICE_ANIMATED_MAX;
7044        let (insert, remove) = if quiet {
7045            (
7046                NSTableViewAnimationOptions::EffectNone,
7047                NSTableViewAnimationOptions::EffectNone,
7048            )
7049        } else {
7050            (
7051                NSTableViewAnimationOptions::SlideDown,
7052                NSTableViewAnimationOptions::SlideUp,
7053            )
7054        };
7055        if quiet {
7056            NSAnimationContext::beginGrouping();
7057            NSAnimationContext::currentContext().setDuration(0.0);
7058        }
7059        // While the deltas land, the delegate answers for the rows each one leaves, not the
7060        // source's final rows (`SpliceRows`), and a change arriving meanwhile is held.
7061        let shown = unsafe { table.numberOfRows() }.max(0) as usize;
7062        *self.ivars().splice.borrow_mut() = Some(SpliceRows::new(shown, deltas));
7063        {
7064            let applying = self.ivars().applying.replace(true);
7065            let _done = std::mem::DropGuard::new((), |()| {
7066                self.ivars().applying.set(applying);
7067            });
7068            for d in deltas {
7069                if let Some(splice) = self.ivars().splice.borrow_mut().as_mut() {
7070                    splice.apply(*d);
7071                }
7072                unsafe {
7073                    table.beginUpdates();
7074                    match d {
7075                        day_spec::props::RowDelta::Insert(i) => table
7076                            .insertRowsAtIndexes_withAnimation(
7077                                &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
7078                                insert,
7079                            ),
7080                        day_spec::props::RowDelta::Remove(i) => table
7081                            .removeRowsAtIndexes_withAnimation(
7082                                &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
7083                                remove,
7084                            ),
7085                        day_spec::props::RowDelta::Move(from, to) => {
7086                            table.moveRowAtIndex_toIndex(*from as isize, *to as isize);
7087                        }
7088                    }
7089                    table.endUpdates();
7090                }
7091            }
7092        }
7093        self.ivars().splice.borrow_mut().take();
7094        if quiet {
7095            NSAnimationContext::endGrouping();
7096        }
7097        // The displayed order matches the source again: refresh the cache a committed drag
7098        // keeps in step and `permutation_moves` compares, or the next Reload finds a stale
7099        // length and reloads flat instead of animating.
7100        if let Some(source) = self.ivars().source.borrow().as_ref() {
7101            let n = (source.len)();
7102            *self.ivars().tokens.borrow_mut() = (0..n).map(|i| (source.token_at)(i)).collect();
7103        }
7104        // A change that arrived while the deltas landed now maps the rows shown.
7105        self.map_held(table);
7106    }
7107
7108    /// `ListPatch::Reload`. `NSTableView`'s `reloadData` clears the selection of this view-based
7109    /// source, so the selection is kept by identity, not index, across refreshes and reorders;
7110    /// removed items leave it without selecting their successor.
7111    fn reload_rows(&self, table: &NSTableView) {
7112        let selected = unsafe { table.selectedRowIndexes() };
7113        let tokens: Vec<u64> = self
7114            .ivars()
7115            .tokens
7116            .borrow()
7117            .iter()
7118            .enumerate()
7119            .filter(|(row, _)| selected.containsIndex(*row))
7120            .map(|(_, token)| *token)
7121            .collect();
7122        self.ivars().suppress.set(true);
7123        {
7124            let applying = self.ivars().applying.replace(true);
7125            let _done = std::mem::DropGuard::new((), |()| {
7126                self.ivars().applying.set(applying);
7127            });
7128            // A reload whose rows are the same set in a new order (a shuffle, a programmatic
7129            // sort) animates as native row moves instead of a blink: a `moveRowAtIndex` batch,
7130            // the same animation a drag commit gets. Anything else (insert/remove/content
7131            // change) reloads flat. reloadData queries numberOfRows synchronously (snapshot
7132            // only, no tree) and defers viewForRow, so both paths are safe in with_tree.
7133            if let Some(moves) = self.permutation_moves(table) {
7134                unsafe {
7135                    table.beginUpdates();
7136                    for (from, to) in moves {
7137                        table.moveRowAtIndex_toIndex(from as isize, to as isize);
7138                    }
7139                    table.endUpdates();
7140                }
7141            } else {
7142                unsafe { table.reloadData() };
7143            }
7144        }
7145        let restored = objc2_foundation::NSMutableIndexSet::new();
7146        for (row, token) in self.ivars().tokens.borrow().iter().enumerate() {
7147            if tokens.contains(token) {
7148                restored.addIndex(row);
7149            }
7150        }
7151        unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
7152        self.ivars().suppress.set(false);
7153        self.map_held(table);
7154    }
7155
7156    /// Select `rows` (empty clears the selection) without reporting it back as the reader's
7157    /// selection (`ListPatch::Selected`).
7158    fn select_rows(&self, table: &NSTableView, rows: &[usize]) {
7159        self.ivars().suppress.set(true);
7160        unsafe {
7161            if rows.is_empty() {
7162                table.deselectAll(None);
7163            } else {
7164                let set = objc2_foundation::NSMutableIndexSet::new();
7165                let count = table.numberOfRows().max(0) as usize;
7166                for r in rows.iter().copied().filter(|r| *r < count) {
7167                    set.addIndex(r);
7168                }
7169                table.selectRowIndexes_byExtendingSelection(&set, false);
7170            }
7171        }
7172        self.ivars().suppress.set(false);
7173    }
7174
7175    /// Whether display row `row` is a supplementary row: the list's header, footer, empty state
7176    /// or content padding (docs/list.md "Header, footer and empty state").
7177    fn is_supplement(&self, row: isize) -> bool {
7178        self.source_row(row).is_some_and(|row| {
7179            self.ivars()
7180                .source
7181                .borrow()
7182                .as_ref()
7183                .and_then(|s| s.is_supplement.clone())
7184                .is_some_and(|is_supplement| is_supplement(row))
7185        })
7186    }
7187
7188    /// Tell the source what the list shows (docs/list.md "Visible rows"): the first and last
7189    /// rows with any part in the viewport and the distance from its end to the content's end,
7190    /// where the piece asked for that; the first visible row where it asked for that alone.
7191    /// Nothing while the table and the source disagree on the row count (mid-update) or no row
7192    /// shows. Enqueue-only: safe from inside day-core's borrow.
7193    fn report_viewport(&self, table: &NSTableView) {
7194        let Some(source) = self.ivars().source.borrow().clone() else {
7195            return;
7196        };
7197        let n = (source.len)();
7198        if n == 0 || unsafe { table.numberOfRows() } != n as isize {
7199            return;
7200        }
7201        let visible = table.visibleRect();
7202        let shown = unsafe { table.rowsInRect(visible) };
7203        if let Some(report) = &source.viewport {
7204            let top = visible.origin.y;
7205            let bottom = top + visible.size.height;
7206            let count = shown.length.min(n.saturating_sub(shown.location));
7207            let span = scroll::visible_span(top, bottom, shown.location, count, |row| {
7208                let rect = unsafe { table.rectOfRow(row as isize) };
7209                (rect.origin.y, rect.origin.y + rect.size.height)
7210            });
7211            let Some((first, last)) = span else {
7212                return;
7213            };
7214            let end = unsafe { table.rectOfRow(n as isize - 1) };
7215            report(day_spec::ListViewport {
7216                first,
7217                last,
7218                end_distance: (end.origin.y + end.size.height - bottom).max(0.0),
7219            });
7220        } else if let Some(report) = &source.first_visible {
7221            report(shown.location.min(n - 1));
7222        }
7223    }
7224
7225    /// The clip view moved: when the reader is moving it (a live scroll, or a wheel or key
7226    /// event of theirs being handled), tell the source the scroll is theirs (docs/list.md
7227    /// "Following the end"), before the viewport report that says where it went. Not while
7228    /// the list is at or past its end (the rubber band of a reader pushing at the end): the
7229    /// reader is still at the end, and the report that would say so is the one already sent.
7230    fn note_reader_scroll(&self, table: &NSTableView) {
7231        let ivars = self.ivars();
7232        if ivars.live.get() || ivars.input.get() {
7233            self.report_reader_scroll(table);
7234        }
7235    }
7236
7237    /// Tell the source the reader is moving the list, unless it is at or past its end.
7238    fn report_reader_scroll(&self, table: &NSTableView) {
7239        let rows = unsafe { table.numberOfRows() };
7240        if rows <= 0 {
7241            return;
7242        }
7243        let end = unsafe { table.rectOfRow(rows - 1) };
7244        let visible = table.visibleRect();
7245        if end.origin.y + end.size.height - (visible.origin.y + visible.size.height) > 0.0 {
7246            self.report_reader_leaving(table);
7247        }
7248    }
7249
7250    /// Tell the source the reader is moving the list away from its end, wherever it is now: an
7251    /// event of theirs that will move it there.
7252    fn report_reader_leaving(&self, table: &NSTableView) {
7253        let report = self
7254            .ivars()
7255            .source
7256            .borrow()
7257            .as_ref()
7258            .and_then(|s| s.reader_scroll.clone());
7259        if let Some(report) = report
7260            && unsafe { table.numberOfRows() } > 0
7261        {
7262            report();
7263        }
7264    }
7265
7266    /// `ListPatch::RowSizeInvalidated`: the row in `cell` was re-laid at `height`. Arrives under
7267    /// the day-core borrow, so it only records the height; the table is told after the pass.
7268    fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
7269        let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
7270        if let Some(token) = token {
7271            self.ivars().heights.borrow_mut().insert(token, height);
7272            self.post_row_heights(table);
7273        }
7274    }
7275
7276    /// Tell the table, on the next main-loop turn, about every row near the viewport whose drawn
7277    /// height differs from the one Day laid it at. Coalesced: a pass that re-lays many rows
7278    /// posts one correction.
7279    fn post_row_heights(&self, table: &NSTableView) {
7280        if self.ivars().heights_pending.replace(true) {
7281            return;
7282        }
7283        // Raw +1 pointers across the post (the closure must be Send, which Retained is not;
7284        // everything stays on the main thread).
7285        let Some(this) = (unsafe { Retained::retain(std::ptr::from_ref::<Self>(self).cast_mut()) })
7286        else {
7287            return;
7288        };
7289        let this = Retained::into_raw(this) as usize;
7290        let table = Retained::into_raw(table.retain()) as usize;
7291        <AppKit as Platform>::post(Box::new(move || {
7292            // Reclaim both +1s first, so every early return balances them.
7293            let this = unsafe { Retained::from_raw(this as *mut DayListData) };
7294            let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
7295            let (Some(this), Some(table)) = (this, table) else {
7296                return;
7297            };
7298            this.ivars().heights_pending.set(false);
7299            ffi_guard::contain((), || this.apply_row_heights(&table));
7300        }));
7301    }
7302
7303    fn apply_row_heights(&self, table: &NSTableView) {
7304        // The rows below are the source's: a held change lands first.
7305        self.apply_held(table);
7306        let Some(source) = self.ivars().source.borrow().clone() else {
7307            return;
7308        };
7309        let count = unsafe { table.numberOfRows() }.max(0) as usize;
7310        let shown = unsafe { table.rowsInRect(table.visibleRect()) };
7311        // The viewport and the rows AppKit prepares around it.
7312        let first = shown.location.saturating_sub(8);
7313        let last = (shown.location + shown.length + 8)
7314            .min(count)
7315            .min((source.len)());
7316        let changed = objc2_foundation::NSMutableIndexSet::new();
7317        {
7318            let heights = self.ivars().heights.borrow();
7319            for row in first..last {
7320                if let Some(&height) = heights.get(&(source.token_at)(row)) {
7321                    let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
7322                    if (drawn - height).abs() > 0.5 {
7323                        unsafe { changed.addIndex(row) };
7324                    }
7325                }
7326            }
7327        }
7328        if changed.count() == 0 {
7329            return;
7330        }
7331        // Unanimated: the row takes its content's height, it does not grow into it.
7332        NSAnimationContext::beginGrouping();
7333        NSAnimationContext::currentContext().setDuration(0.0);
7334        unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
7335        NSAnimationContext::endGrouping();
7336        // The content's height changed, and with it the distance to the end.
7337        self.report_viewport(table);
7338    }
7339
7340    /// If this Reload is the same row set in a new order, the incremental `moveRowAtIndex`
7341    /// steps (each `(from, to)` interpreted against the already-moved rows, `NSTableView`'s
7342    /// semantics) that transform the displayed order into the new one — and `None` for
7343    /// anything else (insert/remove/content change/no change), which reloads flat. Always
7344    /// refreshes the displayed-order cache.
7345    ///
7346    /// Every row that changes position must have a REALIZED row view (`table`): moving a
7347    /// viewless row (its old position sat outside the viewport, so it was never bound)
7348    /// animates nothing and leaves the row unbound at its new position — its content, and any
7349    /// element ids inside it, would simply not exist. Such a reorder returns `None` and
7350    /// reloads flat, which realizes and binds the row at its new position.
7351    fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
7352        let source = self.ivars().source.borrow();
7353        let source = source.as_ref()?;
7354        let n = (source.len)();
7355        let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
7356        let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
7357        if old.len() != n || n == 0 || old == new {
7358            return None;
7359        }
7360        let (mut so, mut sn) = (old.clone(), new.clone());
7361        so.sort_unstable();
7362        sn.sort_unstable();
7363        if so != sn {
7364            return None;
7365        }
7366        for i in 0..n {
7367            if old[i] != new[i]
7368                && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
7369            {
7370                return None;
7371            }
7372        }
7373        let mut work = old;
7374        let mut moves = Vec::new();
7375        for i in 0..n {
7376            if work[i] == new[i] {
7377                continue;
7378            }
7379            let j = (i + 1..n).find(|&j| work[j] == new[i])?;
7380            let t = work.remove(j);
7381            work.insert(i, t);
7382            moves.push((j, i));
7383        }
7384        Some(moves)
7385    }
7386
7387    /// The dragged row + current row count for an in-flight LOCAL reorder drag — `None` when the
7388    /// drag came from anywhere but this table (day never accepts foreign drops into a list) or
7389    /// the pasteboard doesn't carry the day row type.
7390    fn drag_context(
7391        &self,
7392        tv: &NSTableView,
7393        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
7394    ) -> Option<(usize, usize)> {
7395        let src = unsafe { info.draggingSource() }?;
7396        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
7397            != std::ptr::from_ref::<NSTableView>(tv).cast::<std::ffi::c_void>()
7398        {
7399            return None;
7400        }
7401        let pb = unsafe { info.draggingPasteboard() };
7402        let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
7403            .to_string()
7404            .parse::<usize>()
7405            .ok()?;
7406        let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
7407        (from < len).then_some((from, len))
7408    }
7409
7410    /// The guard's verdict for `from -> to` (accepted index, or -1), through the sync seam.
7411    fn can_move(&self, from: usize, to: usize) -> i64 {
7412        self.ivars()
7413            .source
7414            .borrow()
7415            .as_ref()
7416            .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
7417            .unwrap_or(-1)
7418    }
7419}
7420
7421/// The reuse identifiers of a list's row cells and its section-header cells.
7422const DAY_ROW_CELL: &str = "day.cell";
7423const DAY_HEADER_CELL: &str = "day.header";
7424/// The reuse identifier of a list's supplementary-row cells (header, footer, empty state,
7425/// content padding), pooled apart so an item row never reuses one.
7426const DAY_EXTRA_CELL: &str = "day.extra";
7427
7428/// The private pasteboard type carrying a dragged day list row's index (local reorder only).
7429const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
7430
7431/// The most row deltas a `ListPatch::Splice` animates; a larger one applies without animation.
7432const SPLICE_ANIMATED_MAX: usize = 64;
7433
7434/// An `NSTableView` drop lands at an INSERTION point (`row` with `.Above` semantics, 0..=len);
7435/// day's seam speaks post-removal target indices. Dropping `from` at insertion `ins`:
7436fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
7437    let to = if ins > from { ins - 1 } else { ins };
7438    to.min(len.saturating_sub(1))
7439}
7440
7441/// Whether sequential row `deltas` (`ListPatch::Splice`) apply to a table showing `shown` rows
7442/// and leave it with `now`, the source's count: every index exists when its delta runs (an
7443/// insert may land one past the end) and the count comes out right. A splice that fails this
7444/// would make `NSTableView` index rows that are not there.
7445fn splice_fits(shown: usize, deltas: &[day_spec::props::RowDelta], now: usize) -> bool {
7446    use day_spec::props::RowDelta;
7447    let mut count = shown;
7448    for delta in deltas {
7449        match *delta {
7450            RowDelta::Insert(i) if i <= count => count += 1,
7451            RowDelta::Remove(i) if i < count => count -= 1,
7452            RowDelta::Move(from, to) if from < count && to < count => {}
7453            _ => return false,
7454        }
7455    }
7456    count == now
7457}
7458
7459/// The inverse, for retargeting the drop gap: where the gap sits for a post-removal target.
7460fn target_to_insertion(from: usize, to: usize) -> usize {
7461    if to > from { to + 1 } else { to }
7462}
7463
7464/// A realized LIST's scroll view ptr → (table, data source) for `attach_list` / update / measure.
7465type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
7466
7467/// Clone a list's (table, data) out of `LIST_STATE` under a SHORT borrow. Every caller then
7468/// talks to AppKit with the map free: table calls that look innocuous (`endUpdates`, a scroll's
7469/// tiling, `viewAtColumn:row:makeIfNecessary:`, even `layoutSubtreeIfNeeded`) can synchronously
7470/// re-enter `viewForRow` → `bind_row` → a flush that tears nodes down — and `release` must be
7471/// able to take its own borrow at that depth. Holding the map across any of them was the
7472/// "`RefCell` already borrowed" contained panic every list walkthrough used to log, 24 a run.
7473fn list_entry(key: usize) -> Option<ListEntry> {
7474    LIST_STATE.with(|m| m.borrow().get(&key).cloned())
7475}
7476
7477// ---------------------------------------------------------------------------
7478// DayTreeData — NSOutlineView data-source + delegate for the hierarchical tree (docs/tree.md)
7479// ---------------------------------------------------------------------------
7480
7481struct TreeIvars {
7482    node: NodeId,
7483    /// Injected by `attach_tree` once day-core wires the driver.
7484    source: RefCell<Option<TreeSource>>,
7485    selectable: std::cell::Cell<bool>,
7486    /// Programmatic selection/disclosure in flight: don't re-emit the event (echo rule).
7487    suppress: std::cell::Cell<bool>,
7488    /// token → its interned `NSNumber`. `NSOutlineView` tracks items (selection, expansion,
7489    /// rowForItem) by object identity/equality, so every query for a token must answer with
7490    /// the same object — which is also what preserves expansion across reloadData.
7491    items: RefCell<HashMap<u64, Retained<NSNumber>>>,
7492}
7493
7494define_class!(
7495    #[unsafe(super(NSObject))]
7496    #[thread_kind = MainThreadOnly]
7497    #[name = "DayTreeData"]
7498    #[ivars = TreeIvars]
7499    struct DayTreeData;
7500
7501    unsafe impl NSObjectProtocol for DayTreeData {}
7502
7503    unsafe impl NSOutlineViewDataSource for DayTreeData {
7504        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
7505        fn number_of_children(
7506            &self,
7507            _ov: &objc2_app_kit::NSOutlineView,
7508            item: Option<&objc2::runtime::AnyObject>,
7509        ) -> isize {
7510            // Reads the piece's snapshot only (no tree access) — safe even when called
7511            // synchronously from reloadData inside a with_tree borrow. Guarded because
7512            // the closures are day-core's.
7513            ffi_guard::contain(0, || {
7514                let parent = item.and_then(Self::token_of_item);
7515                if item.is_some() && parent.is_none() {
7516                    return 0; // not one of ours (stale query racing a reload)
7517                }
7518                self.ivars()
7519                    .source
7520                    .borrow()
7521                    .as_ref()
7522                    .map_or(0, |s| (s.children_len)(parent) as isize)
7523            })
7524        }
7525
7526        #[unsafe(method_id(outlineView:child:ofItem:))]
7527        fn child_of_item(
7528            &self,
7529            _ov: &objc2_app_kit::NSOutlineView,
7530            index: isize,
7531            item: Option<&objc2::runtime::AnyObject>,
7532        ) -> Retained<objc2::runtime::AnyObject> {
7533            // AppKit only asks for children it was told exist, but a stale query racing a
7534            // reload must degrade (token 0, an unmatched identity) rather than panic — an
7535            // unwind here crosses an ObjC frame and aborts.
7536            let token = ffi_guard::contain(0, || {
7537                let parent = item.and_then(Self::token_of_item);
7538                self.ivars()
7539                    .source
7540                    .borrow()
7541                    .as_ref()
7542                    .map_or(0, |s| (s.child_token)(parent, index.max(0) as usize))
7543            });
7544            let ns = self.intern(token);
7545            unsafe { objc2::rc::Retained::cast_unchecked(ns) }
7546        }
7547
7548        #[unsafe(method(outlineView:isItemExpandable:))]
7549        fn is_expandable(
7550            &self,
7551            _ov: &objc2_app_kit::NSOutlineView,
7552            item: &objc2::runtime::AnyObject,
7553        ) -> bool {
7554            ffi_guard::contain(false, || {
7555                let Some(token) = Self::token_of_item(item) else {
7556                    return false;
7557                };
7558                self.ivars()
7559                    .source
7560                    .borrow()
7561                    .as_ref()
7562                    .is_some_and(|s| (s.expandable)(token))
7563            })
7564        }
7565
7566        // --- drag-to-move (docs/tree.md): the dragged node rides the pasteboard as a
7567        // private-typed token string; `validateDrop` consults the guard live (forbidden
7568        // cursor where it denies, including ONTO-a-row drops via childIndex -1), and
7569        // `acceptDrop` commits through the sync seam — the app's own data write reloads.
7570
7571        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
7572        fn pasteboard_writer_for_item(
7573            &self,
7574            _ov: &objc2_app_kit::NSOutlineView,
7575            item: &objc2::runtime::AnyObject,
7576        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
7577            let make = || {
7578                let movable = self
7579                    .ivars()
7580                    .source
7581                    .borrow()
7582                    .as_ref()
7583                    .is_some_and(|s| s.moves.is_some());
7584                let token = Self::token_of_item(item)?;
7585                if !movable {
7586                    return None;
7587                }
7588                let pbitem = objc2_app_kit::NSPasteboardItem::new();
7589                unsafe {
7590                    pbitem.setString_forType(
7591                        &NSString::from_str(&token.to_string()),
7592                        &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
7593                    );
7594                }
7595                Some(ProtocolObject::from_retained(pbitem))
7596            };
7597            ffi_guard::contain(None, make)
7598        }
7599
7600        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
7601        fn validate_drop(
7602            &self,
7603            ov: &objc2_app_kit::NSOutlineView,
7604            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
7605            item: Option<&objc2::runtime::AnyObject>,
7606            child_index: isize,
7607        ) -> objc2_app_kit::NSDragOperation {
7608            ffi_guard::contain(
7609                objc2_app_kit::NSDragOperation::None,
7610                || match Self::drop_proposal(ov, info, item, child_index) {
7611                    Some((token, parent, index)) if self.can_move(token, parent, index) => {
7612                        objc2_app_kit::NSDragOperation::Move
7613                    }
7614                    _ => objc2_app_kit::NSDragOperation::None,
7615                },
7616            )
7617        }
7618
7619        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
7620        fn accept_drop(
7621            &self,
7622            ov: &objc2_app_kit::NSOutlineView,
7623            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
7624            item: Option<&objc2::runtime::AnyObject>,
7625            child_index: isize,
7626        ) -> bool {
7627            let drop = || {
7628                let Some((token, parent, index)) = Self::drop_proposal(ov, info, item, child_index)
7629                else {
7630                    return false;
7631                };
7632                if !self.can_move(token, parent, index) {
7633                    return false;
7634                }
7635                // Commit through the sync seam: defers the app's `on_move`; the app's own
7636                // data write drives the Reload (no native row animation on this path).
7637                let mv = self
7638                    .ivars()
7639                    .source
7640                    .borrow()
7641                    .as_ref()
7642                    .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
7643                let Some(mv) = mv else { return false };
7644                mv(token, parent, index);
7645                true
7646            };
7647            ffi_guard::contain(false, drop)
7648        }
7649    }
7650
7651    unsafe impl NSControlTextEditingDelegate for DayTreeData {}
7652
7653    unsafe impl NSOutlineViewDelegate for DayTreeData {
7654        #[unsafe(method(outlineView:isGroupItem:))]
7655        fn is_group_item(
7656            &self,
7657            _ov: &objc2_app_kit::NSOutlineView,
7658            item: &objc2::runtime::AnyObject,
7659        ) -> bool {
7660            Self::token_of_item(item).is_some_and(|t| {
7661                self.ivars()
7662                    .source
7663                    .borrow()
7664                    .as_ref()
7665                    .is_some_and(|s| (s.section_header)(t))
7666            })
7667        }
7668        #[unsafe(method(outlineView:shouldSelectItem:))]
7669        fn should_select_item(
7670            &self,
7671            _ov: &objc2_app_kit::NSOutlineView,
7672            item: &objc2::runtime::AnyObject,
7673        ) -> bool {
7674            Self::token_of_item(item).is_some_and(|t| {
7675                self.ivars()
7676                    .source
7677                    .borrow()
7678                    .as_ref()
7679                    .is_some_and(|s| !(s.section_header)(t))
7680            })
7681        }
7682
7683        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
7684        fn view_for_item(
7685            &self,
7686            ov: &objc2_app_kit::NSOutlineView,
7687            _col: Option<&NSTableColumn>,
7688            item: &objc2::runtime::AnyObject,
7689        ) -> Option<Retained<NSView>> {
7690            // Guarded: `bind_row` builds the app's row content.
7691            ffi_guard::contain(None, || {
7692                let mtm = self.mtm();
7693                let token = Self::token_of_item(item)?;
7694                let ident = NSString::from_str("day.tree.cell");
7695                // Recycle a cell view if one is free; else make a fresh flipped container
7696                // (DayTreeCell re-lays its Day row at its own width — indentation makes
7697                // every tree cell's width per-row).
7698                let cell: Retained<NSView> =
7699                    unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
7700                        let v: Retained<NSView> =
7701                            Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
7702                        unsafe { v.setIdentifier(Some(&ident)) };
7703                        v
7704                    });
7705                if let Some(source) = self.ivars().source.borrow().as_ref() {
7706                    let raw = Retained::as_ptr(&cell) as RawHandle;
7707                    if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
7708                        unsafe {
7709                            cell.setTextField(None);
7710                        }
7711                    }
7712                    (source.bind_row)(token, raw);
7713                    // Associate the actual Day label with NSTableCellView so AppKit can
7714                    // apply group typography and source-list background styles normally.
7715                    if (source.section_header)(token) {
7716                        fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
7717                            for child in &unsafe { view.subviews() } {
7718                                if let Ok(label) = child.clone().downcast::<NSTextField>() {
7719                                    return Some(label);
7720                                }
7721                                if let Some(label) = label_in(&child) {
7722                                    return Some(label);
7723                                }
7724                            }
7725                            None
7726                        }
7727                        if let Some(label) = label_in(&cell) {
7728                            let cell = cell.downcast_ref::<DayTreeCell>()?;
7729                            unsafe {
7730                                cell.setTextField(Some(&label));
7731                            }
7732                        }
7733                    }
7734                }
7735                Some(cell)
7736            })
7737        }
7738
7739        #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
7740        fn type_select_string(
7741            &self,
7742            _ov: &objc2_app_kit::NSOutlineView,
7743            _col: Option<&NSTableColumn>,
7744            item: &objc2::runtime::AnyObject,
7745        ) -> Option<Retained<NSString>> {
7746            ffi_guard::contain(None, || {
7747                let token = Self::token_of_item(item)?;
7748                let text = self
7749                    .ivars()
7750                    .source
7751                    .borrow()
7752                    .as_ref()
7753                    .map_or_default(|s| (s.type_select_text)(token));
7754                // Empty = this row doesn't participate in type-select.
7755                (!text.is_empty()).then(|| NSString::from_str(&text))
7756            })
7757        }
7758
7759        #[unsafe(method_id(outlineView:rowViewForItem:))]
7760        fn row_view_for_item(
7761            &self,
7762            ov: &objc2_app_kit::NSOutlineView,
7763            _item: &objc2::runtime::AnyObject,
7764        ) -> Retained<objc2_app_kit::NSTableRowView> {
7765            if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
7766                // AppKit owns source-list group backgrounds, floating headers and selection.
7767                unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
7768            } else {
7769                // The rounded-selection row (see DayTreeRowView).
7770                let rv: Retained<DayTreeRowView> =
7771                    unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
7772                Retained::into_super(rv)
7773            }
7774        }
7775
7776        #[unsafe(method(outlineViewSelectionDidChange:))]
7777        fn selection_did_change(&self, notification: &NSNotification) {
7778            ffi_guard::contain((), || {
7779                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
7780                    return;
7781                }
7782                let Some(obj) = (unsafe { notification.object() }) else {
7783                    return;
7784                };
7785                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
7786                    return;
7787                };
7788                // Always the FULL token set (docs/tree.md): a tree cannot speak row indices.
7789                let idx = unsafe { ov.selectedRowIndexes() };
7790                let mut tokens = Vec::with_capacity(idx.count());
7791                let mut i = idx.firstIndex();
7792                while i != objc2_foundation::NSNotFound as usize {
7793                    if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
7794                        && let Some(tok) = Self::token_of_item(&item)
7795                    {
7796                        tokens.push(tok);
7797                    }
7798                    i = unsafe { idx.indexGreaterThanIndex(i) };
7799                }
7800                emit(self.ivars().node, Event::TreeSelection(tokens));
7801            });
7802        }
7803
7804        #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
7805        fn did_remove_row_view(
7806            &self,
7807            ov: &objc2_app_kit::NSOutlineView,
7808            row_view: &objc2_app_kit::NSTableRowView,
7809            _row: isize,
7810        ) {
7811            // The row went back to the reuse pool (a collapse, a reload dropping it): clear
7812            // its day element ids so it stops answering `find_by_id`. DEFERRED — this fires
7813            // inside collapse/reload stacks that hold the day-core borrow — and re-checked:
7814            // a cell already reused by the same turn's reload has a window again, and its
7815            // fresh ids must survive.
7816            ffi_guard::contain((), || {
7817                let mut cell_ptr: Option<usize> = None;
7818                for sub in &row_view.subviews() {
7819                    let is_cell = sub
7820                        .identifier()
7821                        .is_some_and(|i| i.to_string() == "day.tree.cell");
7822                    if is_cell {
7823                        cell_ptr = Some(Retained::as_ptr(&sub) as usize);
7824                    }
7825                }
7826                let Some(cell) = cell_ptr else { return };
7827                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
7828                    return;
7829                };
7830                let key = Retained::as_ptr(&scroll) as usize;
7831                // Carry a RETAIN across the post as a raw +1 pointer (the boxed closure must
7832                // be Send, which Retained is not; we stay on the main thread throughout).
7833                // AppKit is free to dealloc removed row views — a bare pointer died here once.
7834                let retained =
7835                    unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
7836                        as usize;
7837                <AppKit as Platform>::post(Box::new(move || {
7838                    // Reclaim the +1 first, unconditionally — every early return below must
7839                    // still balance the retain.
7840                    let cell_view: Retained<NSView> =
7841                        match unsafe { Retained::from_raw(retained as *mut NSView) } {
7842                            Some(v) => v,
7843                            None => return,
7844                        };
7845                    let recycle = tree_entry(key).and_then(|(_, data)| {
7846                        data.ivars()
7847                            .source
7848                            .borrow()
7849                            .as_ref()
7850                            .map(|s| s.recycle.clone())
7851                    });
7852                    let Some(recycle) = recycle else { return };
7853                    if cell_view.window().is_some() {
7854                        return; // reused already — its ids are the live row's
7855                    }
7856                    recycle(cell as RawHandle);
7857                }));
7858            });
7859        }
7860
7861        #[unsafe(method(outlineViewItemDidExpand:))]
7862        fn item_did_expand(&self, notification: &NSNotification) {
7863            self.report_disclosure(notification, true);
7864        }
7865
7866        #[unsafe(method(outlineViewItemDidCollapse:))]
7867        fn item_did_collapse(&self, notification: &NSNotification) {
7868            self.report_disclosure(notification, false);
7869        }
7870    }
7871);
7872
7873impl DayTreeData {
7874    fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
7875        let this = Self::alloc(mtm).set_ivars(TreeIvars {
7876            node,
7877            source: RefCell::new(None),
7878            selectable: std::cell::Cell::new(selectable),
7879            suppress: std::cell::Cell::new(false),
7880            items: RefCell::new(HashMap::new()),
7881        });
7882        unsafe { msg_send![super(this), init] }
7883    }
7884
7885    /// The same `NSNumber` for a token, every time — `NSOutlineView`'s item identity.
7886    fn intern(&self, token: u64) -> Retained<NSNumber> {
7887        self.ivars()
7888            .items
7889            .borrow_mut()
7890            .entry(token)
7891            .or_insert_with(|| NSNumber::new_u64(token))
7892            .clone()
7893    }
7894
7895    fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
7896        item.downcast_ref::<NSNumber>()
7897            .map(objc2_foundation::NSNumber::as_u64)
7898    }
7899
7900    /// A native disclosure (user click, keyboard left/right) → `Event::TreeExpanded`.
7901    /// Programmatic `TreePatch::Expand` applications are suppressed (the echo rule).
7902    fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
7903        ffi_guard::contain((), || {
7904            if self.ivars().suppress.get() {
7905                return;
7906            }
7907            let token = unsafe { notification.userInfo() }
7908                .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
7909                .and_then(|item| Self::token_of_item(&item));
7910            if let Some(token) = token {
7911                emit(self.ivars().node, Event::TreeExpanded { token, expanded });
7912            }
7913        });
7914    }
7915
7916    /// The full drop proposal — `(dragged token, parent token, index)` — for a LOCAL drag
7917    /// from this outline; `None` for a foreign drag or an unparseable one. `index: None`
7918    /// means "ONTO the parent" (`NSOutlineView`'s childIndex -1, `NSOutlineViewDropOnItemIndex`).
7919    fn drop_proposal(
7920        ov: &objc2_app_kit::NSOutlineView,
7921        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
7922        item: Option<&objc2::runtime::AnyObject>,
7923        child_index: isize,
7924    ) -> Option<(u64, Option<u64>, Option<usize>)> {
7925        let src = unsafe { info.draggingSource() }?;
7926        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
7927            != std::ptr::from_ref::<objc2_app_kit::NSOutlineView>(ov).cast::<std::ffi::c_void>()
7928        {
7929            return None;
7930        }
7931        let pb = unsafe { info.draggingPasteboard() };
7932        let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
7933            .to_string()
7934            .parse::<u64>()
7935            .ok()?;
7936        let parent = match item {
7937            Some(i) => Some(Self::token_of_item(i)?), // a non-token item is not ours
7938            None => None,
7939        };
7940        let index = (child_index >= 0).then_some(child_index as usize);
7941        Some((token, parent, index))
7942    }
7943
7944    /// The guard's live verdict through the sync seam.
7945    fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
7946        self.ivars()
7947            .source
7948            .borrow()
7949            .as_ref()
7950            .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
7951            .is_some_and(|v| v == MoveVerdict::Allow)
7952    }
7953}
7954
7955// DayOutlineView — an NSOutlineView that PINS its width to its clip on every layout pass.
7956// A table sizes itself from its COLUMNS, and the autoresizing mask only tracks deltas, so
7957// any early pass at a different pane width leaves a permanent offset (a 233pt table in a
7958// 220pt pane, whose selection pill then clips mid-corner). Enforcing it in `layout` — not
7959// in occasional deferred posts — closes every window where a stale width could draw.
7960define_class!(
7961    #[unsafe(super(objc2_app_kit::NSOutlineView))]
7962    #[thread_kind = MainThreadOnly]
7963    #[name = "DayOutlineView"]
7964    struct DayOutlineView;
7965
7966    impl DayOutlineView {
7967        #[unsafe(method(layout))]
7968        fn layout(&self) {
7969            sync_tree_width(self);
7970            let _: () = unsafe { msg_send![super(self), layout] };
7971        }
7972
7973        /// A summon-time ROW context menu (docs/menus.md, docs/tree.md): right-click asks
7974        /// the tree's `row_menu` provider for the row under the pointer.
7975        #[unsafe(method_id(menuForEvent:))]
7976        fn menu_for_event(
7977            &self,
7978            event: &objc2_app_kit::NSEvent,
7979        ) -> Option<Retained<NSMenu>> {
7980            ffi_guard::contain(None, || {
7981                let scroll = unsafe { self.enclosingScrollView() }?;
7982                let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
7983                let row_menu = data
7984                    .ivars()
7985                    .source
7986                    .borrow()
7987                    .as_ref()
7988                    .and_then(|s| s.row_menu.clone())?;
7989                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
7990                let row = unsafe { self.rowAtPoint(p) };
7991                if row < 0 {
7992                    return None;
7993                }
7994                let token =
7995                    unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
7996                let items = row_menu(token);
7997                if items.is_empty() {
7998                    return None;
7999                }
8000                Some(build_ns_menu(self.mtm(), "", &items))
8001            })
8002        }
8003    }
8004);
8005
8006// DayTreeRowView — a tree row with the MODERN selection: a rounded pill, inset from the
8007// pane's edges, in the system's semantic selection colors (accent when the tree has focus,
8008// the quiet gray otherwise). Drawn by hand rather than through `NSTableViewStyle::Inset`,
8009// whose machinery pads the table wider than its clip and fights day's fixed-frame layout —
8010// and a hand-drawn plain color also captures correctly offscreen, where materials go black
8011// (docs/navigation.md's sidebar-screenshot rule).
8012define_class!(
8013    #[unsafe(super(objc2_app_kit::NSTableRowView))]
8014    #[thread_kind = MainThreadOnly]
8015    #[name = "DayTreeRowView"]
8016    struct DayTreeRowView;
8017
8018    impl DayTreeRowView {
8019        #[unsafe(method(drawSelectionInRect:))]
8020        fn draw_selection_in_rect(&self, _dirty: NSRect) {
8021            if !unsafe { self.isSelected() } {
8022                return;
8023            }
8024            let color = if unsafe { self.isEmphasized() } {
8025                unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
8026            } else {
8027                unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
8028            };
8029            let b = self.bounds();
8030            let pill = NSRect::new(
8031                NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
8032                NSSize::new(
8033                    (b.size.width - 10.0).max(0.0),
8034                    (b.size.height - 2.0).max(0.0),
8035                ),
8036            );
8037            unsafe {
8038                color.setFill();
8039                objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
8040                    pill, 5.0, 5.0,
8041                )
8042                .fill();
8043            }
8044        }
8045    }
8046);
8047
8048// DayTreeCell — a tree row's flipped cell container. NSOutlineView frames it at the row's
8049// INDENTED position, so its width is per-row; every native layout pass re-lays the Day row
8050// content inside it at that width through the seam's `layout_cell`.
8051define_class!(
8052    #[unsafe(super(objc2_app_kit::NSTableCellView))]
8053    #[thread_kind = MainThreadOnly]
8054    #[name = "DayTreeCell"]
8055    struct DayTreeCell;
8056
8057    impl DayTreeCell {
8058        #[unsafe(method(isFlipped))]
8059        fn is_flipped(&self) -> bool {
8060            true
8061        }
8062
8063        #[unsafe(method(layout))]
8064        fn layout(&self) {
8065            let _: () = unsafe { msg_send![super(self), layout] };
8066            ffi_guard::contain((), || {
8067                let width = self.bounds().size.width;
8068                if width <= 0.0 {
8069                    return;
8070                }
8071                // This cell's tree: walk up to the outline, then to its scroll host, which
8072                // keys TREE_STATE. (The cell may be in the reuse pool — no outline — or the
8073                // tree may be mid-teardown; both just skip.)
8074                let mut cur = unsafe { self.superview() };
8075                let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
8076                while let Some(v) = cur {
8077                    cur = unsafe { v.superview() };
8078                    if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
8079                        outline = Some(ov);
8080                        break;
8081                    }
8082                }
8083                let Some(ov) = outline else { return };
8084                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
8085                    return;
8086                };
8087                let f = tree_entry(Retained::as_ptr(&scroll) as usize)
8088                    .and_then(|(_, data)| {
8089                        data.ivars()
8090                            .source
8091                            .borrow()
8092                            .as_ref()
8093                            .map(|s| s.layout_cell_size.clone())
8094                    });
8095                if let Some(f) = f {
8096                    f(std::ptr::from_ref::<Self>(self) as RawHandle, Size::new(width, self.bounds().size.height));
8097                }
8098            });
8099        }
8100    }
8101);
8102
8103impl DayTreeCell {
8104    fn new(mtm: MainThreadMarker) -> Retained<Self> {
8105        unsafe { msg_send![Self::alloc(mtm), init] }
8106    }
8107}
8108
8109/// The private pasteboard type carrying a dragged day tree node's token (local moves only).
8110const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
8111
8112/// A realized TREE's scroll view ptr → (outline, data source).
8113type TreeEntry = (
8114    Retained<objc2_app_kit::NSOutlineView>,
8115    Retained<DayTreeData>,
8116);
8117
8118/// Clone a tree's (outline, data) out of `TREE_STATE` under a SHORT borrow — the same
8119/// re-entrancy rule as `list_entry` (its comment has the war story).
8120fn tree_entry(key: usize) -> Option<TreeEntry> {
8121    TREE_STATE.with(|m| m.borrow().get(&key).cloned())
8122}
8123
8124/// Keep the outline exactly as wide as its clip — `DayOutlineView` calls this on every layout
8125/// pass (its comment has the why). The list never noticed the width drift because it lays
8126/// row content at the HOST's width; tree rows lay out at the CELL's, which exposes it.
8127fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
8128    let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
8129        return;
8130    };
8131    let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
8132    let f = outline.frame();
8133    if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
8134        unsafe {
8135            outline.setFrameSize(NSSize::new(clip_w, f.size.height));
8136            outline.sizeLastColumnToFit();
8137        }
8138    }
8139}
8140
8141/// Realize the tree's visible rows on the next main-loop turn, outside any borrow — the
8142/// tree twin of `post_realize_visible_rows` (its comment explains the occluded-window trap).
8143fn post_realize_visible_tree_rows(key: usize) {
8144    <AppKit as Platform>::post(Box::new(move || {
8145        if let Some((outline, _)) = tree_entry(key) {
8146            let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
8147            for row in range.location..range.location + range.length {
8148                let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
8149            }
8150        }
8151        day_core::pump_events();
8152    }));
8153}
8154
8155/// A realized `NAV_MENU`'s native outline view paired with its data-source object.
8156type NavMenuEntry = (
8157    Retained<objc2_app_kit::NSOutlineView>,
8158    Retained<DayNavMenuData>,
8159);
8160
8161fn ns_rect(r: day_spec::Rect) -> NSRect {
8162    NSRect::new(
8163        NSPoint::new(r.origin.x, r.origin.y),
8164        NSSize::new(r.size.width, r.size.height),
8165    )
8166}
8167
8168fn draw_op(op: &DrawOp, replay: &mut Replay) {
8169    unsafe {
8170        match op {
8171            // One path for the whole batch, then one fill or stroke: the template is appended
8172            // once per position, so the rasterizer is entered once however many copies there are
8173            // (docs/canvas.md "Stamping"). A gradient resolves against the batch's own bounds,
8174            // which is what makes a stamped scatter shade across the group rather than repeating
8175            // the ramp inside every dot.
8176            DrawOp::Stamp(st) => {
8177                let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
8178                for p in &st.at {
8179                    if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
8180                        unsafe { batch.appendBezierPath(&copy) };
8181                    }
8182                }
8183                let day_spec::Paint::Solid(color) = &st.paint else {
8184                    // A gradient shades across the whole batch: clip to every copy at once
8185                    // (or to the region their strokes cover) and draw it through that.
8186                    let Some(bounds) = stamp_bounds(st) else {
8187                        return;
8188                    };
8189                    draw_grouped(replay, || {
8190                        match &st.stroke {
8191                            None => unsafe { batch.addClip() },
8192                            Some(style) => clip_to_stroke(&batch, style),
8193                        }
8194                        draw_gradient_in(&st.paint, bounds);
8195                    });
8196                    return;
8197                };
8198                match &st.stroke {
8199                    None => {
8200                        nscolor((*color).resolved()).setFill();
8201                        unsafe { batch.fill() };
8202                    }
8203                    Some(style) => {
8204                        nscolor((*color).resolved()).setStroke();
8205                        apply_stroke_style(&batch, style);
8206                        unsafe { batch.stroke() };
8207                    }
8208                }
8209            }
8210            DrawOp::Fill(shape, paint) => match paint {
8211                day_spec::Paint::Solid(color) => {
8212                    nscolor((*color).resolved()).setFill();
8213                    if let Some(p) = bezier(shape) {
8214                        p.fill();
8215                    }
8216                }
8217                // A gradient: clip to the shape's path, then draw it through the clip, resolved
8218                // against the shape's bounds.
8219                gradient => {
8220                    if let Some(p) = bezier(shape) {
8221                        draw_grouped(replay, || {
8222                            p.addClip();
8223                            draw_gradient_in(gradient, shape.bounds());
8224                        });
8225                    }
8226                }
8227            },
8228            DrawOp::Stroke(shape, paint, style) => {
8229                if let Some(p) = bezier(shape) {
8230                    apply_stroke_style(&p, style);
8231                    if let day_spec::Paint::Solid(color) = paint {
8232                        nscolor((*color).resolved()).setStroke();
8233                        p.stroke();
8234                    } else {
8235                        // No gradient-stroke primitive: convert the stroke into the REGION it
8236                        // covers, clip to that, then draw the gradient through it.
8237                        draw_grouped(replay, || {
8238                            clip_to_stroke(&p, style);
8239                            draw_gradient_in(paint, shape.bounds());
8240                        });
8241                    }
8242                }
8243            }
8244            DrawOp::Clip(shape) => {
8245                // `addClip` intersects with the current clip and honors the path's winding rule.
8246                if let Some(p) = bezier(shape) {
8247                    p.addClip();
8248                }
8249            }
8250            DrawOp::Text {
8251                text,
8252                at,
8253                size,
8254                color,
8255                anchor,
8256                font,
8257            } => {
8258                let font = canvas_nsfont(*size, font);
8259                let attrs = canvas_text_attrs(&font, *color);
8260                let ns = NSString::from_str(text);
8261                let mut origin = NSPoint::new(at.x, at.y);
8262                // `drawAtPoint:` takes the top-leading corner of the line box, so any other
8263                // anchor is an offset from it. The size comes from the attributes the draw is
8264                // about to use, which is why the alignment belongs here and not in the app: the
8265                // caller would have to ask for these same metrics through `measure_text` first.
8266                if *anchor != day_spec::TextAnchor::LEADING {
8267                    let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
8268                    let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
8269                    origin.x += dx;
8270                    origin.y += dy;
8271                }
8272                let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
8273            }
8274            // A released bitmap draws nothing rather than a placeholder: the canvas re-records
8275            // on every tracked read, so a handle can be dropped between the record and the
8276            // replay, and a frame that flashes a grey box is worse than one that omits the image.
8277            DrawOp::Image {
8278                image,
8279                rect,
8280                opacity,
8281                source,
8282            } => {
8283                let held = BITMAPS.with(|m| {
8284                    m.borrow()
8285                        .get(&image.0)
8286                        .map(|b| (b.image.clone(), b.info.pixels))
8287                });
8288                if let Some((img, pixels)) = held {
8289                    // A zero `fromRect` means the whole image. A region (`source`, in the
8290                    // bitmap's pixels) clamps to the bitmap with its mapping into `rect` kept,
8291                    // and an empty intersection draws nothing. `fromRect` is in the image's own
8292                    // space: its point size, origin at the BOTTOM-left the way NSImage counts,
8293                    // so the pixel region converts by the points-per-pixel ratio and flips.
8294                    let region = match source {
8295                        None => Some((NSRect::ZERO, *rect)),
8296                        Some(src) => {
8297                            day_spec::clamp_image_source(*src, *rect, pixels).map(|(src, dest)| {
8298                                let sz = img.size();
8299                                let (rx, ry) = (sz.width / pixels.width, sz.height / pixels.height);
8300                                let from = NSRect::new(
8301                                    NSPoint::new(
8302                                        src.origin.x * rx,
8303                                        (pixels.height - src.origin.y - src.size.height) * ry,
8304                                    ),
8305                                    NSSize::new(src.size.width * rx, src.size.height * ry),
8306                                );
8307                                (from, dest)
8308                            })
8309                        }
8310                    };
8311                    if let Some((from, dest)) = region {
8312                        let dest = NSRect::new(
8313                            NSPoint::new(dest.origin.x, dest.origin.y),
8314                            NSSize::new(dest.size.width, dest.size.height),
8315                        );
8316                        // DayCanvas is flipped (top-left origin). Respect that context so image
8317                        // rows stay upright, including under the canvas's rotation/zoom
8318                        // transforms. `fraction` multiplies the image's alpha.
8319                        img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
8320                            dest,
8321                            from,
8322                            ns_compositing(replay.ink.blend),
8323                            *opacity,
8324                            true,
8325                            None,
8326                        );
8327                    }
8328                }
8329            }
8330            // Both are graphics state: the context saves and restores them with the clip and
8331            // the transform, and `replay` mirrors them for the arms that ask.
8332            DrawOp::Shadow(shadow) => {
8333                let shadow = shadow.as_ref().filter(|s| s.color.resolved().a > 0.0);
8334                replay.ink.shadow = shadow.is_some();
8335                if let Some(ctx) = NSGraphicsContext::currentContext() {
8336                    cg_set_shadow(&ctx.CGContext(), shadow, replay.base_scale);
8337                }
8338            }
8339            DrawOp::Blend(mode) => {
8340                replay.ink.blend = *mode;
8341                if let Some(ctx) = NSGraphicsContext::currentContext() {
8342                    objc2_core_graphics::CGContext::set_blend_mode(
8343                        Some(&ctx.CGContext()),
8344                        cg_blend_mode(*mode),
8345                    );
8346                }
8347            }
8348            DrawOp::Save => {
8349                replay.save();
8350                NSGraphicsContext::saveGraphicsState_class();
8351            }
8352            DrawOp::Restore => {
8353                if replay.restore() {
8354                    NSGraphicsContext::restoreGraphicsState_class();
8355                }
8356            }
8357            DrawOp::Concat(m) => {
8358                let t = NSAffineTransform::new();
8359                t.setTransformStruct(NSAffineTransformStruct {
8360                    m11: m.a,
8361                    m12: m.b,
8362                    m21: m.c,
8363                    m22: m.d,
8364                    tX: m.tx,
8365                    tY: m.ty,
8366                });
8367                t.concat();
8368            }
8369        }
8370    }
8371}
8372
8373/// Intersect the clip with the region a stroke of `path` in `style` covers: Core Graphics can
8374/// turn a stroke into its outline, and `NSGraphicsContext` hands over its context. The style
8375/// goes on the context, whose line state is what the conversion reads.
8376fn clip_to_stroke(path: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
8377    use objc2_core_graphics::CGContext;
8378    // SAFETY: reading the current graphics context on the thread that set it.
8379    let Some(ctx) = (unsafe { NSGraphicsContext::currentContext() }) else {
8380        return;
8381    };
8382    let cg = ctx.CGContext();
8383    cg_stroke_style(&cg, style);
8384    CGContext::begin_path(Some(&cg));
8385    // SAFETY: an immutable snapshot of the path's geometry.
8386    CGContext::add_path(Some(&cg), Some(&*unsafe { path.CGPath() }));
8387    CGContext::replace_path_with_stroked_path(Some(&cg));
8388    CGContext::clip(Some(&cg));
8389}
8390
8391/// The box a stamped batch's gradient resolves against: the template's bounds at every
8392/// position, joined. `None` for a batch with no positions.
8393fn stamp_bounds(stamp: &day_spec::Stamp) -> Option<day_spec::Rect> {
8394    let (first, rest) = stamp.at.split_first()?;
8395    let (mut min, mut max) = (*first, *first);
8396    for p in rest {
8397        min = Point::new(min.x.min(p.x), min.y.min(p.y));
8398        max = Point::new(max.x.max(p.x), max.y.max(p.y));
8399    }
8400    let b = stamp.shape.bounds();
8401    Some(day_spec::Rect::new(
8402        b.origin.x + min.x,
8403        b.origin.y + min.y,
8404        b.size.width + (max.x - min.x),
8405        b.size.height + (max.y - min.y),
8406    ))
8407}
8408
8409/// An `NSGradient` from a display-list gradient's stops (sRGB, like every canvas color).
8410fn nsgradient(
8411    stops: &[(f64, day_spec::Color)],
8412) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
8413    if stops.is_empty() {
8414        return None;
8415    }
8416    let colors = objc2_foundation::NSArray::from_retained_slice(
8417        &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
8418    );
8419    let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
8420    unsafe {
8421        objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
8422            objc2_app_kit::NSGradient::alloc(),
8423            &colors,
8424            locations.as_ptr(),
8425            &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
8426        )
8427    }
8428}
8429
8430/// Concat a bounds-mapping transform (unit gradient space → `b`) onto the current context, so a
8431/// circular gradient drawn in unit coordinates renders elliptically stretched to the bounds.
8432fn concat_unit_to_bounds(b: day_spec::Rect) {
8433    let t = NSAffineTransform::new();
8434    t.setTransformStruct(NSAffineTransformStruct {
8435        m11: b.size.width,
8436        m12: 0.0,
8437        m21: 0.0,
8438        m22: b.size.height,
8439        tX: b.origin.x,
8440        tY: b.origin.y,
8441    });
8442    unsafe { t.concat() };
8443}
8444
8445/// Put a [`day_spec::StrokeStyle`] onto a path.
8446///
8447/// NOTE: this backend used to force ROUND caps on every stroke. It now honors the style, whose
8448/// default is BUTT — the same default the spec and every other backend use. A line that wants
8449/// round ends asks for `StrokeStyle::round`.
8450fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
8451    use day_spec::{LineCap, LineJoin};
8452    unsafe {
8453        p.setLineWidth(style.width);
8454        p.setLineCapStyle(match style.cap {
8455            LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
8456            LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
8457            LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
8458        });
8459        if style.is_plain() {
8460            return;
8461        }
8462        p.setLineJoinStyle(match style.join {
8463            LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
8464            LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
8465            LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
8466        });
8467        p.setMiterLimit(style.miter_limit);
8468        if !style.dash.is_empty() {
8469            let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
8470            p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
8471        }
8472    }
8473}
8474
8475/// A gradient's stops in the current drawing appearance (`color::ink_now`): a canvas's fixed
8476/// inks as they are, a surface's pairs and roles for the appearance its `drawRect` runs in.
8477fn stops_now(stops: &[(f64, day_spec::Ink)]) -> Vec<(f64, day_spec::Color)> {
8478    stops
8479        .iter()
8480        .map(|(at, ink)| (*at, color::ink_now(*ink)))
8481        .collect()
8482}
8483
8484/// Draw a gradient through whatever clip is installed, in AppKit's own `NSGradient` terms.
8485/// Shared by the gradient FILL arms and the gradient STROKE arm, which differ only in what they
8486/// clipped to first.
8487fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
8488    let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
8489        | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
8490    match paint {
8491        day_spec::Paint::Linear(g) => {
8492            if let Some(grad) = nsgradient(&stops_now(&g.stops)) {
8493                let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
8494                unsafe {
8495                    grad.drawFromPoint_toPoint_options(
8496                        NSPoint::new(s.x, s.y),
8497                        NSPoint::new(e.x, e.y),
8498                        opts,
8499                    );
8500                };
8501            }
8502        }
8503        day_spec::Paint::Radial(g) => {
8504            if let Some(grad) = nsgradient(&stops_now(&g.stops)) {
8505                NSGraphicsContext::saveGraphicsState_class();
8506                concat_unit_to_bounds(bounds);
8507                let c = NSPoint::new(g.center.x, g.center.y);
8508                unsafe {
8509                    grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts);
8510                };
8511                NSGraphicsContext::restoreGraphicsState_class();
8512            }
8513        }
8514        day_spec::Paint::Conic(g) => {
8515            // SAFETY: reading the current graphics context on the thread that set it.
8516            if let Some(ctx) = unsafe { NSGraphicsContext::currentContext() } {
8517                draw_conic(&ctx.CGContext(), g, bounds);
8518            }
8519        }
8520        day_spec::Paint::Solid(_) => {}
8521    }
8522}
8523
8524fn apply_button_content(
8525    btn: &NSButton,
8526    title: &str,
8527    icon: Option<&day_spec::Icon>,
8528    icon_only: bool,
8529) {
8530    let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
8531    if let Some(image) = &image {
8532        let size = image.size();
8533        let longest = size.width.max(size.height);
8534        if longest > 0.0 {
8535            image.setSize(objc2_foundation::NSSize::new(
8536                size.width * 20.0 / longest,
8537                size.height * 20.0 / longest,
8538            ));
8539        }
8540    }
8541    let style = BUTTON_STYLES
8542        .with(|m| m.borrow().get(&ptr_of(btn)).copied())
8543        .unwrap_or_default();
8544    BUTTON_IMAGES.with(|images| {
8545        let _ = images.remove(ptr_of(btn));
8546        if let Some(image) = &image {
8547            images.insert(ptr_of(btn), image.clone());
8548        }
8549    });
8550    set_button_title(btn, title, style);
8551    // The position first: the image setter pads a glyph that sits beside a title, and leaves
8552    // an icon-only one alone, by reading it.
8553    unsafe {
8554        btn.setImagePosition(if image.is_none() {
8555            objc2_app_kit::NSCellImagePosition::NoImage
8556        } else if icon_only {
8557            objc2_app_kit::NSCellImagePosition::ImageOnly
8558        } else {
8559            objc2_app_kit::NSCellImagePosition::ImageLeading
8560        });
8561    }
8562    set_button_image(btn, style);
8563    unsafe {
8564        // The title is the spoken name (an icon-only button shows none), unless the app named
8565        // the button itself; overwriting that here replaced app labels on every title change.
8566        if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
8567            btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
8568        }
8569        let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
8570        btn.setToolTip(tooltip.as_deref());
8571    }
8572}
8573
8574/// Bordered buttons do not reliably apply contentTintColor to template images. Keep
8575/// the native button, but supply an image that draws the original vector's alpha in
8576/// the requested contrast color at the destination resolution.
8577fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
8578    use day_spec::props::ButtonStyleSpec as S;
8579    let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
8580    let image = image.map(|source| {
8581        let S::Tinted(fill) = style else {
8582            return source;
8583        };
8584        let size = source.size();
8585        // Dynamic: the drawing handler runs per appearance, and so resolves it.
8586        let ink = color::nsink(color::map_ink(fill, S::on_tint));
8587        let draw = block2::RcBlock::new(move |rect: NSRect| {
8588            source.drawInRect_fromRect_operation_fraction(
8589                rect,
8590                NSRect::ZERO,
8591                objc2_app_kit::NSCompositingOperation::SourceOver,
8592                1.0,
8593            );
8594            unsafe {
8595                ink.setFill();
8596                objc2_app_kit::NSRectFillUsingOperation(
8597                    rect,
8598                    objc2_app_kit::NSCompositingOperation::SourceIn,
8599                );
8600            }
8601            objc2::runtime::Bool::YES
8602        });
8603        objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
8604    });
8605    unsafe {
8606        let position = btn.imagePosition();
8607        // Beside a title, the glyph gets a clear gap: AppKit draws a leading image flush
8608        // against the text, so the image carries the space itself (a template stays one, so
8609        // the label color still tints it). The cell centers the image in its slot, so half
8610        // the extra width lands on each side.
8611        let image = image.map(|source| {
8612            // The position is set after this on a fresh button, so an unset one counts as
8613            // "beside a title"; only an icon-only button keeps the glyph as drawn.
8614            if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
8615                return source;
8616            }
8617            let size = source.size();
8618            let template = source.isTemplate();
8619            let padded = NSSize::new(size.width + 8.0, size.height);
8620            let draw = block2::RcBlock::new(move |_rect: NSRect| {
8621                source.drawInRect_fromRect_operation_fraction(
8622                    NSRect::new(NSPoint::new(0.0, 0.0), size),
8623                    NSRect::ZERO,
8624                    objc2_app_kit::NSCompositingOperation::SourceOver,
8625                    1.0,
8626                );
8627                objc2::runtime::Bool::YES
8628            });
8629            let out =
8630                objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
8631            out.setTemplate(template);
8632            out
8633        });
8634        btn.setImage(image.as_deref());
8635        btn.setImagePosition(position);
8636        btn.setImageHugsTitle(true);
8637    }
8638}
8639
8640/// Put `ButtonProps::selected` on an `NSButton`, keeping it an `NSButton`. A momentary button
8641/// shows no state, so the first `true` makes it push-on/push-off, whose on state AppKit draws
8642/// as the bezel's highlighted fill and VoiceOver reads as selected; a button that never
8643/// selects keeps its momentary type. A click toggles the state natively before the action
8644/// runs, so the `action:` handler restores the value recorded here.
8645fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
8646    BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
8647    unsafe {
8648        if on {
8649            btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
8650        }
8651        btn.setState(if on {
8652            NSControlStateValueOn
8653        } else {
8654            NSControlStateValueOff
8655        });
8656    }
8657}
8658
8659/// The corner radius of the tint painted behind a tinted button's bezel: the rounded push
8660/// bezel's own, so the fill reads as the bezel rather than as a box around it.
8661const TINT_CORNER_RADIUS: f64 = 6.0;
8662
8663/// Put a [`day_spec::props::ButtonStyleSpec`] on an `NSButton`, keeping it an `NSButton`.
8664///
8665/// Prominent = the return-key default button. Tinted = `bezelColor`, which AppKit composites
8666/// through the button's own bezel — so the pressed darkening, the focus ring and the disabled
8667/// look all still come from the control rather than from us painting a rectangle. macOS 26
8668/// composites the push bezel as a system material that ignores `bezelColor` on screen (an
8669/// offscreen `cacheDisplay` still honors it), so the tint is also painted on the control's
8670/// backing layer, where the translucent material lets it through; on older systems the opaque
8671/// tinted bezel covers that layer, so nothing changes there.
8672fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
8673    use day_spec::props::ButtonStyleSpec as S;
8674    let title = unsafe { btn.title() }.to_string();
8675    unsafe {
8676        // Reset first, so a patch from one style to another leaves nothing of the old one.
8677        btn.setKeyEquivalent(&NSString::from_str(""));
8678        btn.setBezelColor(None);
8679        btn.setBordered(!matches!(style, S::Plain));
8680        match style {
8681            S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
8682            S::Tinted(c) => btn.setBezelColor(Some(&color::nsink(c))),
8683            // Bordered is the stock NSButton look already; Automatic asks for nothing, and an
8684            // NSButton hugs a one-glyph title already, so Compact asks for nothing either.
8685            S::Bordered | S::Automatic | S::Compact | S::Plain => {}
8686        }
8687        btn.setWantsLayer(true);
8688        if let Some(layer) = btn.layer() {
8689            match style {
8690                S::Tinted(c) => {
8691                    // A layer color holds one appearance: `color::refresh_layers` sets a
8692                    // pair or a role again when the appearance changes.
8693                    layer.setBackgroundColor(Some(&color::cg_for(btn, c)));
8694                    layer.setCornerRadius(TINT_CORNER_RADIUS);
8695                    if c.is_dynamic() {
8696                        color::track_tinted(btn);
8697                    }
8698                }
8699                _ => layer.setBackgroundColor(None),
8700            }
8701        }
8702    }
8703    BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
8704    let ink = match style {
8705        S::Tinted(c) => Some(color::nsink(color::map_ink(c, S::on_tint))),
8706        _ => None,
8707    };
8708    unsafe {
8709        btn.setContentTintColor(ink.as_deref());
8710    }
8711    set_button_title(btn, &title, style);
8712    set_button_image(btn, style);
8713}
8714
8715/// Set a button's title, coloring it for the tint where there is one.
8716///
8717/// `contentTintColor` is NOT the seam for this: on a bordered `NSButton`,
8718/// AppKit keeps drawing the title in its own control text color — which is how a
8719/// white-on-rust button came out black-on-rust. An ATTRIBUTED title is the documented way to
8720/// control the text color, so that is what a tinted button gets.
8721///
8722/// The button's own font is carried into the attributes: an attributed title supplies the whole
8723/// run, so leaving the font out would drop the control font and render at the system default.
8724fn set_button_title(
8725    btn: &objc2_app_kit::NSButton,
8726    title: &str,
8727    style: day_spec::props::ButtonStyleSpec,
8728) {
8729    use day_spec::props::ButtonStyleSpec as S;
8730    // Changing an attributed title can reset NSButton's image placement. A reactive
8731    // tint must keep an icon-only button icon-only, including its native template tint.
8732    let position = unsafe { btn.imagePosition() };
8733    let S::Tinted(fill) = style else {
8734        // Plain title: AppKit picks the label color that suits the bezel it is drawing.
8735        unsafe {
8736            btn.setTitle(&NSString::from_str(title));
8737            btn.setImagePosition(position);
8738        }
8739        return;
8740    };
8741    unsafe {
8742        let col = color::nsink(color::map_ink(fill, S::on_tint));
8743        let font = btn
8744            .font()
8745            .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
8746        // Centered, matching a plain NSButton title: an attributed title carries its own
8747        // paragraph style, and the default is left-aligned.
8748        let para = objc2_app_kit::NSMutableParagraphStyle::new();
8749        para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
8750        let keys: [&NSString; 3] = [
8751            objc2_app_kit::NSFontAttributeName,
8752            objc2_app_kit::NSForegroundColorAttributeName,
8753            objc2_app_kit::NSParagraphStyleAttributeName,
8754        ];
8755        let objs: [&objc2::runtime::AnyObject; 3] = [
8756            font.as_ref() as &objc2::runtime::AnyObject,
8757            col.as_ref() as &objc2::runtime::AnyObject,
8758            para.as_ref() as &objc2::runtime::AnyObject,
8759        ];
8760        let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
8761        let s = objc2_foundation::NSAttributedString::initWithString_attributes(
8762            objc2_foundation::NSAttributedString::alloc(),
8763            &NSString::from_str(title),
8764            Some(&attrs),
8765        );
8766        btn.setAttributedTitle(&s);
8767        btn.setImagePosition(position);
8768    }
8769}
8770
8771// NSImageView supports aspect-fit but not aspect-fill. Expand its native drawing about
8772// the center and clip to the view; this retains vector rendering and template tinting.
8773define_class!(
8774    #[unsafe(super(objc2_app_kit::NSImageView))]
8775    #[thread_kind = MainThreadOnly]
8776    #[name = "DayFillImageView"]
8777    struct FillImageView;
8778
8779    impl FillImageView {
8780        #[unsafe(method(drawRect:))]
8781        fn draw_rect(&self, dirty: NSRect) {
8782            let bounds = self.bounds();
8783            let image = unsafe { self.image() };
8784            let Some(size) = image.map(|image| image.size()).filter(|size| {
8785                size.width > 0.0 && size.height > 0.0
8786                    && bounds.size.width > 0.0 && bounds.size.height > 0.0
8787            }) else {
8788                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
8789                return;
8790            };
8791            let x = bounds.size.width / size.width;
8792            let y = bounds.size.height / size.height;
8793            let scale = x.max(y) / x.min(y);
8794            let cx = bounds.origin.x + bounds.size.width / 2.0;
8795            let cy = bounds.origin.y + bounds.size.height / 2.0;
8796            NSGraphicsContext::saveGraphicsState_class();
8797            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
8798            let transform = NSAffineTransform::transform();
8799            transform.translateXBy_yBy(cx, cy);
8800            transform.scaleBy(scale);
8801            transform.translateXBy_yBy(-cx, -cy);
8802            transform.concat();
8803            let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
8804            NSGraphicsContext::restoreGraphicsState_class();
8805        }
8806
8807        #[unsafe(method(setFrameSize:))]
8808        fn set_frame_size(&self, size: NSSize) {
8809            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
8810            NSView::setNeedsDisplay(self, true);
8811        }
8812    }
8813);
8814
8815fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
8816    use day_spec::Shape;
8817    use objc2_app_kit::NSBezierPath;
8818    unsafe {
8819        Some(match shape {
8820            Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
8821            Shape::RoundedRect(r, rad) => {
8822                NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
8823            }
8824            Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
8825            Shape::Arc { rect, start, sweep } => {
8826                let (start_deg, sweep_deg) = (&start.degrees(), &sweep.degrees());
8827                let p = NSBezierPath::new();
8828                let center = NSPoint::new(
8829                    rect.origin.x + rect.size.width / 2.0,
8830                    rect.origin.y + rect.size.height / 2.0,
8831                );
8832                let radius = rect.size.width.min(rect.size.height) / 2.0;
8833                // Flipped view: increasing angle is visually clockwise, matching the spec.
8834                p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
8835                    center,
8836                    radius,
8837                    *start_deg,
8838                    *start_deg + *sweep_deg,
8839                );
8840                p
8841            }
8842            Shape::Line(a, b) => {
8843                let p = NSBezierPath::new();
8844                p.moveToPoint(NSPoint::new(a.x, a.y));
8845                p.lineToPoint(NSPoint::new(b.x, b.y));
8846                p
8847            }
8848            Shape::Polygon(pts) => {
8849                if pts.len() < 2 {
8850                    return None;
8851                }
8852                let p = NSBezierPath::new();
8853                p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
8854                for pt in &pts[1..] {
8855                    p.lineToPoint(NSPoint::new(pt.x, pt.y));
8856                }
8857                p.closePath();
8858                p
8859            }
8860            Shape::Path(path) => {
8861                use day_spec::PathSeg;
8862                if path.segs.is_empty() {
8863                    return None;
8864                }
8865                let p = NSBezierPath::new();
8866                // NSBezierPath's own quadratic API is macOS 14+, so quads are ELEVATED to
8867                // cubics with the standard formula (c1 = p0 + 2/3(c - p0), c2 = p1 + 2/3(c -
8868                // p1)), which is exact rather than an approximation.
8869                let mut cur = NSPoint::new(0.0, 0.0);
8870                for seg in &path.segs {
8871                    match seg {
8872                        PathSeg::Move(a) => {
8873                            cur = NSPoint::new(a.x, a.y);
8874                            p.moveToPoint(cur);
8875                        }
8876                        PathSeg::Line(a) => {
8877                            cur = NSPoint::new(a.x, a.y);
8878                            p.lineToPoint(cur);
8879                        }
8880                        PathSeg::Quad(c, a) => {
8881                            let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
8882                            let c1 = NSPoint::new(
8883                                cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
8884                                cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
8885                            );
8886                            let c2 = NSPoint::new(
8887                                end.x + 2.0 / 3.0 * (ctl.x - end.x),
8888                                end.y + 2.0 / 3.0 * (ctl.y - end.y),
8889                            );
8890                            p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
8891                            cur = end;
8892                        }
8893                        PathSeg::Cubic(c1, c2, a) => {
8894                            cur = NSPoint::new(a.x, a.y);
8895                            p.curveToPoint_controlPoint1_controlPoint2(
8896                                cur,
8897                                NSPoint::new(c1.x, c1.y),
8898                                NSPoint::new(c2.x, c2.y),
8899                            );
8900                        }
8901                        PathSeg::Close => p.closePath(),
8902                    }
8903                }
8904                p.setWindingRule(match path.rule {
8905                    day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
8906                    day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
8907                });
8908                p
8909            }
8910        })
8911    }
8912}
8913
8914// ---------------------------------------------------------------------------
8915// DayUndoManager — the native FRONT of the app's one undo stack (docs/model.md)
8916// ---------------------------------------------------------------------------
8917
8918/// The mirrored [`day_spec::UndoState`]: what the stock Edit menu reads through the standard
8919/// `undo:`/`redo:` validation. The stack itself lives in day-model; this object only answers
8920/// questions and forwards invocations — two histories can never fork.
8921struct UndoIvars {
8922    state: std::cell::RefCell<day_spec::UndoState>,
8923}
8924
8925define_class!(
8926    #[unsafe(super(objc2_foundation::NSUndoManager))]
8927    #[thread_kind = MainThreadOnly]
8928    #[name = "DayUndoManager"]
8929    #[ivars = UndoIvars]
8930    struct DayUndoManager;
8931
8932    /// Overrides of the questions AppKit's menu validation asks, answered from the mirrored
8933    /// state — and of the two verbs, forwarded as `Event::Undo` (enqueue-only, like every
8934    /// other event). Registration/grouping machinery of the superclass is never used.
8935    impl DayUndoManager {
8936        #[unsafe(method(canUndo))]
8937        fn can_undo(&self) -> bool {
8938            self.ivars().state.borrow().can_undo
8939        }
8940
8941        #[unsafe(method(canRedo))]
8942        fn can_redo(&self) -> bool {
8943            self.ivars().state.borrow().can_redo
8944        }
8945
8946        #[unsafe(method(undo))]
8947        fn do_undo(&self) {
8948            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }));
8949        }
8950
8951        #[unsafe(method(redo))]
8952        fn do_redo(&self) {
8953            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }));
8954        }
8955
8956        #[unsafe(method_id(undoMenuItemTitle))]
8957        fn undo_menu_item_title(&self) -> Retained<NSString> {
8958            // Route through the superclass's own title former, so "Undo" itself comes out in
8959            // the system language; the action label arrived already localized from the app.
8960            let label = self.ivars().state.borrow().undo_label.clone();
8961            unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
8962        }
8963
8964        #[unsafe(method_id(redoMenuItemTitle))]
8965        fn redo_menu_item_title(&self) -> Retained<NSString> {
8966            let label = self.ivars().state.borrow().redo_label.clone();
8967            unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
8968        }
8969    }
8970);
8971
8972fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
8973    UNDO_FRONT.with(|u| {
8974        u.borrow_mut()
8975            .get_or_insert_with(|| {
8976                let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
8977                    state: std::cell::RefCell::new(day_spec::UndoState::default()),
8978                });
8979                unsafe { msg_send![super(this), init] }
8980            })
8981            .clone()
8982    })
8983}
8984
8985// ---------------------------------------------------------------------------
8986// DayWinDelegate — resize + close + key tracking, per window
8987// ---------------------------------------------------------------------------
8988
8989/// `node`: the day window-root id this delegate's window reports to. `None` = the PRIMARY
8990/// window — resize goes to `WINDOW_NODE` and close terminates the app; a secondary window
8991/// (docs/windows.md) reports to its own root and close tears down just that window.
8992struct WinIvars {
8993    node: Option<NodeId>,
8994    /// The tab group this window was opened in (`WindowTabbing::Group`/`Preferred`): the
8995    /// tab bar's "+" opens another window of the same group.
8996    group: Option<String>,
8997    /// The last display state reported (`WindowState::code`), so a resize that does not change
8998    /// the zoom state reports nothing.
8999    last_state: Cell<i32>,
9000}
9001
9002define_class!(
9003    #[unsafe(super(NSObject))]
9004    #[thread_kind = MainThreadOnly]
9005    #[name = "DayWinDelegate"]
9006    #[ivars = WinIvars]
9007    struct DayWinDelegate;
9008
9009    unsafe impl NSObjectProtocol for DayWinDelegate {}
9010
9011    /// The responder chain's last stop for the standard edit nav hosts: a focused text view
9012    /// answered `cut:`/`copy:`/`paste:` long before the window asked its delegate, so what
9013    /// arrives here is the app's to handle — the same precedence the undo manager route uses.
9014    impl DayWinDelegate {
9015        /// Edit ▸ Undo. The stock item's nil-target `undo:` finds no implementor among Day's
9016        /// plain views, so the delegate is where the chain lands — resolving through the
9017        /// acting manager keeps a focused field's typing undo ahead of the document stack.
9018        #[unsafe(method(undo:))]
9019        fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9020            ffi_guard::contain((), || {
9021                if let Some(m) = self.acting_undo_manager() {
9022                    unsafe { m.undo() };
9023                }
9024            });
9025        }
9026
9027        /// Edit ▸ Redo.
9028        #[unsafe(method(redo:))]
9029        fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9030            ffi_guard::contain((), || {
9031                if let Some(m) = self.acting_undo_manager() {
9032                    unsafe { m.redo() };
9033                }
9034            });
9035        }
9036
9037        #[unsafe(method(cut:))]
9038        fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9039            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
9040        }
9041
9042        #[unsafe(method(copy:))]
9043        fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9044            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
9045        }
9046
9047        #[unsafe(method(paste:))]
9048        fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9049            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
9050        }
9051
9052        #[unsafe(method(selectAll:))]
9053        fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
9054            ffi_guard::contain((), || {
9055                emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
9056            });
9057        }
9058
9059        /// AppKit's menu validation, the same machinery that greys Edit items for text views:
9060        /// the bridge state answers for cut/copy, and paste additionally requires the
9061        /// pasteboard to actually hold text.
9062        #[unsafe(method(validateMenuItem:))]
9063        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
9064            ffi_guard::contain(false, || {
9065                let state = EDIT_STATE.with(std::cell::Cell::get);
9066                match unsafe { item.action() } {
9067                    // The undo pair enables from the acting manager and takes its titles
9068                    // ("Undo Move Shape"), exactly as AppKit's own windows do.
9069                    Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
9070                        Some(m) => {
9071                            item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
9072                            unsafe { m.canUndo() }
9073                        }
9074                        None => false,
9075                    },
9076                    Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
9077                        Some(m) => {
9078                            item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
9079                            unsafe { m.canRedo() }
9080                        }
9081                        None => false,
9082                    },
9083                    Some(a) if a == sel!(selectAll:) => state.can_select_all,
9084                    Some(a) if a == sel!(cut:) => state.can_cut,
9085                    Some(a) if a == sel!(copy:) => state.can_copy,
9086                    Some(a) if a == sel!(paste:) => {
9087                        state.can_paste && {
9088                            let pb = unsafe { NSPasteboard::generalPasteboard() };
9089                            pb.types().is_some_and(|types| !types.is_empty())
9090                        }
9091                    }
9092                    _ => true,
9093                }
9094            })
9095        }
9096    }
9097
9098    unsafe impl NSWindowDelegate for DayWinDelegate {
9099        #[unsafe(method(windowDidResize:))]
9100        fn window_did_resize(&self, notification: &NSNotification) {
9101            ffi_guard::contain((), || {
9102                if let Some(obj) = unsafe { notification.object() }
9103                    && let Ok(win) = obj.downcast::<NSWindow>()
9104                    && let Some(size) = pin_below_title_bar(&win)
9105                {
9106                    let target = self.ivars().node.unwrap_or(WINDOW_NODE);
9107                    emit(target, Event::WindowResized(size));
9108                }
9109                // Zooming is a resize with no notification of its own.
9110                self.report_state_of(notification);
9111            });
9112        }
9113
9114        #[unsafe(method(windowShouldClose:))]
9115        fn window_should_close(&self, _window: &NSWindow) -> bool {
9116            ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
9117        }
9118
9119        #[unsafe(method(windowWillClose:))]
9120        fn window_will_close(&self, _notification: &NSNotification) {
9121            ffi_guard::contain((), || {
9122                match self.ivars().node {
9123                    // Secondary window: confirm the close to day-core, which tears the
9124                    // subtree down on a DEFERRED hop (never inside this AppKit close frame).
9125                    Some(node) => emit(node, Event::WindowClosed),
9126                    // Primary window: closing it quits, taking secondaries with it
9127                    // (docs/windows.md close policy), unless the app keeps running without a
9128                    // window (a status item, `KeepRunning::Always`): then it closes like any
9129                    // other window and day-core decides.
9130                    None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
9131                    None => {
9132                        let app = NSApplication::sharedApplication(self.mtm());
9133                        unsafe { app.terminate(None) };
9134                    }
9135                }
9136            });
9137        }
9138
9139        #[unsafe(method_id(windowWillReturnUndoManager:))]
9140        fn window_will_return_undo_manager(
9141            &self,
9142            _window: &NSWindow,
9143        ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
9144            // The responder chain already gave a focused text field its OWN manager before
9145            // asking the window — typing undo stays the field's, the model stack gets the
9146            // rest, exactly the precedence the plan's typing rule wants.
9147            ffi_guard::contain(None, || {
9148                UNDO_FRONT.with(|u| {
9149                    u.borrow()
9150                        .as_ref()
9151                        .map(|m| Retained::into_super(m.clone()))
9152                })
9153            })
9154        }
9155
9156        #[unsafe(method(windowDidBecomeKey:))]
9157        fn window_did_become_key(&self, _notification: &NSNotification) {
9158            ffi_guard::contain((), || {
9159                if let Some(node) = self.ivars().node {
9160                    emit(node, Event::WindowFocused(true));
9161                }
9162            });
9163        }
9164
9165        #[unsafe(method(windowDidResignKey:))]
9166        fn window_did_resign_key(&self, _notification: &NSNotification) {
9167            ffi_guard::contain((), || {
9168                if let Some(node) = self.ivars().node {
9169                    emit(node, Event::WindowFocused(false));
9170                }
9171            });
9172        }
9173
9174        #[unsafe(method(windowDidMiniaturize:))]
9175        fn window_did_miniaturize(&self, notification: &NSNotification) {
9176            ffi_guard::contain((), || self.report_state_of(notification));
9177        }
9178
9179        #[unsafe(method(windowDidDeminiaturize:))]
9180        fn window_did_deminiaturize(&self, notification: &NSNotification) {
9181            ffi_guard::contain((), || self.report_state_of(notification));
9182        }
9183
9184        #[unsafe(method(windowDidEnterFullScreen:))]
9185        fn window_did_enter_full_screen(&self, notification: &NSNotification) {
9186            ffi_guard::contain((), || self.report_state_of(notification));
9187        }
9188
9189        #[unsafe(method(windowDidExitFullScreen:))]
9190        fn window_did_exit_full_screen(&self, notification: &NSNotification) {
9191            ffi_guard::contain((), || self.report_state_of(notification));
9192        }
9193    }
9194
9195    // The tab bar's "+" button walks the responder chain (window → delegate) for
9196    // `newWindowForTab:` — present only when the app registered a new-window builder
9197    // (otherwise automatic tabbing is off and no "+" exists).
9198    impl DayWinDelegate {
9199        #[unsafe(method(newWindowForTab:))]
9200        fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
9201            ffi_guard::contain((), || {
9202                // A window in a tab group of its own gets another window of that group
9203                // (`register_new_window_for`); everything else gets File ▸ New Window's.
9204                let _ = match self.ivars().group.as_deref() {
9205                    Some(group) => day_core::windows::open_new_window_for_group(group),
9206                    None => day_core::windows::open_new_window(),
9207                };
9208            });
9209        }
9210    }
9211);
9212
9213impl DayWinDelegate {
9214    fn report_state_of(&self, notification: &NSNotification) {
9215        if let Some(obj) = unsafe { notification.object() }
9216            && let Ok(win) = obj.downcast::<NSWindow>()
9217        {
9218            self.report_state(&win);
9219        }
9220    }
9221}
9222
9223/// The day name for a key press, or `None` for every key the route does not carry — the
9224/// [`day_spec::KeyEvent`] names (docs/menus.md).
9225fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
9226    match unsafe { event.keyCode() } {
9227        123 => Some("ArrowLeft"),
9228        124 => Some("ArrowRight"),
9229        125 => Some("ArrowDown"),
9230        126 => Some("ArrowUp"),
9231        // Not the delete keys. This backend draws a menu bar, so a Delete accelerator on a
9232        // menu item owns them (docs/menus.md) — and a focused piece that CLAIMS a key stops
9233        // that accelerator from ever seeing it, which is how a canvas ends up swallowing the
9234        // Delete its own Edit menu was going to act on.
9235        //
9236        // A digit, main row or keypad, named by what it types. Never under ⌘, ⌥ or ⌃: those
9237        // combinations are accelerators, and claiming one would starve the menu the same way.
9238        _ => {
9239            let held = NSEventModifierFlags::Command
9240                | NSEventModifierFlags::Option
9241                | NSEventModifierFlags::Control;
9242            if event.modifierFlags().intersects(held) {
9243                return None;
9244            }
9245            let typed = event.characters()?.to_string();
9246            let mut chars = typed.chars();
9247            match (chars.next(), chars.next()) {
9248                (Some(c), None) => day_spec::KeyEvent::digit_name(c),
9249                _ => None,
9250            }
9251        }
9252    }
9253}
9254
9255/// A key press on the short route (docs/menus.md "Keys"): an arrow or a digit, for a node with
9256/// a key handler, with its phase. A press is claimed, so the input monitor reports its release
9257/// to `node`; a repeat is reported only while it continues a press Day delivered to whatever
9258/// holds focus now (a key held down into a newly focused view is not that view's until it is
9259/// pressed again, and gets no release either). Answers whether the key was claimed.
9260fn short_route_key_down(node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
9261    let Some(key) = key_name(event) else {
9262        return false;
9263    };
9264    if !day_spec::keys::handled(node) {
9265        return false;
9266    }
9267    let mods = key_modifiers(event.modifierFlags());
9268    if event.isARepeat() {
9269        if !input::owns_repeat(event) {
9270            return false;
9271        }
9272        emit(
9273            node,
9274            Event::Key(day_spec::KeyEvent::named(key, mods).with_phase(day_spec::KeyPhase::Repeat)),
9275        );
9276        return true;
9277    }
9278    emit(node, Event::Key(day_spec::KeyEvent::named(key, mods)));
9279    input::claim_key(event, node, key.to_string());
9280    true
9281}
9282
9283/// The web name for a key that types nothing, by its virtual key code, or `None` for a key
9284/// that types (docs/menus.md "The full route").
9285fn named_key(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
9286    Some(match unsafe { event.keyCode() } {
9287        123 => "ArrowLeft",
9288        124 => "ArrowRight",
9289        125 => "ArrowDown",
9290        126 => "ArrowUp",
9291        36 | 76 => "Enter",
9292        48 => "Tab",
9293        53 => "Escape",
9294        51 => "Backspace",
9295        117 => "Delete",
9296        115 => "Home",
9297        119 => "End",
9298        116 => "PageUp",
9299        121 => "PageDown",
9300        114 => "Insert",
9301        122 => "F1",
9302        120 => "F2",
9303        99 => "F3",
9304        118 => "F4",
9305        96 => "F5",
9306        97 => "F6",
9307        98 => "F7",
9308        100 => "F8",
9309        101 => "F9",
9310        109 => "F10",
9311        103 => "F11",
9312        111 => "F12",
9313        _ => return None,
9314    })
9315}
9316
9317/// A key press on the full route (`Decorate::keyboard`, docs/menus.md "The full route"), for
9318/// a canvas that took the whole keyboard. Answers whether the press was claimed.
9319///
9320/// The order is the policy: a ⌘ chord is the menu's and goes back to AppKit first, whatever
9321/// the key; a composition in progress owns every key until the input method commits or
9322/// cancels it; a key that types nothing is named; a ⌃ chord names its key and types nothing;
9323/// everything else is handed to the text input system, which turns a dead key into marked
9324/// text, an input method's keys into a composition, and a plain or ⌥ key into `insertText:`
9325/// with what it typed (⌥ types on a Mac: ⌥8 is "{" on a German layout; the piece still sees
9326/// [`day_spec::Modifiers::ALT.bits()`] and decides).
9327///
9328/// Phases (docs/menus.md "Keys"): a press is claimed for its release, which the input monitor
9329/// reports; a repeat continues only a press Day delivered here, and one that types still types
9330/// (holding `a` gives `aaaa`). A repeat of a press this canvas never heard is swallowed: the
9331/// canvas holds the whole keyboard, but the key is not its press.
9332fn full_route_key_down(view: &DayCanvas, node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
9333    let ptr = std::ptr::from_ref::<DayCanvas>(view).cast::<NSView>() as usize;
9334    let flags = event.modifierFlags();
9335    let mods = key_modifiers(flags);
9336    if flags.contains(NSEventModifierFlags::Command) {
9337        return false;
9338    }
9339    let composing = MARKED.with(|t| t.contains(ptr));
9340    let phase = if event.isARepeat() {
9341        if !composing && !input::owns_repeat(event) {
9342            return true;
9343        }
9344        day_spec::KeyPhase::Repeat
9345    } else {
9346        day_spec::KeyPhase::Down
9347    };
9348    // The press is this canvas's: its release is owed here (a composition's keys are the
9349    // input method's, and report no phases).
9350    let claim = |key: String| {
9351        if phase == day_spec::KeyPhase::Down {
9352            input::claim_key(event, node, key);
9353        }
9354    };
9355    if !composing && let Some(named) = named_key(event) {
9356        emit(
9357            node,
9358            Event::Key(day_spec::KeyEvent::named(named, mods).with_phase(phase)),
9359        );
9360        claim(named.to_string());
9361        return true;
9362    }
9363    let unmodified =
9364        unsafe { event.charactersIgnoringModifiers() }.map_or_default(|s| s.to_string());
9365    // A function or editing key the vocabulary lacks types a private-use glyph.
9366    let typeable = !unmodified.is_empty()
9367        && !unmodified
9368            .chars()
9369            .any(|c| c.is_control() || ('\u{f700}'..='\u{f8ff}').contains(&c));
9370    if !composing && flags.contains(NSEventModifierFlags::Control) {
9371        if typeable {
9372            emit(
9373                node,
9374                Event::Key(day_spec::KeyEvent::named(unmodified.clone(), mods).with_phase(phase)),
9375            );
9376            claim(unmodified);
9377        }
9378        return true;
9379    }
9380    if !composing && !typeable {
9381        return true;
9382    }
9383    INTERPRETING.with(|i| {
9384        *i.borrow_mut() = Some(Interpreting {
9385            key: unmodified,
9386            mods,
9387            phase,
9388            event: event.retain(),
9389        });
9390    });
9391    view.interpretKeyEvents(&NSArray::from_slice(&[event]));
9392    INTERPRETING.with(|i| *i.borrow_mut() = None);
9393    true
9394}
9395
9396/// The key press the text input system is interpreting (`full_route_key_down`): its unmodified
9397/// name, the modifier mask and the phase, so the text it commits is named by the key that typed
9398/// it; and the event, so a press that types is claimed for its release.
9399struct Interpreting {
9400    key: String,
9401    mods: u8,
9402    phase: day_spec::KeyPhase,
9403    event: Retained<NSEvent>,
9404}
9405
9406/// The text of an `NSString` or `NSAttributedString` the text input system hands over.
9407fn text_of_input_string(string: &AnyObject) -> String {
9408    if let Some(s) = string.downcast_ref::<NSString>() {
9409        s.to_string()
9410    } else if let Some(s) = string.downcast_ref::<objc2_foundation::NSAttributedString>() {
9411        s.string().to_string()
9412    } else {
9413        String::new()
9414    }
9415}
9416
9417/// AppKit's modifier flags as day's mask.
9418fn key_modifiers(f: NSEventModifierFlags) -> u8 {
9419    let mut modifiers = 0u8;
9420    if f.contains(NSEventModifierFlags::Shift) {
9421        modifiers |= day_spec::Modifiers::SHIFT.bits();
9422    }
9423    if f.contains(NSEventModifierFlags::Command) {
9424        modifiers |= day_spec::Modifiers::PRIMARY.bits();
9425    }
9426    if f.contains(NSEventModifierFlags::Option) {
9427        modifiers |= day_spec::Modifiers::ALT.bits();
9428    }
9429    if f.contains(NSEventModifierFlags::Control) {
9430        modifiers |= day_spec::Modifiers::CONTROL.bits();
9431    }
9432    modifiers
9433}
9434
9435impl DayWinDelegate {
9436    /// The manager AppKit's own undo mechanics act on: ask the FIRST RESPONDER, whose
9437    /// `undoManager` walks the chain itself — a field editor answers with its typing
9438    /// history, everything else falls through to `windowWillReturnUndoManager` and lands on
9439    /// the app's front. Falls back to the front when no window is key yet.
9440    fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
9441        let responder = NSApplication::sharedApplication(self.mtm())
9442            .keyWindow()
9443            .and_then(|w| w.firstResponder());
9444        responder
9445            .and_then(|r| unsafe { r.undoManager() })
9446            .or_else(|| {
9447                UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
9448            })
9449    }
9450}
9451
9452impl DayWinDelegate {
9453    fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
9454        let this = Self::alloc(mtm).set_ivars(WinIvars {
9455            node,
9456            group,
9457            last_state: Cell::new(day_spec::WindowState::Normal.code()),
9458        });
9459        unsafe { msg_send![super(this), init] }
9460    }
9461
9462    /// Report the window's display state if it changed since the last report
9463    /// (docs/windows.md "Window properties"): to the window's root node, or `WINDOW_NODE` for the
9464    /// primary, the same routing as `WindowResized`.
9465    fn report_state(&self, window: &NSWindow) {
9466        let state = ns_window_state(window);
9467        if self.ivars().last_state.replace(state.code()) != state.code() {
9468            log::debug!("appkit: window state now {state:?}");
9469            let target = self.ivars().node.unwrap_or(WINDOW_NODE);
9470            emit(target, Event::WindowStateChanged(state));
9471        }
9472    }
9473}
9474
9475/// What AppKit says a window is showing as: miniaturized wins (a fullscreen window can be
9476/// neither), then fullscreen (whose frame also reads as zoomed), then zoomed.
9477fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
9478    if window.isMiniaturized() {
9479        day_spec::WindowState::Minimized
9480    } else if window
9481        .styleMask()
9482        .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
9483    {
9484        day_spec::WindowState::Fullscreen
9485    } else if window.isZoomed() {
9486        day_spec::WindowState::Maximized
9487    } else {
9488        day_spec::WindowState::Normal
9489    }
9490}
9491
9492/// Ask AppKit for `state`, undoing whatever the window is in first: fullscreen and miniaturized
9493/// have to be left before a window can zoom, and each is its own toggle.
9494fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
9495    use day_spec::WindowState as S;
9496    let current = ns_window_state(window);
9497    if current == state {
9498        return;
9499    }
9500    unsafe {
9501        match current {
9502            S::Minimized => window.deminiaturize(None),
9503            // Leaving fullscreen animates; asking for another state in the same turn would be
9504            // dropped by AppKit mid-transition, so the request stops at leaving it. The state
9505            // signal reads back `Normal`, and a second request takes it from there.
9506            S::Fullscreen => {
9507                window.toggleFullScreen(None);
9508                return;
9509            }
9510            S::Maximized if state != S::Minimized => window.zoom(None),
9511            _ => {}
9512        }
9513        match state {
9514            S::Normal => {}
9515            S::Minimized => window.miniaturize(None),
9516            S::Maximized => {
9517                if !window.isZoomed() {
9518                    window.zoom(None);
9519                }
9520            }
9521            S::Fullscreen => window.toggleFullScreen(None),
9522        }
9523    }
9524}
9525
9526// ---------------------------------------------------------------------------
9527// The backend
9528// ---------------------------------------------------------------------------
9529
9530/// Renderers registered by external Day Piece crates (§8.2 layer 3 — linkme convenience).
9531#[distributed_slice]
9532pub static RENDERERS: [fn() -> Renderer<AppKit>];
9533
9534/// A live secondary window (docs/windows.md). The delegate is RETAINED here —
9535/// `setDelegate:` holds it weakly, and unlike the primary's (kept alive because `run`
9536/// never returns) a secondary's delegate would die at the end of `open_window` otherwise.
9537struct SecondaryWin {
9538    window: Retained<NSWindow>,
9539    #[allow(dead_code)] // held for lifetime only; AppKit talks to it via the weak delegate ref
9540    delegate: Retained<DayWinDelegate>,
9541    content: Handle,
9542}
9543
9544/// Deliver an explicitly registered Escape accelerator before a field editor swallows it.
9545/// The monitor is local to this process and removed with the backend.
9546struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
9547impl Drop for MenuEscapeMonitor {
9548    fn drop(&mut self) {
9549        unsafe { NSEvent::removeMonitor(&self.0) };
9550    }
9551}
9552
9553pub struct AppKit {
9554    menu_escape_monitor: Option<MenuEscapeMonitor>,
9555    sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
9556    /// The picker's delegate, which the picker holds only weakly.
9557    sharing_delegate: Option<Retained<DaySharePickerDelegate>>,
9558
9559    mtm: MainThreadMarker,
9560    registry: Registry<AppKit>,
9561    window: Option<Retained<NSWindow>>,
9562    content: Option<Handle>,
9563    secondary: Vec<SecondaryWin>,
9564    app_name: String,
9565    /// Where the next secondary window's top-left goes (docs/windows.md). macOS staggers new
9566    /// windows rather than stacking them: `cascadeTopLeftFromPoint:` places the window and
9567    /// answers the point after it, so threading that answer through here is the whole
9568    /// mechanism. `None` until the primary exists — the cascade starts from its corner.
9569    cascade: Option<NSPoint>,
9570    /// One tracking-area owner per view carrying a `.cursor()` (docs/cursor.md), keyed by the
9571    /// view pointer. Removed when the cursor goes back to `Default`.
9572    cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
9573}
9574
9575impl AppKit {
9576    /// Rebuild a `text_field` as the other class (plain ⇄ secure) and put the replacement
9577    /// where the old view was: same text, look and place among its siblings, same focus and
9578    /// selection, and every view-keyed entry moved to it. day-core drops the old handle
9579    /// without a `release`, so nothing keyed by it may stay behind.
9580    fn swap_text_field(
9581        &mut self,
9582        h: &Handle,
9583        old: &NSTextField,
9584        node: NodeId,
9585        secure: bool,
9586    ) -> Retained<NSTextField> {
9587        let new = new_text_field(self.mtm, node, secure);
9588        let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
9589        // Focus and selection first: reading them is only meaningful while the old field
9590        // still edits. `stringValue` below answers the field editor's live text.
9591        let window = h.window();
9592        let focused = window
9593            .as_deref()
9594            .is_some_and(|w| owns_first_responder(w, h));
9595        let selection = old.currentEditor().map(|e| e.selectedRange());
9596        unsafe {
9597            new.setStringValue(&old.stringValue());
9598            new.setPlaceholderString(old.placeholderString().as_deref());
9599            new.setEnabled(old.isEnabled());
9600            new.setFont(old.font().as_deref());
9601            new.setFrame(h.frame());
9602            new.setHidden(h.isHidden());
9603            new.setMenu(h.menu().as_deref());
9604            new.setToolTip(h.toolTip().as_deref());
9605            // Opacity and transform ride the layer (`set_opacity` / `set_transform`).
9606            if h.wantsLayer() {
9607                new.setWantsLayer(true);
9608                new.setAlphaValue(h.alphaValue());
9609                let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
9610                let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
9611                if !from.is_null() && !to.is_null() {
9612                    let t: CGAffineTransform = msg_send![from, affineTransform];
9613                    let _: () = msg_send![to, setAffineTransform: t];
9614                }
9615            }
9616            // Accessibility (`set_a11y`): only what was set explicitly, so the new class
9617            // keeps its own defaults (a secure field's role and hidden value) for the rest.
9618            if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
9619                new.setAccessibilityIdentifier(Some(&id));
9620            }
9621            if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
9622                new.setAccessibilityLabel(Some(&label));
9623            }
9624            if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
9625                new.setAccessibilityHelp(Some(&help));
9626            }
9627            if !h.isAccessibilityElement() {
9628                new.setAccessibilityElement(false);
9629            }
9630        }
9631        // Recognizers and the cursor's tracking area move as objects, keeping their targets.
9632        for r in &unsafe { h.gestureRecognizers() } {
9633            unsafe {
9634                h.removeGestureRecognizer(&r);
9635                new.addGestureRecognizer(&r);
9636            }
9637        }
9638        GESTURES.with(|m| {
9639            let mut m = m.borrow_mut();
9640            if let Some(targets) = m.remove(&old_key) {
9641                m.insert(new_key, targets);
9642            }
9643        });
9644        if let Some((owner, area)) = self.cursors.remove(&old_key) {
9645            unsafe {
9646                h.removeTrackingArea(&area);
9647                new.addTrackingArea(&area);
9648            }
9649            self.cursors.insert(new_key, (owner, area));
9650        }
9651        PAN_NODES.with(|t| rekey(t, old_key, new_key));
9652        HOVER_NODES.with(|t| rekey(t, old_key, new_key));
9653        ROTATE_NODES.with(|t| rekey(t, old_key, new_key));
9654        ROTATE_ANGLE.with(|t| rekey(t, old_key, new_key));
9655        KEY_NODES.with(|t| rekey(t, old_key, new_key));
9656        FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
9657        CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
9658        transfer::moved(h, &new);
9659        // The old field goes silent before it leaves: ending its editing session would
9660        // otherwise report a focus loss for a node that keeps its focus.
9661        unsafe { old.setDelegate(None) };
9662        TARGETS.with(|m| {
9663            m.borrow_mut().remove(&old_key);
9664        });
9665        if let Some(parent) = unsafe { h.superview() } {
9666            unsafe {
9667                parent.addSubview_positioned_relativeTo(
9668                    &new,
9669                    objc2_app_kit::NSWindowOrderingMode::Above,
9670                    Some(h),
9671                );
9672                h.removeFromSuperview();
9673            }
9674        }
9675        if focused && let Some(window) = window {
9676            FIELD_SWAP.with(|s| s.set(true));
9677            let taken = window.makeFirstResponder(Some(&new));
9678            FIELD_SWAP.with(|s| s.set(false));
9679            // Taking focus selects the whole text; put back what was selected (the caret,
9680            // usually). Both classes count in UTF-16 units, so the range carries over.
9681            if taken && let Some(editor) = new.currentEditor() {
9682                let len = unsafe { new.stringValue() }.length();
9683                let range = selection
9684                    .filter(|r| r.location.saturating_add(r.length) <= len)
9685                    .unwrap_or(objc2_foundation::NSRange::new(len, 0));
9686                editor.setSelectedRange(range);
9687            }
9688        }
9689        // Whatever else was keyed by the old view goes with it.
9690        day_spec::sidetable::sweep(old_key);
9691        new
9692    }
9693
9694    /// Create the AppKit toolkit with every registered renderer.
9695    ///
9696    /// # Panics
9697    ///
9698    /// Panics when called off the main thread.
9699    #[must_use]
9700    pub fn new() -> Self {
9701        let mtm =
9702            MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
9703        let mut registry = Registry::default();
9704        for f in RENDERERS {
9705            registry.register(f());
9706        }
9707        AppKit {
9708            menu_escape_monitor: None,
9709            mtm,
9710            registry,
9711            window: None,
9712            sharing: None,
9713            sharing_delegate: None,
9714            content: None,
9715            secondary: Vec::new(),
9716            app_name: "Day".into(),
9717            cascade: None,
9718            cursors: HashMap::new(),
9719        }
9720    }
9721
9722    /// Public helper for external renderers.
9723    #[must_use]
9724    pub fn mtm(&self) -> MainThreadMarker {
9725        self.mtm
9726    }
9727
9728    /// The `NSWindow` whose content container is `host`: a secondary window, or the primary.
9729    /// What the main window's capture should show when the main window itself is hidden.
9730    ///
9731    /// Native document tabs (`group_windows`) move every document into its own window of an
9732    /// `NSWindowTabGroup` and leave the primary window an off-screen host. A capture of that
9733    /// host is an empty frame (or no frame at all), while the user sees the group's selected
9734    /// tab: that window's content is the stand-in, preferring the group of the app's main
9735    /// window. `None` while the primary window is on screen, or when no document window is.
9736    fn shown_document_content(&self, content: &NSView) -> Option<Handle> {
9737        if content.window().is_none_or(|w| w.isVisible()) {
9738            return None;
9739        }
9740        let main = NSApplication::sharedApplication(self.mtm).mainWindow();
9741        let anchor = main
9742            .filter(|m| {
9743                self.secondary
9744                    .iter()
9745                    .any(|w| std::ptr::eq(&raw const *w.window, &raw const **m))
9746            })
9747            .or_else(|| {
9748                self.secondary
9749                    .iter()
9750                    .find(|w| w.window.isVisible())
9751                    .map(|w| w.window.clone())
9752            })?;
9753        let shown = anchor
9754            .tabGroup()
9755            .and_then(|g| g.selectedWindow())
9756            .unwrap_or(anchor);
9757        self.secondary
9758            .iter()
9759            .find(|w| std::ptr::eq(&raw const *w.window, &raw const *shown) && w.window.isVisible())
9760            .map(|w| w.content.clone())
9761    }
9762
9763    fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
9764        if let Some(w) = self
9765            .secondary
9766            .iter()
9767            .find(|w| ptr_of(&w.content) == ptr_of(host))
9768        {
9769            return Some(w.window.clone());
9770        }
9771        self.content
9772            .as_ref()
9773            .filter(|c| ptr_of(c) == ptr_of(host))
9774            .and(self.window.clone())
9775    }
9776
9777    /// Build a Day window: titled + closable (Preferences kind drops resize/minimize and
9778    /// disallows tabbing per macOS convention; Normal windows share the `day.normal`
9779    /// tabbing group), a flipped content view, and a per-window delegate (`node`: `None` =
9780    /// primary). The window is NOT released-when-closed — Rust's `Retained` owns it, and
9781    /// the AppKit default would double-release under us on close.
9782    fn make_window(
9783        &self,
9784        options: &WindowOptions,
9785        prefs_style: bool,
9786        node: Option<NodeId>,
9787    ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
9788        use day_spec::WindowTabbing as T;
9789        use objc2_app_kit::NSWindowTabbingMode as M;
9790        let mtm = self.mtm;
9791        let (title, size, min_size, tabbing) = (
9792            options.title.as_str(),
9793            options.size,
9794            options.min_size,
9795            &options.tabbing,
9796        );
9797        let content_rect =
9798            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
9799        // The kind decides the controls, the chrome decides the frame (docs/window-chrome.md).
9800        let style = window_chrome::style_mask(options, prefs_style);
9801        let window = window_chrome::alloc_window(
9802            mtm,
9803            content_rect,
9804            style,
9805            options.chrome == day_spec::WindowChrome::Frameless,
9806        );
9807        unsafe { window.setReleasedWhenClosed(false) };
9808        window.setTitle(&NSString::from_str(title));
9809        if let Some(min) = min_size {
9810            unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
9811        }
9812        if let Some(max) = options.max_size {
9813            unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
9814        }
9815        let group = match tabbing {
9816            T::Group(g) | T::Preferred(g) => Some(g.clone()),
9817            T::Automatic | T::Disallowed => None,
9818        };
9819        match tabbing {
9820            _ if prefs_style => window.setTabbingMode(M::Disallowed),
9821            T::Disallowed => window.setTabbingMode(M::Disallowed),
9822            // Same-kind Day windows group as native tabs (System Settings "prefer tabs",
9823            // View ▸ Show Tab Bar, Merge All Windows) — meaningful once a second Normal
9824            // window can exist; inert while automatic tabbing is globally off (see `run`).
9825            T::Automatic => unsafe {
9826                window.setTabbingIdentifier(&NSString::from_str("day.normal"));
9827            },
9828            T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
9829            T::Preferred(g) => {
9830                unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
9831                window.setTabbingMode(M::Preferred);
9832            }
9833        }
9834        if group.is_some() {
9835            // A named group is the app asking for tabs, so the class-wide switch `run` may have
9836            // turned off (no New Window builder) goes back on for it.
9837            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
9838        }
9839        let delegate = DayWinDelegate::new(mtm, node, group);
9840        window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
9841        let content = view_of(&DayFlipped::new(mtm));
9842        window.setContentView(Some(&content));
9843        window_chrome::apply(&window, &content, options);
9844        // Tab / Shift-Tab (docs/focus.md). AppKit does NOT derive the key view loop from the view
9845        // hierarchy: `nextKeyView` is nil on a programmatically built window and the loop stays
9846        // empty, so Tab moves focus OUT of a text field and onto nothing — measured on the
9847        // showcase's Focus page, where three Tabs in a row left every field unfocused. Every other
9848        // Day backend gets traversal from its widget order for free; this is the one that has to
9849        // ask. Autorecalculation rather than a call at the end of each layout because Day's tree
9850        // is reactive: fields appear, move, and vanish between passes, and AppKit rebuilding the
9851        // loop on hierarchy changes is the same rule expressed once.
9852        window.setAutorecalculatesKeyViewLoop(true);
9853        (window, delegate, content)
9854    }
9855}
9856
9857impl Default for AppKit {
9858    fn default() -> Self {
9859        Self::new()
9860    }
9861}
9862
9863fn view_of<T: AsRef<NSView>>(x: &Retained<T>) -> Handle {
9864    Retained::from((**x).as_ref())
9865}
9866
9867fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
9868    unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
9869}
9870
9871/// The macOS native semantic text style for a logical [`Font`] (`None` for a custom size).
9872/// `NSFont.preferredFont(forTextStyle:)` gives the OS's own typography, tracking the system settings.
9873fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
9874    use objc2_app_kit::*;
9875    unsafe {
9876        Some(match f {
9877            Font::LargeTitle => NSFontTextStyleLargeTitle,
9878            Font::Title => NSFontTextStyleTitle1,
9879            Font::Title2 => NSFontTextStyleTitle2,
9880            Font::Title3 => NSFontTextStyleTitle3,
9881            Font::Headline => NSFontTextStyleHeadline,
9882            Font::Subheadline => NSFontTextStyleSubheadline,
9883            Font::Body => NSFontTextStyleBody,
9884            Font::Callout => NSFontTextStyleCallout,
9885            Font::Footnote => NSFontTextStyleFootnote,
9886            Font::Caption => NSFontTextStyleCaption1,
9887            Font::Caption2 => NSFontTextStyleCaption2,
9888            Font::System(_) | Font::Custom(..) => return None,
9889        })
9890    }
9891}
9892
9893fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
9894    use day_spec::FontWeight as W;
9895    use objc2_app_kit::*;
9896    unsafe {
9897        match w {
9898            W::UltraLight => NSFontWeightUltraLight,
9899            W::Thin => NSFontWeightThin,
9900            W::Light => NSFontWeightLight,
9901            W::Regular => NSFontWeightRegular,
9902            W::Medium => NSFontWeightMedium,
9903            W::Semibold => NSFontWeightSemibold,
9904            W::Bold => NSFontWeightBold,
9905            W::Heavy => NSFontWeightHeavy,
9906            W::Black => NSFontWeightBlack,
9907        }
9908    }
9909}
9910
9911/// The `NSFontManager` weight rung (0 … 15) for a Day weight — the scale
9912/// `fontWithFamily:traits:weight:size:` matches faces on (5 = regular, 9 = bold).
9913fn nsfm_weight(w: day_spec::FontWeight) -> isize {
9914    use day_spec::FontWeight as W;
9915    match w {
9916        W::UltraLight => 2,
9917        W::Thin => 3,
9918        W::Light => 4,
9919        W::Regular => 5,
9920        W::Medium => 6,
9921        W::Semibold => 8,
9922        W::Bold => 9,
9923        W::Heavy => 10,
9924        W::Black => 12,
9925    }
9926}
9927
9928/// Resolve a canvas font (docs/fonts.md) at an absolute size: the system face for `None`,
9929/// else the family's nearest member through `NSFontManager` (which also synthesizes a bold or
9930/// italic the family lacks), falling back to a PostScript/full-name lookup (a bundled font
9931/// registered in `run`) and then to the system font with one warning.
9932fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
9933    use objc2_app_kit::*;
9934    let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
9935    // A painting thread draws with the fonts the UI thread resolved for this export
9936    // (`OffscreenResources`); on the UI thread the table is empty and the lookup falls through.
9937    let prepared = OFFSCREEN_FONTS.with(|t| {
9938        t.borrow()
9939            .iter()
9940            .find(|(key, _)| key.0 == size.to_bits() && key.1 == *font)
9941            .map(|(_, f)| f.clone())
9942    });
9943    if let Some(f) = prepared {
9944        return f;
9945    }
9946    let Some(mtm) = objc2::MainThreadMarker::new() else {
9947        // Off the UI thread with a font the collector never saw (it walks every text op, so
9948        // this is a guard, not a path): the system face, since `NSFontManager` is not ours to
9949        // call here. `NSFont` itself is usable from any thread.
9950        return unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
9951    };
9952    let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
9953    let mut traits = NSFontTraitMask::empty();
9954    if weight >= day_spec::FontWeight::Semibold {
9955        traits |= NSFontTraitMask::BoldFontMask;
9956    }
9957    if font.italic {
9958        traits |= NSFontTraitMask::ItalicFontMask;
9959    }
9960    let Some(family) = font.family.as_deref() else {
9961        let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
9962        return if font.italic {
9963            unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
9964        } else {
9965            base
9966        };
9967    };
9968    let ns_family = NSString::from_str(family);
9969    if let Some(f) = unsafe {
9970        manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
9971    } {
9972        return f;
9973    }
9974    if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
9975        return if traits.is_empty() {
9976            f
9977        } else {
9978            unsafe { manager.convertFont_toHaveTrait(&f, traits) }
9979        };
9980    }
9981    log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
9982    unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
9983}
9984
9985/// The attribute dictionary canvas text draws and measures with (the same one, so
9986/// `measure_text` and `replay` agree on the line box).
9987fn canvas_text_attrs(
9988    font: &NSFont,
9989    color: day_spec::Color,
9990) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
9991    let col = nscolor(color);
9992    // SAFETY: both are AppKit's own attribute-name constants, valid for the process lifetime.
9993    let keys: [&NSString; 2] = unsafe {
9994        [
9995            objc2_app_kit::NSFontAttributeName,
9996            objc2_app_kit::NSForegroundColorAttributeName,
9997        ]
9998    };
9999    let objs: [&objc2::runtime::AnyObject; 2] = [
10000        font as &objc2::runtime::AnyObject,
10001        col.as_ref() as &objc2::runtime::AnyObject,
10002    ];
10003    objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
10004}
10005
10006/// Resolve a [`FontSpec`] to a native `NSFont`: a semantic style via `preferredFont(forTextStyle:)`
10007/// (or a custom system size), then an optional weight override (at the same size) and italic trait.
10008fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
10009    use objc2_app_kit::*;
10010    let base: Retained<NSFont> = match spec.style {
10011        Font::System(pt) => {
10012            let w = spec
10013                .weight
10014                .map_or(unsafe { NSFontWeightRegular }, ns_weight);
10015            unsafe { NSFont::systemFontOfSize_weight(pt, w) }
10016        }
10017        // A bundled family (§18.4), registered with CoreText in run(). fontWithName resolves
10018        // family, full, and PostScript names. A weight override maps to the bold trait (the
10019        // family decides what it can supply); unknown families fall back to the system font.
10020        Font::Custom(name, pt) => {
10021            if let Some(f) = unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
10022                if spec
10023                    .weight
10024                    .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
10025                {
10026                    let mtm =
10027                        objc2::MainThreadMarker::new().expect("labels realize on the main thread");
10028                    unsafe {
10029                        NSFontManager::sharedFontManager(mtm)
10030                            .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
10031                    }
10032                } else {
10033                    f
10034                }
10035            } else {
10036                log::warn!(
10037                    "unknown font family {name:?} — falling back to the system font \
10038                     (is the file in the project's fonts/ directory?)"
10039                );
10040                let w = spec
10041                    .weight
10042                    .map_or(unsafe { NSFontWeightRegular }, ns_weight);
10043                unsafe { NSFont::systemFontOfSize_weight(pt, w) }
10044            }
10045        }
10046        style => {
10047            // Invariant: System/Custom matched above, so only the semantic styles — which
10048            // `ns_text_style` maps exhaustively — can reach this arm.
10049            let ts = ns_text_style(style).expect("semantic style");
10050            let opts = objc2_foundation::NSDictionary::new();
10051            let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
10052            match spec.weight {
10053                // A weight override keeps the style's (system-resolved) size but re-picks the weight.
10054                Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
10055                None => f,
10056            }
10057        }
10058    };
10059    // Tabular figures. Cocoa exposes them as a whole font, not a trait, so this re-picks the
10060    // system font at the resolved size/weight rather than converting — which is why it only
10061    // applies to the system styles: a bundled `Font::Custom` family keeps its own figures (asking
10062    // for the system's monospaced-digit face there would silently swap the typeface).
10063    let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
10064        let w = spec
10065            .weight
10066            .map_or(unsafe { NSFontWeightRegular }, ns_weight);
10067        unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
10068    } else {
10069        base
10070    };
10071    // Monospace, by the same rule as tabular: Cocoa ships it as a whole font, so this re-picks
10072    // the system's monospaced face at the resolved size and weight. Skipped for a bundled family
10073    // — swapping a chosen typeface for the system mono would be a surprise, not a refinement.
10074    let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
10075        let w = spec
10076            .weight
10077            .map_or(unsafe { NSFontWeightRegular }, ns_weight);
10078        unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
10079    } else {
10080        base
10081    };
10082    // Relative size (`FontSpec::scale`). Applied last, over whatever face the traits above
10083    // settled on, and through `convertFont_toSize` so a bundled family keeps its typeface —
10084    // re-picking the system font here would undo the Custom/monospace/tabular work above.
10085    #[expect(
10086        clippy::float_cmp,
10087        reason = "1.0 is the exact unscaled default of `FontSpec::scale`"
10088    )]
10089    let base = if spec.scale == 1.0 {
10090        base
10091    } else {
10092        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
10093        let pts = spec.resolved_points(base.pointSize());
10094        unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
10095    };
10096    let base = if spec.italic {
10097        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
10098        unsafe {
10099            NSFontManager::sharedFontManager(mtm)
10100                .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
10101        }
10102    } else {
10103        base
10104    };
10105    with_font_features(base, spec.small_caps, spec.oldstyle_figures)
10106}
10107
10108/// Small capitals (`smcp`) and oldstyle figures (`onum`) as the font descriptor's AAT
10109/// feature settings: `kLowerCaseType`/`kLowerCaseSmallCapsSelector` (37/1) and
10110/// `kNumberCaseType`/`kLowerCaseNumbersSelector` (21/0). Last of the font steps, because the
10111/// font manager's trait conversions above re-pick the face and would drop them. A face without
10112/// the feature draws its ordinary glyphs; nothing is synthesized.
10113fn with_font_features(
10114    font: Retained<NSFont>,
10115    small_caps: bool,
10116    oldstyle: bool,
10117) -> Retained<NSFont> {
10118    use objc2_app_kit::{
10119        NSFontFeatureSelectorIdentifierKey, NSFontFeatureSettingsAttribute,
10120        NSFontFeatureTypeIdentifierKey,
10121    };
10122    let mut pairs: Vec<(i64, i64)> = Vec::new();
10123    if small_caps {
10124        pairs.push((37, 1));
10125    }
10126    if oldstyle {
10127        pairs.push((21, 0));
10128    }
10129    if pairs.is_empty() {
10130        return font;
10131    }
10132    let settings: Vec<Retained<NSDictionary<NSString, AnyObject>>> = pairs
10133        .into_iter()
10134        .map(|(kind, selector)| {
10135            let kind: Retained<AnyObject> = NSNumber::new_i64(kind).into();
10136            let selector: Retained<AnyObject> = NSNumber::new_i64(selector).into();
10137            unsafe {
10138                NSDictionary::from_retained_objects(
10139                    &[
10140                        NSFontFeatureTypeIdentifierKey,
10141                        NSFontFeatureSelectorIdentifierKey,
10142                    ],
10143                    &[kind, selector],
10144                )
10145            }
10146        })
10147        .collect();
10148    let settings: Retained<AnyObject> = NSArray::from_retained_slice(&settings).into();
10149    let attrs = NSDictionary::from_retained_objects(
10150        &[unsafe { NSFontFeatureSettingsAttribute }],
10151        &[settings],
10152    );
10153    let descriptor = unsafe {
10154        font.fontDescriptor()
10155            .fontDescriptorByAddingAttributes(&attrs)
10156    };
10157    NSFont::fontWithDescriptor_size(&descriptor, font.pointSize()).unwrap_or(font)
10158}
10159
10160/// How many lines a label may draw: one when it does not wrap, else its limit (0 = no limit).
10161fn label_line_limit(wraps: bool, max_lines: u32) -> u32 {
10162    if wraps { max_lines } else { 1 }
10163}
10164
10165/// The line break mode for a label held to `lines` lines (0 = no limit). One line takes the
10166/// truncation mode itself. More lines must word-wrap: a truncating mode makes the text system lay the
10167/// whole paragraph on one line (and `NSCell` turns `wraps` off with it), so a multi-line limit
10168/// wraps and lets `truncatesLastVisibleLine` end the last line, which AppKit does at the tail
10169/// only (docs/text.md "Line limits and truncation").
10170fn label_line_break(lines: u32, mode: day_spec::props::Truncation) -> NSLineBreakMode {
10171    use day_spec::props::Truncation;
10172    if lines != 1 {
10173        return NSLineBreakMode::ByWordWrapping;
10174    }
10175    match mode {
10176        Truncation::Tail => NSLineBreakMode::ByTruncatingTail,
10177        Truncation::Head => NSLineBreakMode::ByTruncatingHead,
10178        Truncation::Middle => NSLineBreakMode::ByTruncatingMiddle,
10179    }
10180}
10181
10182/// A line height multiple as points, or `None` for the font's natural height (`0.0`,
10183/// negative or nonfinite: `LabelProps::line_height`).
10184fn label_line_points(multiple: f64, font_points: f64) -> Option<f64> {
10185    (multiple.is_finite() && multiple > 0.0).then_some(multiple * font_points)
10186}
10187
10188/// The font's natural line height (ascender + descender + leading), as the text system lays a
10189/// line.
10190fn natural_line_height(font: &NSFont) -> f64 {
10191    thread_local! {
10192        static METRICS: Retained<objc2_app_kit::NSLayoutManager> =
10193            objc2_app_kit::NSLayoutManager::new();
10194    }
10195    METRICS.with(|metrics| metrics.defaultLineHeightForFont(font))
10196}
10197
10198/// Apply a label's paragraph attributes (docs/text.md "Line limits and truncation", "Letter
10199/// spacing and line height", "Alignment") from its ivars: the field's line limit and break
10200/// mode, its alignment and writing direction, and, where the text is attributed, the same
10201/// across the string. Idempotent; called at realize and after every label patch.
10202///
10203/// Letter spacing (`NSKernAttributeName`) and line height (`minimumLineHeight` =
10204/// `maximumLineHeight`) exist only as string attributes, so a plain label that asks for
10205/// either becomes attributed and stays so ("stamped"), its font and color copied from the
10206/// field.
10207fn apply_label_paragraph(label: &DayLabel) {
10208    let iv = label.ivars();
10209    let p = iv.paragraph.get();
10210    let lines = label_line_limit(iv.wraps.get(), p.max_lines);
10211    let mode = label_line_break(lines, p.truncation);
10212    let rtl = match iv.direction.get() {
10213        Some(d) => d == day_spec::LayoutDirection::Rtl,
10214        None => {
10215            label.userInterfaceLayoutDirection()
10216                == objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft
10217        }
10218    };
10219    let writing = match iv.direction.get() {
10220        None => objc2_app_kit::NSWritingDirection::Natural,
10221        Some(_) if rtl => objc2_app_kit::NSWritingDirection::RightToLeft,
10222        Some(_) => objc2_app_kit::NSWritingDirection::LeftToRight,
10223    };
10224    let align = nstextalign(iv.align.get(), rtl);
10225    unsafe {
10226        label.setMaximumNumberOfLines(lines as isize);
10227        // `setLineBreakMode:` last: on `NSCell` it also decides `wraps` (a truncating mode
10228        // turns wrapping off, word wrapping turns it on).
10229        if let Some(cell) = label.cell() {
10230            cell.setWraps(lines != 1);
10231            cell.setUsesSingleLineMode(lines == 1);
10232            cell.setTruncatesLastVisibleLine(lines > 0);
10233        }
10234        label.setLineBreakMode(mode);
10235        label.setAlignment(align);
10236        label.setBaseWritingDirection(writing);
10237    }
10238    let needs_string = p.letter_spacing != 0.0 || label_line_points(p.line_height, 1.0).is_some();
10239    if !iv.has_runs.get() && !needs_string && !iv.stamped.get() {
10240        return;
10241    }
10242    if !iv.has_runs.get() {
10243        iv.stamped.set(true);
10244    }
10245    stamp_paragraph(label, &p, mode, align, writing);
10246}
10247
10248/// Stamp the paragraph attributes across a label's whole attributed string. The cell's
10249/// settings alone do not reach an attributed string: the string carries its own paragraph
10250/// style, and the string's wins.
10251fn stamp_paragraph(
10252    label: &DayLabel,
10253    p: &day_spec::props::LabelParagraph,
10254    mode: NSLineBreakMode,
10255    align: objc2_app_kit::NSTextAlignment,
10256    writing: objc2_app_kit::NSWritingDirection,
10257) {
10258    use objc2_foundation::{NSMutableAttributedString, NSRange};
10259    let font = unsafe { label.font() }.unwrap_or_else(|| nsfont(day_spec::FontSpec::default()));
10260    let points = font.pointSize();
10261    unsafe {
10262        let cur = label.attributedStringValue();
10263        let m = NSMutableAttributedString::initWithAttributedString(
10264            NSMutableAttributedString::alloc(),
10265            &cur,
10266        );
10267        let whole = NSRange::new(0, cur.length());
10268        if !label.ivars().has_runs.get() {
10269            // A stamped plain label: the field's font and color are the truth, the string a
10270            // copy of them (a font or color patch sets the field, then stamps again).
10271            let fg = label
10272                .textColor()
10273                .unwrap_or_else(objc2_app_kit::NSColor::labelColor);
10274            m.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &font, whole);
10275            m.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
10276        }
10277        let style = objc2_app_kit::NSMutableParagraphStyle::new();
10278        style.setAlignment(align);
10279        style.setLineBreakMode(mode);
10280        style.setBaseWritingDirection(writing);
10281        let line = label_line_points(p.line_height, points);
10282        if let Some(h) = line {
10283            style.setMinimumLineHeight(h);
10284            style.setMaximumLineHeight(h);
10285        }
10286        m.addAttribute_value_range(objc2_app_kit::NSParagraphStyleAttributeName, &style, whole);
10287        if p.letter_spacing == 0.0 {
10288            m.removeAttribute_range(objc2_app_kit::NSKernAttributeName, whole);
10289        } else {
10290            let kern = NSNumber::new_f64(p.letter_spacing * points);
10291            m.addAttribute_value_range(objc2_app_kit::NSKernAttributeName, &kern, whole);
10292        }
10293        // TextKit puts a fixed line's extra height above the glyphs; raising the baseline by
10294        // half of it centers them in the line box, the CSS model the spec asks for.
10295        match line {
10296            Some(h) => {
10297                let offset = NSNumber::new_f64((h - natural_line_height(&font)) / 2.0);
10298                m.addAttribute_value_range(
10299                    objc2_app_kit::NSBaselineOffsetAttributeName,
10300                    &offset,
10301                    whole,
10302                );
10303            }
10304            None => m.removeAttribute_range(objc2_app_kit::NSBaselineOffsetAttributeName, whole),
10305        }
10306        label.setAttributedStringValue(&m);
10307    }
10308}
10309
10310/// Build an `NSAttributedString` for a label's text + runs (docs/text-runs.md).
10311///
10312/// Ranges arrive as BYTE offsets into a Rust `str`; `NSAttributedString` indexes UTF-16. The
10313/// conversion is per-run rather than a blanket assumption: any text with an emoji or a CJK
10314/// character makes the two disagree, and an off-by-N range there styles the wrong words.
10315fn attributed_label(
10316    text: &str,
10317    base_font: &NSFont,
10318    color: Option<day_spec::Ink>,
10319    role: day_spec::props::TextRole,
10320    runs: &[day_spec::TextRun],
10321) -> Retained<objc2_foundation::NSAttributedString> {
10322    use objc2_foundation::{NSMutableAttributedString, NSRange};
10323    let ns = NSString::from_str(text);
10324    let s = unsafe {
10325        NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
10326    };
10327    let whole = NSRange::new(0, ns.length());
10328    unsafe {
10329        s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
10330        // Always a foreground: an attributed range with no color attribute draws in black,
10331        // which is unreadable in dark mode. `labelColor` is the adaptive default the field
10332        // would have used on its own.
10333        // An explicit color wins; otherwise the ROLE picks which adaptive system color to use.
10334        // Both are adaptive, which is the point of asking for a role instead of a grey: the
10335        // secondary label is legible against either appearance's background, and a literal one
10336        // cannot be.
10337        let fg = color.map_or_else(
10338            || match role {
10339                day_spec::props::TextRole::Secondary => {
10340                    objc2_app_kit::NSColor::secondaryLabelColor()
10341                }
10342                day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
10343            },
10344            color::nsink,
10345        );
10346        s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
10347    }
10348    for r in runs {
10349        let Some(range) = utf16_range(text, &r.range) else {
10350            continue;
10351        };
10352        unsafe {
10353            s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
10354            if let Some(c) = r.color {
10355                s.addAttribute_value_range(
10356                    objc2_app_kit::NSForegroundColorAttributeName,
10357                    &color::nsink(c),
10358                    range,
10359                );
10360            }
10361            if let Some(c) = r.background {
10362                s.addAttribute_value_range(
10363                    objc2_app_kit::NSBackgroundColorAttributeName,
10364                    &color::nsink(c),
10365                    range,
10366                );
10367            }
10368            // A decoration's color rides beside its style; `None` leaves the attribute out,
10369            // which AppKit draws in the run's foreground color.
10370            for (line, style_key, color_key) in [
10371                (
10372                    r.underline,
10373                    objc2_app_kit::NSUnderlineStyleAttributeName,
10374                    objc2_app_kit::NSUnderlineColorAttributeName,
10375                ),
10376                (
10377                    r.strikethrough,
10378                    objc2_app_kit::NSStrikethroughStyleAttributeName,
10379                    objc2_app_kit::NSStrikethroughColorAttributeName,
10380                ),
10381            ] {
10382                let Some(d) = line else { continue };
10383                let style = objc2_foundation::NSNumber::new_i64(ns_underline(Some(d)));
10384                s.addAttribute_value_range(style_key, &style, range);
10385                if let Some(c) = d.color {
10386                    s.addAttribute_value_range(color_key, &color::nsink(c), range);
10387                }
10388            }
10389            if let Some(url) = r.link.as_deref() {
10390                // The native field editor hit-tests this attribute; DayLabel handles its
10391                // delegate callback and reports LinkActivated without opening the URL itself.
10392                let value = NSString::from_str(url);
10393                s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
10394            }
10395        }
10396    }
10397    s.into_super()
10398}
10399
10400/// [`Decoration`](day_spec::Decoration) as an `NSUnderlineStyle` bitmask: the line style in the low
10401/// byte, the pattern in the second. `Dotted`/`Wavy` are patterns over a single line, which is
10402/// exactly how AppKit spells them. AppKit has no wavy pattern; `Wavy` draws the dash-dot-dot
10403/// pattern. The same mask serves `NSStrikethroughStyleAttributeName`; the color goes in
10404/// `NSUnderlineColorAttributeName`/`NSStrikethroughColorAttributeName` beside it.
10405fn ns_underline(u: Option<day_spec::Decoration>) -> i64 {
10406    use day_spec::DecorationStyle as U;
10407    match u.map(|d| d.style) {
10408        None => 0,
10409        Some(U::Single) => 0x01,
10410        Some(U::Double) => 0x09,
10411        Some(U::Dotted) => 0x01 | 0x0100,
10412        Some(U::Wavy) => 0x01 | 0x0400,
10413    }
10414}
10415
10416/// A byte range in `text` as an `NSRange` in UTF-16 units, or `None` if it is out of bounds.
10417fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
10418    let start = text.get(..r.start)?.encode_utf16().count();
10419    let len = text.get(r.clone())?.encode_utf16().count();
10420    Some(objc2_foundation::NSRange::new(start, len))
10421}
10422
10423/// Register every bundled font file (the project's `fonts/`, staged per §18.4) with CoreText for
10424/// this process, so `Font::Custom` family names resolve through `NSFont::fontWithName`. Called
10425/// once from `run()`; a failure (already registered on a hot relaunch, or a broken file) only
10426/// means that family won't resolve, so it logs and moves on.
10427fn register_bundled_fonts() {
10428    // CFURLRef is toll-free bridged with NSURL, so the NSURL pointer passes straight through.
10429    #[link(name = "CoreText", kind = "framework")]
10430    unsafe extern "C" {
10431        fn CTFontManagerRegisterFontsForURL(
10432            font_url: *const std::ffi::c_void,
10433            scope: u32, // kCTFontManagerScopeProcess = 1
10434            error: *mut *const std::ffi::c_void,
10435        ) -> bool;
10436    }
10437    for path in day_spec::fonts::bundled_fonts() {
10438        let url = unsafe {
10439            objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
10440        };
10441        let ok = unsafe {
10442            CTFontManagerRegisterFontsForURL(
10443                Retained::as_ptr(&url).cast::<std::ffi::c_void>(),
10444                1,
10445                std::ptr::null_mut(),
10446            )
10447        };
10448        if !ok {
10449            log::warn!("could not register bundled font {}", path.display());
10450        }
10451    }
10452}
10453
10454/// `TextAlign` → AppKit. `Natural` rather than `Left` for the leading case: it follows the
10455/// writing direction, so an RTL locale aligns right without the app asking (docs/localization.md).
10456/// `Trailing` has no natural form, so it takes the edge opposite the label's direction (`rtl`).
10457/// `Justified` is AppKit's own: the last line follows the writing direction.
10458fn nstextalign(a: day_spec::props::TextAlign, rtl: bool) -> objc2_app_kit::NSTextAlignment {
10459    match a {
10460        day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
10461        day_spec::props::TextAlign::Justified => objc2_app_kit::NSTextAlignment::Justified,
10462        day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
10463        day_spec::props::TextAlign::Trailing if rtl => objc2_app_kit::NSTextAlignment::Left,
10464        day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
10465    }
10466}
10467
10468/// If `parent` is a scroll view, children go into its (flipped) document view.
10469fn content_of(parent: &Handle) -> Retained<NSView> {
10470    if let Some(sv) = parent.downcast_ref::<NSScrollView>()
10471        && let Some(doc) = unsafe { sv.documentView() }
10472    {
10473        return doc;
10474    }
10475    parent.clone()
10476}
10477
10478/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
10479/// a visible placeholder. A missing renderer usually means the piece's `appkit` feature wasn't enabled
10480/// (Tier A.2 derives it automatically under `day build`; a bare `cargo` build may miss it). Deduped
10481/// per kind so a placeholder rendered every frame doesn't spam the log.
10482fn warn_missing_renderer(kind: PieceKind) {
10483    day_spec::placeholder::report(kind, "appkit");
10484}
10485
10486/// The visible-but-harmless placeholder label the unregistered-kind arm renders. Shared with
10487/// the [`props_of`] mismatch fallback, so a wrong props payload degrades to the same surface
10488/// (the warning is already reported by `props_of` itself).
10489pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
10490    view_of(&unsafe {
10491        NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
10492    })
10493}
10494
10495impl Toolkit for AppKit {
10496    /// Settled unless a toolbar edit is still painting (toolbar.rs `CHROME_SETTLE`); AppKit's
10497    /// own transitions (sheets, nav pushes) complete within the turn that starts them.
10498    fn ui_idle(&mut self) -> bool {
10499        toolbar::chrome_settled()
10500    }
10501
10502    type Handle = Handle;
10503
10504    /// Every role's AppKit color (`color::role_color`), resolved in sRGB for the app's
10505    /// effective appearance: what `Palette::current` holds and `day::resolve` answers.
10506    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
10507        let result = std::cell::Cell::new(role.fallback(self.dark_mode()));
10508        let block = block2::StackBlock::new(|| {
10509            if let Some(rgb) = color::srgb(&color::role_color(role)) {
10510                result.set(rgb);
10511            }
10512        });
10513        NSApplication::sharedApplication(self.mtm())
10514            .effectiveAppearance()
10515            .performAsCurrentDrawingAppearance(&block);
10516        result.get()
10517    }
10518
10519    fn dark_mode(&mut self) -> bool {
10520        // The app's EFFECTIVE appearance — one source for the system setting, the DAY_THEME
10521        // launch force (applied as an NSApp override at startup), and a set_appearance call.
10522        let app = NSApplication::sharedApplication(self.mtm());
10523        app.effectiveAppearance()
10524            .name()
10525            .to_string()
10526            .contains("Dark")
10527    }
10528
10529    /// System Settings › Accessibility › Display › "Reduce motion", as `NSWorkspace` reports it
10530    /// (docs/accessibility.md). `install_reduce_motion_observer` re-reads it on a flip.
10531    fn reduce_motion(&mut self) -> bool {
10532        objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
10533    }
10534
10535    /// macOS is the one platform whose badge takes arbitrary text: `NSDockTile.badgeLabel` is a
10536    /// `String`, so `Text` renders literally and a count is just its decimal form. A nil label
10537    /// clears it (docs/badge.md).
10538    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
10539        use day_spec::AppBadge;
10540        let label = match badge {
10541            // Zero clears, matching the platform convention the doc states.
10542            AppBadge::None | AppBadge::Count(0) => None,
10543            AppBadge::Count(n) => Some(n.to_string()),
10544            AppBadge::Text(t) if t.is_empty() => None,
10545            AppBadge::Text(t) => Some(t.clone()),
10546            // No dedicated dot on the Dock; the smallest honest mark is a single bullet.
10547            AppBadge::Dot => Some("\u{2022}".to_string()),
10548        };
10549        let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
10550        let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
10551        unsafe { tile.setBadgeLabel(ns.as_deref()) };
10552        tile.display();
10553    }
10554
10555    fn set_appearance(&mut self, dark: Option<bool>) {
10556        let app = NSApplication::sharedApplication(self.mtm());
10557        let appearance = dark.and_then(|d| {
10558            objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
10559                if d {
10560                    objc2_app_kit::NSAppearanceNameDarkAqua
10561                } else {
10562                    objc2_app_kit::NSAppearanceNameAqua
10563                }
10564            })
10565        });
10566        // `None` clears the override — back to the system appearance.
10567        unsafe { app.setAppearance(appearance.as_deref()) };
10568        // Day's views re-resolve their inks themselves; the tinted buttons' layers are set
10569        // again here.
10570        color::refresh_layers_soon();
10571    }
10572
10573    fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
10574        controls::refresh_gesture::attach(handle, host);
10575    }
10576
10577    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
10578        unsafe {
10579            handle.setHidden(!visible);
10580        }
10581    }
10582
10583    #[expect(
10584        clippy::match_same_arms,
10585        reason = "one arm per capability, each documented with the AppKit mechanism behind it"
10586    )]
10587    fn capability(&self, cap: Cap) -> Support {
10588        match cap {
10589            // An `NSSharingService` per app action, from the picker's delegate.
10590            Cap::ShareActions => Support::Native,
10591            Cap::SearchField => Support::Native,
10592            Cap::ComboBox => Support::Native,
10593            Cap::Stepper => Support::Native,
10594            Cap::DateTimePicker => Support::Native,
10595            Cap::ColorPicker => Support::Native,
10596            Cap::PullRefresh => Support::Emulated,
10597            Cap::Pager => Support::Emulated,
10598            Cap::PullRefreshGesture => Support::Emulated,
10599            // A tracking-area owner sets an `NSCursor` per view (docs/cursor.md). Wait, progress,
10600            // help, and move take the arrow — AppKit draws no such shapes — and the zoom and
10601            // diagonal-resize cursors need macOS 15.
10602            Cap::Cursor => Support::Native,
10603            // `NSFontManager` enumerates every family and member (docs/fonts.md).
10604            Cap::FontList => Support::Native,
10605            // An image-and-text table cell's content (docs/list.md "List items").
10606            Cap::ListItem => Support::Native,
10607            // ImageIO behind `NSBitmapImageRep` reads every container macOS knows and writes
10608            // back PNG/JPEG/TIFF/BMP/GIF, and carries the container's own metadata dictionary
10609            // (docs/images.md).
10610            Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
10611            // Canvas export (docs/canvas.md "Exporting"): the canvas painter replayed into a
10612            // CGBitmapContext, or a CGPDFContext that keeps shapes and text vector.
10613            Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
10614            // The announcement-requested notification, posted from the primary window
10615            // (docs/accessibility.md).
10616            Cap::Announce => Support::Native,
10617            // `NSWorkspace.accessibilityDisplayShouldReduceMotion`, re-read when the workspace
10618            // posts its display-options change (docs/accessibility.md).
10619            Cap::ReduceMotion => Support::Native,
10620            Cap::Snapshot
10621            | Cap::NativeSymbols
10622            // The rows as chrome: `Rail` is the same source list pinned narrow, `Tabs` an
10623            // NSSegmentedControl docked below the pages. AppKit has no app-level tab bar —
10624            // NSTabView owns its own page content, the opposite of Day's model — so the bar
10625            // is composed from the control a Mac uses for a one-of-N switch this size.
10626            //
10627            // `Cap::NavTabsAdaptive` is deliberately NOT here: a Mac app may PIN a tab bar, but
10628            // a narrow Mac window hides its sidebar and pushes rather than growing one. It falls
10629            // through to the `Unsupported` arm below.
10630            | Cap::NavTabs
10631            | Cap::NavSplit
10632            // Both presentations are the same NSSplitViewController — a stack is that split with
10633            // its sidebar item collapsed — so re-presenting is a collapse plus one `addSubview`
10634            // that re-parents the sidebar page (docs/size-classes.md).
10635            | Cap::NavRepresent
10636            // A REAL `contentList` NSSplitViewItem between sidebar and detail; the pane
10637            // persists through every presentation (docs/navigation.md).
10638            | Cap::NavContentList
10639            | Cap::Dialogs
10640            | Cap::FileDialogs
10641            // NSOpenPanel with `canChooseDirectories` (docs/files.md).
10642            | Cap::FolderDialog
10643            | Cap::Animation
10644            // NSTextView natively honors all three text-area attributes.
10645            | Cap::TextEditable
10646            | Cap::TextSelectable
10647            | Cap::TextSpellCheck
10648            // NSTableView's own drag pipeline, with the `.gap` placeholder (docs/list.md), in
10649            // lists and in the source-list sidebar itself (docs/navigation.md).
10650            | Cap::NavReorder | Cap::ListReorder
10651            // NSTableView's view-based reuse queue (`makeViewWithIdentifier`) hands Day's cells
10652            // back for new rows; `didRemoveRowView` recycles them (docs/list.md).
10653            | Cap::ListRecycling
10654            // NSTableView row actions: reveal-as-you-swipe buttons with the native full-slide
10655            // activation (docs/list.md).
10656            | Cap::ListSwipeActions
10657            // NSTableView group rows with `floatsGroupRows` (docs/list.md "Sections").
10658            | Cap::ListSections
10659            // NSOutlineView hosts Day-built rows natively, drag-reparent included
10660            // (docs/tree.md).
10661            | Cap::Tree
10662            | Cap::TreeSections
10663            | Cap::TreeMove
10664            // Real NSWindows with native tabbing + the Windows menu (docs/windows.md).
10665            | Cap::MultiWindow
10666            // `miniaturize:` / `zoom:` / `toggleFullScreen:`, reported back through the window
10667            // delegate's notifications (docs/windows.md "Window properties").
10668            | Cap::WindowStates
10669            | Cap::WindowFullscreen
10670            // `NSWindowSharingNone`: captures, recordings and screen sharing see an empty window.
10671            | Cap::ContentProtection
10672            // Per-window `tabbingIdentifier` / `tabbingMode`, with the "+" opening the group's
10673            // own builder.
10674            | Cap::WindowTabbing
10675            // `applicationDockMenu:` on the app delegate (docs/menus.md).
10676            | Cap::DockMenu
10677            // Borderless windows that still take key, a transparent title bar over the
10678            // content, a clear window background, and `NSVisualEffectView` materials behind the
10679            // content (docs/window-chrome.md).
10680            | Cap::FramelessWindow
10681            | Cap::OverlayTitleBar
10682            | Cap::TransparentWindow
10683            | Cap::WindowMaterial
10684            // `performWindowDragWithEvent:` from a press on the region's own background.
10685            | Cap::DragRegion
10686            // `NSStatusItem`s in the menu bar, a progress bar drawn on the Dock tile, and the
10687            // accessory activation policy (docs/status-item.md).
10688            | Cap::StatusItem
10689            | Cap::AppProgress
10690            | Cap::DockVisibility
10691            // Frame, limits, level, Spaces, style-mask controls, per-window appearance, Dock
10692            // bounces, and `NSScreen` (docs/windows.md "Window properties").
10693            | Cap::WindowGeometry
10694            | Cap::WindowPosition
10695            | Cap::WindowLevel
10696            | Cap::WindowAppearance
10697            | Cap::RequestAttention
10698            | Cap::Monitors
10699            // Run-time shortcuts appear in the Dock menu beside the declared ones.
10700            | Cap::DynamicShortcuts
10701            // A real NSToolbar in the title bar (docs/toolbars.md).
10702            | Cap::Toolbar
10703            // The bar holds a native search field (docs/search.md).
10704            | Cap::ToolbarSearch
10705            | Cap::AppMenu
10706            // NSDockTile.badgeLabel is an arbitrary String, so all three payloads render — the
10707            // only backend where Text is real (docs/badge.md).
10708            | Cap::AppBadgeCount
10709            | Cap::AppBadgeText
10710            // NSUndoManager fronted by DayUndoManager: the stock Edit menu retitles and
10711            // enables itself, ⌘Z/⇧⌘Z land through the responder chain (docs/model.md).
10712            | Cap::UndoBridge
10713            | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
10714            | Cap::AppBadgeDot
10715            | Cap::Appearance
10716            // firstBaselineOffsetFromTop — the platform's own answer (docs/baseline.md).
10717            | Cap::BaselineAlignment
10718            // A REAL inspector NSSplitViewItem (`inspectorWithViewController:`): the system
10719            // trailing-pane material and full-height layout (docs/inspector.md).
10720            | Cap::Inspector
10721            // A plain NSSplitView with two arranged panes (docs/split.md).
10722            | Cap::Split
10723            | Cap::TextRuns
10724            | Cap::TextLinks => Support::Native,
10725            // A topmost autoresizing child of the content view — not a system modal
10726            // (docs/cover.md's ArkUI tier).
10727            Cap::Cover => Support::Emulated,
10728            // `.sheet()` is a window sheet on the primary window (docs/cover.md "Modal sheet").
10729            Cap::CoverSheet => Support::Native,
10730            // A focusable container joins the key view loop, takes focus on a press, reports
10731            // both directions, hears the arrows and digits, and draws the focus ring when Tab
10732            // brought focus (docs/focus.md).
10733            Cap::Focusable => Support::Native,
10734            // `isARepeat` on the press; the release from the input monitor's key-up, for the
10735            // node that heard the press (docs/menus.md "Keys").
10736            Cap::KeyPhases => Support::Native,
10737            // `hitTest:` on Day's containers answers inside each child's grown rect
10738            // (docs/gestures.md "Hit slop").
10739            Cap::HitSlop => Support::Native,
10740            // The field editor's selection changes, through the label's
10741            // `textViewDidChangeSelection:` (docs/text.md "Hearing about the selection").
10742            Cap::LabelSelection => Support::Native,
10743            // The clip view's bounds-changed notification, coalesced to changes
10744            // (docs/scroll.md "Offset and phase").
10745            Cap::ScrollOffset => Support::Native,
10746            // `NSScrollViewWillStartLiveScroll`/`DidEndLiveScroll` and each wheel event's
10747            // `phase`/`momentumPhase`; a classic mouse wheel, which has no phases, ends after
10748            // 150 ms without a tick.
10749            Cap::ScrollPhases => Support::Native,
10750            // AppKit has no snapping scroll view: the clip view animates to the nearest stop
10751            // once a live scroll (momentum included) or a wheel burst ends.
10752            Cap::ScrollSnap => Support::Emulated,
10753            // `allowsMagnification` with the range as min/max magnification.
10754            Cap::ScrollZoom => Support::Native,
10755            // The clip view's bounds and frame notifications report rows and the distance to
10756            // the end; `list_scroll` places rows itself with `rectOfRow:` (docs/list.md).
10757            Cap::ListViewport | Cap::ListScrollAlign => Support::Native,
10758            // The scroll view's live scroll notifications (a gesture with its momentum, the
10759            // scroller) and its own `scrollWheel:` (a mouse wheel), plus the keys the table
10760            // handles, mark what moves the clip view as the reader's (docs/list.md
10761            // "Following the end").
10762            Cap::ListReaderScroll => Support::Native,
10763            // No software keyboard on a Mac (docs/scroll.md "Keyboard"); and the pager is the
10764            // composed fallback (`Cap::Pager` is Emulated), whose progress rests on the selected
10765            // page in the shared layer (docs/pager.md "Progress").
10766            Cap::ScrollKeyboardDismiss | Cap::PagerProgress => Support::Unsupported,
10767            _ => Support::Unsupported,
10768        }
10769    }
10770
10771    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
10772        let mtm = self.mtm;
10773        match Builtin::from_key(kind) {
10774            Some(Builtin::Container) => {
10775                let v = DayFlipped::new(mtm);
10776                if let Some(p) = props.downcast_ref::<ContainerProps>() {
10777                    if p.role == Some(day_spec::SurfaceRole::SectionCard) {
10778                        v.set_section_card(p.corner_radius);
10779                    } else if p.fill.is_some()
10780                        || p.border.is_some()
10781                        || p.shadow.is_some()
10782                        || p.corner_radius > 0.0
10783                        || p.clips
10784                    {
10785                        v.set_surface(p);
10786                    }
10787                }
10788                view_of(&v)
10789            }
10790            Some(Builtin::Scroll) => {
10791                let p = props
10792                    .downcast_ref::<day_spec::props::ScrollProps>()
10793                    .cloned()
10794                    .unwrap_or_default();
10795                scroll::realize(mtm, id, &p)
10796            }
10797            Some(Builtin::Label) => {
10798                // `props_of`, not a panicking downcast, for every typed-props arm: a mismatch
10799                // (a piece registered under a builtin key, or a day-core regression) warns once
10800                // per kind and degrades to the placeholder — realize runs inside native
10801                // up-calls, where a panic is a process kill.
10802                let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
10803                    return placeholder_view(mtm, kind);
10804                };
10805                let tf = DayLabel::new(mtm, id, &p.text);
10806                tf.ivars().wraps.set(p.wraps);
10807                tf.ivars().paragraph.set(p.paragraph());
10808                tf.ivars().align.set(p.align);
10809                tf.ivars().reports_selection.set(p.reports_selection);
10810                tf.ivars().color.set(p.color);
10811                tf.ivars().role.set(p.role);
10812                unsafe { tf.setFont(Some(&nsfont(p.font))) };
10813                // The PLAIN path needs the role as much as the attributed one below: a label
10814                // with no runs never reaches `attributed_label`, and reading the role only there
10815                // left every ordinary `.secondary()` label rendering in the primary color.
10816                match (p.color, p.role) {
10817                    (Some(c), _) => unsafe { tf.setTextColor(Some(&color::nsink(c))) },
10818                    (None, day_spec::props::TextRole::Secondary) => unsafe {
10819                        tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
10820                    },
10821                    (None, day_spec::props::TextRole::Primary) => {}
10822                }
10823                if !p.runs.is_empty() {
10824                    let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
10825                    unsafe { tf.setAttributedStringValue(&s) };
10826                }
10827                tf.ivars().has_runs.set(!p.runs.is_empty());
10828                tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
10829                // The paragraph goes on last and, for a runs label, has to reach inside the
10830                // attributed string. `setAlignment:` writes the cell's paragraph style, which an
10831                // attributed string then overrides wholesale with its own — so a markdown label
10832                // set only through the cell comes out leading-aligned no matter what was asked.
10833                apply_label_paragraph(&tf);
10834                view_of(&Retained::into_super(tf))
10835            }
10836            Some(Builtin::Button) => {
10837                let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
10838                    return placeholder_view(mtm, kind);
10839                };
10840                let target = DayTarget::new(mtm, id);
10841                let btn = unsafe {
10842                    NSButton::buttonWithTitle_target_action(
10843                        &NSString::from_str(&p.title),
10844                        Some(&*target),
10845                        Some(sel!(action:)),
10846                        mtm,
10847                    )
10848                };
10849                apply_button_style(&btn, p.style);
10850                if p.icon.is_some() {
10851                    apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
10852                }
10853                unsafe { btn.setEnabled(p.enabled) };
10854                set_button_selected(&btn, p.selected);
10855                let view = view_of(&btn);
10856                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
10857                view
10858            }
10859            Some(Builtin::Toggle) => {
10860                let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
10861                    return placeholder_view(mtm, kind);
10862                };
10863                let target = DayTarget::new(mtm, id);
10864                let sw = unsafe { NSSwitch::new(mtm) };
10865                unsafe {
10866                    sw.setState(isize::from(p.on));
10867                    sw.setEnabled(p.enabled);
10868                    sw.setTarget(Some(&*target));
10869                    sw.setAction(Some(sel!(action:)));
10870                }
10871                let view = view_of(&sw);
10872                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
10873                view
10874            }
10875            Some(Builtin::Slider) => {
10876                let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
10877                    return placeholder_view(mtm, kind);
10878                };
10879                let target = DayTarget::new(mtm, id);
10880                let sl = unsafe {
10881                    NSSlider::sliderWithValue_minValue_maxValue_target_action(
10882                        p.value,
10883                        p.min,
10884                        p.max,
10885                        Some(&*target),
10886                        Some(sel!(action:)),
10887                        mtm,
10888                    )
10889                };
10890                unsafe { sl.setContinuous(true) };
10891                let view = view_of(&sl);
10892                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
10893                view
10894            }
10895            Some(Builtin::Picker) => picker::realize_any(self, props, id),
10896            Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
10897            Some(Builtin::TextField) => {
10898                let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
10899                    return placeholder_view(mtm, kind);
10900                };
10901                let tf = new_text_field(mtm, id, false);
10902                unsafe {
10903                    tf.setStringValue(&NSString::from_str(&p.text));
10904                    tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
10905                }
10906                view_of(&tf)
10907            }
10908            Some(Builtin::Divider) => {
10909                let b = unsafe { NSBox::new(mtm) };
10910                unsafe { b.setBoxType(NSBoxType::Separator) };
10911                view_of(&b)
10912            }
10913            Some(Builtin::Progress) => {
10914                let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
10915                    return placeholder_view(mtm, kind);
10916                };
10917                if p.value.is_none() {
10918                    return crate::controls::spinner::make(self, p, id);
10919                }
10920                let pi = unsafe { NSProgressIndicator::new(mtm) };
10921                unsafe {
10922                    if let Some(v) = p.value {
10923                        pi.setStyle(NSProgressIndicatorStyle::Bar);
10924                        pi.setIndeterminate(false);
10925                        pi.setMinValue(0.0);
10926                        pi.setMaxValue(1.0);
10927                        pi.setDoubleValue(v);
10928                    } else {
10929                        pi.setStyle(NSProgressIndicatorStyle::Spinning);
10930                        pi.setIndeterminate(true);
10931                        pi.startAnimation(None);
10932                    }
10933                }
10934                view_of(&pi)
10935            }
10936            Some(Builtin::Canvas) => {
10937                let canvas = DayCanvas::new(mtm);
10938                KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
10939                view_of(&canvas)
10940            }
10941            Some(Builtin::Inspector) => {
10942                let (visible, width, leading) =
10943                    props
10944                        .downcast_ref::<InspectorProps>()
10945                        .map_or((false, 280.0, false), |p| {
10946                            (
10947                                p.visible,
10948                                p.width,
10949                                p.edge == day_spec::props::PaneEdge::Leading,
10950                            )
10951                        });
10952                let content_wrap = view_of(&DayFlipped::new(mtm));
10953                let panel_flipped = DayFlipped::new(mtm);
10954                // The panel draws an opaque window-background backdrop over the item's
10955                // vibrancy material — without it the section cards' thin quaternary fill
10956                // composites into near-black in dark mode (see `FlippedIvars`).
10957                panel_flipped.set_pane_backdrop();
10958                let panel_wrap = view_of(&panel_flipped);
10959                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
10960                // Force loadView before the items go in — the same lifecycle rule the nav
10961                // host below documents.
10962                let _ = unsafe { split_vc.view() };
10963                let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
10964                let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
10965                unsafe {
10966                    content_vc.setView(&content_wrap);
10967                    panel_vc.setView(&panel_wrap);
10968                }
10969                let content_item = unsafe {
10970                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
10971                };
10972                // A TRAILING pane is a real inspector item (the system treatment). A LEADING
10973                // one is a plain item placed first: `sidebarWithViewController:` would bring
10974                // sidebar material, which captures black offscreen (docs/navigation.md), and
10975                // the panel wrap already paints its own backdrop.
10976                let panel_item = unsafe {
10977                    if leading {
10978                        objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
10979                    } else {
10980                        objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
10981                    }
10982                };
10983                unsafe {
10984                    // Day's signal is the only visibility driver: with the pinned width the
10985                    // divider has nothing to drag and the pane cannot be user-collapsed, so
10986                    // there is no native-initiated change to report back.
10987                    panel_item.setCanCollapse(false);
10988                    panel_item.setCollapsed(!visible);
10989                    panel_item.setMinimumThickness(width);
10990                    panel_item.setMaximumThickness(width);
10991                    panel_item.setAllowsFullHeightLayout(true);
10992                    if leading {
10993                        split_vc.addSplitViewItem(&panel_item);
10994                        split_vc.addSplitViewItem(&content_item);
10995                    } else {
10996                        split_vc.addSplitViewItem(&content_item);
10997                        split_vc.addSplitViewItem(&panel_item);
10998                    }
10999                }
11000                let split = unsafe { split_vc.splitView() };
11001                unsafe {
11002                    split.setVertical(true);
11003                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
11004                    // The same Auto Layout hand-back as the nav host below: Day owns this
11005                    // view's frame outside the split; the controller's own constraints keep
11006                    // doing the pane sizing inside it.
11007                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
11008                }
11009                let view = view_of(&split);
11010                INSPECTOR_STATE.with(|m| {
11011                    m.borrow_mut().insert(
11012                        ptr_of(&view),
11013                        InspectorState {
11014                            content_wrap,
11015                            panel_wrap,
11016                            split_vc,
11017                            panel_item,
11018                        },
11019                    )
11020                });
11021                view
11022            }
11023            Some(Builtin::InspectorPane) => {
11024                // A DayNavPage for its `setFrameSize:` → `FrameChanged` report: the pane's
11025                // frame is native-owned (the split sizes it), exactly like a nav page —
11026                // NAV_PAGES membership is what makes `set_frame` skip it.
11027                let pane = view_of(&DayNavPage::new(mtm, id));
11028                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
11029                let panel = props
11030                    .downcast_ref::<InspectorPaneProps>()
11031                    .is_some_and(|p| p.panel);
11032                INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
11033                pane
11034            }
11035            Some(Builtin::Split) => {
11036                let (axis, fraction, min_pane) = props
11037                    .downcast_ref::<SplitProps>()
11038                    .map_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0), |p| {
11039                        (p.axis, p.fraction, p.min_pane)
11040                    });
11041                let wrap = view_of(&DayFlipped::new(mtm));
11042                let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
11043                let first_wrap = view_of(&DayFlipped::new(mtm));
11044                let second_wrap = view_of(&DayFlipped::new(mtm));
11045                unsafe {
11046                    // AppKit's "vertical" is the divider's orientation: panes side by side.
11047                    split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
11048                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
11049                    split.addArrangedSubview(&first_wrap);
11050                    split.addArrangedSubview(&second_wrap);
11051                    split.setFrame(wrap.bounds());
11052                    split.setAutoresizingMask(
11053                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
11054                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
11055                    );
11056                    wrap.addSubview(&split);
11057                }
11058                let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
11059                split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
11060                SPLIT_STATE.with(|m| {
11061                    m.borrow_mut().insert(
11062                        ptr_of(&wrap),
11063                        SplitState {
11064                            split,
11065                            first_wrap,
11066                            second_wrap,
11067                            delegate,
11068                        },
11069                    )
11070                });
11071                wrap
11072            }
11073            Some(Builtin::SplitPane) => {
11074                // A DayNavPage, as an inspector pane: the splitter owns its frame, and its
11075                // `setFrameSize:` reports `FrameChanged`.
11076                let pane = view_of(&DayNavPage::new(mtm, id));
11077                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
11078                let second = props
11079                    .downcast_ref::<SplitPaneProps>()
11080                    .is_some_and(|p| p.second);
11081                SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
11082                pane
11083            }
11084            Some(Builtin::Nav) => {
11085                let presentation = props
11086                    .downcast_ref::<NavProps>()
11087                    .map_or(NavPresentation::Split, |p| p.presentation);
11088                let is_split = presentation.is_split();
11089                // The host is an NSSplitViewController, not a bare NSSplitView. Handing the
11090                // sidebar pane to `NSSplitViewItem::sidebarWithViewController:` is what buys
11091                // the system treatment: AppKit installs its own backing material and vibrancy
11092                // (so no hand-rolled NSVisualEffectView), pins the thickness with a sidebar
11093                // holding priority, animates collapse/expand, and drives the window's titlebar
11094                // separator. Day still owns the CONTENT of each pane — the two wraps below are
11095                // the item view controllers' views, so `insert`/`remove`/the NAV patches are
11096                // unchanged.
11097                let sidebar_wrap = view_of(&DayFlipped::new(mtm));
11098                let detail_wrap = view_of(&DayFlipped::new(mtm));
11099                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
11100                // Force loadView/viewDidLoad before the items go in. NSSplitViewController
11101                // installs an item's view into the split as the item is added, which it can
11102                // only do once its own view exists — and reading `splitView` does not trigger
11103                // the lifecycle the way reading `view` does. Skipping this leaves a split view
11104                // with zero subviews: correct frame, nothing in it.
11105                let _ = unsafe { split_vc.view() };
11106                // Plain NSViewControllers with their view set explicitly: setting `view` up
11107                // front is what stops NSViewController looking for a nib named after itself.
11108                let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
11109                let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
11110                unsafe {
11111                    sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
11112                    detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
11113                }
11114                let sidebar_item = unsafe {
11115                    objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
11116                };
11117                let detail_item = unsafe {
11118                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
11119                };
11120                // The content-list pane (docs/navigation.md): a REAL `contentList`
11121                // NSSplitViewItem between the sidebar and the detail — Mail's own machinery,
11122                // holding priorities included. Its `Pane::List` page fills `list_wrap` exactly
11123                // as the sidebar page fills its own wrap, and the pane persists through every
11124                // presentation (only `NavPatch::ListVisible` collapses it).
11125                let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
11126                // Set before the item joins the split, exactly as the sidebar's is below. A
11127                // collapsed state applied afterwards — by `NavPatch::ListVisible`, on a window
11128                // that has not been displayed — reports as collapsed and is then laid back out
11129                // from the item's holding priorities, which is how an app whose first
11130                // destination has no list opened with one beside it anyway.
11131                let list_visible = props
11132                    .downcast_ref::<NavProps>()
11133                    .is_none_or(|p| p.list_visible);
11134                let (list_wrap, list_item) = match list_width {
11135                    Some(w) => {
11136                        let wrap = view_of(&DayFlipped::new(mtm));
11137                        let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
11138                        unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
11139                        let item = unsafe {
11140                            objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
11141                        };
11142                        unsafe {
11143                            item.setCanCollapse(true);
11144                            item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
11145                            item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
11146                            item.setCollapsed(!list_visible);
11147                        }
11148                        (Some(wrap), Some(item))
11149                    }
11150                    None => (None, None),
11151                };
11152                unsafe {
11153                    // A stack presentation has no sidebar to show: collapse the (empty) pane
11154                    // and refuse the drag, so the detail owns the full width.
11155                    sidebar_item.setCanCollapse(is_split);
11156                    sidebar_item.setCollapsed(!is_split);
11157                    if is_split {
11158                        // Run the sidebar's material to the top of the window, under the
11159                        // titlebar, the way Mail and Finder do. Pairs with the unified toolbar
11160                        // style the window already uses (toolbar.rs).
11161                        sidebar_item.setAllowsFullHeightLayout(true);
11162                        sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
11163                        sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
11164                    } else {
11165                        sidebar_item.setMinimumThickness(0.0);
11166                        sidebar_item.setMaximumThickness(0.0);
11167                    }
11168                    split_vc.addSplitViewItem(&sidebar_item);
11169                    if let Some(item) = list_item.as_ref() {
11170                        split_vc.addSplitViewItem(item);
11171                    }
11172                    split_vc.addSplitViewItem(&detail_item);
11173                }
11174                let split = unsafe { split_vc.splitView() };
11175                // NSToolbarToggleSidebarItem sends `toggleSidebar:` down the RESPONDER chain,
11176                // and NSSplitViewController implements it — but a view controller only patches
11177                // itself into that chain when it is parented (a window's contentViewController
11178                // or another controller's child), and Day's tree is view-based all the way to
11179                // the window. Insert it by hand, directly after the split view, so a first
11180                // responder anywhere inside either pane walks up through it.
11181                unsafe {
11182                    let after = split.nextResponder();
11183                    split.setNextResponder(Some(&split_vc));
11184                    // The controller must never end up aiming at itself or at its OWN view,
11185                    // or its dealloc aborts the process: `-[NSViewController dealloc]`
11186                    // splices itself out with `view.nextResponder = self.nextResponder`, and
11187                    // if that lands the view on itself AppKit raises "The next responder
11188                    // should never be yourself!" — an NSException that unwinds into Rust and
11189                    // aborts. Both shapes occur here naturally: before macOS 15 the freshly
11190                    // loaded split view's next IS the controller, and on 15+ `view` is a
11191                    // WRAPPER above `splitView` whose auto-wiring makes the split's next
11192                    // that wrapper. Neither is a real upstream hop, so drop them.
11193                    let own_view = split_vc.view();
11194                    let vc_resp: *const objc2_app_kit::NSResponder = {
11195                        let r: &objc2_app_kit::NSResponder = &split_vc;
11196                        r
11197                    };
11198                    let view_resp: *const objc2_app_kit::NSResponder = {
11199                        let r: &objc2_app_kit::NSResponder = &own_view;
11200                        r
11201                    };
11202                    let upstream = after.filter(|a| {
11203                        let p: *const objc2_app_kit::NSResponder = &raw const **a;
11204                        p != vc_resp && p != view_resp
11205                    });
11206                    split_vc.setNextResponder(upstream.as_deref());
11207                }
11208                unsafe {
11209                    split.setVertical(true);
11210                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
11211                    // Day owns this view's frame (`set_frame`). A split view vended by
11212                    // NSSplitViewController arrives switched over to Auto Layout, which
11213                    // ignores that frame and lays the split out at zero — a window with
11214                    // chrome and nothing under it. Hand it back to autoresizing translation
11215                    // so Day stays the layout owner outside the split; the constraints the
11216                    // controller installs BETWEEN the split and its panes are untouched and
11217                    // keep doing the pane sizing.
11218                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
11219                }
11220                let root_title = props
11221                    .downcast_ref::<NavProps>()
11222                    .map_or_default(|p| p.title.clone());
11223                // Stack presentation: a back header (hidden at root) — desktop has no system
11224                // back affordance, so a pushed page needs its own way out (docs/navigation.md).
11225                let header = if presentation == NavPresentation::Stack {
11226                    Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
11227                } else {
11228                    None
11229                };
11230                // A tabs host: the Mac's own tab control fills the detail pane and takes the
11231                // detail pages as its items (`TabHost`).
11232                let tabs = (presentation == NavPresentation::Tabs).then(|| {
11233                    let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
11234                    let documents = props
11235                        .downcast_ref::<NavProps>()
11236                        .is_some_and(|p| p.documents.is_some());
11237                    // Inset from the pane, the way a tab view sits in any Mac window: its
11238                    // tabs stand above the bezel, so flush to the top they run into the
11239                    // toolbar's edge, and flush to the sides the bezel hugs the sidebar. The
11240                    // autoresizing mask keeps the margins as the pane resizes. A document host
11241                    // draws no tabs and no bezel, so its pages fill the pane edge to edge.
11242                    let (inset, inset_top) = if documents {
11243                        (0.0, 0.0)
11244                    } else {
11245                        (NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP)
11246                    };
11247                    let b = detail_wrap.bounds();
11248                    let frame = NSRect::new(
11249                        NSPoint::new(inset, inset_top),
11250                        NSSize::new(
11251                            (b.size.width - 2.0 * inset).max(0.0),
11252                            (b.size.height - inset_top - inset).max(0.0),
11253                        ),
11254                    );
11255                    unsafe {
11256                        tv.setTabViewType(if documents {
11257                            objc2_app_kit::NSTabViewType::NoTabsNoBorder
11258                        } else {
11259                            objc2_app_kit::NSTabViewType::TopTabsBezelBorder
11260                        });
11261                        tv.setFrame(frame);
11262                        tv.setAutoresizingMask(
11263                            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
11264                                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
11265                        );
11266                        detail_wrap.addSubview(&tv);
11267                    }
11268                    TabHost {
11269                        view: tv,
11270                        target: None,
11271                    }
11272                });
11273                let view = view_of(&split);
11274                NAV_STATE.with(|m| {
11275                    m.borrow_mut().insert(
11276                        ptr_of(&view),
11277                        NavState {
11278                            sidebar_wrap,
11279                            detail_wrap,
11280                            split_vc,
11281                            sidebar_item,
11282                            list_wrap,
11283                            list_item,
11284                            pages: Vec::new(),
11285                            list_page: None,
11286                            sidebar_page: None,
11287                            list_width,
11288                            list_visible,
11289                            list_positioned: false,
11290                            positioned: false,
11291                            presentation,
11292                            selected: 0,
11293                            tabs,
11294                            header,
11295                            root_title,
11296                            node: id,
11297                            title_strip: 0.0,
11298                        },
11299                    )
11300                });
11301                view
11302            }
11303            Some(Builtin::NavPage) => {
11304                let page = view_of(&DayNavPage::new(mtm, id));
11305                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
11306                if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
11307                    PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
11308                }
11309                page
11310            }
11311            // Emulated fullscreen cover (docs/cover.md, the ArkUI tier): a DayNavPage — its
11312            // setFrameSize: override reports FrameChanged, so a window resize re-lays the cover
11313            // content for free — parked hidden until CoverPatch::Present re-homes it on top.
11314            Some(Builtin::Cover) => {
11315                let page = DayNavPage::new(mtm, id);
11316                let cover_props = props.downcast_ref::<CoverProps>();
11317                // A half sheet is a sheet here: macOS has no half-height presentation of its
11318                // own, so the window sheet stands in, at half the parent's height.
11319                page.ivars()
11320                    .sheet
11321                    .set(cover_props.is_some_and(|p| p.sheet || p.half));
11322                page.ivars().half.set(cover_props.is_some_and(|p| p.half));
11323                page.ivars().large.set(cover_props.is_some_and(|p| p.large));
11324                unsafe { page.setHidden(true) };
11325                view_of(&page)
11326            }
11327            Some(Builtin::NavMenu) => {
11328                let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
11329                    return placeholder_view(mtm, kind);
11330                };
11331                let data = DayNavMenuData::new(
11332                    mtm,
11333                    id,
11334                    &p.items,
11335                    &p.icons,
11336                    &p.badges,
11337                    &p.badge_icons,
11338                    &p.badge_tints,
11339                    &p.sections,
11340                    &p.tints,
11341                    &p.menus,
11342                );
11343                (*data.ivars().movable.borrow_mut()).clone_from(&p.movable);
11344                data.ivars().regroup.set(p.regroup);
11345                (*data.ivars().sorted.borrow_mut()).clone_from(&p.sorted);
11346                // The Day subclass serves per-row context menus via menuForEvent:.
11347                let outline: Retained<objc2_app_kit::NSOutlineView> = {
11348                    let o: Retained<DayNavOutlineView> =
11349                        unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
11350                    NAV_OUTLINE_MENUS
11351                        .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
11352                    unsafe { msg_send![&*o, self] }
11353                };
11354                let col = unsafe {
11355                    objc2_app_kit::NSTableColumn::initWithIdentifier(
11356                        objc2_app_kit::NSTableColumn::alloc(mtm),
11357                        &NSString::from_str("item"),
11358                    )
11359                };
11360                unsafe {
11361                    outline.addTableColumn(&col);
11362                    outline.setOutlineTableColumn(Some(&col));
11363                    outline.setHeaderView(None);
11364                    // SourceList: the real sidebar treatment (Finder/Mail). The outline now
11365                    // lives inside a sidebar NSSplitViewItem, so AppKit supplies the backing
11366                    // material and the vibrancy the source-list selection composites through.
11367                    // This was Inset until 2026-08 because the earlier hand-rolled
11368                    // NSVisualEffectView blended behind the window, and an offscreen capture
11369                    // (`cacheDisplayInRect`) has no backdrop to sample — the selection came out
11370                    // a black pill that swallowed the row label. The material is AppKit's own
11371                    // now, and captures go through the window server (`snapshot_view`), which
11372                    // composites the material for real instead of guessing at it.
11373                    // `style = SourceList` is the whole switch: the matching
11374                    // `selectionHighlightStyle` constant is deprecated precisely because the
11375                    // style property now implies it.
11376                    outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
11377                    // The default row size style follows the system's Sidebar icon size
11378                    // (Small, Medium, Large), live, as Finder's and Mail's sidebars do: AppKit
11379                    // sets the row height, the label's font and the icon's size. A table made
11380                    // in code starts at Custom, which ignores the setting.
11381                    outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
11382                    // Section headers pin to the top of the scroll as their group passes under
11383                    // it, the way Finder's sidebar groups do.
11384                    outline.setFloatsGroupRows(true);
11385                    outline.setIndentationPerLevel(0.0);
11386                    // Drag-to-reorder within this sidebar only (docs/navigation.md): rows that
11387                    // cannot move offer no drag, so registering costs a plain sidebar nothing.
11388                    outline.registerForDraggedTypes(
11389                        &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
11390                            DAY_NAV_PASTEBOARD_TYPE,
11391                        )]),
11392                    );
11393                    outline.setDraggingSourceOperationMask_forLocal(
11394                        objc2_app_kit::NSDragOperation::Move,
11395                        true,
11396                    );
11397                    outline.setDraggingSourceOperationMask_forLocal(
11398                        objc2_app_kit::NSDragOperation::None,
11399                        false,
11400                    );
11401                    outline.setDraggingDestinationFeedbackStyle(
11402                        objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
11403                    );
11404                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
11405                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
11406                    outline.reloadData();
11407                }
11408                let scroll = unsafe { NSScrollView::new(mtm) };
11409                unsafe {
11410                    scroll.setDrawsBackground(false);
11411                    scroll.setHasVerticalScroller(true);
11412                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
11413                    // clip the trailing edge of rows laid out at the full frame width (see
11414                    // the SCROLL realize).
11415                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
11416                    // One column, sized to the pane: a sidebar never scrolls sideways.
11417                    scroll.setHasHorizontalScroller(false);
11418                    outline.setAutoresizingMask(
11419                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
11420                    );
11421                    outline.setColumnAutoresizingStyle(
11422                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
11423                    );
11424                    scroll.setDocumentView(Some(&outline));
11425                }
11426                let view = view_of(&scroll);
11427                // Day selects by ITEM index; section headers make that differ from the
11428                // outline's row index, so every programmatic selection maps through `rows`.
11429                if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
11430                    data.ivars().suppress.set(true);
11431                    unsafe {
11432                        outline.selectRowIndexes_byExtendingSelection(
11433                            &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
11434                            false,
11435                        );
11436                    };
11437                    data.ivars().suppress.set(false);
11438                }
11439                NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
11440                view
11441            }
11442            Some(Builtin::List) => {
11443                let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
11444                    return placeholder_view(mtm, kind);
11445                };
11446                // Every list reports responder changes, even without an activation handler.
11447                let table: Retained<DayListView> =
11448                    unsafe { msg_send![DayListView::alloc(mtm), init] };
11449                let table = Retained::into_super(table);
11450                if p.inset_grouped {
11451                    // macOS 11's inset style: rows set in from the edges with rounded selection,
11452                    // the grouped look `ListProps::inset_grouped` asks for.
11453                    unsafe { table.setStyle(objc2_app_kit::NSTableViewStyle::Inset) };
11454                }
11455                let col = unsafe {
11456                    NSTableColumn::initWithIdentifier(
11457                        NSTableColumn::alloc(mtm),
11458                        &NSString::from_str("day.list.col"),
11459                    )
11460                };
11461                let data = DayListData::new(
11462                    mtm,
11463                    id,
11464                    p.selectable,
11465                    p.multi_select,
11466                    p.row_height == RowHeight::Automatic,
11467                    p.sections,
11468                );
11469                unsafe {
11470                    if p.multi_select {
11471                        table.setAllowsMultipleSelection(true);
11472                    }
11473                    table.addTableColumn(&col);
11474                    table.setHeaderView(None);
11475                    // PLAIN, the classic edge-to-edge style: the macOS 11+ decorated styles
11476                    // (automatic ~14pt, FullWidth ~6pt) inset every cell view, clipping day
11477                    // row content laid out at the host's full frame width. This table ran
11478                    // FullWidth with a custom NSTableRowView pinning cells back to the row
11479                    // bounds until 2026-08 — and that pin also clobbered the cell-frame slide
11480                    // AppKit performs for row-action swipes, so the actions revealed behind a
11481                    // row whose CONTENT never moved. Plain has no inset to fight: standard
11482                    // row views, standard cell frames, and the swipe slide works untouched.
11483                    table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
11484                    // ...and the default intercell spacing (3pt × 2pt) shaves the column the
11485                    // same way — the last few points of a trailing control. Day rows own all
11486                    // of their spacing.
11487                    table.setIntercellSpacing(NSSize::new(0.0, 0.0));
11488                    // Host-drawn row separators (docs/list.md): the native horizontal grid
11489                    // line, which sits exactly at the row boundary — aligned with the
11490                    // selection, stationary under a row-action swipe, the Mail look.
11491                    if p.separators == Some(true) {
11492                        table.setGridStyleMask(
11493                            objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
11494                        );
11495                        table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
11496                    }
11497                    table.setColumnAutoresizingStyle(
11498                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
11499                    );
11500                    // Section headers pin to the top while their section scrolls under them,
11501                    // the way Mail's and Finder's group rows do (docs/list.md "Sections").
11502                    table.setFloatsGroupRows(p.sections);
11503                    match p.row_height {
11504                        RowHeight::Uniform(h) => table.setRowHeight(h),
11505                        RowHeight::Automatic => table.setRowHeight(44.0),
11506                    }
11507                    if !p.selectable {
11508                        table.setSelectionHighlightStyle(
11509                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
11510                        );
11511                    }
11512                    // Transparent: day panes own their backgrounds — the stock
11513                    // controlBackgroundColor would paint an appearance-colored slab that
11514                    // fights a themed app (visible whenever rows don't fill the viewport).
11515                    table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
11516                    table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
11517                    table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
11518                    table.setTarget(Some(&*data));
11519                    if p.activatable {
11520                        table.setDoubleAction(Some(sel!(doubleClickRow:)));
11521                    }
11522                    if p.reorderable {
11523                        // Native drag-to-reorder (docs/list.md): rows drag within this table
11524                        // only (move locally, nothing leaves the app), and the drop target shows
11525                        // macOS's temporary placeholder GAP while the drag is over the table.
11526                        table.registerForDraggedTypes(
11527                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
11528                                DAY_ROW_PASTEBOARD_TYPE,
11529                            )]),
11530                        );
11531                        table.setDraggingSourceOperationMask_forLocal(
11532                            objc2_app_kit::NSDragOperation::Move,
11533                            true,
11534                        );
11535                        table.setDraggingSourceOperationMask_forLocal(
11536                            objc2_app_kit::NSDragOperation::None,
11537                            false,
11538                        );
11539                        table.setDraggingDestinationFeedbackStyle(
11540                            objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
11541                        );
11542                    }
11543                }
11544                let scroll: Retained<DayListScrollView> =
11545                    unsafe { msg_send![DayListScrollView::alloc(mtm), init] };
11546                let scroll = Retained::into_super(scroll);
11547                unsafe {
11548                    scroll.setDrawsBackground(false);
11549                    scroll.setHasVerticalScroller(true);
11550                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
11551                    // clip the trailing edge of rows laid out at the full frame width (see
11552                    // the SCROLL realize).
11553                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
11554                    scroll.setDocumentView(Some(&table));
11555                    let clip = scroll.contentView();
11556                    clip.setPostsBoundsChangedNotifications(true);
11557                    clip.setPostsFrameChangedNotifications(true);
11558                    let center = objc2_foundation::NSNotificationCenter::defaultCenter();
11559                    // Scrolled, or resized (docs/list.md "Visible rows").
11560                    for name in [
11561                        objc2_app_kit::NSViewBoundsDidChangeNotification,
11562                        objc2_app_kit::NSViewFrameDidChangeNotification,
11563                    ] {
11564                        center.addObserver_selector_name_object(
11565                            &data,
11566                            sel!(listViewportChanged:),
11567                            Some(name),
11568                            Some(&clip),
11569                        );
11570                    }
11571                    // The reader's live scrolls (docs/list.md "Following the end").
11572                    for (name, selector) in [
11573                        (
11574                            objc2_app_kit::NSScrollViewWillStartLiveScrollNotification,
11575                            sel!(listLiveScrollStarted:),
11576                        ),
11577                        (
11578                            objc2_app_kit::NSScrollViewDidEndLiveScrollNotification,
11579                            sel!(listLiveScrollEnded:),
11580                        ),
11581                    ] {
11582                        center.addObserver_selector_name_object(
11583                            &data,
11584                            selector,
11585                            Some(name),
11586                            Some(&scroll),
11587                        );
11588                    }
11589                }
11590                let view = view_of(&scroll);
11591                LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
11592                view
11593            }
11594            Some(Builtin::Tree) => {
11595                let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
11596                    return placeholder_view(mtm, kind);
11597                };
11598                // The width-pinning subclass (see DayOutlineView).
11599                let outline: Retained<objc2_app_kit::NSOutlineView> = {
11600                    let o: Retained<DayOutlineView> =
11601                        unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
11602                    unsafe { msg_send![&*o, self] }
11603                };
11604                let col = unsafe {
11605                    NSTableColumn::initWithIdentifier(
11606                        NSTableColumn::alloc(mtm),
11607                        &NSString::from_str("day.tree.col"),
11608                    )
11609                };
11610                let data = DayTreeData::new(mtm, id, p.selectable);
11611                unsafe {
11612                    if p.multi_select {
11613                        outline.setAllowsMultipleSelection(true);
11614                    }
11615                    outline.addTableColumn(&col);
11616                    outline.setOutlineTableColumn(Some(&col));
11617                    outline.setHeaderView(None);
11618                    if p.section_headers {
11619                        // Real source-list groups use AppKit's trailing, hover-revealed
11620                        // show/hide button and float over their children while scrolling.
11621                        outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
11622                        outline.setFloatsGroupRows(true);
11623                    } else {
11624                        // Generic trees keep their existing full-width cells and rounded
11625                        // DayTreeRowView selection. Source lists use native row drawing.
11626                        outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
11627                        outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
11628                    }
11629                    outline.setColumnAutoresizingStyle(
11630                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
11631                    );
11632                    outline.setAutoresizesOutlineColumn(true);
11633                    if let Some(indent) = p.indent {
11634                        outline.setIndentationPerLevel(indent);
11635                    }
11636                    match p.row_height {
11637                        RowHeight::Uniform(h) => outline.setRowHeight(h),
11638                        RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
11639                        RowHeight::Automatic => {}
11640                    }
11641                    if !p.selectable {
11642                        outline.setSelectionHighlightStyle(
11643                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
11644                        );
11645                    }
11646                    outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
11647                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
11648                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
11649                    if p.movable {
11650                        // Native drag-to-move (docs/tree.md): nodes drag within this outline
11651                        // only. The REGULAR feedback style (not the list's Gap): a tree drop
11652                        // must distinguish "between rows" (insertion line) from "ONTO a row"
11653                        // (the highlighted-parent drop), and Gap has no onto affordance.
11654                        outline.registerForDraggedTypes(
11655                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
11656                                DAY_TREE_PASTEBOARD_TYPE,
11657                            )]),
11658                        );
11659                        outline.setDraggingSourceOperationMask_forLocal(
11660                            objc2_app_kit::NSDragOperation::Move,
11661                            true,
11662                        );
11663                        outline.setDraggingSourceOperationMask_forLocal(
11664                            objc2_app_kit::NSDragOperation::None,
11665                            false,
11666                        );
11667                    }
11668                }
11669                let scroll = unsafe { NSScrollView::new(mtm) };
11670                unsafe {
11671                    scroll.setDrawsBackground(false);
11672                    scroll.setHasVerticalScroller(true);
11673                    scroll.setHasHorizontalScroller(false);
11674                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
11675                    outline.setAutoresizingMask(
11676                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
11677                    );
11678                    scroll.setDocumentView(Some(&outline));
11679                }
11680                let view = view_of(&scroll);
11681                TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
11682                view
11683            }
11684            Some(Builtin::Image) => {
11685                let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
11686                    return placeholder_view(mtm, kind);
11687                };
11688                let iv: Retained<objc2_app_kit::NSImageView> =
11689                    if p.content_mode == ContentMode::Fill {
11690                        let view: Retained<FillImageView> =
11691                            unsafe { msg_send![FillImageView::alloc(mtm), init] };
11692                        Retained::from(
11693                            <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
11694                        )
11695                    } else {
11696                        unsafe { objc2_app_kit::NSImageView::new(mtm) }
11697                    };
11698                // Fill expands the native aspect-fit drawing in FillImageView; Stretch
11699                // scales each axis independently, and Fit keeps the stock image view.
11700                let scaling = match p.content_mode {
11701                    ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
11702                    _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
11703                };
11704                unsafe { iv.setImageScaling(scaling) };
11705                if let Some(img) = appkit_image_for(&p.source) {
11706                    // Tint (docs/vectors.md, docs/images.md): template rendering + the view's
11707                    // content tint — AppKit recolors the alpha mask natively, for a raster as
11708                    // for a vector glyph. A template with no tint keeps the view's nil tint:
11709                    // the neutral template color the nav menu's own rows draw with, light in
11710                    // dark mode, dark in light.
11711                    let img = image_rendered(img, p.tint.is_some() || p.template);
11712                    unsafe { iv.setImage(Some(&img)) };
11713                }
11714                if let Some(t) = p.tint {
11715                    unsafe { iv.setContentTintColor(Some(&color::nsink(t))) };
11716                }
11717                IMAGE_MODES.with(|t| {
11718                    t.insert(
11719                        ptr_of(&iv),
11720                        ImageMode {
11721                            template: p.template,
11722                            tinted: p.tint.is_some(),
11723                        },
11724                    )
11725                });
11726                view_of(&iv)
11727            }
11728            Some(Builtin::ListItem) => {
11729                let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
11730                else {
11731                    return placeholder_view(mtm, kind);
11732                };
11733                make_list_item(p, mtm)
11734            }
11735            // A recycled list cell is ADOPTED from the native list, never realized
11736            // through this path; anything else is an extension piece.
11737            Some(Builtin::ListCell) | None => {
11738                if let Some(make) = self.registry.get(kind).map(|r| r.make) {
11739                    return make(self, props, id);
11740                }
11741                // Unregistered kind: LOUD once-per-kind warning, then a visible-but-harmless
11742                // placeholder (§8.2's debug check will panic first in debug builds once the
11743                // required-kinds set lands).
11744                warn_missing_renderer(kind);
11745                placeholder_view(mtm, kind)
11746            }
11747        }
11748    }
11749
11750    fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, anim: Option<&AnimSpec>) {
11751        match kind {
11752            kinds::LIST_ITEM => {
11753                let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
11754                    return;
11755                };
11756                let props = LIST_ITEMS.with(|m| {
11757                    use day_spec::props::ListItemPatch as P;
11758                    let mut m = m.borrow_mut();
11759                    let props = m.get_mut(&ptr_of(h))?;
11760                    match p {
11761                        P::Title(t) => props.title.clone_from(t),
11762                        P::Subtitle(t) => props.subtitle.clone_from(t),
11763                        P::Detail(t) => props.detail.clone_from(t),
11764                        P::Icon(i) => props.icon.clone_from(i),
11765                        P::IconTint(c) => props.icon_tint = *c,
11766                        P::Checked(on) => props.checked = *on,
11767                    }
11768                    Some(props.clone())
11769                });
11770                if let Some(props) = props {
11771                    dress_list_item(h, &props, self.mtm());
11772                }
11773            }
11774            kinds::IMAGE => {
11775                if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
11776                    match p {
11777                        day_spec::props::ImagePatch::Tint(c) => {
11778                            // Template rendering + the view's content tint, exactly as at realize
11779                            // — the glyph repaints in place rather than being rebuilt
11780                            // (docs/vectors.md). A template glyph stays one when the tint goes.
11781                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
11782                                let key = ptr_of(&iv);
11783                                let template = IMAGE_MODES
11784                                    .with(|t| {
11785                                        t.with(key, |m| {
11786                                            m.tinted = c.is_some();
11787                                            m.renders_template()
11788                                        })
11789                                    })
11790                                    .unwrap_or(c.is_some());
11791                                if let Some(img) = unsafe { iv.image() } {
11792                                    let img = image_rendered(img, template);
11793                                    unsafe { iv.setImage(Some(&img)) };
11794                                }
11795                                let tint = c.map(color::nsink);
11796                                unsafe { iv.setContentTintColor(tint.as_deref()) };
11797                            }
11798                        }
11799                        // A source swap repaints the same view (docs/images.md), so an `image()`
11800                        // bound to a signal shows new pixels without rebuilding its subtree —
11801                        // which is what makes a decode-then-show flow a patch and not a rebuild.
11802                        day_spec::props::ImagePatch::Source(source) => {
11803                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
11804                                // A source that will not load leaves the view showing what it
11805                                // was — the patch's contract, and what GTK, Qt and Android do.
11806                                // The new image renders the way the view does: a tinted or
11807                                // template glyph stays one, so a recycled sidebar row shows the
11808                                // icon it was rebound to in the same color.
11809                                if let Some(img) = appkit_image_for(source) {
11810                                    let template = IMAGE_MODES
11811                                        .with(|t| t.get(ptr_of(&iv)))
11812                                        .is_some_and(ImageMode::renders_template);
11813                                    let img = image_rendered(img, template);
11814                                    unsafe { iv.setImage(Some(&img)) };
11815                                }
11816                            }
11817                        }
11818                    }
11819                }
11820            }
11821            kinds::CONTAINER => {
11822                let (Some(patch), Ok(v)) = (
11823                    patch.downcast_ref::<ContainerPatch>(),
11824                    h.clone().downcast::<DayFlipped>(),
11825                ) else {
11826                    return;
11827                };
11828                match patch {
11829                    // The fill is drawRect content; an animated change plays on the layer's
11830                    // backgroundColor for its length (see `motion`).
11831                    ContainerPatch::Fill(fill) => motion::set_background(&v, fill.clone(), anim),
11832                    // A reactive surface (or a radius Day re-resolved for a new frame): the
11833                    // whole style again. The role is realize-time: a section card keeps its
11834                    // own fill and takes the radius only. A changed solid fill animates as a
11835                    // `Fill` does; the radius, the corners, the border and the shadow apply at
11836                    // once, since the fill they shape is drawRect content Core Animation
11837                    // cannot tween.
11838                    ContainerPatch::Surface(p) => {
11839                        if v.ivars().section_card.get().is_some() {
11840                            v.set_section_card(p.corner_radius);
11841                            return;
11842                        }
11843                        let fill = v.ivars().surface.borrow().as_ref().map(|s| s.fill.clone());
11844                        if fill.as_ref() != Some(&p.fill) {
11845                            motion::set_background(&v, p.fill.clone(), anim);
11846                        }
11847                        v.set_surface(p);
11848                    }
11849                }
11850            }
11851            kinds::LABEL => {
11852                if let (Some(p), Ok(tf)) = (
11853                    patch.downcast_ref::<LabelPatch>(),
11854                    h.clone().downcast::<NSTextField>(),
11855                ) {
11856                    let label = h.downcast_ref::<DayLabel>();
11857                    match p {
11858                        LabelPatch::Paragraph(para) => {
11859                            if let Some(label) = label {
11860                                label.ivars().paragraph.set(*para);
11861                            }
11862                        }
11863                        LabelPatch::Text(t) => {
11864                            unsafe { tf.setStringValue(&NSString::from_str(t)) };
11865                            if let Some(label) = label {
11866                                label.clear_selection();
11867                                label.ivars().has_runs.set(false);
11868                                label.set_links(false);
11869                            }
11870                        }
11871                        LabelPatch::Color(c) => {
11872                            if let Some(label) = label {
11873                                label.ivars().color.set(*c);
11874                            }
11875                            unsafe { tf.setTextColor(c.map(color::nsink).as_deref()) };
11876                        }
11877                        LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
11878                        LabelPatch::Runs(text, runs) => {
11879                            // The field's current font is the base the runs sit on, taken as the
11880                            // live object rather than rebuilt from a `FontSpec`, which would lose
11881                            // the semantic style behind the resolved size.
11882                            let base = unsafe { tf.font() };
11883                            // The label's own color and role, under the runs.
11884                            let (own, role) = label.map_or((None, TextRole::default()), |l| {
11885                                (l.ivars().color.get(), l.ivars().role.get())
11886                            });
11887                            let s = match base.as_deref() {
11888                                Some(f) => attributed_label(text, f, own, role, runs),
11889                                None => attributed_label(
11890                                    text,
11891                                    &nsfont(day_spec::FontSpec::default()),
11892                                    own,
11893                                    role,
11894                                    runs,
11895                                ),
11896                            };
11897                            unsafe { tf.setAttributedStringValue(&s) };
11898                            // Activate links introduced by a reactive markdown update without
11899                            // replacing the native label; the paragraph is stamped below.
11900                            if let Some(label) = label {
11901                                label.clear_selection();
11902                                label.ivars().has_runs.set(!runs.is_empty());
11903                                label.set_links(runs.iter().any(|r| r.link.is_some()));
11904                            }
11905                        }
11906                    }
11907                    // Every patch can move what the paragraph depends on: the string it is
11908                    // stamped across, the font size letter spacing and line height scale with,
11909                    // the color a stamped plain label copies.
11910                    if let Some(label) = label {
11911                        apply_label_paragraph(label);
11912                    }
11913                }
11914            }
11915            kinds::BUTTON => {
11916                if let (Some(p), Ok(btn)) = (
11917                    patch.downcast_ref::<ButtonPatch>(),
11918                    h.clone().downcast::<NSButton>(),
11919                ) {
11920                    match p {
11921                        ButtonPatch::Content(c) => {
11922                            apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only);
11923                        }
11924                        ButtonPatch::Title(t) => {
11925                            let style = BUTTON_STYLES
11926                                .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
11927                                .unwrap_or_default();
11928                            set_button_title(&btn, t, style);
11929                        }
11930                        ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
11931                        ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
11932                        ButtonPatch::Style(s) => apply_button_style(&btn, *s),
11933                    }
11934                }
11935            }
11936            kinds::TOGGLE => {
11937                if let (Some(p), Ok(sw)) = (
11938                    patch.downcast_ref::<TogglePatch>(),
11939                    h.clone().downcast::<NSSwitch>(),
11940                ) {
11941                    match p {
11942                        TogglePatch::On(on) => {
11943                            let want = isize::from(*on);
11944                            if unsafe { sw.state() } != want {
11945                                unsafe { sw.setState(want) };
11946                            }
11947                        }
11948                        TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
11949                    }
11950                }
11951            }
11952            kinds::SLIDER => {
11953                if let (Some(p), Ok(sl)) = (
11954                    patch.downcast_ref::<SliderPatch>(),
11955                    h.clone().downcast::<NSSlider>(),
11956                ) {
11957                    match p {
11958                        SliderPatch::Value(v) => {
11959                            if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
11960                                unsafe { sl.setDoubleValue(*v) };
11961                            }
11962                        }
11963                        SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
11964                    }
11965                }
11966            }
11967            kinds::PROGRESS => {
11968                if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
11969                {
11970                    crate::controls::spinner::update(self, h, p);
11971                    return;
11972                }
11973
11974                if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
11975                    patch.downcast_ref::<ProgressPatch>(),
11976                    h.clone().downcast::<NSProgressIndicator>(),
11977                ) {
11978                    unsafe {
11979                        if let Some(val) = v {
11980                            if pi.isIndeterminate() {
11981                                pi.stopAnimation(None);
11982                                pi.setIndeterminate(false);
11983                                pi.setStyle(NSProgressIndicatorStyle::Bar);
11984                                pi.setMinValue(0.0);
11985                                pi.setMaxValue(1.0);
11986                            }
11987                            if (pi.doubleValue() - val).abs() > 0.0001 {
11988                                pi.setDoubleValue(*val);
11989                            }
11990                        } else {
11991                            pi.setIndeterminate(true);
11992                            pi.setStyle(NSProgressIndicatorStyle::Spinning);
11993                            pi.startAnimation(None);
11994                        }
11995                    }
11996                }
11997            }
11998            kinds::NAV_MENU => {
11999                if let Some(NavMenuPatch::Items {
12000                    items,
12001                    icons,
12002                    badges,
12003                    badge_icons,
12004                    badge_tints,
12005                    sections,
12006                    tints,
12007                    menus,
12008                    movable,
12009                    sorted,
12010                    selected,
12011                    rows_changed,
12012                    ..
12013                }) = patch.downcast_ref::<NavMenuPatch>()
12014                {
12015                    NAV_MENUS.with(|m| {
12016                        let m = m.borrow();
12017                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
12018                            return;
12019                        };
12020                        (*data.ivars().movable.borrow_mut()).clone_from(movable);
12021                        (*data.ivars().sorted.borrow_mut()).clone_from(sorted);
12022                        data.set_items(
12023                            items,
12024                            icons,
12025                            badges,
12026                            badge_icons,
12027                            badge_tints,
12028                            sections,
12029                            tints,
12030                            menus,
12031                        );
12032                        data.ivars().suppress.set(true);
12033                        // The same rows with new words or counts: reload just those rows, which
12034                        // keeps the selection and every other row's view.
12035                        if let Some(rows) = rows_changed {
12036                            let set = objc2_foundation::NSMutableIndexSet::new();
12037                            for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
12038                                unsafe { set.addIndex(row) };
12039                            }
12040                            unsafe {
12041                                outline.reloadDataForRowIndexes_columnIndexes(
12042                                    &set,
12043                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
12044                                );
12045                            };
12046                            data.ivars().suppress.set(false);
12047                            return;
12048                        }
12049                        unsafe {
12050                            outline.reloadData();
12051                            match selected.and_then(|i| data.row_of_item(i)) {
12052                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
12053                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
12054                                    false,
12055                                ),
12056                                None => outline.deselectAll(None),
12057                            }
12058                        }
12059                        data.ivars().suppress.set(false);
12060                    });
12061                    // The rows are a tabs host's labels where the menu sits in one.
12062                    adopt_menu_for_tabs(self.mtm(), h);
12063                } else if let Some(NavMenuPatch::IconProgress(progress)) =
12064                    patch.downcast_ref::<NavMenuPatch>()
12065                {
12066                    NAV_MENUS.with(|menus| {
12067                        let menus = menus.borrow();
12068                        let Some((outline, data)) = menus.get(&ptr_of(h)) else {
12069                            return;
12070                        };
12071                        let previous = data.ivars().icon_progress.replace(progress.clone());
12072                        for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
12073                            let Some(index) = item else {
12074                                continue;
12075                            };
12076                            let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
12077                            if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
12078                                continue;
12079                            }
12080                            if let Some(view) = unsafe {
12081                                outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
12082                            } && let Some(cell) =
12083                                view.downcast_ref::<objc2_app_kit::NSTableCellView>()
12084                                && let Some(icon) = unsafe { cell.imageView() }
12085                            {
12086                                nav_progress::update(&icon, value);
12087                            }
12088                        }
12089                    });
12090                } else if let Some(NavMenuPatch::Selected(sel)) =
12091                    patch.downcast_ref::<NavMenuPatch>()
12092                {
12093                    NAV_MENUS.with(|m| {
12094                        let m = m.borrow();
12095                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
12096                            return;
12097                        };
12098                        data.ivars().suppress.set(true);
12099                        unsafe {
12100                            match sel.and_then(|i| data.row_of_item(i)) {
12101                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
12102                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
12103                                    false,
12104                                ),
12105                                None => outline.deselectAll(None),
12106                            }
12107                        }
12108                        data.ivars().suppress.set(false);
12109                    });
12110                }
12111            }
12112            kinds::INSPECTOR => {
12113                if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
12114                    INSPECTOR_STATE.with(|m| {
12115                        if let Some(state) = m.borrow().get(&ptr_of(h)) {
12116                            // Directly, not through the animator proxy: a screenshot must not
12117                            // catch a mid-animation pane (the sidebar-toggle rule).
12118                            state.panel_item.setCollapsed(!*v);
12119                        }
12120                    });
12121                }
12122            }
12123            kinds::SPLIT => {
12124                if let Some(p) = patch.downcast_ref::<SplitPatch>() {
12125                    SPLIT_STATE.with(|m| {
12126                        let m = m.borrow();
12127                        let Some(state) = m.get(&ptr_of(h)) else {
12128                            return;
12129                        };
12130                        let iv = state.delegate.ivars();
12131                        match p {
12132                            SplitPatch::Fraction(f) => {
12133                                iv.share.set(f.clamp(0.0, 1.0));
12134                                if iv.positioned.get() {
12135                                    split_place(&state.split, iv);
12136                                }
12137                            }
12138                            SplitPatch::Axis(axis) => unsafe {
12139                                state
12140                                    .split
12141                                    .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
12142                                state.split.adjustSubviews();
12143                                if iv.positioned.get() {
12144                                    split_place(&state.split, iv);
12145                                }
12146                            },
12147                        }
12148                    });
12149                }
12150            }
12151            kinds::NAV => {
12152                if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
12153                    nav_present(self.mtm(), h, *next);
12154                    return;
12155                }
12156                if let Some(p) = patch.downcast_ref::<NavPatch>() {
12157                    NAV_STATE.with(|m| {
12158                        let mut m = m.borrow_mut();
12159                        let Some(state) = m.get_mut(&ptr_of(h)) else {
12160                            return;
12161                        };
12162                        match p {
12163                            NavPatch::Pushed { title, .. } => {
12164                                // Only the new top detail page stays visible.
12165                                let last = state.pages.len().saturating_sub(1);
12166                                state.selected = last;
12167                                for (i, page) in state.pages.iter().enumerate() {
12168                                    page.setHidden(i != last);
12169                                }
12170                                if let Some(hdr) = state.header.as_mut() {
12171                                    hdr.titles.push(title.clone());
12172                                    sync_nav_header(hdr, &state.detail_wrap, &state.pages);
12173                                }
12174                            }
12175                            NavPatch::Popped => {
12176                                // Hide the outgoing top; reveal its predecessor (Day
12177                                // removes the popped page right after this patch).
12178                                let n = state.pages.len();
12179                                if let Some(top) = state.pages.last() {
12180                                    top.setHidden(true);
12181                                }
12182                                if n >= 2 {
12183                                    state.pages[n - 2].setHidden(false);
12184                                }
12185                                state.selected = n.saturating_sub(2);
12186                                if let Some(hdr) = state.header.as_mut() {
12187                                    if hdr.titles.len() > 1 {
12188                                        hdr.titles.pop();
12189                                    }
12190                                    // The popped page is still in `pages` here (Day removes
12191                                    // it right after this patch), so frame for depth-after-pop.
12192                                    let after: Vec<Retained<NSView>> = state
12193                                        .pages
12194                                        .iter()
12195                                        .take(n.saturating_sub(1))
12196                                        .cloned()
12197                                        .collect();
12198                                    sync_nav_header(hdr, &state.detail_wrap, &after);
12199                                }
12200                            }
12201                            NavPatch::Title(t) => {
12202                                if let Some(hdr) = state.header.as_mut() {
12203                                    if let Some(last) = hdr.titles.last_mut() {
12204                                        last.clone_from(t);
12205                                    }
12206                                    unsafe {
12207                                        hdr.title.setStringValue(&NSString::from_str(t));
12208                                    }
12209                                }
12210                            }
12211                            // The custom back header always routes back through Day
12212                            // (NavBack{already_popped:false}), so there is no native auto-pop to
12213                            // suppress; the guard runs in the pieces layer (docs/navigation.md).
12214                            #[expect(
12215                                clippy::match_same_arms,
12216                                reason = "each no-op patch keeps its own arm and the comment saying why it is one"
12217                            )]
12218                            NavPatch::GuardTop(_) => {}
12219                            NavPatch::Reorder(order) => {
12220                                let old = state.pages.clone();
12221                                state.pages =
12222                                    order.iter().filter_map(|i| old.get(*i).cloned()).collect();
12223                                if let Some(tabs) = &state.tabs {
12224                                    TAB_PICK_SUPPRESS.with(|s| s.set(true));
12225                                    unsafe {
12226                                        let items = tabs.view.tabViewItems();
12227                                        for item in &items {
12228                                            tabs.view.removeTabViewItem(&item);
12229                                        }
12230                                        for i in order {
12231                                            if let Some(item) = items.iter().nth(*i) {
12232                                                tabs.view.addTabViewItem(&item);
12233                                            }
12234                                        }
12235                                    }
12236                                    TAB_PICK_SUPPRESS.with(|s| s.set(false));
12237                                }
12238                            }
12239                            // Handled outside this borrow (it re-homes views and builds chrome).
12240                            #[expect(
12241                                clippy::match_same_arms,
12242                                reason = "each no-op patch keeps its own arm and the comment saying why it is one"
12243                            )]
12244                            NavPatch::Presentation(_) => {}
12245                            // Resident-page switch (docs/navigation.md): every page stays in the
12246                            // view hierarchy and only one is unhidden, so switching tabs keeps
12247                            // each page's scroll position and first responder exactly as left.
12248                            NavPatch::Select(i) => {
12249                                state.selected = *i;
12250                                match state.tabs.as_ref() {
12251                                    // The tab view shows exactly its selected item's page.
12252                                    Some(tabs) => {
12253                                        let n = unsafe { tabs.view.numberOfTabViewItems() };
12254                                        if (*i as isize) < n {
12255                                            TAB_PICK_SUPPRESS.with(|s| s.set(true));
12256                                            unsafe {
12257                                                tabs.view.selectTabViewItemAtIndex(*i as isize);
12258                                            };
12259                                            TAB_PICK_SUPPRESS.with(|s| s.set(false));
12260                                        }
12261                                    }
12262                                    None => {
12263                                        for (n, page) in state.pages.iter().enumerate() {
12264                                            page.setHidden(n != *i);
12265                                        }
12266                                    }
12267                                }
12268                            }
12269                            // Per-destination pane visibility (docs/navigation.md). Directly,
12270                            // not through the animator proxy: a screenshot must not catch a
12271                            // mid-animation pane (the sidebar-toggle rule), and settled now,
12272                            // like a re-present, so the detail's frame is right the instant
12273                            // the patch returns rather than one layout pass later.
12274                            NavPatch::ListVisible(v) => {
12275                                state.list_visible = *v;
12276                                if let Some(item) = state.list_item.as_ref() {
12277                                    item.setCollapsed(!*v);
12278                                    let split = unsafe { state.split_vc.splitView() };
12279                                    unsafe { split.layoutSubtreeIfNeeded() };
12280                                    // First time this pane is actually on screen: give it the
12281                                    // width the app asked for. The frame pass that would
12282                                    // otherwise do it has already run, back when there was no
12283                                    // pane to size.
12284                                    if let Some(w) = take_list_placement(state) {
12285                                        unsafe {
12286                                            split.setPosition_ofDividerAtIndex(
12287                                                day_spec::NAV_SIDEBAR_WIDTH + w,
12288                                                1,
12289                                            );
12290                                        }
12291                                    }
12292                                    // Re-frame the pane's page to the wrap it fills. A page
12293                                    // inserted while the pane was collapsed got a zero-width
12294                                    // frame, and `ViewWidthSizable` scales zero to zero however
12295                                    // wide the wrap becomes, so the list stayed invisible while
12296                                    // its rows were still there to click. An app opening on a
12297                                    // full-page section hits this on the first reveal.
12298                                    if *v
12299                                        && let Some(wrap) = state.list_wrap.as_ref()
12300                                        && let Some(page) = state.list_page.as_ref()
12301                                    {
12302                                        unsafe {
12303                                            wrap.layoutSubtreeIfNeeded();
12304                                            page.setFrame(wrap.bounds());
12305                                        }
12306                                    }
12307                                }
12308                            }
12309                            // Never arrives here: the pane persists through every presentation
12310                            // (`Cap::NavContentList` = Native), so the pieces layer never asks
12311                            // for the merged-stack shape.
12312                            NavPatch::ListInStack(_) => {}
12313                        }
12314                    });
12315                }
12316            }
12317            // Emulated cover (docs/cover.md): present = re-home onto the window's content view
12318            // at full bounds, topmost, autoresized with the window (the DayNavPage handle
12319            // reports FrameChanged on every resize). Dismiss = hide + report `CoverHidden`
12320            // immediately (no transition on this tier). Interactive dismissal doesn't exist on
12321            // this backend, so DismissDisabled has nothing to disable.
12322            kinds::COVER => {
12323                if let (Some(p), Ok(page)) = (
12324                    patch.downcast_ref::<CoverPatch>(),
12325                    h.clone().downcast::<DayNavPage>(),
12326                ) {
12327                    let node = page.ivars().node;
12328                    match p {
12329                        CoverPatch::Present { background, .. } => {
12330                            if page.ivars().sheet.get() {
12331                                if let Some(parent) =
12332                                    primary_content().and_then(|v| unsafe { v.window() })
12333                                {
12334                                    let bounds = parent.frame().size;
12335                                    let max = if page.ivars().large.get() {
12336                                        day_spec::props::LARGE_SHEET_MAX
12337                                    } else {
12338                                        day_spec::props::SHEET_MAX
12339                                    };
12340                                    let height = if page.ivars().half.get() {
12341                                        (bounds.height * 0.5).clamp(160.0, max.height)
12342                                    } else {
12343                                        (bounds.height - 80.0).clamp(300.0, max.height)
12344                                    };
12345                                    let size = NSSize::new(
12346                                        (bounds.width - 40.0).clamp(320.0, max.width),
12347                                        height,
12348                                    );
12349                                    let window = unsafe {
12350                                        NSWindow::initWithContentRect_styleMask_backing_defer(
12351                                            NSWindow::alloc(MainThreadMarker::new().unwrap()),
12352                                            NSRect::new(NSPoint::new(0.0, 0.0), size),
12353                                            NSWindowStyleMask::Titled,
12354                                            NSBackingStoreType::Buffered,
12355                                            false,
12356                                        )
12357                                    };
12358                                    unsafe {
12359                                        window.setReleasedWhenClosed(false);
12360                                        page.removeFromSuperview();
12361                                        page.setHidden(false);
12362                                        page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
12363                                        window.setContentView(Some(&page));
12364                                    }
12365                                    let key = ptr_of(h);
12366                                    SHEET_NODES.with(|t| {
12367                                        t.insert(Retained::as_ptr(&window) as usize, node)
12368                                    });
12369                                    install_sheet_escape_monitor();
12370                                    COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
12371                                    dispatch2::DispatchQueue::main().exec_async(move || {
12372                                        ffi_guard::contain((), || {
12373                                            let window =
12374                                                COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
12375                                            if let (Some(window), Some(parent)) = (
12376                                                window,
12377                                                primary_content()
12378                                                    .and_then(|v| unsafe { v.window() }),
12379                                            ) {
12380                                                unsafe {
12381                                                    parent.beginSheet_completionHandler(
12382                                                        &window, None,
12383                                                    );
12384                                                }
12385                                            }
12386                                        });
12387                                    });
12388                                    emit(
12389                                        node,
12390                                        Event::FrameChanged(Size::new(size.width, size.height)),
12391                                    );
12392                                }
12393                                return;
12394                            }
12395                            // A cover must occlude the window (the native tiers' modal surfaces
12396                            // are opaque): default to the window background when the app sets
12397                            // no explicit color.
12398                            page.set_fill(
12399                                background.unwrap_or(day_spec::SystemColor::Background.into()),
12400                            );
12401                            // The primary window's content, specifically: firstObject()
12402                            // is arbitrary once secondary windows exist (docs/windows.md).
12403                            if let Some(content) = primary_content() {
12404                                if let Some(window) = unsafe { content.window() } {
12405                                    toolbar::cover_presented(ptr_of(h), &window);
12406                                }
12407                                // Edge to edge like the root's own background, laid out below
12408                                // the title bar like the root's content: the page starts at the
12409                                // top of the window (above the pinned content origin) and
12410                                // keeps the same strip above its own layout origin.
12411                                let top = title_bar_inset(&content);
12412                                let full = content.frame().size;
12413                                page.ivars().top_inset.set(top);
12414                                unsafe {
12415                                    page.removeFromSuperview();
12416                                    content.addSubview(&page);
12417                                    page.setFrame(NSRect::new(
12418                                        NSPoint::new(0.0, -top),
12419                                        NSSize::new(full.width, full.height),
12420                                    ));
12421                                    page.setBoundsOrigin(NSPoint::new(0.0, -top));
12422                                    page.setAutoresizingMask(
12423                                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12424                                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12425                                    );
12426                                    page.setHidden(false);
12427                                }
12428                                emit(
12429                                    node,
12430                                    Event::FrameChanged(Size::new(
12431                                        full.width,
12432                                        (full.height - top).max(0.0),
12433                                    )),
12434                                );
12435                            }
12436                        }
12437                        CoverPatch::DismissDisabled(_) => {}
12438                        CoverPatch::Dismiss => {
12439                            COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
12440                            toolbar::cover_dismissed(ptr_of(h));
12441                            unsafe {
12442                                page.setHidden(true);
12443                                page.removeFromSuperview();
12444                            }
12445                            emit(node, Event::CoverHidden);
12446                        }
12447                    }
12448                }
12449            }
12450            kinds::PICKER => picker::update_any(self, h, patch),
12451            kinds::TEXT_AREA => textarea::update_any(self, h, patch),
12452            kinds::TEXT_FIELD => {
12453                if let (Some(p), Ok(tf)) = (
12454                    patch.downcast_ref::<TextFieldPatch>(),
12455                    h.clone().downcast::<NSTextField>(),
12456                ) {
12457                    match p {
12458                        TextFieldPatch::Text { text, from_native } => {
12459                            // Origin-tagged echo suppression (§4.4).
12460                            if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
12461                                unsafe { tf.setStringValue(&NSString::from_str(text)) };
12462                            }
12463                        }
12464                        TextFieldPatch::Placeholder(t) => unsafe {
12465                            tf.setPlaceholderString(Some(&NSString::from_str(t)));
12466                        },
12467                        TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
12468                        // A selection lives in the field editor, which a field has only while
12469                        // it edits (docs/textfield.md "Selection"): an unfocused field has none
12470                        // to set, and taking focus selects the whole text anyway.
12471                        TextFieldPatch::Select(sel) => {
12472                            if let Some(editor) = tf.currentEditor() {
12473                                let (start, end) = sel.utf16(&editor.string().to_string());
12474                                editor.setSelectedRange(objc2_foundation::NSRange::new(
12475                                    start,
12476                                    end - start,
12477                                ));
12478                            }
12479                        }
12480                    }
12481                }
12482            }
12483            kinds::SCROLL => {
12484                if let Some(ScrollPatch::Zoom { scale, animated }) =
12485                    patch.downcast_ref::<ScrollPatch>()
12486                {
12487                    scroll::zoom(h, *scale, *animated);
12488                }
12489            }
12490            kinds::LIST => {
12491                let key = ptr_of(h);
12492                let entry = list_entry(key);
12493                // A change held through a pass over the rows lands before anything newer
12494                // (`DayListData::change_rows`); inside a pass it stays held.
12495                if let Some((table, data)) = &entry {
12496                    data.apply_held(table);
12497                }
12498                match patch.downcast_ref::<ListPatch>() {
12499                    Some(ListPatch::Splice(deltas)) => {
12500                        // The set changed by exactly these deltas: animate each row in, out, or
12501                        // across (`DayListData::splice_rows`). Row realization stays deferred,
12502                        // as with Reload.
12503                        if let Some((table, data)) = &entry {
12504                            data.change_rows(key, table, Some(deltas));
12505                        }
12506                        post_realize_visible_rows(key);
12507                    }
12508                    Some(ListPatch::Reload) => {
12509                        if let Some((table, data)) = &entry {
12510                            data.change_rows(key, table, None);
12511                        }
12512                        // Realize the visible rows on the next main-loop turn, outside this
12513                        // borrow. An occluded window (locked screen, covered, headless CI) gets
12514                        // no normal draw pass; NSTableView would first realize these rows inside
12515                        // a snapshot's `cacheDisplayInRect`, where `bind_row` must skip the held
12516                        // borrow and the table would cache permanently blank cells.
12517                        post_realize_visible_rows(key);
12518                    }
12519                    Some(ListPatch::ScrollToRow(row)) => {
12520                        // Same deferral discipline as ScrollToEnd: the scroll tiles target rows
12521                        // synchronously, which must happen outside this `with_tree` borrow.
12522                        let row = *row;
12523                        <AppKit as Platform>::post(Box::new(move || {
12524                            if let Some((table, data)) = list_entry(key) {
12525                                // The row is the source's: a held change lands first.
12526                                data.apply_held(&table);
12527                                let rows = unsafe { table.numberOfRows() };
12528                                if rows > 0 {
12529                                    unsafe {
12530                                        table.scrollRowToVisible((row as isize).min(rows - 1));
12531                                    };
12532                                }
12533                            }
12534                        }));
12535                        post_realize_visible_rows(key);
12536                    }
12537                    Some(ListPatch::ScrollToEnd) => {
12538                        // Deferred to the next main-loop turn: an actual scroll forces
12539                        // NSTableView to tile (realize) the target rows synchronously, and this
12540                        // patch arrives inside a `with_tree` borrow where `bind_row` must skip;
12541                        // the table would cache blank cells for every newly exposed row (see
12542                        // Reload above).
12543                        <AppKit as Platform>::post(Box::new(move || {
12544                            if let Some((table, data)) = list_entry(key) {
12545                                // The end is the source's: a held change lands first.
12546                                data.apply_held(&table);
12547                                let rows = unsafe { table.numberOfRows() };
12548                                if rows > 0 {
12549                                    unsafe { table.scrollRowToVisible(rows - 1) };
12550                                }
12551                            }
12552                        }));
12553                        // ...and realize whatever the scroll exposed, still outside the borrow.
12554                        post_realize_visible_rows(key);
12555                    }
12556                    Some(ListPatch::Selected(rows)) => {
12557                        if let Some((table, data)) = &entry {
12558                            data.select(table, rows);
12559                        }
12560                    }
12561                    Some(ListPatch::RowSizeInvalidated { cell, height }) => {
12562                        if let Some((table, data)) = &entry {
12563                            data.row_resized(table, *cell, *height);
12564                        }
12565                    }
12566                    // `None` = a patch for another kind's enum. A desktop table has no editing
12567                    // mode (Cap::ListEditing is Unsupported).
12568                    Some(ListPatch::Editing(_)) | None => {}
12569                }
12570            }
12571            kinds::TREE => match patch.downcast_ref::<TreePatch>() {
12572                Some(TreePatch::Reload) => {
12573                    // Interned items keep their identity across reloadData, so NSOutlineView
12574                    // itself preserves expansion; the piece re-asserts it (and the selection)
12575                    // by token right after, belt and braces. reloadData queries the child
12576                    // counts synchronously (snapshot only, no tree) and defers viewForItem.
12577                    if let Some((outline, _)) = tree_entry(ptr_of(h)) {
12578                        unsafe { outline.reloadData() };
12579                    }
12580                    post_realize_visible_tree_rows(ptr_of(h));
12581                }
12582                Some(TreePatch::Expand(token, on)) => {
12583                    // Deferred: expandItem/collapseItem realize (or remove) the disclosed
12584                    // rows synchronously, and this patch arrives inside a `with_tree` borrow
12585                    // where `bind_row` must skip; the outline would cache permanently blank,
12586                    // id-less rows (the ScrollToEnd rule, one arm over).
12587                    let (key, token, on) = (ptr_of(h), *token, *on);
12588                    <AppKit as Platform>::post(Box::new(move || {
12589                        if let Some((outline, data)) = tree_entry(key) {
12590                            let item = data.intern(token);
12591                            // Suppressed: a programmatic disclosure must not echo back as
12592                            // `Event::TreeExpanded`. Redundant applications are AppKit no-ops.
12593                            data.ivars().suppress.set(true);
12594                            unsafe {
12595                                if on {
12596                                    outline.expandItem(Some(&item));
12597                                } else {
12598                                    outline.collapseItem(Some(&item));
12599                                }
12600                            }
12601                            data.ivars().suppress.set(false);
12602                        }
12603                        day_core::pump_events();
12604                    }));
12605                    post_realize_visible_tree_rows(ptr_of(h));
12606                }
12607                Some(TreePatch::Selected(tokens)) => {
12608                    if let Some((outline, data)) = tree_entry(ptr_of(h)) {
12609                        data.ivars().suppress.set(true);
12610                        unsafe {
12611                            if tokens.is_empty() {
12612                                outline.deselectAll(None);
12613                            } else {
12614                                let set = objc2_foundation::NSMutableIndexSet::new();
12615                                for t in tokens {
12616                                    // A token under a collapsed ancestor has no row, so it is
12617                                    // skipped; the piece re-applies after expansion changes.
12618                                    let row = outline.rowForItem(Some(&data.intern(*t)));
12619                                    if row >= 0 {
12620                                        set.addIndex(row as usize);
12621                                    }
12622                                }
12623                                outline.selectRowIndexes_byExtendingSelection(&set, false);
12624                            }
12625                        }
12626                        data.ivars().suppress.set(false);
12627                    }
12628                }
12629                Some(TreePatch::Reveal(token)) => {
12630                    // Deferred: the scroll tiles target rows synchronously, which must
12631                    // happen outside this `with_tree` borrow (the ScrollToRow rule).
12632                    let (key, token) = (ptr_of(h), *token);
12633                    <AppKit as Platform>::post(Box::new(move || {
12634                        if let Some((outline, data)) = tree_entry(key) {
12635                            let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
12636                            if row >= 0 {
12637                                unsafe { outline.scrollRowToVisible(row) };
12638                            }
12639                        }
12640                    }));
12641                    post_realize_visible_tree_rows(ptr_of(h));
12642                }
12643                None => {}
12644            },
12645            _ => {
12646                if let Some(update) = self.registry.get(kind).map(|r| r.update) {
12647                    update(self, h, patch);
12648                }
12649            }
12650        }
12651    }
12652
12653    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
12654    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
12655        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
12656        // the hook needs it mutably.
12657        let f = self.registry.get(kind).and_then(|r| r.release);
12658        if let Some(f) = f {
12659            f(self, h);
12660        }
12661    }
12662    fn release(&mut self, h: Handle) {
12663        LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
12664        // A released window content = that window is gone (docs/windows.md teardown):
12665        // drop the SecondaryWin (closing a straggler NSWindow) and its delegate with it.
12666        // (A re-fired windowWillClose emits to a torn-down node: dropped, harmless.)
12667        self.secondary.retain(|w| {
12668            if ptr_of(&w.content) == ptr_of(&h) {
12669                w.window.close();
12670                // The window's keyed state goes with it: its toolbar (toolbar.rs BARS,
12671                // keyed by the window pointer) used to survive a secondary close, and its
12672                // items, targets, retained NSToolbar and delegate all leaked.
12673                day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
12674                false
12675            } else {
12676                true
12677            }
12678        });
12679        TARGETS.with(|m| {
12680            m.borrow_mut().remove(&ptr_of(&h));
12681        });
12682        LIST_STATE.with(|m| {
12683            m.borrow_mut().remove(&ptr_of(&h));
12684        });
12685        TREE_STATE.with(|m| {
12686            m.borrow_mut().remove(&ptr_of(&h));
12687        });
12688        GESTURES.with(|m| {
12689            m.borrow_mut().remove(&ptr_of(&h));
12690        });
12691        NAV_STATE.with(|m| {
12692            if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
12693                // Unhook the split view controller from the responder chain before the drop
12694                // deallocs it. AppKit rewires these pointers behind day's back (mounting the
12695                // split resets its next to the superview; the controller's own view keeps
12696                // aiming at the controller), and a controller whose next responder is its own
12697                // view dies in dealloc's chain splice with the "next responder should never
12698                // be yourself" NSException, foreign to Rust, so it aborts the process
12699                // instead of unwinding (the Stack-page teardown crash, 2026-08).
12700                unsafe {
12701                    nav.split_vc.setNextResponder(None);
12702                    let split = nav.split_vc.splitView();
12703                    if split.nextResponder().is_some_and(|r| {
12704                        core::ptr::eq::<objc2::runtime::AnyObject>(
12705                            r.as_ref(),
12706                            nav.split_vc.as_ref(),
12707                        )
12708                    }) {
12709                        split.setNextResponder(None);
12710                    }
12711                }
12712            }
12713        });
12714        NAV_PAGES.with(|set| {
12715            set.borrow_mut().remove(&ptr_of(&h));
12716        });
12717        SPLIT_STATE.with(|m| {
12718            if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
12719                state.split.setDelegate(None);
12720            }
12721        });
12722        INSPECTOR_STATE.with(|m| {
12723            if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
12724                // The same dealloc-splice guard as the nav host above: never let the
12725                // controller (or its split) dealloc aiming at itself.
12726                unsafe {
12727                    insp.split_vc.setNextResponder(None);
12728                    let split = insp.split_vc.splitView();
12729                    if split.nextResponder().is_some_and(|r| {
12730                        core::ptr::eq::<objc2::runtime::AnyObject>(
12731                            r.as_ref(),
12732                            insp.split_vc.as_ref(),
12733                        )
12734                    }) {
12735                        split.setNextResponder(None);
12736                    }
12737                }
12738            }
12739        });
12740        NAV_MENUS.with(|m| {
12741            if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
12742                // The outline registers under its pointer (`menuForEvent:` resolves by
12743                // outline, not by this scroll handle): sweep that auxiliary key too, so
12744                // NAV_OUTLINE_MENUS, and any future outline-keyed table, drops it. A
12745                // surviving entry served the dead menu's rows once the address was recycled.
12746                day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
12747            }
12748        });
12749        // One call reclaims this handle's entry from every SideTable on this thread (canvas
12750        // OPS, PAGE_PANE, the picker/textarea state, and whatever lands later), running each
12751        // table's teardown hook (day-spec sidetable). The explicit removals above are the
12752        // older per-map checklist; new per-view maps should be SideTables so this sweep covers
12753        // them without another line here.
12754        // A group disabled with `set_subtree_enabled` that leaves the tree disabled gives back
12755        // what it held (the ledger is keyed by the handle, not swept with the side tables).
12756        input::forget_disabled_root(ptr_of(&h));
12757        day_spec::sidetable::sweep(ptr_of(&h));
12758        unsafe { h.removeFromSuperview() };
12759    }
12760
12761    fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
12762        // A nav menu that has just gained ancestors: if one of them is a tabs host, its rows
12763        // Are that host's tab labels (`adopt_menu_for_tabs`). The menu is built after its rows
12764        // page joined the host, so this is the first moment the host can see its rows.
12765        if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
12766            unsafe { content_of(parent).addSubview(child) };
12767            adopt_menu_for_tabs(self.mtm(), child);
12768            return;
12769        }
12770        // Nav host: pages land by their pane, not their position (docs/size-classes.md). Pages
12771        // fill their pane via autoresizing; the pane, not Day, owns their frames.
12772        let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
12773        let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
12774        let handled = NAV_STATE.with(|m| {
12775            let mut m = m.borrow_mut();
12776            let Some(state) = m.get_mut(&ptr_of(parent)) else {
12777                return false;
12778            };
12779            // The content-list page fills its pane at every presentation
12780            // (docs/navigation.md), never a member of the detail stack.
12781            if page_pane == Some(day_spec::props::Pane::List)
12782                && let Some(wrap) = state.list_wrap.as_ref()
12783            {
12784                state.list_page = Some(child.clone());
12785                unsafe {
12786                    child.setFrame(wrap.bounds());
12787                    child.setAutoresizingMask(
12788                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12789                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12790                    );
12791                    wrap.addSubview(child);
12792                }
12793                return true;
12794            }
12795            if is_sidebar_page {
12796                state.sidebar_page = Some(child.clone());
12797            }
12798            // Split (nav host Sidebar): the sidebar pane's page goes in the sidebar; the rest are
12799            // detail pages. Stack: every page, including the sidebar's, which is the stack's
12800            // root, lives in the detail pane so push/pop visibility covers them all.
12801            // The rows page goes to the sidebar pane in every presentation but `Stack`, where
12802            // it is the stack root and joins the detail pages instead.
12803            let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
12804            // A tabs host's detail page becomes an item of its tab view, which frames it (the
12805            // page's `setFrameSize:` reports the size to Day). Its label comes with the
12806            // menu's rows: already here when a page joins a live host, otherwise when the
12807            // menu is inserted (`adopt_menu_for_tabs`).
12808            if !to_pane && let Some(tabs) = state.tabs.as_ref() {
12809                state.pages.push(child.clone());
12810                let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
12811                unsafe {
12812                    child.setAutoresizingMask(
12813                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12814                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12815                    );
12816                    item.setView(Some(child));
12817                    tabs.view.addTabViewItem(&item);
12818                }
12819                if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
12820                    sync_tab_labels(tabs, &titles, state.selected);
12821                }
12822                return true;
12823            }
12824            let (wrap, frame) = if to_pane {
12825                (&state.sidebar_wrap, state.sidebar_wrap.bounds())
12826            } else {
12827                state.pages.push(child.clone());
12828                let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
12829                (
12830                    &state.detail_wrap,
12831                    nav_page_frame(&state.detail_wrap, visible),
12832                )
12833            };
12834            unsafe {
12835                child.setFrame(frame);
12836                child.setAutoresizingMask(
12837                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12838                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12839                );
12840                wrap.addSubview(child);
12841            }
12842            true
12843        });
12844        if handled {
12845            return;
12846        }
12847        // Split host (docs/split.md): each pane fills its wrap, an arranged subview the
12848        // splitter sizes; the pane's own `setFrameSize:` reports the size to Day.
12849        let split_pane = SPLIT_STATE.with(|m| {
12850            let m = m.borrow();
12851            let Some(state) = m.get(&ptr_of(parent)) else {
12852                return false;
12853            };
12854            let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
12855            let wrap = if second {
12856                &state.second_wrap
12857            } else {
12858                &state.first_wrap
12859            };
12860            unsafe {
12861                child.setFrame(wrap.bounds());
12862                child.setAutoresizingMask(
12863                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12864                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12865                );
12866                wrap.addSubview(child);
12867            }
12868            true
12869        });
12870        if split_pane {
12871            return;
12872        }
12873        // Inspector host: each pane fills its wrap via autoresizing, the nav-page contract;
12874        // the split, not Day, owns the pane frames (docs/inspector.md).
12875        let inspected = INSPECTOR_STATE.with(|m| {
12876            let m = m.borrow();
12877            let Some(state) = m.get(&ptr_of(parent)) else {
12878                return false;
12879            };
12880            let panel = INSPECTOR_PANES
12881                .with(|t| t.get(ptr_of(child)))
12882                .unwrap_or(false);
12883            let wrap = if panel {
12884                &state.panel_wrap
12885            } else {
12886                &state.content_wrap
12887            };
12888            unsafe {
12889                child.setFrame(wrap.bounds());
12890                child.setAutoresizingMask(
12891                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
12892                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
12893                );
12894                wrap.addSubview(child);
12895            }
12896            true
12897        });
12898        if !inspected {
12899            // Absolute positioning: z-order is build order; index is irrelevant for
12900            // non-overlapping frames (stack_z will need ordered insertion later).
12901            unsafe { content_of(parent).addSubview(child) };
12902        }
12903    }
12904
12905    fn remove(&mut self, parent: &Handle, child: &Handle) {
12906        PAGE_PANE.with(|t| t.remove(ptr_of(child)));
12907        let mtm = self.mtm();
12908        NAV_STATE.with(|m| {
12909            if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
12910                // A tabs host: the page leaves with its tab item.
12911                if let Some(tabs) = state.tabs.as_ref() {
12912                    unsafe {
12913                        let n = tabs.view.numberOfTabViewItems();
12914                        for i in 0..n {
12915                            let item = tabs.view.tabViewItemAtIndex(i);
12916                            if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
12917                                tabs.view.removeTabViewItem(&item);
12918                                break;
12919                            }
12920                        }
12921                    }
12922                }
12923                state.pages.retain(|p| ptr_of(p) != ptr_of(child));
12924                if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
12925                    state.sidebar_page = None;
12926                }
12927            }
12928        });
12929        unsafe { child.removeFromSuperview() };
12930    }
12931
12932    fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
12933        unsafe { content_of(parent).addSubview(child) };
12934    }
12935
12936    fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
12937        match kind {
12938            kinds::LABEL => {
12939                if let Some(tf) = h.downcast_ref::<NSTextField>() {
12940                    let w = p.width.unwrap_or(1.0e6);
12941                    // The field owns maximumNumberOfLines; measuring its cell bypasses it.
12942                    let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
12943                    let mut height = s.height.ceil();
12944                    // AppKit's truncating single-line mode still measures explicit newlines
12945                    // as multiple lines. Bound that case by one line box: the label's fixed
12946                    // line height where it sets one, else AppKit's own font metrics.
12947                    if tf.maximumNumberOfLines() == 1
12948                        && let Some(font) = unsafe { tf.font() }
12949                    {
12950                        let fixed = h.downcast_ref::<DayLabel>().and_then(|l| {
12951                            label_line_points(
12952                                l.ivars().paragraph.get().line_height,
12953                                font.pointSize(),
12954                            )
12955                        });
12956                        let line = fixed.unwrap_or_else(|| natural_line_height(&font));
12957                        height = height.min(line.ceil());
12958                    }
12959                    return Size::new(s.width.ceil().min(w), height);
12960                }
12961                Size::ZERO
12962            }
12963            kinds::BUTTON | kinds::TOGGLE => {
12964                let s = unsafe { h.fittingSize() };
12965                Size::new(s.width.ceil(), s.height.ceil())
12966            }
12967            kinds::SLIDER => {
12968                let s = unsafe { h.fittingSize() };
12969                Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
12970            }
12971            kinds::PICKER => picker::measure_any(self, h, p),
12972            kinds::TEXT_AREA => textarea::measure_any(self, h, p),
12973            kinds::TEXT_FIELD => {
12974                let s = unsafe { h.fittingSize() };
12975                Size::new(
12976                    p.width.unwrap_or(s.width.max(160.0)),
12977                    s.height.max(22.0).ceil(),
12978                )
12979            }
12980            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
12981            // The stack's own fitting size, at least a table row's 28pt; the words truncate to
12982            // the row's width.
12983            kinds::LIST_ITEM => {
12984                let s = h.fittingSize();
12985                Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
12986            }
12987            kinds::PROGRESS => {
12988                // Indeterminate spinner is a fixed square; determinate bar fills width.
12989                let indeterminate = h
12990                    .clone()
12991                    .downcast::<NSProgressIndicator>()
12992                    .is_ok_and(|pi| unsafe { pi.isIndeterminate() });
12993                if indeterminate {
12994                    let large = h
12995                        .downcast_ref::<NSProgressIndicator>()
12996                        .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
12997                    let side = if large { 32.0 } else { 20.0 };
12998                    Size::new(side, side)
12999                } else {
13000                    Size::new(p.width.unwrap_or(180.0), 20.0)
13001                }
13002            }
13003            kinds::NAV_MENU => {
13004                let rows = NAV_MENUS.with(|m| {
13005                    m.borrow()
13006                        .get(&ptr_of(h))
13007                        .map_or(0, |(_, d)| d.ivars().items.borrow().len())
13008                });
13009                Size::new(
13010                    p.width.unwrap_or(220.0),
13011                    p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
13012                )
13013            }
13014            // The recycling list fills the space it is offered (its native scroll owns overflow).
13015            kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
13016            _ => {
13017                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
13018                    measure(self, h, p)
13019                } else {
13020                    let s = unsafe { h.fittingSize() };
13021                    Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
13022                }
13023            }
13024        }
13025    }
13026
13027    /// The whole `AnimSpec` on the layer's `opacity` (docs/tween.md; see `motion`).
13028    fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
13029        motion::set_opacity(h, opacity, anim);
13030    }
13031
13032    fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
13033        // Expressed in the view's own geometry (see `TRANSFORMS`), so hit-testing follows the
13034        // drawing, as UIKit's does. Without a laid-out frame yet, `set_frame` applies it. An
13035        // animated change plays on the layer from the geometry shown (see `motion`).
13036        let from = motion::shown_geometry(h);
13037        TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
13038        if let Some(base) = BASE_FRAMES.with(|m| m.get(ptr_of(h))) {
13039            motion::move_geometry(h, from, (base, t), anim, || apply_geometry(h, base, t));
13040        }
13041    }
13042
13043    /// What the layer shows mid-animation (docs/tween.md "Toolkit support"; see `motion`).
13044    fn read_displayed(&self, h: &Handle) -> day_spec::Displayed {
13045        motion::displayed(h)
13046    }
13047
13048    /// macOS has no system text-size setting that `NSFont.preferredFont(forTextStyle:)`
13049    /// follows, so every style is at its default size (docs/text.md "Text scale").
13050    fn text_scale(&mut self, _style: Font) -> f64 {
13051        1.0
13052    }
13053
13054    /// A leaf control's reading direction (docs/localization.md "Direction of a subtree"):
13055    /// `userInterfaceLayoutDirection` on the view and its cell (a slider's fill side, a
13056    /// switch's on side, a pop-up's arrow), and for text the base writing direction, which
13057    /// `NSTextAlignment.natural` and Day's `Trailing` follow. Containers, scroll views, lists
13058    /// and other hosts are skipped: Day places their children and mirrors them itself.
13059    fn set_layout_direction(
13060        &mut self,
13061        h: &Handle,
13062        kind: PieceKind,
13063        direction: day_spec::LayoutDirection,
13064    ) {
13065        use objc2_app_kit::{NSUserInterfaceLayoutDirection as Ui, NSWritingDirection as Writing};
13066        let rtl = direction == day_spec::LayoutDirection::Rtl;
13067        let (ui, writing) = if rtl {
13068            (Ui::RightToLeft, Writing::RightToLeft)
13069        } else {
13070            (Ui::LeftToRight, Writing::LeftToRight)
13071        };
13072        if kind == kinds::TEXT_AREA {
13073            textarea::set_direction(h, ui, writing);
13074            return;
13075        }
13076        if !matches!(
13077            kind,
13078            kinds::LABEL
13079                | kinds::BUTTON
13080                | kinds::TOGGLE
13081                | kinds::SLIDER
13082                | kinds::TEXT_FIELD
13083                | kinds::PICKER
13084                | kinds::PROGRESS
13085        ) {
13086            return;
13087        }
13088        h.setUserInterfaceLayoutDirection(ui);
13089        if let Some(label) = h.downcast_ref::<DayLabel>() {
13090            label.ivars().direction.set(Some(direction));
13091            apply_label_paragraph(label);
13092            return;
13093        }
13094        if let Some(control) = h.downcast_ref::<NSControl>() {
13095            if let Some(cell) = unsafe { control.cell() } {
13096                cell.setUserInterfaceLayoutDirection(ui);
13097            }
13098            // A text field's natural alignment follows its base writing direction.
13099            if control.isKindOfClass(<NSTextField as objc2::ClassType>::class()) {
13100                unsafe { control.setBaseWritingDirection(writing) };
13101            }
13102        }
13103    }
13104
13105    fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
13106        if let Some(label) = h.downcast_ref::<DayLabel>() {
13107            label.ivars().selectable.set(selectable);
13108            label.set_links(label.ivars().has_links.get());
13109        } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
13110            unsafe { tf.setSelectable(selectable) };
13111        }
13112        None
13113    }
13114
13115    fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
13116        let node = text_field_node(h)?;
13117        let old = h.downcast_ref::<NSTextField>()?;
13118        // Hidden characters are a class on AppKit. A field already of the right class is
13119        // dressed in place; otherwise its replacement is, and the node moves to it.
13120        let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
13121            .then(|| self.swap_text_field(h, old, node, traits.secure));
13122        let tf = swapped.as_deref().unwrap_or(old);
13123        unsafe {
13124            // Read-only keeps the bezel and the ordinary text color; the text stays
13125            // selectable, so it can still be copied.
13126            tf.setEditable(!traits.read_only);
13127            tf.setSelectable(true);
13128        }
13129        // The purpose is AutoFill's hint on the desktop: which saved credential or contact
13130        // detail the system offers. `Number` and `Decimal` have no content type. A constant
13131        // newer than the running system leaves the field untyped.
13132        let content_type = match traits.purpose {
13133            InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
13134            InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
13135            InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
13136            InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
13137            InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
13138            InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
13139            InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
13140            InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
13141            InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
13142        };
13143        unsafe {
13144            tf.setContentType(content_type);
13145            // Only free text wants the system finishing words; a name, an address or a code
13146            // is typed exactly.
13147            tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
13148        }
13149        // No on-screen keyboard, so no action key to label; and no native length limit:
13150        // day-pieces holds `max_length`.
13151        swapped.as_ref().map(view_of)
13152    }
13153
13154    fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
13155        let key = Retained::as_ptr(h) as usize;
13156        if cursor == Cursor::Default {
13157            // Release: drop the tracking area, and the hide if this owner holds one.
13158            if let Some((owner, area)) = self.cursors.remove(&key) {
13159                unsafe { h.removeTrackingArea(&area) };
13160                if owner.ivars().hiding.replace(false) {
13161                    NSCursor::unhide();
13162                }
13163            }
13164            return;
13165        }
13166        let hidden = cursor == Cursor::None;
13167        let shape = if hidden { None } else { ns_cursor(&cursor) };
13168        let mtm = self.mtm;
13169        let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
13170            let owner = DayCursorOwner::new(mtm);
13171            // InVisibleRect: the area follows the view's bounds, so no rect to keep in step
13172            // with layout. ActiveInKeyWindow: the shape belongs to the window taking input.
13173            let opts = NSTrackingAreaOptions::CursorUpdate
13174                | NSTrackingAreaOptions::MouseEnteredAndExited
13175                | NSTrackingAreaOptions::ActiveInKeyWindow
13176                | NSTrackingAreaOptions::InVisibleRect;
13177            let any: &objc2::runtime::AnyObject = &owner;
13178            let area = unsafe {
13179                NSTrackingArea::initWithRect_options_owner_userInfo(
13180                    NSTrackingArea::alloc(),
13181                    NSRect::ZERO,
13182                    opts,
13183                    Some(any),
13184                    None,
13185                )
13186            };
13187            unsafe { h.addTrackingArea(&area) };
13188            (owner, area)
13189        });
13190        let changed = {
13191            let iv = owner.ivars();
13192            let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
13193                (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
13194                (None, None) => true,
13195                _ => false,
13196            };
13197            *iv.cursor.borrow_mut() = shape;
13198            let was_hidden = iv.hidden.replace(hidden);
13199            !same || was_hidden != hidden
13200        };
13201        // A reactive change while the pointer is already inside: AppKit only asks on entry,
13202        // so ask it to re-evaluate now.
13203        if changed && let Some(w) = h.window() {
13204            unsafe { w.invalidateCursorRectsForView(h) };
13205        }
13206    }
13207
13208    /// Where the control actually draws its first line of text (docs/baseline.md).
13209    ///
13210    /// AppKit publishes `firstBaselineOffsetFromTop`, but it is measured from the top of the
13211    /// view's alignment rect and it is rounded to whole points, and that rounding is visible.
13212    /// An `NSDatePicker` in a 26pt frame insets its alignment rect 4pt and answers 15, i.e. 19
13213    /// in frame terms, while it paints at 19.9; a label beside it then sits a point high, which
13214    /// is exactly the drift baseline alignment exists to remove.
13215    ///
13216    /// So derive it from the metrics AppKit rounded: a single line of the control's own font,
13217    /// centered in its alignment rect, with the baseline an ascender below the line's top. That
13218    /// reproduces AppKit's own numbers for a plain label and a bezeled field (12.91 → its 13,
13219    /// 19.91 → its 20) while keeping the fractional part that makes a picker land on the line.
13220    /// Controls with no font of their own keep AppKit's answer.
13221    fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
13222        if !day_spec::kind_has_baseline(kind) {
13223            return None;
13224        }
13225        // The view has to be at the height the row settled on before it answers: a control
13226        // that centers its text vertically moves its baseline with its box.
13227        let current = unsafe { h.frame() };
13228        if (current.size.height - size.height).abs() > 0.5 {
13229            unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
13230        }
13231        let insets = unsafe { h.alignmentRectInsets() };
13232        let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
13233        let font = h
13234            .downcast_ref::<NSControl>()
13235            .and_then(|c| unsafe { c.font() });
13236        let offset = match font {
13237            // A multi-line editor's first line sits at the top of its text container, not
13238            // centered in it, so the centering model would put its baseline half a box too low.
13239            Some(_) if kind == kinds::TEXT_AREA => reported,
13240            Some(f) => {
13241                let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
13242                let line = ascender - descender;
13243                let align_h = (size.height - insets.top - insets.bottom).max(0.0);
13244                insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
13245            }
13246            None => reported,
13247        };
13248        // AppKit's documented "no baseline" answer is the view's own height.
13249        (offset > 0.0 && offset < size.height).then_some(offset)
13250    }
13251
13252    fn set_frame(&mut self, h: &Handle, frame: Rect, anim: Option<&AnimSpec>) {
13253        // Nav pages: the splitter pane / nav container owns the frame (autoresized).
13254        if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
13255            return;
13256        }
13257        // Every Day parent is flipped (DayFlipped containers, flipped scroll document views),
13258        // so top-left frames apply directly.
13259        let r = NSRect::new(
13260            NSPoint::new(frame.origin.x, frame.origin.y),
13261            NSSize::new(frame.size.width, frame.size.height),
13262        );
13263        // Nav host: the sidebar holds its width when the window resizes and the detail pane
13264        // absorbs the change. That is now the sidebar NSSplitViewItem's behavior, so the
13265        // only thing left to do here is give the split its frame and place the divider once;
13266        // re-placing it on every resize would fight the item and undo a user's drag.
13267        if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
13268            // A host at the top of a window's pinned content reaches up under the title bar,
13269            // where its controller expects to be (see `pane_under_title_bar`); its panes keep
13270            // their content below the strip, so nothing Day laid out moves.
13271            let strip = unsafe { split.superview() }
13272                .and_then(|sup| {
13273                    let content = unsafe { sup.window() }?.contentView()?;
13274                    // Layout wrappers (for example zstack with a reader cover) may sit
13275                    // between the window root and its navigation host. A direct-parent
13276                    // check misses them and puts AppKit's frosted pocket over page text.
13277                    let mut ancestor = Some(sup.clone());
13278                    while let Some(view) = ancestor {
13279                        if std::ptr::eq(&raw const *view, &raw const *content) {
13280                            break;
13281                        }
13282                        if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
13283                            return None; // nested navigation belongs to the outer pane
13284                        }
13285                        ancestor = unsafe { view.superview() };
13286                    }
13287                    let point = unsafe {
13288                        sup.convertPoint_toView(
13289                            NSPoint::new(frame.origin.x, frame.origin.y),
13290                            Some(&content),
13291                        )
13292                    };
13293                    (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
13294                })
13295                .unwrap_or(0.0);
13296            let r = NSRect::new(
13297                NSPoint::new(r.origin.x, r.origin.y - strip),
13298                NSSize::new(r.size.width, r.size.height + strip),
13299            );
13300            let wraps = NAV_STATE.with(|m| {
13301                m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
13302                    #[expect(
13303                        clippy::float_cmp,
13304                        reason = "unchanged-value check against the strip stored last time"
13305                    )]
13306                    let changed = s.title_strip != strip;
13307                    changed.then(|| {
13308                        s.title_strip = strip;
13309                        let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
13310                        w.extend(s.list_wrap.clone());
13311                        w
13312                    })
13313                })
13314            });
13315            let first = NAV_STATE.with(|m| {
13316                m.borrow_mut()
13317                    .get_mut(&ptr_of(h))
13318                    .map_or((false, None), |s| {
13319                        if !s.presentation.is_split() {
13320                            return (false, None);
13321                        }
13322                        let sidebar = !std::mem::replace(&mut s.positioned, true);
13323                        // The list's divider waits for the pane to be showing. Placing it while
13324                        // the pane is collapsed re-opens it (which is how an app whose first
13325                        // destination has no list opened with one beside it) and spends the one
13326                        // placement the pane gets, leaving it at the solver's width later on.
13327                        (sidebar, take_list_placement(s))
13328                    })
13329            });
13330            unsafe {
13331                split.setFrame(r);
13332                split.layoutSubtreeIfNeeded();
13333            }
13334            // After the panes have their new size, so each wrap is placed in the final pane;
13335            // autoresizing keeps the strip from then on.
13336            for wrap in wraps.iter().flatten() {
13337                place_below_strip(wrap, strip);
13338            }
13339            unsafe {
13340                if first.0 {
13341                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
13342                }
13343                // A triple split has a second divider, and nothing else places it: left alone,
13344                // the controller's initial constraint pass lands it wherever the solver liked, so
13345                // the content list opens at an arbitrary width and the detail pane gets the
13346                // leftovers until the first manual drag re-settles them.
13347                if let Some(w) = first.1 {
13348                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
13349                }
13350            }
13351        } else {
13352            let base = [
13353                frame.origin.x,
13354                frame.origin.y,
13355                frame.size.width,
13356                frame.size.height,
13357            ];
13358            let from = motion::shown_geometry(h);
13359            BASE_FRAMES.with(|m| m.insert(ptr_of(h), base));
13360            // A transform (`set_transform`) is applied to the frame Day laid out. An animated
13361            // change plays on the layer from the geometry shown (see `motion`).
13362            let t = TRANSFORMS.with(|m| m.get(ptr_of(h)));
13363            let to = (base, t.unwrap_or(Transform::IDENTITY));
13364            motion::move_geometry(h, from, to, anim, || match t {
13365                Some(t) => apply_geometry(h, base, t),
13366                None => h.setFrame(r),
13367            });
13368        }
13369    }
13370
13371    fn set_scroll_content(&mut self, h: &Handle, content: Size) {
13372        if let Some(sv) = h.downcast_ref::<NSScrollView>()
13373            && let Some(doc) = unsafe { sv.documentView() }
13374        {
13375            unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
13376        }
13377    }
13378
13379    /// A macOS table row: the dense rows of a Finder or Mail list, 28pt for an icon and a line of body text.
13380    fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
13381        day_spec::RowMetrics {
13382            insets: day_spec::Insets {
13383                top: 4.0,
13384                leading: 8.0,
13385                bottom: 4.0,
13386                trailing: 8.0,
13387            },
13388            min_height: 28.0,
13389        }
13390    }
13391
13392    /// The least scroll that shows `target` (`scrollRectToVisible:`'s rule), through the clip
13393    /// view's animator when `animated`, else a jump that also stops a running animation.
13394    fn scroll_to(&mut self, h: &Handle, target: Rect, animated: bool) {
13395        if let Some(sv) = h.downcast_ref::<NSScrollView>()
13396            && unsafe { sv.documentView() }.is_some()
13397        {
13398            let bounds = unsafe { sv.contentView() }.bounds();
13399            let to = NSPoint::new(
13400                scroll::reveal_origin(
13401                    bounds.origin.x,
13402                    bounds.size.width,
13403                    target.origin.x,
13404                    target.size.width,
13405                ),
13406                scroll::reveal_origin(
13407                    bounds.origin.y,
13408                    bounds.size.height,
13409                    target.origin.y,
13410                    target.size.height,
13411                ),
13412            );
13413            scroll::scroll_clip_to(sv, to, animated, None);
13414        }
13415    }
13416
13417    fn scroll_offset(&mut self, h: &Handle) -> Point {
13418        scroll::offset(h)
13419    }
13420
13421    /// Place the row where `to.align` says from its `rectOfRow:` and the clip view's bounds
13422    /// (docs/list.md "Programmatic scrolling"), animated through the clip view's animator or a
13423    /// jump; then realize the rows it exposed and report the viewport. Deferred one turn, as
13424    /// the patches were: the scroll tiles rows synchronously, outside this borrow.
13425    fn list_scroll(&mut self, h: &Handle, to: day_spec::ListScroll) -> bool {
13426        let key = ptr_of(h);
13427        if list_entry(key).is_none() {
13428            return false;
13429        }
13430        <AppKit as Platform>::post(Box::new(move || {
13431            let Some((table, data)) = list_entry(key) else {
13432                return;
13433            };
13434            // The reader's live scroll holds the list (docs/list.md "Following the end"): the
13435            // app's scroll would run against their gesture.
13436            if data.ivars().live.get() {
13437                return;
13438            }
13439            // The row is the source's: a held change lands first.
13440            data.apply_held(&table);
13441            let rows = unsafe { table.numberOfRows() };
13442            let Some(scroll) = table.enclosingScrollView() else {
13443                return;
13444            };
13445            if rows <= 0 {
13446                return;
13447            }
13448            let bounds = unsafe { scroll.contentView() }.bounds();
13449            let y = match to.row {
13450                Some(row) => {
13451                    let rect = unsafe { table.rectOfRow((row as isize).min(rows - 1)) };
13452                    scroll::row_origin(
13453                        bounds.origin.y,
13454                        bounds.size.height,
13455                        rect.origin.y,
13456                        rect.origin.y + rect.size.height,
13457                        to.align,
13458                    )
13459                }
13460                // The very end: past a footer or bottom padding, which are rows too.
13461                None => table.frame().size.height - bounds.size.height,
13462            };
13463            let done: Box<dyn FnOnce()> = Box::new(move || post_realize_visible_rows(key));
13464            scroll::scroll_clip_to(
13465                &scroll,
13466                NSPoint::new(bounds.origin.x, y),
13467                to.animated,
13468                Some(done),
13469            );
13470        }));
13471        true
13472    }
13473
13474    fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
13475        let Some(window) = h.window() else { return };
13476        // A list's public handle is its scroll view; keyboard focus belongs to the table.
13477        let list = list_entry(ptr_of(h));
13478        let responder: &NSResponder = match &list {
13479            Some((table, _)) => table,
13480            None => h,
13481        };
13482        let responder_ptr = std::ptr::from_ref::<NSResponder>(responder) as usize;
13483        if focused {
13484            window.makeFirstResponder(Some(responder));
13485            return;
13486        }
13487        // Resign only while this view still owns focus, so a stale release can't blur a
13488        // sibling.
13489        let owns = window
13490            .firstResponder()
13491            .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
13492            || owns_first_responder(&window, h);
13493        if owns {
13494            window.makeFirstResponder(None);
13495        }
13496    }
13497
13498    fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
13499        // The overrides live on `DayFlipped` (the container view); registering any other
13500        // view is harmless but inert, the graceful silence the duty documents.
13501        if focusable {
13502            FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
13503        } else {
13504            FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
13505        }
13506    }
13507
13508    fn set_event_sink(&mut self, sink: EventSink) {
13509        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
13510        // Press, the input kind and key releases (docs/gestures.md, docs/menus.md "Keys").
13511        input::install_monitor();
13512    }
13513
13514    fn set_edit_state(&mut self, state: &day_spec::EditState) {
13515        EDIT_STATE.with(|s| s.set(*state));
13516    }
13517
13518    fn modifiers(&mut self) -> day_spec::Modifiers {
13519        let f = NSEvent::modifierFlags_class();
13520        day_spec::Modifiers::NONE
13521            .with(
13522                day_spec::Modifiers::SHIFT,
13523                f.contains(NSEventModifierFlags::Shift),
13524            )
13525            .with(
13526                day_spec::Modifiers::PRIMARY,
13527                f.contains(NSEventModifierFlags::Command),
13528            )
13529            .with(
13530                day_spec::Modifiers::ALT,
13531                f.contains(NSEventModifierFlags::Option),
13532            )
13533    }
13534
13535    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
13536        let front = undo_front(self.mtm);
13537        *front.ivars().state.borrow_mut() = state.clone();
13538    }
13539
13540    fn attach_list(&mut self, host: &Handle, source: ListSource) {
13541        let key = ptr_of(host);
13542        if let Some((table, data)) = list_entry(key) {
13543            let supplements = source.is_supplement.is_some();
13544            data.ivars().source.replace(Some(source));
13545            // A change held for the old source means nothing to the new one: it reloads.
13546            data.ivars().held.replace(None);
13547            data.ivars().splice.replace(None);
13548            if data.ivars().supplements.replace(supplements) != supplements {
13549                // NSTableView reads which optional delegate methods exist when its delegate is
13550                // set: set it again so a uniform list starts answering `heightOfRow`.
13551                unsafe {
13552                    table.setDelegate(None);
13553                    table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
13554                }
13555            }
13556            // Initial fill: numberOfRows reads the snapshot only; viewForRow is deferred.
13557            unsafe { table.reloadData() };
13558        }
13559        // Force the table to realize its visible row views on the next main-loop turn, outside
13560        // any `with_tree` borrow, so `viewForRow`/`bind_row` build the cells then. Otherwise a
13561        // headless CI window never lays the table out until a snapshot's `cacheDisplayInRect`
13562        // forces it *inside* the snapshot borrow, where `bind_row` must skip (blank rows).
13563        post_realize_visible_rows(key);
13564    }
13565
13566    fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
13567        let key = ptr_of(host);
13568        if let Some((outline, data)) = tree_entry(key) {
13569            data.ivars().source.replace(Some(source));
13570            // Initial fill: child counts read the snapshot only; viewForItem is deferred.
13571            unsafe { outline.reloadData() };
13572        }
13573        // Realize visible rows on the next main-loop turn, outside any borrow (the
13574        // attach_list comment has the occluded-window story).
13575        <AppKit as Platform>::post(Box::new(move || {
13576            if let Some((outline, _)) = tree_entry(key) {
13577                unsafe { outline.layoutSubtreeIfNeeded() };
13578            }
13579        }));
13580    }
13581
13582    fn adopt(&mut self, raw: RawHandle) -> Handle {
13583        // A recycling NSTableView cell view; Day builds/rebinds its row content in place.
13584        // Invariant, not app input: day-core only passes back the cell pointer this backend
13585        // itself vended through `bind_row`, so a null here is a framework bug worth stopping on.
13586        let ptr = raw.cast::<NSView>();
13587        unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
13588    }
13589
13590    fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
13591        self.edit_toolbar(h, ops)
13592    }
13593
13594    fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
13595        Self::patch_toolbar(h, patch);
13596    }
13597
13598    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
13599        let mtm = self.mtm;
13600        if self.menu_escape_monitor.is_none() {
13601            let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
13602                ffi_guard::contain(event.as_ptr(), || {
13603                    let event_ref = unsafe { event.as_ref() };
13604                    let app = NSApplication::sharedApplication(mtm);
13605                    // Native dialogs retain their cancellation behavior. Only an enabled
13606                    // menu key equivalent can consume Escape, never the general key stream.
13607                    if app.modalWindow().is_none()
13608                        && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
13609                        && unsafe { event_ref.charactersIgnoringModifiers() }
13610                            .is_some_and(|s| s.to_string() == "\u{1b}")
13611                        && app
13612                            .mainMenu()
13613                            .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
13614                    {
13615                        std::ptr::null_mut()
13616                    } else {
13617                        event.as_ptr()
13618                    }
13619                })
13620            });
13621            self.menu_escape_monitor = unsafe {
13622                NSEvent::addLocalMonitorForEventsMatchingMask_handler(
13623                    objc2_app_kit::NSEventMask::KeyDown,
13624                    &block,
13625                )
13626            }
13627            .map(MenuEscapeMonitor);
13628        }
13629        let app = NSApplication::sharedApplication(mtm);
13630        let menubar = NSMenu::new(mtm);
13631        // macOS owns the application menu; relocate app-level roles while preserving
13632        // their callbacks, shortcuts, and enabled state.
13633        let mut items = items.to_vec();
13634        let about = extract_app_role(&mut items, day_spec::MenuRole::About);
13635        let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
13636        let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
13637        let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
13638        let services =
13639            install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
13640        // Fill the standard slots the app did not claim, in the platform's bar order
13641        // (day-core owns that policy so every backend arranges its bar the same way).
13642        // Fill the standard slots the app left open, in macOS's bar order. The Window menu is
13643        // installed natively below, so the style deliberately supplies none.
13644        let items =
13645            day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
13646        let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
13647        // Each top-level entry becomes a menu-bar menu.
13648        for item in &items {
13649            match item {
13650                day_spec::MenuItem::Submenu { label, items, role } => {
13651                    let sub = build_ns_menu(mtm, label, items);
13652                    let it = NSMenuItem::new(mtm);
13653                    // Help is held back: the Window menu is installed natively after this loop
13654                    // (AppKit owns it so it can append the live window list), and Help sits
13655                    // last on every Mac menu bar.
13656                    if *role == Some(day_spec::MenuBarRole::Help)
13657                        || *label == day_localization::t(day_localization::key::day_help)
13658                    {
13659                        help_menu = Some((label.clone(), sub));
13660                        continue;
13661                    }
13662                    it.setTitle(&NSString::from_str(label));
13663                    it.setSubmenu(Some(&sub));
13664                    menubar.addItem(&it);
13665                }
13666                other => {
13667                    // A bare top-level action → wrap in a one-item menu so it has a submenu.
13668                    let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
13669                    let it = NSMenuItem::new(mtm);
13670                    it.setSubmenu(Some(&sub));
13671                    menubar.addItem(&it);
13672                }
13673            }
13674        }
13675        // The Window menu (docs/windows.md): auto-installed unless the app's model owns
13676        // `MenuRole::Minimize` (then the app is composing its own window management).
13677        if !model_has_role(&items, day_spec::MenuRole::Minimize) {
13678            install_windows_menu(mtm, &app, &menubar);
13679        }
13680        if let Some((label, help)) = help_menu {
13681            let it = NSMenuItem::new(mtm);
13682            it.setTitle(&NSString::from_str(&label));
13683            it.setSubmenu(Some(&help));
13684            menubar.addItem(&it);
13685            // Registering it makes AppKit add the Help search field and index the help book —
13686            // behavior no hand-built menu reproduces.
13687            unsafe { app.setHelpMenu(Some(&help)) };
13688        }
13689        app.setMainMenu(Some(&menubar));
13690        unsafe { app.setServicesMenu(Some(&services)) };
13691    }
13692
13693    fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
13694        fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
13695            for sub in v.subviews() {
13696                unsafe { sub.setMenu(Some(menu)) };
13697                apply_to_subviews(&sub, menu);
13698            }
13699        }
13700        let Some(view) = h.downcast_ref::<NSView>() else {
13701            return;
13702        };
13703        if items.is_empty() {
13704            unsafe { view.setMenu(None) };
13705            return;
13706        }
13707        let menu = build_ns_menu(self.mtm, "", items);
13708        // Attach to the view AND its current subviews: a right-click that hit-tests a child
13709        // control (the label inside a padded target) must find the menu on the view it hit —
13710        // AppKit does not walk ancestors for `.menu`, and controls swallow the event.
13711        // DayFlipped's `rightMouseDown:` pops the menu explicitly; native controls (labels)
13712        // show their `.menu` through their own default path.
13713        unsafe { view.setMenu(Some(&menu)) };
13714        apply_to_subviews(view, &menu);
13715    }
13716
13717    fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
13718        transfer::source(h, source);
13719    }
13720    fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
13721        transfer::target(h, target);
13722    }
13723    fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
13724        // Consulted by the classes that override `menuForEvent:` (the canvas; docs/menus.md
13725        // "Dynamic context menus" lists the covered surfaces per backend).
13726        CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
13727    }
13728
13729    fn set_button_menu(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
13730        let Some(btn) = h.downcast_ref::<NSButton>() else {
13731            return;
13732        };
13733        // A pull-down opens on the mouse going down, as `NSPopUpButton` does, so a press can
13734        // drag straight onto an item and release there. Space and the accessibility press
13735        // still arrive through `performClick:`, which sends the same action.
13736        unsafe { btn.sendActionOn(objc2_app_kit::NSEventMask::LeftMouseDown) };
13737        BUTTON_MENUS.with(|t| t.insert(ptr_of(h), f));
13738    }
13739
13740    fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
13741        let key = ptr_of(h);
13742        // Pan is not a recognizer on macOS: the two-finger idiom is the trackpad SCROLL, so
13743        // the canvas view's own `scrollWheel:` override reports it for registered nodes.
13744        // Containers use a horizontal-only monitor so nested vertical scrolling still works.
13745        if kind == day_spec::GestureKind::Pan {
13746            PAN_NODES.with(|t| t.insert(key, node));
13747            install_container_pan_monitor();
13748            return;
13749        }
13750        // Nor is rotation: `DayCanvas::rotateWithEvent:` reads the trackpad's rotate events, so
13751        // it runs alongside the magnification recognizer a pinch attaches. Like Pan and Hover,
13752        // a rotation enabled on another view emits nothing.
13753        if kind == day_spec::GestureKind::Rotate {
13754            ROTATE_NODES.with(|t| t.insert(key, node));
13755            return;
13756        }
13757        // Nor is hover: it is a tracking area plus `mouseEntered:`/`mouseMoved:`/`mouseExited:`,
13758        // which Day's canvas, container and label views override (`input::report_hover`) — a
13759        // hover enabled on another view (a native control, an image) emits nothing.
13760        if kind == day_spec::GestureKind::Hover {
13761            // Idempotent, and it has to be checked here rather than falling through to the
13762            // recognizer guard below: day-core re-enables a gesture on rebuild, and a second
13763            // tracking area on the same view means a second copy of every hover event.
13764            let first = HOVER_NODES.with(|t| t.get(key)).is_none();
13765            HOVER_NODES.with(|t| t.insert(key, node));
13766            if first {
13767                // `InVisibleRect` makes the area follow the view's bounds (or, with a hit
13768                // slop, the grown bounds); `ActiveInKeyWindow` matches the cursor areas — a
13769                // background window does not report hovers.
13770                input::install_hover_area(h);
13771            }
13772            return;
13773        }
13774        // Press is an observer, not a recognizer (docs/gestures.md "Press"): the input
13775        // monitor reports it for the views registered here, before AppKit dispatches the
13776        // mouse-down, and never consumes an event. A recognizer would have to claim the
13777        // sequence to see it, and AppKit's recognizers report nothing at the down itself.
13778        if kind == day_spec::GestureKind::Press {
13779            input::PRESS_NODES.with(|t| t.insert(key, node));
13780            input::install_monitor();
13781            return;
13782        }
13783        // Raw contacts: a trackpad's touches are not contacts on the screen, so the kind
13784        // stays `Unsupported` (`gesture_support`) and day-core derives one mouse contact.
13785        if kind == day_spec::GestureKind::Touches {
13786            return;
13787        }
13788        // Idempotent: attach each kind at most once per view.
13789        let already = GESTURES.with(|m| {
13790            m.borrow()
13791                .get(&key)
13792                .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
13793        });
13794        if already {
13795            return;
13796        }
13797        let mtm = self.mtm;
13798        let target = DayGesture::new(mtm, node, kind);
13799        let recognizer: Retained<NSGestureRecognizer> = unsafe {
13800            match kind {
13801                day_spec::GestureKind::Drag => {
13802                    Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
13803                        NSPanGestureRecognizer::alloc(mtm),
13804                        Some(&target),
13805                        Some(sel!(fire:)),
13806                    ))
13807                }
13808                day_spec::GestureKind::Pinch => Retained::into_super(
13809                    objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
13810                        objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
13811                        Some(&target),
13812                        Some(sel!(fire:)),
13813                    ),
13814                ),
13815                // A held primary button (docs/gestures.md "Long press"): AppKit's own press
13816                // recognizer, at its default delay (0.5 s) and allowable movement. It must not
13817                // hold the mouse-down back from the view (a canvas focuses on it).
13818                day_spec::GestureKind::LongPress => {
13819                    let press = NSPressGestureRecognizer::initWithTarget_action(
13820                        NSPressGestureRecognizer::alloc(mtm),
13821                        Some(&target),
13822                        Some(sel!(fire:)),
13823                    );
13824                    press.setDelaysPrimaryMouseButtonEvents(false);
13825                    press.setDelegate(Some(ProtocolObject::from_ref(&*target)));
13826                    Retained::into_super(press)
13827                }
13828                // Two clicks within the system's double-click interval and distance. The
13829                // single-click recognizer beside it waits that interval out by hand
13830                // (`input::hold_tap`); this one delays nothing.
13831                day_spec::GestureKind::DoubleTap => {
13832                    let double = NSClickGestureRecognizer::initWithTarget_action(
13833                        NSClickGestureRecognizer::alloc(mtm),
13834                        Some(&target),
13835                        Some(sel!(fire:)),
13836                    );
13837                    double.setNumberOfClicksRequired(2);
13838                    double.setDelaysPrimaryMouseButtonEvents(false);
13839                    double.setDelegate(Some(ProtocolObject::from_ref(&*target)));
13840                    Retained::into_super(double)
13841                }
13842                _ => {
13843                    let click = NSClickGestureRecognizer::initWithTarget_action(
13844                        NSClickGestureRecognizer::alloc(mtm),
13845                        Some(&target),
13846                        Some(sel!(fire:)),
13847                    );
13848                    click.setDelegate(Some(ProtocolObject::from_ref(&*target)));
13849                    Retained::into_super(click)
13850                }
13851            }
13852        };
13853        unsafe { h.addGestureRecognizer(&recognizer) };
13854        GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
13855    }
13856
13857    /// Press, long press and double tap are AppKit's own (see `enable_gesture`). Touches stay
13858    /// derived: a Mac's pointer is one mouse, and a trackpad's touches are not contacts on the
13859    /// screen.
13860    fn gesture_support(&self, kind: day_spec::GestureKind) -> Support {
13861        match kind {
13862            day_spec::GestureKind::Touches => Support::Unsupported,
13863            _ => Support::Native,
13864        }
13865    }
13866
13867    fn set_hit_slop(&mut self, h: &Handle, _node: NodeId, slop: day_spec::Insets) {
13868        input::set_hit_slop(h, slop);
13869    }
13870
13871    /// Nothing to do on a Mac (docs/gestures.md "Gestures inside a scroll view"): an
13872    /// `NSScrollView` scrolls on the wheel and the trackpad's two-finger scroll
13873    /// (`scrollWheel:`), never on a mouse drag, so a drag is never contested and a trackpad
13874    /// scroll over the node still reaches the scroll view behind it. day-core withholds the
13875    /// cross-axis drags from the handler.
13876    fn set_drag_axis(&mut self, _h: &Handle, _node: NodeId, _axis: Option<day_spec::DragAxis>) {}
13877
13878    fn set_subtree_enabled(&mut self, h: &Handle, _node: NodeId, enabled: bool) {
13879        input::set_subtree_enabled(h, enabled);
13880    }
13881
13882    /// A Mac's pointer is a mouse or a trackpad until a pen says otherwise.
13883    fn primary_pointer(&self) -> day_spec::PointerKind {
13884        input::pointer_kind()
13885    }
13886
13887    fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
13888        unsafe {
13889            if let Some(id) = &a11y.identifier {
13890                h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
13891            }
13892            if let Some(label) = &a11y.label {
13893                h.setAccessibilityLabel(Some(&NSString::from_str(label)));
13894                APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
13895            } else {
13896                APP_LABELED.with(|t| t.remove(ptr_of(h)));
13897            }
13898            if let Some(hint) = &a11y.hint {
13899                h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
13900            }
13901            if let Some(value) = &a11y.value {
13902                let ns = NSString::from_str(value);
13903                h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
13904            }
13905            // Only apply an EXPLICIT role (canvas/custom pieces, e.g. a Meter): native controls
13906            // already report the right role, so Day records but doesn't override theirs (§13).
13907            if let Some(role) = ns_role(a11y.role) {
13908                h.setAccessibilityRole(Some(role));
13909            }
13910            if a11y.role == day_spec::Role::Tab {
13911                h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
13912            }
13913            if let Some(on) = a11y.selected {
13914                h.setAccessibilitySelected(on);
13915            }
13916            // Decorative / hidden: drop from the AX tree entirely. An ignored view alone is
13917            // not enough — AppKit promotes an ignored element's children into its parent's
13918            // list — so the subtree is cut off too, which also covers subviews added later
13919            // (list rows, re-created children). Hidden never flips back, so the override is
13920            // never lifted.
13921            if a11y.hidden {
13922                h.setAccessibilityElement(false);
13923                h.setAccessibilityChildren(Some(&NSArray::new()));
13924            }
13925        }
13926    }
13927
13928    /// The announcement request goes out from the primary window (any live element will
13929    /// do; the app object stands in before the window exists). Without VoiceOver nothing
13930    /// observes the notification, so posting is free.
13931    fn announce(&mut self, text: &str, urgent: bool) {
13932        use objc2_app_kit::{
13933            NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
13934            NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
13935            NSAccessibilityPriorityLevel,
13936        };
13937        let app = NSApplication::sharedApplication(self.mtm());
13938        let window = primary_content().and_then(|content| content.window());
13939        let element: &objc2::runtime::AnyObject = match &window {
13940            Some(window) => window,
13941            None => &app,
13942        };
13943        // High priority interrupts the current sentence; medium waits its turn.
13944        let priority = if urgent {
13945            NSAccessibilityPriorityLevel::High
13946        } else {
13947            NSAccessibilityPriorityLevel::Medium
13948        };
13949        let announcement = NSString::from_str(text);
13950        let priority = NSNumber::new_isize(priority.0);
13951        let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
13952        // SAFETY: the keys are AppKit's constants and both values are the types the
13953        // announcement notification documents (an NSString and an NSNumber).
13954        unsafe {
13955            let user_info = NSDictionary::from_slices::<NSString>(
13956                &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
13957                &values,
13958            );
13959            NSAccessibilityPostNotificationWithUserInfo(
13960                element,
13961                NSAccessibilityAnnouncementRequestedNotification,
13962                Some(&user_info),
13963            );
13964        }
13965    }
13966
13967    fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
13968        unsafe {
13969            let role = h
13970                .accessibilityRole()
13971                .map_or(day_spec::Role::None, |r| day_role_from_ns(&r.to_string()));
13972            // A picker answers its displayed selection and its enabled state itself: the
13973            // inline style is a stack of radios, not one control.
13974            let picker = picker::read_native(h);
13975            day_spec::NativeSnapshot {
13976                found: true,
13977                role,
13978                label: h.accessibilityLabel().map(|s| s.to_string()),
13979                value: h.accessibilityValue().and_then(|v| {
13980                    v.downcast_ref::<NSString>()
13981                        .map(std::string::ToString::to_string)
13982                }),
13983                identifier: h
13984                    .accessibilityIdentifier()
13985                    .map(|s| s.to_string())
13986                    .filter(|s| !s.is_empty()),
13987                text: match &picker {
13988                    Some((text, _)) => text.clone(),
13989                    None => native_text(h),
13990                },
13991                number: native_number(h),
13992                checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
13993                    match sw.state() {
13994                        s if s == NSControlStateValueOn => Some(true),
13995                        s if s == NSControlStateValueOff => Some(false),
13996                        // Mixed is neither on nor off.
13997                        _ => None,
13998                    }
13999                } else if let Some(btn) = h.downcast_ref::<NSButton>() {
14000                    // A Day button's selected state (`ButtonProps::selected`): its own
14001                    // `state`, which a momentary button holds off at rest.
14002                    BUTTON_SELECTED
14003                        .with(|m| m.borrow().contains_key(&ptr_of(h)))
14004                        .then(|| btn.state() == NSControlStateValueOn)
14005                } else {
14006                    None
14007                },
14008                // A label is a non-editable NSTextField whose `isEnabled` says nothing about
14009                // input; every other control answers for itself.
14010                enabled: match (&picker, h.downcast_ref::<NSControl>()) {
14011                    (Some((_, on)), _) => *on,
14012                    (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
14013                    (None, Some(c)) => Some(c.isEnabled()),
14014                    (None, None) => None,
14015                },
14016                // Off-window counts as not shown: nothing of it reaches the screen.
14017                visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
14018                frame: native_frame(h),
14019            }
14020        }
14021    }
14022
14023    fn request_frame(
14024        &mut self,
14025        host: &Handle,
14026        cb: day_spec::FrameCallback,
14027    ) -> day_spec::CancelFrame {
14028        frame::request(host, cb)
14029    }
14030
14031    fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
14032        OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
14033        unsafe { h.setNeedsDisplay(true) };
14034    }
14035    fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
14036        NAV_STATE.with(|m| {
14037            let m = m.borrow();
14038            let Some(st) = m.get(&ptr_of(host)) else {
14039                return false;
14040            };
14041            // A pane to toggle exists in `Split` and `Rail`; a stack has none and a tab bar
14042            // keeps its rows in the chrome, where hiding them would strand the user.
14043            if !matches!(
14044                st.presentation,
14045                NavPresentation::Split | NavPresentation::Rail
14046            ) {
14047                return false;
14048            }
14049            let item = &st.sidebar_item;
14050            // Set directly, not through the `animator` proxy. The proxy defers the change to
14051            // an animation the dayscript screenshot step does not wait on, so a scripted
14052            // toggle captured a sidebar that had not moved yet. AppKit's own
14053            // NSToolbarToggleSidebarItem still animates — it runs `toggleSidebar:` on the
14054            // controller and never comes through here.
14055            let collapsed = unsafe { item.isCollapsed() };
14056            unsafe { item.setCollapsed(!collapsed) };
14057            true
14058        })
14059    }
14060
14061    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
14062        let content = self.content.as_ref().ok_or("no window content")?;
14063        match self.shown_document_content(content) {
14064            Some(shown) => snapshot_view(&shown),
14065            None => snapshot_view(content),
14066        }
14067    }
14068
14069    /// Decode bytes into an `NSImage` (docs/images.md).
14070    ///
14071    /// `NSBitmapImageRep` is asked first and kept: it is what actually reads the container, it
14072    /// answers in PIXELS (`NSImage.size` is in points and reports a 144-DPI photo at
14073    /// two-thirds its real width), and it is the only thing here that can re-encode later.
14074    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
14075        use objc2::AllocAnyThread as _;
14076        let data = NSData::with_bytes(bytes);
14077        let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
14078        else {
14079            emit(
14080                WINDOW_NODE,
14081                Event::ImageDecoded {
14082                    req,
14083                    result: Err(day_spec::ImageError::Decode),
14084                },
14085            );
14086            return;
14087        };
14088        let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
14089        let info = day_spec::BitmapInfo {
14090            pixels: Size::new(w, h),
14091            // Decoded bytes carry no density — a PNG is simply its pixels. Only a staged @2x
14092            // asset has a scale, and that arrives through the named path instead.
14093            scale: 1.0,
14094            format: day_spec::ImageFormat::sniff(bytes),
14095            has_alpha: unsafe { rep.hasAlpha() },
14096        };
14097        // Built AT the rep's pixel size so it draws 1:1 by default: an NSImage otherwise adopts
14098        // the rep's own `size`, which ImageIO derives from the file's DPI — that is what shrinks
14099        // a 144-DPI photo for no reason the app asked for.
14100        let image = unsafe {
14101            objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
14102        };
14103        unsafe { image.addRepresentation(&rep) };
14104        BITMAPS.with(|m| {
14105            m.borrow_mut().insert(
14106                id.0,
14107                AppKitBitmap {
14108                    image,
14109                    rep: Some(rep),
14110                    info,
14111                },
14112            )
14113        });
14114        emit(
14115            WINDOW_NODE,
14116            Event::ImageDecoded {
14117                req,
14118                result: Ok(info),
14119            },
14120        );
14121    }
14122
14123    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
14124        BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
14125    }
14126
14127    /// The container's own metadata (docs/images.md).
14128    ///
14129    /// DPI is DERIVED rather than read from a tag: AppKit has already resolved the file's
14130    /// resolution into the rep's point size, so pixels-per-point × 72 is the number the platform
14131    /// itself believes — and it is right for containers that record resolution in ways EXIF
14132    /// does not.
14133    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
14134        let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
14135        let mut out = day_spec::ImageProperties::default();
14136        let size = unsafe { rep.size() };
14137        if size.width > 0.0 {
14138            let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
14139            // 72 is "no resolution recorded" wearing a number; reporting it would read as a fact
14140            // the file never stated.
14141            if (dpi - 72.0).abs() > 0.5 {
14142                out.dpi = Some(dpi);
14143            }
14144        }
14145        // EXIF arrives as a dictionary of the format's own keys. It is walked through
14146        // `msg_send!` rather than a downcast because a generic `NSDictionary` is not a
14147        // `DowncastTarget`.
14148        if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
14149            let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
14150            for key in &keys {
14151                let value: Option<Retained<objc2::runtime::AnyObject>> =
14152                    unsafe { msg_send![&*exif, objectForKey: &*key] };
14153                let Some(value) = value else { continue };
14154                let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
14155                let (k, v) = (key.to_string(), text.to_string());
14156                match k.as_str() {
14157                    "Orientation" => out.orientation = v.parse().ok(),
14158                    "DateTimeOriginal" => out.created = Some(v.clone()),
14159                    _ => {}
14160                }
14161                // Keys stay in EXIF's own vocabulary, passed through rather than translated —
14162                // the doc for `extra` promises exactly that.
14163                out.extra.push((k, v));
14164            }
14165        }
14166        Some(out)
14167    }
14168
14169    /// What `NSBitmapImageRep` WRITES. It reads more than this — WebP and HEIF among them — and
14170    /// the asymmetry is the platform's own, which is exactly why this duty exists instead of
14171    /// letting `Cap::ImageEncode` imply every format round-trips.
14172    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
14173        use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
14174        vec![Png, Jpeg, Tiff, Bmp, Gif]
14175    }
14176
14177    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
14178        let result = encode_bitmap(id, spec);
14179        emit(WINDOW_NODE, Event::ImageEncoded { req, result });
14180    }
14181
14182    fn release_image(&mut self, id: day_spec::BitmapId) {
14183        release_bitmap(id);
14184    }
14185
14186    /// Replay `ops` offscreen through the canvas's own painter (docs/canvas.md "Exporting") and
14187    /// keep the result in the decode table, so `image`, `encode_image` and `DrawOp::Image` take
14188    /// it like any decoded bitmap.
14189    ///
14190    /// The paint runs on a `day_spec::offscreen` thread: CoreGraphics draws into a bitmap
14191    /// context from any thread, so a long replay (a map tile of a thousand paths) no longer
14192    /// holds a frame. The images and fonts the ops need are resolved here first, the painted
14193    /// `CGImage` comes back on the main queue, and the table insert and the answer happen
14194    /// there, in that order.
14195    fn render_bitmap(
14196        &mut self,
14197        req: u64,
14198        id: day_spec::BitmapId,
14199        ops: &[DrawOp],
14200        size: Size,
14201        scale: f64,
14202    ) {
14203        let resources = Sendable(OffscreenResources::collect(ops));
14204        let ops = ops.to_vec();
14205        day_spec::offscreen::spawn(move || {
14206            // Bound whole so the closure captures the `Send` wrapper, not its field.
14207            let resources = resources;
14208            let painted = day_spec::ffi_guard::contain(
14209                Err(day_spec::ExportError::Failed(
14210                    "the offscreen painter panicked".into(),
14211                )),
14212                || {
14213                    let started = std::time::Instant::now();
14214                    let painted = resources
14215                        .0
14216                        .with_installed(|| render_bitmap_cgimage(&ops, size, scale));
14217                    // The painter's own cost, apart from the queuing a caller's clock sees.
14218                    log::debug!(
14219                        "day-toolkit-appkit: bitmap {}x{} painted in {:.1} ms ({} ops)",
14220                        size.width * scale,
14221                        size.height * scale,
14222                        started.elapsed().as_secs_f64() * 1000.0,
14223                        ops.len()
14224                    );
14225                    painted
14226                },
14227            );
14228            let painted = Sendable(painted);
14229            <AppKit as Platform>::post(Box::new(move || {
14230                let painted = painted;
14231                let result = painted.0.map(|cg_image| {
14232                    let bitmap = bitmap_from_cgimage(&cg_image, scale);
14233                    let info = bitmap.info;
14234                    BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
14235                    info
14236                });
14237                emit(WINDOW_NODE, Event::BitmapRendered { req, result });
14238            }));
14239        });
14240    }
14241
14242    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
14243        let result = render_pdf_bytes(pages, info);
14244        emit(WINDOW_NODE, Event::PdfRendered { req, result });
14245    }
14246
14247    /// `NSFontManager.availableFontFamilies` + `availableMembersOfFontFamily:`, whose members
14248    /// are `[postscriptName, styleName, weight 0 … 15, traits]` (docs/fonts.md). The `.`-prefixed
14249    /// families are the system's private UI faces and are skipped, as Font Book skips them.
14250    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
14251        use day_spec::FontWeight as W;
14252        let mtm =
14253            objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
14254        let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
14255        let mut out = Vec::new();
14256        for family in &unsafe { manager.availableFontFamilies() } {
14257            let name = family.to_string();
14258            if name.starts_with('.') {
14259                continue;
14260            }
14261            let mut faces = Vec::new();
14262            if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
14263                for member in &members {
14264                    if member.count() < 4 {
14265                        continue;
14266                    }
14267                    let style = member
14268                        .objectAtIndex(1)
14269                        .downcast_ref::<NSString>()
14270                        .map_or_default(std::string::ToString::to_string);
14271                    let weight = member
14272                        .objectAtIndex(2)
14273                        .downcast_ref::<objc2_foundation::NSNumber>()
14274                        .map_or(5, objc2_foundation::NSNumber::integerValue);
14275                    let traits = member
14276                        .objectAtIndex(3)
14277                        .downcast_ref::<objc2_foundation::NSNumber>()
14278                        .map_or(0, objc2_foundation::NSNumber::integerValue);
14279                    let weight = match weight {
14280                        ..=2 => W::UltraLight,
14281                        3 => W::Thin,
14282                        4 => W::Light,
14283                        5 => W::Regular,
14284                        6 => W::Medium,
14285                        7 | 8 => W::Semibold,
14286                        9 => W::Bold,
14287                        10 | 11 => W::Heavy,
14288                        _ => W::Black,
14289                    };
14290                    let italic = traits & 0x1 != 0; // NSItalicFontMask
14291                    faces.push(day_spec::FontFace {
14292                        name: if style.is_empty() {
14293                            day_spec::FontFace::synthesized_name(weight, italic)
14294                        } else {
14295                            style
14296                        },
14297                        weight,
14298                        italic,
14299                    });
14300                }
14301            }
14302            out.push(day_spec::FontFamilyInfo {
14303                family: name,
14304                faces,
14305            });
14306        }
14307        out
14308    }
14309
14310    /// `sizeWithAttributes:` with the attributes `replay` draws with; the ascent is the
14311    /// font's own, so `at.y + ascent` is where the glyphs' baseline lands.
14312    fn measure_text(
14313        &mut self,
14314        text: &str,
14315        size: f64,
14316        font: &day_spec::CanvasFont,
14317    ) -> Option<day_spec::TextMetrics> {
14318        let nsfont = canvas_nsfont(size, font);
14319        let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
14320        let ns = NSString::from_str(text);
14321        let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
14322        // The INK box: `NSStringDrawingUsesDeviceMetrics` is what turns `boundingRectWithSize:`
14323        // from the layout box into the glyphs' own bounds, and it comes back baseline-relative
14324        // with y up — hence the flip. An unbounded size so nothing wraps: this measures one line.
14325        let unbounded = NSSize::new(f64::MAX, f64::MAX);
14326        let ink: NSRect = unsafe {
14327            msg_send![
14328                &ns,
14329                boundingRectWithSize: unbounded,
14330                options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
14331                attributes: &*attrs,
14332            ]
14333        };
14334        Some(day_spec::TextMetrics::from_baseline(
14335            sz.width,
14336            nsfont.ascender(),
14337            sz.height - nsfont.ascender(),
14338            nsfont.capHeight(),
14339            day_spec::Rect::new(
14340                ink.origin.x,
14341                -(ink.origin.y + ink.size.height),
14342                ink.size.width,
14343                ink.size.height,
14344            ),
14345        ))
14346    }
14347
14348    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
14349        let content = self.content.as_ref().ok_or("no window content")?;
14350        match self.shown_document_content(content) {
14351            Some(shown) => snapshot_view_chrome(&shown),
14352            None => snapshot_view_chrome(content),
14353        }
14354    }
14355
14356    fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
14357        snapshot_view(host)
14358    }
14359
14360    fn open_window(
14361        &mut self,
14362        id: NodeId,
14363        options: &WindowOptions,
14364        kind: day_spec::WindowKind,
14365    ) -> day_spec::WindowOpenReply<Handle> {
14366        let prefs = kind.is_panel();
14367        let (window, delegate, content) = self.make_window(options, prefs, Some(id));
14368        if prefs {
14369            // A settings panel is one-of-a-kind and centered, and it stays OUT of the Window
14370            // menu — the macOS convention every stock app follows (docs/windows.md).
14371            window.center();
14372            unsafe { window.setExcludedFromWindowsMenu(true) };
14373        } else {
14374            // Stagger, don't stack. Without this every window opens at the same centered frame
14375            // and the one underneath is invisible — which is exactly what two Day windows did.
14376            //
14377            // `cascadeTopLeftFromPoint:` puts the window AT the point it is given and answers
14378            // the point for the one after, so the series has to be primed from the primary
14379            // rather than seeded with its corner — seeding lands the first new window exactly
14380            // on top of the primary, which is the bug this replaces.
14381            let from = match self.cascade {
14382                Some(p) => p,
14383                None => self.window.as_ref().map_or(NSPoint::new(0.0, 0.0), |w| {
14384                    let f = w.frame();
14385                    let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
14386                    // Asking the primary to cascade from where it already is leaves it
14387                    // there and answers the next slot — the offset the first new window wants.
14388                    unsafe { w.cascadeTopLeftFromPoint(top_left) }
14389                }),
14390            };
14391            self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
14392        }
14393        window_chrome::place(&window, options.placement);
14394        // `center` (a settings panel's, or a `Centered` placement's) uses the main screen, the
14395        // one with the keyboard focus, which on a Mac with several displays need not be the
14396        // app's: such a window goes to the primary's screen instead. A scripted run on the
14397        // capture display relies on this to keep the window in its captures.
14398        if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
14399            center_on_screen_of(&window, self.window.as_deref());
14400        }
14401        // Secondary windows need the same initial client-coordinate pinning as the
14402        // primary. Native document pages may move here before any resize notification.
14403        let _ = pin_below_title_bar(&window);
14404        if !options.start_hidden {
14405            window.makeKeyAndOrderFront(None);
14406        }
14407        // Same macOS 26 quirk as the primary (`run`): a window ordered front before its
14408        // first turn drops pre-run layer displays — nudge every layer once.
14409        mark_tree_needs_display(&content);
14410        self.secondary.push(SecondaryWin {
14411            window,
14412            delegate,
14413            content: content.clone(),
14414        });
14415        day_spec::WindowOpenReply::Open(content)
14416    }
14417
14418    fn native_window_tabs(&self) -> bool {
14419        true
14420    }
14421    fn group_windows(&mut self, hosts: &[Handle]) {
14422        let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
14423        let Some(first) = windows.first() else {
14424            return;
14425        };
14426        unsafe {
14427            NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
14428        }
14429        // Explicit insertion respects the model even when system automatic tabbing is off.
14430        for window in windows.iter().skip(1) {
14431            unsafe {
14432                first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
14433            }
14434        }
14435        if let Some(group) = first.tabGroup() {
14436            if !group.isTabBarVisible() {
14437                unsafe {
14438                    first.toggleTabBar(None);
14439                }
14440            }
14441            for (i, window) in windows.iter().enumerate() {
14442                group.insertWindow_atIndex(window, i as isize);
14443            }
14444        }
14445        // Adding/showing a native tab strip changes contentLayoutRect without necessarily
14446        // resizing the window. Re-pin every member and tell the layout tree its usable size.
14447        for window in &windows {
14448            if let Some(size) = pin_below_title_bar(window) {
14449                let node = window
14450                    .delegate()
14451                    .and_then(|d| d.downcast::<DayWinDelegate>().ok())
14452                    .and_then(|d| d.ivars().node)
14453                    .unwrap_or(WINDOW_NODE);
14454                emit(node, Event::WindowResized(size));
14455            }
14456        }
14457    }
14458    fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
14459        let Some(window) = self.ns_window_for(host) else {
14460            return Vec::new();
14461        };
14462        let windows = window.tabGroup().map(|g| g.windows());
14463        let Some(windows) = windows else {
14464            return Vec::new();
14465        };
14466        windows
14467            .iter()
14468            .filter_map(|window| {
14469                self.secondary
14470                    .iter()
14471                    .find(|w| std::ptr::eq(&raw const *w.window, &raw const *window))
14472                    .and_then(|w| w.delegate.ivars().node)
14473            })
14474            .collect()
14475    }
14476
14477    fn close_window(&mut self, host: &Handle) {
14478        // `close()` runs the full native path — windowWillClose → `WindowClosed` →
14479        // day-core teardown — so programmatic and title-bar closes are one code path.
14480        if let Some(w) = self
14481            .secondary
14482            .iter()
14483            .find(|w| ptr_of(&w.content) == ptr_of(host))
14484        {
14485            w.window.close();
14486        }
14487    }
14488
14489    fn focus_window(&mut self, host: &Handle) {
14490        if let Some(w) = self
14491            .secondary
14492            .iter()
14493            .find(|w| ptr_of(&w.content) == ptr_of(host))
14494        {
14495            w.window.makeKeyAndOrderFront(None);
14496        }
14497    }
14498
14499    fn fit_window(&mut self, host: &Handle, size: Size) {
14500        let Some(w) = self
14501            .secondary
14502            .iter()
14503            .find(|w| ptr_of(&w.content) == ptr_of(host))
14504        else {
14505            return;
14506        };
14507        unsafe {
14508            // `setContentSize:` rather than `setFrame:`: Day measured the CONTENT, and AppKit
14509            // adds the title bar itself. Sizing the frame instead would eat the bar's height out
14510            // of the panel and clip the last row by exactly that much.
14511            w.window
14512                .setContentSize(NSSize::new(size.width, size.height));
14513            // A settings panel that fits its content has no reason to be resizable, and macOS
14514            // panels are not — dropping the mask also stops the user dragging it back to a size
14515            // the content does not fill.
14516            let mask = w.window.styleMask();
14517            w.window
14518                .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
14519            w.window.center();
14520        }
14521        center_on_screen_of(&w.window, self.window.as_deref());
14522    }
14523
14524    fn set_window_title(&mut self, host: &Handle, title: &str) {
14525        if let Some(w) = self
14526            .secondary
14527            .iter()
14528            .find(|w| ptr_of(&w.content) == ptr_of(host))
14529        {
14530            w.window.setTitle(&NSString::from_str(title));
14531            return;
14532        }
14533        // The PRIMARY window is retitlable too. It is an ordinary window (docs/windows.md), so
14534        // `window_title` in the first window's shell and `set_title` on `initial_window()` both
14535        // arrive here — and searching only the secondary list silently dropped them.
14536        if self
14537            .content
14538            .as_ref()
14539            .is_some_and(|c| ptr_of(c) == ptr_of(host))
14540            && let Some(w) = self.window.as_ref()
14541        {
14542            w.setTitle(&NSString::from_str(title));
14543        }
14544    }
14545
14546    fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
14547        use day_spec::WindowChange as C;
14548        let Some(window) = self.ns_window_for(host) else {
14549            return;
14550        };
14551        match change {
14552            C::State(state) => set_ns_window_state(&window, *state),
14553            // Screen capture, recording and sharing see an empty window; the user still does.
14554            C::ContentProtected(on) => window.setSharingType(if *on {
14555                objc2_app_kit::NSWindowSharingType::None
14556            } else {
14557                objc2_app_kit::NSWindowSharingType::ReadOnly
14558            }),
14559            other => window_chrome::apply_property(&window, other),
14560        }
14561    }
14562
14563    fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
14564        self.ns_window_for(host)
14565            .map(|w| window_chrome::frame_of(&w))
14566    }
14567
14568    fn monitors(&self) -> Vec<day_spec::Monitor> {
14569        window_chrome::monitors(self.mtm)
14570    }
14571
14572    /// The Dock menu lists them: day-core folds the run-time shortcuts into the model it sends
14573    /// through `set_dock_menu`, so there is nothing more to install here.
14574    fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
14575
14576    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
14577        dock::set_app_items(self.mtm, items);
14578    }
14579
14580    fn set_drag_region(&mut self, h: &Handle, drag: bool) {
14581        window_chrome::set_drag_region(h, drag);
14582    }
14583
14584    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
14585        status_item::set_items(self.mtm, items);
14586    }
14587
14588    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
14589        status_item::set_progress(self.mtm, progress);
14590    }
14591
14592    fn set_dock_visible(&mut self, visible: bool) {
14593        status_item::set_dock_visible(self.mtm, visible);
14594    }
14595
14596    fn set_keep_running(&mut self, keep: bool) {
14597        status_item::set_keep_running(keep);
14598    }
14599
14600    fn quit_app(&mut self) {
14601        let app = NSApplication::sharedApplication(self.mtm);
14602        unsafe { app.terminate(None) };
14603    }
14604
14605    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
14606        use present::PresentSpec;
14607        let mtm = self.mtm;
14608        // Sheets attach to the KEY window at present time (docs/windows.md) — a dialog
14609        // raised from a secondary/preferences window belongs on it; primary is the
14610        // fallback when no DAY window is key (a system panel may hold key status).
14611        let app = NSApplication::sharedApplication(mtm);
14612        let key = app.keyWindow().filter(|k| {
14613            let mut owner = k.clone();
14614            while let Some(parent) = owner.sheetParent() {
14615                owner = parent;
14616            }
14617            self.window
14618                .as_deref()
14619                .is_some_and(|w| std::ptr::eq(w, &raw const *owner))
14620                || self
14621                    .secondary
14622                    .iter()
14623                    .any(|s| std::ptr::eq(&raw const *s.window, &raw const *owner))
14624        });
14625        let Some(mut window) = key.or_else(|| self.window.clone()) else {
14626            emit(
14627                WINDOW_NODE,
14628                Event::PresentResult {
14629                    req,
14630                    result: present::PresentResult::Dismissed,
14631                },
14632            );
14633            return;
14634        };
14635        // A dialog opened from a modal cover belongs on the active sheet, not behind it.
14636        while let Some(sheet) = window.attachedSheet() {
14637            window = sheet;
14638        }
14639        // File pickers use a different native object (NSOpen/NSSavePanel), not an NSAlert.
14640        match spec {
14641            PresentSpec::OpenFile {
14642                filters, multiple, ..
14643            } => {
14644                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
14645                unsafe {
14646                    panel.setCanChooseFiles(true);
14647                    panel.setCanChooseDirectories(false);
14648                    panel.setAllowsMultipleSelection(*multiple);
14649                    panel.setMessage(Some(&NSString::from_str(spec.title())));
14650                }
14651                apply_allowed_file_types(&panel, filters);
14652                let p = panel.clone();
14653                // Completion blocks run inside a C ABI frame, so their bodies are contained
14654                // like every other trampoline (§8.5) — this one and the four below.
14655                let handler: block2::RcBlock<dyn Fn(isize)> =
14656                    block2::RcBlock::new(move |resp: isize| {
14657                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
14658                    });
14659                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
14660                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
14661                return;
14662            }
14663            // The folder chooser is the same NSOpenPanel with files and directories swapped.
14664            PresentSpec::OpenFolder { .. } => {
14665                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
14666                unsafe {
14667                    panel.setCanChooseFiles(false);
14668                    panel.setCanChooseDirectories(true);
14669                    panel.setCanCreateDirectories(true);
14670                    panel.setAllowsMultipleSelection(false);
14671                    panel.setMessage(Some(&NSString::from_str(spec.title())));
14672                }
14673                let p = panel.clone();
14674                let handler: block2::RcBlock<dyn Fn(isize)> =
14675                    block2::RcBlock::new(move |resp: isize| {
14676                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
14677                    });
14678                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
14679                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
14680                return;
14681            }
14682            PresentSpec::SaveFile { suggested_name, .. } => {
14683                let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
14684                unsafe {
14685                    panel.setMessage(Some(&NSString::from_str(spec.title())));
14686                    panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
14687                }
14688                apply_allowed_file_types(&panel, spec.filters());
14689                let p = panel.clone();
14690                let handler: block2::RcBlock<dyn Fn(isize)> =
14691                    block2::RcBlock::new(move |resp: isize| {
14692                        // The pieces layer copies the staged bytes to the chosen local path.
14693                        ffi_guard::contain((), || emit_panel_result(req, resp, &p));
14694                    });
14695                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
14696                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
14697                return;
14698            }
14699            _ => {}
14700        }
14701        let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
14702        unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
14703        if let Some(msg) = spec.message() {
14704            unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
14705        }
14706        // The completion handler must outlive this call, so it's a heap (Rc) block.
14707        let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
14708            PresentSpec::Dialog { buttons, .. } => {
14709                if buttons
14710                    .iter()
14711                    .any(|b| b.role == present::ButtonRole::Destructive)
14712                {
14713                    unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
14714                }
14715                for b in buttons {
14716                    unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
14717                }
14718                block2::RcBlock::new(move |resp: isize| {
14719                    ffi_guard::contain((), || {
14720                        // NSAlertFirstButtonReturn = 1000; add order == spec order.
14721                        let idx = resp - 1000;
14722                        emit(
14723                            WINDOW_NODE,
14724                            Event::PresentResult {
14725                                req,
14726                                result: present::PresentResult::Button(idx as i64),
14727                            },
14728                        );
14729                        PRESENT_ALERTS.with(|m| {
14730                            m.borrow_mut().remove(&req);
14731                        });
14732                    });
14733                })
14734            }
14735            PresentSpec::Prompt {
14736                placeholder,
14737                initial,
14738                ok,
14739                cancel,
14740                ..
14741            } => {
14742                let tf = unsafe { NSTextField::new(mtm) };
14743                unsafe {
14744                    tf.setFrame(NSRect::new(
14745                        NSPoint::new(0.0, 0.0),
14746                        NSSize::new(260.0, 24.0),
14747                    ));
14748                    tf.setEditable(true);
14749                    tf.setBezeled(true);
14750                    tf.setStringValue(&NSString::from_str(initial));
14751                    tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
14752                    alert.setAccessoryView(Some(&tf));
14753                    alert.addButtonWithTitle(&NSString::from_str(ok)); // resp 1000
14754                    alert.addButtonWithTitle(&NSString::from_str(cancel)); // resp 1001
14755                }
14756                block2::RcBlock::new(move |resp: isize| {
14757                    ffi_guard::contain((), || {
14758                        let result = if resp == 1000 {
14759                            present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
14760                        } else {
14761                            present::PresentResult::Dismissed
14762                        };
14763                        emit(WINDOW_NODE, Event::PresentResult { req, result });
14764                        PRESENT_ALERTS.with(|m| {
14765                            m.borrow_mut().remove(&req);
14766                        });
14767                    });
14768                })
14769            }
14770            // File pickers returned early above.
14771            PresentSpec::OpenFile { .. }
14772            | PresentSpec::OpenFolder { .. }
14773            | PresentSpec::SaveFile { .. } => unreachable!(),
14774        };
14775        unsafe {
14776            alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
14777        }
14778        PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
14779    }
14780
14781    fn dismiss(&mut self, req: u64) {
14782        // Close the sheet; its completion handler fires but its (native) result is dropped
14783        // because day-core already removed the pending request when it resolved.
14784        let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
14785        if let Some(alert) = alert {
14786            let sheet = alert.window();
14787            if let Some(parent) = sheet.sheetParent() {
14788                unsafe { parent.endSheet(&sheet) };
14789            }
14790        }
14791        // File-picker sheets are their own NSWindow.
14792        let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
14793        if let Some(panel) = panel
14794            && let Some(parent) = panel.sheetParent()
14795        {
14796            unsafe { parent.endSheet(&panel) };
14797        }
14798    }
14799
14800    fn application_handlers(
14801        &mut self,
14802        query: &day_spec::applications::HandlerQuery,
14803    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
14804    {
14805        applications::handlers(query)
14806    }
14807
14808    fn open_url_with_application(
14809        &mut self,
14810        url: &str,
14811        application: &str,
14812        completion: day_spec::applications::OpenApplicationCompletion,
14813    ) {
14814        applications::open(url, application, completion);
14815    }
14816
14817    fn share_support(&self) -> day_spec::Support {
14818        day_spec::Support::Native
14819    }
14820    fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
14821        use objc2::{msg_send, runtime::AnyObject};
14822        use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
14823        let Some(mtm) = objc2::MainThreadMarker::new() else {
14824            return false;
14825        };
14826        let Some(url) = NSURL::URLWithString(&NSString::from_str(&spec.url)) else {
14827            return false;
14828        };
14829        let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
14830        let Some(window_view) = app.keyWindow().and_then(|w| w.contentView()) else {
14831            return false;
14832        };
14833        unsafe {
14834            let items = NSArray::from_retained_slice(&[url]);
14835            let picker: objc2::rc::Allocated<AnyObject> =
14836                msg_send![objc2::class!(NSSharingServicePicker), alloc];
14837            let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
14838            let delegate = DaySharePickerDelegate::alloc(mtm).set_ivars(SharePickerIvars {
14839                actions: spec.actions.clone(),
14840            });
14841            let delegate: Retained<DaySharePickerDelegate> = msg_send![super(delegate), init];
14842            let _: () = msg_send![&*picker, setDelegate: &*delegate];
14843            // Pointing at the control that asked, under it; without one, at the window's top
14844            // trailing corner.
14845            let (view, rect, edge) = if let Some(view) = anchor {
14846                (view.clone(), view.bounds(), 1usize)
14847            } else {
14848                let bounds = window_view.bounds();
14849                let y = if window_view.isFlipped() {
14850                    30.0
14851                } else {
14852                    bounds.size.height - 30.0
14853                };
14854                let rect = NSRect::new(
14855                    NSPoint::new(bounds.size.width - 30.0, y),
14856                    NSSize::new(1.0, 1.0),
14857                );
14858                (window_view, rect, 3usize)
14859            };
14860            let _: () =
14861                msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: edge];
14862            // The picker holds its delegate weakly: keep both until the next share.
14863            self.sharing = Some(picker);
14864            self.sharing_delegate = Some(delegate);
14865        }
14866        true
14867    }
14868    fn open_url(&mut self, url: &str) {
14869        // NSWorkspace opens the URL in the user's default handler (Safari for http(s), Mail for
14870        // mailto:, …). An unparseable string yields no NSURL and is silently ignored.
14871        let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
14872        if let Some(nsurl) = nsurl {
14873            unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
14874        }
14875    }
14876}
14877
14878/// Apply a file dialog's extension filters (`allowedFileTypes` — deprecated but still the simplest
14879/// extension-based API; `UTType` would pull in another framework crate for no benefit here).
14880#[allow(deprecated)]
14881fn apply_allowed_file_types(
14882    panel: &objc2_app_kit::NSSavePanel,
14883    filters: &[day_spec::present::FileFilter],
14884) {
14885    let exts: Vec<Retained<NSString>> = filters
14886        .iter()
14887        .flat_map(|f| f.extensions.iter())
14888        .map(|e| NSString::from_str(e))
14889        .collect();
14890    if !exts.is_empty() {
14891        let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
14892        let arr = objc2_foundation::NSArray::from_slice(&refs);
14893        unsafe { panel.setAllowedFileTypes(Some(&arr)) };
14894    }
14895}
14896
14897/// Turn an open panel completion into a `PresentResult` and enqueue it (`NSModalResponseOK` = 1):
14898/// every chosen URL, so a multiple-selection pick reports all of its files (and a folder
14899/// chooser its one directory).
14900fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
14901    let mut paths = Vec::new();
14902    if resp == 1 {
14903        for url in &unsafe { panel.URLs() } {
14904            if let Some(p) = unsafe { url.path() } {
14905                paths.push(p.to_string());
14906            }
14907        }
14908    }
14909    let result = if paths.is_empty() {
14910        present::PresentResult::Dismissed
14911    } else {
14912        present::PresentResult::Files(paths)
14913    };
14914    emit(WINDOW_NODE, Event::PresentResult { req, result });
14915    PRESENT_PANELS.with(|m| {
14916        m.borrow_mut().remove(&req);
14917    });
14918}
14919
14920/// Turn a save panel completion into a `PresentResult` and enqueue it (`NSModalResponseOK` = 1).
14921fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
14922    let result = if resp == 1 {
14923        unsafe { panel.URL() }
14924            .and_then(|url| unsafe { url.path() })
14925            .map_or(present::PresentResult::Dismissed, |p| {
14926                present::PresentResult::Files(vec![p.to_string()])
14927            })
14928    } else {
14929        present::PresentResult::Dismissed
14930    };
14931    emit(WINDOW_NODE, Event::PresentResult { req, result });
14932    PRESENT_PANELS.with(|m| {
14933        m.borrow_mut().remove(&req);
14934    });
14935}
14936
14937impl Platform for AppKit {
14938    const TARGET: &'static str = "macos-appkit";
14939    const TOOLKIT: &'static str = "appkit";
14940
14941    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
14942        let mtm = self.mtm;
14943        // The App menu / About use the app's display name. `app_name` overrides the (possibly
14944        // decorated) window title; setting the process name also makes the standard About panel and
14945        // the bold App-menu title show it (an unbundled binary otherwise shows the exe name).
14946        self.app_name = options
14947            .app_name
14948            .clone()
14949            .unwrap_or_else(|| options.title.clone());
14950        // The bold App-menu title, the About panel and Quit all show the app's NAME. Always set
14951        // it, not just when `app_name` was given explicitly — an app that only set `title` was
14952        // showing its kebab-case cargo target ("day-sheets") where its name belongs.
14953        //
14954        // Two sources, because AppKit consults them in order: the main bundle's CFBundleName
14955        // wins when there is one, and `day launch` runs the binary UNBUNDLED during development,
14956        // where the name falls back to the executable's file name. Writing the info dictionary
14957        // covers the bundled case; the process name covers the unbundled one.
14958        unsafe {
14959            objc2_foundation::NSProcessInfo::processInfo()
14960                .setProcessName(&NSString::from_str(&self.app_name));
14961            let bundle = objc2_foundation::NSBundle::mainBundle();
14962            let info: Option<Retained<objc2_foundation::NSDictionary>> =
14963                msg_send![&bundle, infoDictionary];
14964            if let Some(info) = info {
14965                let key = NSString::from_str("CFBundleName");
14966                let value = NSString::from_str(&self.app_name);
14967                // `infoDictionary` is documented immutable, but the instance backing an
14968                // unbundled process is a mutable dictionary; guard the send so a genuinely
14969                // immutable one is left alone instead of raising.
14970                if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
14971                    let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
14972                }
14973            }
14974        }
14975        // RTL locales (docs/localization): AppleTextDirection flips AppKit's app-wide
14976        // userInterfaceLayoutDirection (label alignment, slider fill, control mirroring) —
14977        // read at NSApplication init, so register before sharedApplication. Registration
14978        // domain only: volatile, never persisted to the app's defaults.
14979        if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
14980            unsafe {
14981                use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
14982                let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
14983                    .into_super()
14984                    .into_super()
14985                    .into_super();
14986                let dict = NSDictionary::from_retained_objects(
14987                    &[
14988                        &*NSString::from_str("AppleTextDirection"),
14989                        &*NSString::from_str("NSForceRightToLeftWritingDirection"),
14990                    ],
14991                    &[yes.clone(), yes],
14992                );
14993                NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
14994            }
14995        }
14996        let app = NSApplication::sharedApplication(mtm);
14997        // A menu-bar app keeps out of the Dock from the first frame (docs/status-item.md): its
14998        // bundle carries LSUIElement, and an unbundled `day launch` run hears DAY_MACOS_DOCK=0.
14999        let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
15000            || unsafe {
15001                let bundle = objc2_foundation::NSBundle::mainBundle();
15002                let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
15003                    &bundle,
15004                    objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
15005                ];
15006                value.is_some_and(|v| {
15007                    let on: bool = msg_send![&v, boolValue];
15008                    on
15009                })
15010            };
15011        app.setActivationPolicy(if menu_bar_app {
15012            NSApplicationActivationPolicy::Accessory
15013        } else {
15014            NSApplicationActivationPolicy::Regular
15015        });
15016        let document_delegate = documents::delegate(mtm);
15017        app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
15018        // DAY_THEME=light|dark forces the appearance app-wide (themed CI screenshot runs and
15019        // local theme checks); unset ⇒ follow the system.
15020        if let Ok(theme) = std::env::var("DAY_THEME") {
15021            let name = match theme.as_str() {
15022                "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
15023                "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
15024                _ => None,
15025            };
15026            if let Some(name) = name {
15027                let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
15028                unsafe { app.setAppearance(appearance.as_deref()) };
15029            }
15030        }
15031        // Bundled custom fonts (§18.4) must be registered before the first label realizes.
15032        register_bundled_fonts();
15033
15034        // Default menu bar (standard app menu + Edit) so ⌘Q / Cut-Copy-Paste work before the app
15035        // installs its own via `app_menu(...)`. Rebuilt after `ready` for the items that depend
15036        // on the app's registrations — see there.
15037        let app_name = self.app_name.clone();
15038        install_main_menu(mtm, &app, &app_name);
15039        // App activation / termination → day lifecycle events (docs/lifecycle.md).
15040        install_lifecycle_observers();
15041        install_appearance_observer();
15042        install_reduce_motion_observer();
15043
15044        let (window, delegate, content) = self.make_window(&options, false, None);
15045        // Optional window-appearance override (opt-in via env). An app with a fixed light/dark
15046        // palette sets `DAY_APPEARANCE=light|dark` so native controls (list, fields, editor) match
15047        // its own colors instead of following the system appearance. Unset = follow the system.
15048        let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
15049            Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
15050            Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
15051            _ => None,
15052        };
15053        if let Some(name) = appearance_name
15054            && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
15055        {
15056            window.setAppearance(Some(&appearance));
15057        }
15058        // The primary delegate lives for the process (this frame never returns); secondary
15059        // delegates are retained in `self.secondary`.
15060        std::mem::forget(delegate);
15061
15062        self.window = Some(window.clone());
15063        self.content = Some(content.clone());
15064        PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
15065
15066        // The root lays out below the title bar, not under it (§7.7).
15067        let layout = pin_below_title_bar(&window)
15068            .unwrap_or(Size::new(options.size.width, options.size.height));
15069        ready(self, content, layout);
15070
15071        // `ready` ran the app's root() — registrations are in. Without a new-window
15072        // builder only one Normal window can ever exist: turn automatic tabbing off so no
15073        // tab bar, "+" button, or dead tab menu items appear (docs/windows.md).
15074        if day_core::windows::new_window_action_id() == 0
15075            && options.tabbing == day_spec::WindowTabbing::Automatic
15076        {
15077            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
15078        }
15079        // The DEFAULT menu bar was built before `root()` ran, so its registration-dependent
15080        // items — Settings…/⌘, and File ▸ New Window — could not exist yet. Rebuild it now that
15081        // they can. An app with its own `app_menu` model already replaced the whole bar and
15082        // gets its items through the injection path instead.
15083        if !day_core::has_app_menu() {
15084            install_main_menu(mtm, &app, &app_name);
15085        }
15086
15087        // Reopen where the user left it (docs/windows.md). AppKit persists the frame under an
15088        // autosave name and hands it back on request; `setFrameUsingName` answers false the
15089        // first time, which is when centering is the right answer.
15090        //
15091        // NOT while a dayscript is driving or `DAY_WINDOW` has forced a size: a restored frame
15092        // would make every captured screenshot's dimensions depend on where the developer last
15093        // dragged the window, and the capture suites compare those across machines.
15094        let deterministic =
15095            std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
15096        let autosave = NSString::from_str("day.main");
15097        if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
15098            window.center();
15099            // An explicit placement wins over centering, but not over the frame the user left.
15100            window_chrome::place(&window, options.placement);
15101        }
15102        // A scripted run whose capture needs a display scale this host's displays lack opens on
15103        // the one `day launch` made for it (`DAY_WINDOW_SCREEN`, a CGDirectDisplayID): a
15104        // capture is the window server's pixels, so it has the scale of the display under it.
15105        if let Some(screen) = capture_screen(mtm) {
15106            let (visible, frame) = (screen.visibleFrame(), window.frame());
15107            window.setFrameOrigin(NSPoint::new(
15108                visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
15109                visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
15110            ));
15111        }
15112        if !deterministic {
15113            unsafe { window.setFrameAutosaveName(&autosave) };
15114        }
15115        if !options.start_hidden {
15116            window.makeKeyAndOrderFront(None);
15117            app.activate();
15118        }
15119        // The root was mounted before the window was shown (ready() runs first), and on
15120        // macOS 26 layer displays requested pre-run are dropped for a window ordered front
15121        // before the app finishes launching — the window stays blank until the next real
15122        // event. Re-mark the whole tree so the first run-loop turn commits a full frame.
15123        if let Some(content) = window.contentView() {
15124            mark_tree_needs_display(&content);
15125        }
15126        if std::env::var_os("DAY_DUMP").is_some() {
15127            std::thread::spawn(|| {
15128                std::thread::sleep(std::time::Duration::from_millis(2000));
15129                Self::post(Box::new(|| {
15130                    // The primary's content specifically (docs/windows.md).
15131                    if let Some(content) = primary_content() {
15132                        let desc: Retained<NSString> =
15133                            unsafe { msg_send![&*content, _subtreeDescription] };
15134                        log::warn!("{desc}");
15135                    }
15136                }));
15137            });
15138        }
15139        app.run();
15140    }
15141
15142    fn post(f: Box<dyn FnOnce() + Send>) {
15143        // Posted-closure trampoline (§8.5): the closure runs inside dispatch's C frame, so a
15144        // panic is contained here rather than unwinding into libdispatch.
15145        dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
15146    }
15147
15148    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
15149        // The timer door behind `day::sleep` (docs/async.md): `dispatch_after` on the main
15150        // queue, so a sleep is a dispatch timer rather than a parked helper thread. Contained
15151        // like `post`. A delay too large for dispatch's clock runs at the far horizon instead.
15152        let when =
15153            dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
15154                .unwrap_or(dispatch2::DispatchTime::FOREVER);
15155        if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
15156            ffi_guard::contain((), f);
15157        }) {
15158            log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
15159        }
15160    }
15161
15162    fn locale_hints(&self) -> Vec<String> {
15163        // The user's ordered language preference from Settings ("fr-FR", "en-US", …), which is
15164        // the ambient locale Day negotiates its catalogs against (§12.2, docs/localization.md).
15165        objc2_foundation::NSLocale::preferredLanguages()
15166            .iter()
15167            .map(|s| s.to_string())
15168            .collect()
15169    }
15170}
15171
15172// `CGWindowListCreateImage` is obsoleted as of the macOS 15 SDK (ScreenCaptureKit is the
15173// sanctioned replacement) but still resolves and answers on macOS 26. It is declared here rather
15174// than taken from a binding because the availability attribute would refuse the call outright,
15175// and every use below treats a NULL return as "ask the offscreen path instead".
15176unsafe extern "C" {
15177    fn CGWindowListCreateImage(
15178        bounds: objc2_core_foundation::CGRect,
15179        list_option: u32,
15180        window_id: u32,
15181        image_option: u32,
15182    ) -> *mut objc2_core_graphics::CGImage;
15183}
15184
15185/// kCGWindowListOptionIncludingWindow — composite only this window, so whatever is stacked over
15186/// it (another app, a CI runner's stray window) cannot appear in the capture.
15187const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
15188/// kCGWindowImageBoundsIgnoreFraming — the window's own frame, without its drop shadow, which
15189/// makes the returned image exactly `window.frame()` at the backing scale.
15190const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
15191
15192/// Encode a captured rep as PNG, in sRGB.
15193///
15194/// A capture arrives in the color space of the display it was composited for, and a PNG of it
15195/// embeds that display's ICC profile: the same color then has different sample values on every
15196/// machine, and on every other Day target, which all capture sRGB. Converting first makes a
15197/// macOS capture's samples comparable with theirs and independent of the capturing display.
15198fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
15199    let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
15200        &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
15201        objc2_app_kit::NSColorRenderingIntent::Default,
15202    );
15203    let rep = srgb.as_deref().unwrap_or(rep);
15204    let data = unsafe {
15205        rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
15206    }
15207    .ok_or("png encode failed")?;
15208    Ok(data.to_vec())
15209}
15210
15211/// Capture `content` by asking the WINDOW SERVER for the composited window and cropping to it.
15212///
15213/// This exists because an offscreen render cannot draw macOS's own materials. As of macOS 26 a
15214/// sidebar `NSSplitViewItem` is a Liquid Glass surface the window server composites from what is
15215/// behind it; `cacheDisplayInRect` has no backdrop to sample, so it renders the sidebar as an
15216/// opaque white slab with none of its rows in it — every macos-appkit gallery shot had a blank
15217/// sidebar. The window server has the real pixels, including the rows.
15218///
15219/// It answers only while the window is actually on screen. A hidden, minimized or
15220/// never-composited window has no image to hand back (verified: hiding the app makes this return
15221/// NULL while the offscreen path still produces a frame), so this returns `Err` and the caller
15222/// falls back rather than failing the capture.
15223fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
15224    let window = content.window().ok_or("view is not in a window")?;
15225    // An attached sheet is the active modal surface and has its own composited window.
15226    // Capturing only the parent's window would show dimmed content without the modal UI.
15227    if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
15228        return snapshot_via_window_server(&sheet, chrome);
15229    }
15230    let number = window.windowNumber();
15231    if number <= 0 {
15232        return Err(format!("window {number} is not on screen"));
15233    }
15234    // The server hands back the frame it last COMPOSITED, which is the previous one whenever the
15235    // app has changed the view tree since. A capture taken right after a state change then shows
15236    // the state before it — a `when` whose outgoing arm is already gone from the tree and from the
15237    // view hierarchy still appears in the image, so a walkthrough asserting on pixels reads a
15238    // stale frame as "the change did not happen". Push the pending work out first: lay out, draw,
15239    // then commit the layer tree to the render server.
15240    unsafe { content.layoutSubtreeIfNeeded() };
15241    window.displayIfNeeded();
15242    CATransaction::flush();
15243    // CGRectNull asks for the window's own bounds rather than a screen region.
15244    let null_rect = objc2_core_foundation::CGRect::new(
15245        objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
15246        objc2_core_foundation::CGSize::new(0.0, 0.0),
15247    );
15248    let shot = unsafe {
15249        CGWindowListCreateImage(
15250            null_rect,
15251            CG_WINDOW_LIST_INCLUDING_WINDOW,
15252            number as u32,
15253            CG_WINDOW_IMAGE_IGNORE_FRAMING,
15254        )
15255    };
15256    if shot.is_null() {
15257        return Err("the window server has no image for this window".into());
15258    }
15259    // SAFETY: non-NULL CGImageRef owned by this call (Create rule); CFRetained takes that
15260    // ownership over, so it is released exactly once.
15261    let shot = unsafe {
15262        objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
15263    };
15264
15265    // A chrome capture is the window image as the server composited it — titlebar, toolbar and
15266    // rounded corners included — so it is done here, before the crop.
15267    if chrome {
15268        let rep = unsafe {
15269            objc2_app_kit::NSBitmapImageRep::initWithCGImage(
15270                objc2_app_kit::NSBitmapImageRep::alloc(),
15271                &shot,
15272            )
15273        };
15274        return png_of_rep(&rep);
15275    }
15276
15277    // Crop the window frame down to the content view. Keeping the framing identical to the
15278    // offscreen path is the point: the titlebar has never been part of a Day capture, and every
15279    // published gallery shot would otherwise change size.
15280    let frame = window.frame();
15281    if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
15282        return Err("zero-size window".into());
15283    }
15284    let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
15285    // Cocoa rects are bottom-left origin; a CGImage's are top-left, so the content's distance
15286    // from the window top is what the crop needs.
15287    let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
15288    let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
15289    let crop = objc2_core_foundation::CGRect::new(
15290        objc2_core_foundation::CGPoint::new(
15291            (in_window.origin.x * scale).round(),
15292            (from_top * scale).round(),
15293        ),
15294        objc2_core_foundation::CGSize::new(
15295            (in_window.size.width * scale).round(),
15296            (in_window.size.height * scale).round(),
15297        ),
15298    );
15299    let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
15300        .ok_or("crop to the content view failed")?;
15301    let rep = unsafe {
15302        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
15303            objc2_app_kit::NSBitmapImageRep::alloc(),
15304            &cropped,
15305        )
15306    };
15307    png_of_rep(&rep)
15308}
15309
15310/// Capture a window content view as PNG (the dayscript screenshot seam, §14).
15311///
15312/// The window server first, because it is the only one of the two that can show macOS's own
15313/// composited materials; the offscreen render when it declines, because it is the only one of the
15314/// two that works with no window on screen. See each for why.
15315/// Put a [`Transform`] on a view through its own geometry rather than its layer: the frame is
15316/// the laid-out `base` scaled about its center and moved by the translation, the bounds keep the
15317/// laid-out size (so the content draws at the scale), and the rotation is the frame's center
15318/// rotation (positive is clockwise on screen: Day's parents are flipped, y down).
15319fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
15320    let [x, y, w, h] = base;
15321    let (sw, sh) = (w * t.sx, h * t.sy);
15322    let frame = NSRect::new(
15323        NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
15324        NSSize::new(sw, sh),
15325    );
15326    unsafe {
15327        // The rotation goes first and comes back last: a rotated view's frame is its bounding
15328        // box, so setting the frame of a rotated view would scale it.
15329        v.setFrameCenterRotation(0.0);
15330        v.setFrame(frame);
15331        v.setBoundsSize(NSSize::new(w, h));
15332        if t.rotation.degrees() != 0.0 {
15333            v.setFrameCenterRotation(t.rotation.degrees());
15334        }
15335    }
15336}
15337
15338fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
15339    // A capture's own pool. AppKit autoreleases the window image, its crop, the color-converted
15340    // rep and CoreGraphics' rasterized copy of the image (about 32 MB at 2560×1600). Left to the
15341    // main thread's outer pool, which a scripted run with no input events does not drain, a full
15342    // macos-appkit `day test` (a few hundred `sample_pixel` steps) peaked at 2.6 GB; with this
15343    // pool it stays under 150 MB.
15344    objc2::rc::autoreleasepool(|_| {
15345        let modal = content
15346            .window()
15347            .and_then(|w| w.attachedSheet())
15348            .and_then(|s| s.contentView());
15349        let content = modal.as_deref().unwrap_or(content);
15350        match snapshot_via_window_server(content, false) {
15351            Ok(bytes) => Ok(bytes),
15352            Err(_) => snapshot_view_cache(content),
15353        }
15354    })
15355}
15356
15357/// Capture a window *with* its chrome — the titlebar and toolbar the content capture crops away
15358/// (`day::window_image().chrome()`, docs/window-image.md).
15359///
15360/// Only the window server can produce this: the offscreen path renders the content view's own
15361/// hierarchy, which the titlebar is not part of. When it declines (an offscreen or hidden window)
15362/// the content capture stands in — a smaller image beats no image, and it is what the caller
15363/// would have got from the plain duty.
15364fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
15365    // Its own pool, for the reason `snapshot_view` gives.
15366    objc2::rc::autoreleasepool(|_| {
15367        let modal = content
15368            .window()
15369            .and_then(|w| w.attachedSheet())
15370            .and_then(|s| s.contentView());
15371        let content = modal.as_deref().unwrap_or(content);
15372        match snapshot_via_window_server(content, true) {
15373            Ok(bytes) => Ok(bytes),
15374            Err(_) => snapshot_view_cache(content),
15375        }
15376    })
15377}
15378
15379/// The offscreen fallback: `cacheDisplayInRect` over a window-background pre-fill resolved for
15380/// the view's light/dark appearance. Renders the view hierarchy Day drew, and nothing the window
15381/// server composites (see `snapshot_via_window_server`).
15382fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
15383    let bounds = content.bounds();
15384    let rep =
15385        unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
15386    // Day containers are transparent (the window server paints the backdrop), so pre-fill
15387    // the rep with the window background — resolved for the window's light/dark appearance —
15388    // before compositing the view hierarchy over it (§14).
15389    let ctx =
15390        NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
15391    NSGraphicsContext::saveGraphicsState_class();
15392    NSGraphicsContext::setCurrentContext(Some(&ctx));
15393    content
15394        .effectiveAppearance()
15395        .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
15396            NSColor::windowBackgroundColor().setFill();
15397            objc2_app_kit::NSRectFill(bounds);
15398        }));
15399    NSGraphicsContext::restoreGraphicsState_class();
15400    unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
15401    png_of_rep(&rep)
15402}
15403
15404/// The screen a scripted run asked to open on: `DAY_WINDOW_SCREEN`, the `CGDirectDisplayID` of the
15405/// capture display `day launch --script` provides when no attached display has the capture's
15406/// scale. `None` when unset or when no screen has that id, which leaves the window where it was.
15407/// Center `window` on `primary`'s screen when `center` put it on another, as high as `center`
15408/// places a window (a third of the free height above it, two below).
15409fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
15410    let Some(screen) = primary.and_then(objc2_app_kit::NSWindow::screen) else {
15411        return;
15412    };
15413    if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
15414        return;
15415    }
15416    let (visible, frame) = (screen.visibleFrame(), window.frame());
15417    window.setFrameOrigin(NSPoint::new(
15418        visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
15419        visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
15420    ));
15421}
15422
15423fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
15424    let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
15425        .ok()?
15426        .trim()
15427        .parse()
15428        .ok()?;
15429    let key = NSString::from_str("NSScreenNumber");
15430    objc2_app_kit::NSScreen::screens(mtm)
15431        .into_iter()
15432        .find(|screen| {
15433            let number: Option<Retained<objc2_foundation::NSNumber>> =
15434                unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
15435            number.is_some_and(|n| n.unsignedIntValue() == wanted)
15436        })
15437}
15438
15439/// Recursively mark a view tree as needing display (startup first-frame fix, see `run`).
15440fn mark_tree_needs_display(view: &NSView) {
15441    view.setNeedsDisplay(true);
15442    for sub in view.subviews() {
15443        mark_tree_needs_display(&sub);
15444    }
15445}
15446
15447/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
15448/// macOS has no true background/foreground or memory-warning lifecycle. `const` so
15449/// `day::require_lifecycle!` can reject unsupported phases at compile time. Must agree with the
15450/// `Toolkit::supports_lifecycle` default (which also returns `is_universal`).
15451#[must_use]
15452pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
15453    phase.is_universal()
15454}
15455
15456/// Follow the SYSTEM appearance while the app runs: macOS posts the distributed
15457/// "`AppleInterfaceThemeChangedNotification`" on a theme switch, and AppKit updates
15458/// `effectiveAppearance` just after — so re-read on the next main-queue turn and refresh
15459/// day-core's reactive dark-mode signal (palette closures recolor live instead of going
15460/// stale until the next rebuild). The token is leaked to observe for the app's lifetime.
15461fn install_appearance_observer() {
15462    use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
15463    let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
15464    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
15465        dispatch2::DispatchQueue::main().exec_async(|| {
15466            ffi_guard::contain((), || {
15467                day_core::note_appearance_changed();
15468                color::refresh_layers();
15469            });
15470        });
15471    });
15472    let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
15473    let token = unsafe {
15474        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
15475    };
15476    std::mem::forget(token);
15477    // Accent and contrast changes can leave the appearance name unchanged.
15478    let center = objc2_foundation::NSNotificationCenter::defaultCenter();
15479    let name = NSString::from_str("NSSystemColorsDidChangeNotification");
15480    let token = unsafe {
15481        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
15482    };
15483    std::mem::forget(token);
15484}
15485
15486/// Follow the SYSTEM reduce-motion switch while the app runs: `NSWorkspace` posts
15487/// `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification` on its own notification
15488/// center when any Accessibility › Display option flips, and
15489/// `accessibilityDisplayShouldReduceMotion` already answers the new value by then. The
15490/// notification arrives on the main thread; the main-queue hop keeps the re-read off the
15491/// poster's stack, as the appearance observer does. The token is leaked to observe for the
15492/// app's lifetime.
15493fn install_reduce_motion_observer() {
15494    use objc2_foundation::NSNotification;
15495    let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
15496    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
15497        dispatch2::DispatchQueue::main()
15498            .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
15499    });
15500    let token = unsafe {
15501        center.addObserverForName_object_queue_usingBlock(
15502            Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
15503            None,
15504            None,
15505            &block,
15506        )
15507    };
15508    std::mem::forget(token);
15509}
15510
15511/// Bridge the `NSApplication` activation/termination notifications to day lifecycle events
15512/// (docs/lifecycle.md). The observer tokens are leaked to live for the whole app.
15513fn install_lifecycle_observers() {
15514    use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
15515    let center = unsafe { NSNotificationCenter::defaultCenter() };
15516    let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
15517        let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
15518            ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
15519        });
15520        let token = unsafe {
15521            center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
15522        };
15523        std::mem::forget(token); // observe for the app's lifetime
15524    };
15525    unsafe {
15526        observe(
15527            NSApplicationDidBecomeActiveNotification,
15528            day_spec::Lifecycle::DidBecomeActive,
15529        );
15530        observe(
15531            NSApplicationWillResignActiveNotification,
15532            day_spec::Lifecycle::WillResignActive,
15533        );
15534        observe(
15535            NSApplicationWillTerminateNotification,
15536            day_spec::Lifecycle::WillTerminate,
15537        );
15538        // `terminate:` exits the process from inside the run loop, so the loop never returns to
15539        // `launch_with`: the last Day code to run is this notification's second observer, which
15540        // NSNotificationCenter calls after the first (docs/lifecycle.md).
15541        observe(
15542            NSApplicationWillTerminateNotification,
15543            day_spec::Lifecycle::DidExit,
15544        );
15545    }
15546}
15547
15548day_localization_ui::locales!();
15549
15550/// Shared by the initial menu and every reactive replacement. AppKit owns Services
15551/// and the hide actions; these commands must not depend on a window or app callback.
15552fn install_application_menu(
15553    mtm: MainThreadMarker,
15554    menubar: &NSMenu,
15555    title: &str,
15556    about: Option<day_spec::MenuItem>,
15557    updates: Option<day_spec::MenuItem>,
15558    prefs: Option<day_spec::MenuItem>,
15559    quit: Option<day_spec::MenuItem>,
15560) -> Retained<NSMenu> {
15561    use day_spec::{MenuItem as M, MenuRole as R};
15562    let app = NSApplication::sharedApplication(mtm);
15563    let standard = |role, label| M::Action {
15564        id: None,
15565        action: 0,
15566        label,
15567        shortcut: None,
15568        enabled: true,
15569        checked: None,
15570        role: Some(role),
15571        icon: None,
15572    };
15573    let mut about =
15574        about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
15575    let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
15576    for (item, title) in [
15577        (&mut about, res::str::about_app(title).format()),
15578        (&mut quit, res::str::quit_app(title).format()),
15579    ] {
15580        if let M::Action { label, .. } = item {
15581            *label = title;
15582        }
15583    }
15584    // A registered Day About (docs/settings.md) replaces the stock Info.plist panel: the
15585    // item fires the dispatch action instead of `orderFrontStandardAboutPanel:`.
15586    if let M::Action { action, .. } = &mut about
15587        && *action == 0
15588    {
15589        *action = day_core::windows::about_action_id();
15590    }
15591    // Check for Updates… sits directly under About (the Sparkle convention), whether the app
15592    // placed the role itself or the updater only registered its action.
15593    let updates_id = day_core::windows::check_for_updates_action_id();
15594    let updates = updates.or_else(|| {
15595        (updates_id != 0).then(|| {
15596            standard(
15597                R::CheckForUpdates,
15598                day_localization::t(day_localization::key::day_check_for_updates),
15599            )
15600        })
15601    });
15602    let mut head = vec![about];
15603    if let Some(mut updates) = updates {
15604        if let M::Action { action, .. } = &mut updates
15605            && *action == 0
15606        {
15607            *action = updates_id;
15608        }
15609        head.push(updates);
15610    }
15611    head.push(M::Separator);
15612    let menu = build_ns_menu(mtm, title, &head);
15613    if let Some(mut prefs) = prefs {
15614        if let M::Action { label, .. } = &mut prefs {
15615            *label = res::str::settings().format();
15616        }
15617        let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
15618        for item in section.itemArray() {
15619            section.removeItem(&item);
15620            menu.addItem(&item);
15621        }
15622    }
15623    // AppKit keeps the registered Services menu across main-menu replacements.
15624    // Move that same menu to the new bar rather than abandoning its system-populated items.
15625    let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
15626    if let Some(parent) = unsafe { services.supermenu() } {
15627        let index = parent.indexOfItemWithSubmenu(Some(&services));
15628        if index >= 0 {
15629            parent.itemAtIndex(index).unwrap().setSubmenu(None);
15630        }
15631    }
15632    let services_item = NSMenuItem::new(mtm);
15633    services_item.setTitle(&NSString::from_str(&res::str::services().format()));
15634    services_item.setSubmenu(Some(&services));
15635    menu.addItem(&services_item);
15636    menu.addItem(&NSMenuItem::separatorItem(mtm));
15637    for (label, selector, shortcut) in [
15638        (
15639            res::str::hide_app(title).format(),
15640            sel!(hide:),
15641            Some(day_spec::Shortcut::primary("h")),
15642        ),
15643        (
15644            res::str::hide_others().format(),
15645            sel!(hideOtherApplications:),
15646            Some(day_spec::Shortcut::primary("h").alt()),
15647        ),
15648        (
15649            res::str::show_all().format(),
15650            sel!(unhideAllApplications:),
15651            None,
15652        ),
15653    ] {
15654        let item = unsafe {
15655            NSMenuItem::initWithTitle_action_keyEquivalent(
15656                NSMenuItem::alloc(mtm),
15657                &NSString::from_str(&label),
15658                Some(selector),
15659                &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
15660            )
15661        };
15662        if let Some(shortcut) = shortcut {
15663            item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
15664        }
15665        // Explicitly target the application so window responders cannot override Hide.
15666        unsafe { item.setTarget(Some(&app)) };
15667        menu.addItem(&item);
15668    }
15669    menu.addItem(&NSMenuItem::separatorItem(mtm));
15670    let section = build_ns_menu(mtm, title, &[quit]);
15671    let quit = section.itemAtIndex(0).unwrap();
15672    section.removeItem(&quit);
15673    menu.addItem(&quit);
15674    let item = NSMenuItem::new(mtm);
15675    item.setSubmenu(Some(&menu));
15676    menubar.addItem(&item);
15677    services
15678}
15679
15680/// The default main menu (§21.2 M2): standard application menu; Edit menu wired to the responder
15681/// chain so Cmd+C/V/X/A work in `NSTextFields`; Window menu basics.
15682fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
15683    let menubar = NSMenu::new(mtm);
15684
15685    let prefs_id = day_core::windows::preferences_action_id();
15686    let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
15687        id: None,
15688        action: prefs_id,
15689        label: res::str::settings().format(),
15690        shortcut: None,
15691        enabled: true,
15692        checked: None,
15693        role: Some(day_spec::MenuRole::Preferences),
15694        icon: None,
15695    });
15696    let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
15697
15698    // File ▸ New Window / Close, when the app registered a new-window builder — the same
15699    // zero-menu-code rule as Settings…/⌘, above (docs/windows.md). Without this an app that
15700    // never calls `app_menu` gets the tab-bar "+" and the Window menu's tab commands but no
15701    // File ▸ New Window, because the default menu bar has no File menu to put it in.
15702    let new_window_id = day_core::windows::new_window_action_id();
15703    if new_window_id != 0 {
15704        let file_item = NSMenuItem::new(mtm);
15705        let file_menu = unsafe {
15706            NSMenu::initWithTitle(
15707                NSMenu::alloc(mtm),
15708                &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
15709            )
15710        };
15711        let new_window = unsafe {
15712            NSMenuItem::initWithTitle_action_keyEquivalent(
15713                NSMenuItem::alloc(mtm),
15714                &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
15715                Some(sel!(fire:)),
15716                &NSString::from_str("n"),
15717            )
15718        };
15719        let target = menu_target(mtm);
15720        let tobj: &objc2::runtime::AnyObject = target.as_ref();
15721        unsafe { new_window.setTarget(Some(tobj)) };
15722        new_window.setTag(new_window_id as isize);
15723        file_menu.addItem(&new_window);
15724        file_menu.addItem(&NSMenuItem::separatorItem(mtm));
15725        // Nil-targeted, so it closes whatever window is key — the standard responder route.
15726        let close = unsafe {
15727            NSMenuItem::initWithTitle_action_keyEquivalent(
15728                NSMenuItem::alloc(mtm),
15729                &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
15730                Some(sel!(performClose:)),
15731                &NSString::from_str("w"),
15732            )
15733        };
15734        file_menu.addItem(&close);
15735        file_item.setSubmenu(Some(&file_menu));
15736        menubar.addItem(&file_item);
15737    }
15738
15739    let edit_item = NSMenuItem::new(mtm);
15740    let edit_menu = unsafe {
15741        NSMenu::initWithTitle(
15742            NSMenu::alloc(mtm),
15743            &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
15744        )
15745    };
15746    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
15747        let item = unsafe {
15748            NSMenuItem::initWithTitle_action_keyEquivalent(
15749                NSMenuItem::alloc(mtm),
15750                &NSString::from_str(&day_localization::t(key)),
15751                Some(action),
15752                &NSString::from_str(accel),
15753            )
15754        };
15755        edit_menu.addItem(&item);
15756    };
15757    add("day_undo", sel!(undo:), "z");
15758    add("day_redo", sel!(redo:), "Z");
15759    edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
15760    add("day_cut", sel!(cut:), "x");
15761    add("day_copy", sel!(copy:), "c");
15762    add("day_paste", sel!(paste:), "v");
15763    add("day_select_all", sel!(selectAll:), "a");
15764    edit_item.setSubmenu(Some(&edit_menu));
15765    menubar.addItem(&edit_item);
15766
15767    install_windows_menu(mtm, app, &menubar);
15768
15769    app.setMainMenu(Some(&menubar));
15770    unsafe { app.setServicesMenu(Some(&services)) };
15771}
15772
15773/// The standard Window menu (docs/windows.md): Minimize ⌘M / Zoom / Bring All to Front,
15774/// registered as `NSApp.windowsMenu` — AppKit then appends the open-window list and, with
15775/// tabbing live, the tab commands (Show Next/Previous Tab, Merge All Windows) itself. All
15776/// nav hosts are nil-targeted (responder chain), so they act on the key window.
15777fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
15778    let menu = unsafe {
15779        NSMenu::initWithTitle(
15780            NSMenu::alloc(mtm),
15781            &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
15782        )
15783    };
15784    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
15785        let item = unsafe {
15786            NSMenuItem::initWithTitle_action_keyEquivalent(
15787                NSMenuItem::alloc(mtm),
15788                &NSString::from_str(&day_localization::t(key)),
15789                Some(action),
15790                &NSString::from_str(accel),
15791            )
15792        };
15793        menu.addItem(&item);
15794    };
15795    add("day_minimize", sel!(performMiniaturize:), "m");
15796    add("day_zoom", sel!(performZoom:), "");
15797    menu.addItem(&NSMenuItem::separatorItem(mtm));
15798    add("day_bring_all_front", sel!(arrangeInFront:), "");
15799    let item = NSMenuItem::new(mtm);
15800    item.setTitle(&NSString::from_str(&day_localization::t(
15801        day_localization::key::day_window,
15802    )));
15803    item.setSubmenu(Some(&menu));
15804    menubar.addItem(&item);
15805    unsafe { app.setWindowsMenu(Some(&menu)) };
15806}
15807
15808/// Hoist application roles even from nested menus. First declaration wins; remove
15809/// duplicates and empty containers, then normalize separators left by the move.
15810fn extract_app_role(
15811    items: &mut Vec<day_spec::MenuItem>,
15812    role: day_spec::MenuRole,
15813) -> Option<day_spec::MenuItem> {
15814    use day_spec::MenuItem as M;
15815    let mut found = None;
15816    let mut remaining = Vec::new();
15817    for mut item in items.drain(..) {
15818        match &mut item {
15819            M::Action { role: Some(r), .. } if *r == role => {
15820                found.get_or_insert(item);
15821                continue;
15822            }
15823            M::Submenu { items, .. } => {
15824                let nested = extract_app_role(items, role);
15825                if found.is_none() {
15826                    found = nested;
15827                }
15828                if items.is_empty() {
15829                    continue;
15830                }
15831            }
15832            M::Separator
15833                if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
15834            {
15835                continue;
15836            }
15837            _ => {}
15838        }
15839        remaining.push(item);
15840    }
15841    while matches!(remaining.last(), Some(M::Separator)) {
15842        remaining.pop();
15843    }
15844    *items = remaining;
15845    found
15846}
15847
15848/// Whether any action in the model (recursively) carries `role`.
15849fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
15850    items.iter().any(|it| match it {
15851        day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
15852        day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
15853        day_spec::MenuItem::Separator => false,
15854    })
15855}
15856
15857// ---------------------------------------------------------------------------
15858// Menus (§ menus): render day's MenuItem model with NSMenu. Custom items route to a shared
15859// DayMenuTarget (id in the item's tag → Event::MenuAction); role items use the native selector.
15860// ---------------------------------------------------------------------------
15861
15862define_class!(
15863    #[unsafe(super(NSObject))]
15864    #[thread_kind = MainThreadOnly]
15865    #[name = "DayMenuTarget"]
15866    #[ivars = ()]
15867    struct DayMenuTarget;
15868
15869    unsafe impl NSObjectProtocol for DayMenuTarget {}
15870
15871    impl DayMenuTarget {
15872        #[unsafe(method(fire:))]
15873        fn fire(&self, sender: &NSMenuItem) {
15874            ffi_guard::contain((), || {
15875                let id = sender.tag() as u64;
15876                if id != 0 {
15877                    emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
15878                }
15879            });
15880        }
15881    }
15882);
15883
15884/// The primary window's content view (set once in `run`).
15885/// Pin the window's content coordinate space under its title bar and toolbar (§7.7). The
15886/// content view is full-size (`FullSizeContentView`, for the unified toolbar), so it runs
15887/// beneath the bar; moving its bounds origin up by that strip makes Day's root, laid out from
15888/// (0, 0), start below the bar — the way UIKit pins the root inside `safeAreaInsets` — while
15889/// the view's own background still paints edge to edge. Returns the size Day lays out at, the
15890/// window's `contentLayoutRect`. Called wherever that rect can change: window creation, every
15891/// resize, and a toolbar coming or going.
15892pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
15893    let content = window.contentView()?;
15894    let full = content.frame().size;
15895    let layout = unsafe { window.contentLayoutRect() }.size;
15896    let top = (full.height - layout.height).max(0.0);
15897    // An overlay title bar (docs/window-chrome.md) is the one place the content belongs under
15898    // the bar: it keeps the full height, and the bar's height goes to the app as a safe-area
15899    // inset so it can pad its own content.
15900    if window_chrome::is_overlay(window) {
15901        unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
15902        window_chrome::report_title_bar_inset(window, top);
15903        return Some(Size::new(full.width, full.height));
15904    }
15905    unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
15906    Some(Size::new(full.width, (full.height - top).max(0.0)))
15907}
15908
15909/// The text a widget displays, for `read_native`: a label's or text field's string, a
15910/// button's title, a text area's contents. `None` for a secure field (it masks its text), an
15911/// icon-only button (its title is a tooltip), and every other view.
15912fn native_text(h: &NSView) -> Option<String> {
15913    if h.downcast_ref::<NSSecureTextField>().is_some() {
15914        return None;
15915    }
15916    if let Some(tf) = h.downcast_ref::<NSTextField>() {
15917        // `stringValue` answers the field editor's live text while the field edits.
15918        return Some(tf.stringValue().to_string());
15919    }
15920    if let Some(btn) = h.downcast_ref::<NSButton>() {
15921        if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
15922            return None;
15923        }
15924        return Some(btn.title().to_string());
15925    }
15926    // A text area is an NSTextView inside the scroll view its handle names (textarea.rs).
15927    let sv = h.downcast_ref::<NSScrollView>()?;
15928    let doc = sv.documentView()?;
15929    let tv = doc.downcast_ref::<NSTextView>()?;
15930    Some(tv.string().to_string())
15931}
15932
15933/// A slider's value or a determinate progress bar's fraction, for `read_native`. Both native
15934/// ranges are the ones Day gave: the slider is built with Day's min and max, the bar runs 0–1.
15935fn native_number(h: &NSView) -> Option<f64> {
15936    if let Some(sl) = h.downcast_ref::<NSSlider>() {
15937        return Some(sl.doubleValue());
15938    }
15939    let pi = h.downcast_ref::<NSProgressIndicator>()?;
15940    (!pi.isIndeterminate()).then(|| pi.doubleValue())
15941}
15942
15943/// The view's frame in its window's content coordinates, origin top left, for `read_native`.
15944/// The content view is flipped and pinned below the title bar (`pin_below_title_bar`), so
15945/// converting into it gives Day's layout space; an unflipped content view is flipped here.
15946fn native_frame(h: &NSView) -> Option<Rect> {
15947    let content = h.window()?.contentView()?;
15948    let r = h.convertRect_toView(h.bounds(), Some(&content));
15949    let y = if content.isFlipped() {
15950        r.origin.y
15951    } else {
15952        let b = content.bounds();
15953        b.origin.y + b.size.height - (r.origin.y + r.size.height)
15954    };
15955    Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
15956}
15957
15958/// The strip a pinned content view keeps above its layout origin (see `pin_below_title_bar`).
15959fn title_bar_inset(content: &NSView) -> f64 {
15960    (-content.bounds().origin.y).max(0.0)
15961}
15962
15963fn primary_content() -> Option<Retained<NSView>> {
15964    PRIMARY_CONTENT.with(|c| c.borrow().clone())
15965}
15966
15967fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
15968    MENU_TARGET.with(|t| {
15969        t.borrow_mut()
15970            .get_or_insert_with(|| {
15971                let this = DayMenuTarget::alloc(mtm).set_ivars(());
15972                let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
15973                obj
15974            })
15975            .clone()
15976    })
15977}
15978
15979fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
15980    use objc2_app_kit::NSEventModifierFlags as F;
15981    let mut m = F::empty();
15982    if s.primary {
15983        m |= F::Command;
15984    }
15985    if s.shift {
15986        m |= F::Shift;
15987    }
15988    if s.alt {
15989        m |= F::Option;
15990    }
15991    if s.control {
15992        m |= F::Control;
15993    }
15994    m
15995}
15996
15997/// A shortcut's key-equivalent string. Single chars pass through (lowercased); a few named keys map
15998/// to their control characters. Modifiers ride separately via `setKeyEquivalentModifierMask`.
15999fn ns_key_equivalent(key: &str) -> String {
16000    match key {
16001        "Return" | "Enter" => "\r".into(),
16002        "Tab" => "\t".into(),
16003        "Delete" | "Backspace" => "\u{8}".into(),
16004        "Escape" => "\u{1b}".into(),
16005        "Space" => " ".into(),
16006        k if k.chars().count() == 1 => k.to_lowercase(),
16007        _ => String::new(), // named keys we don't map get no key-equivalent (still shown in menu)
16008    }
16009}
16010
16011/// A standard role → (default label, nav host, default shortcut). Nav host `None` = no native action
16012/// (the app should attach its own via a custom item); the role then only supplies label placement.
16013fn role_spec(
16014    role: day_spec::MenuRole,
16015) -> (
16016    &'static str,
16017    Option<objc2::runtime::Sel>,
16018    Option<day_spec::Shortcut>,
16019) {
16020    use day_spec::MenuRole as R;
16021    use day_spec::Shortcut as S;
16022    match role {
16023        R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
16024        R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
16025        R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
16026        R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
16027        R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
16028        R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
16029        R::Delete => ("Delete", Some(sel!(delete:)), None),
16030        R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
16031        R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
16032        R::Preferences => ("Settings…", None, Some(S::primary(","))),
16033        R::Minimize => (
16034            "Minimize",
16035            Some(sel!(performMiniaturize:)),
16036            Some(S::primary("m")),
16037        ),
16038        R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
16039        R::Fullscreen => (
16040            "Enter Full Screen",
16041            Some(sel!(toggleFullScreen:)),
16042            Some(S::primary("f").control()),
16043        ),
16044        // No native selector (docs/windows.md): the item dispatches the registered
16045        // new-window action through the ordinary custom-item path (`fire:`).
16046        R::NewWindow => ("New Window", None, Some(S::primary("n"))),
16047        // Likewise: no selector, the registered updater action fires through `fire:`.
16048        R::CheckForUpdates => ("Check for Updates…", None, None),
16049    }
16050}
16051
16052pub(crate) fn build_ns_menu(
16053    mtm: MainThreadMarker,
16054    title: &str,
16055    items: &[day_spec::MenuItem],
16056) -> Retained<NSMenu> {
16057    use day_spec::MenuItem as MI;
16058    let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
16059    let target = menu_target(mtm);
16060    for item in items {
16061        match item {
16062            MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
16063            MI::Submenu { label, items, .. } => {
16064                let sub = build_ns_menu(mtm, label, items);
16065                let it = NSMenuItem::new(mtm);
16066                it.setTitle(&NSString::from_str(label));
16067                it.setSubmenu(Some(&sub));
16068                menu.addItem(&it);
16069            }
16070            MI::Action {
16071                action,
16072                label,
16073                shortcut,
16074                enabled,
16075                checked,
16076                role,
16077                icon,
16078                ..
16079            } => {
16080                // Resolve label/nav host/shortcut, folding in the role's native defaults.
16081                let (mut lbl, sel, mut sc) = match role {
16082                    Some(r) => {
16083                        let (dl, ds, dsc) = role_spec(*r);
16084                        (dl.to_string(), ds, dsc)
16085                    }
16086                    None => (String::new(), None, None),
16087                };
16088                if !label.is_empty() {
16089                    lbl.clone_from(label);
16090                }
16091                if shortcut.is_some() {
16092                    sc.clone_from(shortcut);
16093                }
16094                // Custom action (nonzero id) overrides any role nav host and targets our
16095                // trampoline — except the responder-routed set (undo pair, clipboard trio),
16096                // whose nonzero ids are only the other platforms' fallback dispatchers: here
16097                // the nil-target nav hosts must stay, so the responder chain resolves the
16098                // acting object (a focused text field before the app's bridge).
16099                let responder_role = matches!(
16100                    role,
16101                    Some(
16102                        day_spec::MenuRole::Undo
16103                            | day_spec::MenuRole::Redo
16104                            | day_spec::MenuRole::Cut
16105                            | day_spec::MenuRole::Copy
16106                            | day_spec::MenuRole::Paste
16107                            | day_spec::MenuRole::SelectAll
16108                    )
16109                );
16110                let custom = *action != 0 && !responder_role;
16111                let key = sc.as_ref().map_or_default(|s| ns_key_equivalent(&s.key));
16112                let it = unsafe {
16113                    NSMenuItem::initWithTitle_action_keyEquivalent(
16114                        NSMenuItem::alloc(mtm),
16115                        &NSString::from_str(&lbl),
16116                        if custom { Some(sel!(fire:)) } else { sel },
16117                        &NSString::from_str(&key),
16118                    )
16119                };
16120                if let Some(s) = &sc {
16121                    it.setKeyEquivalentModifierMask(ns_modifiers(s));
16122                    // AppKit's own per-layout/per-language adjustments (macOS 12+): remap a
16123                    // key equivalent the current keyboard layout cannot type, and MIRROR
16124                    // directional pairs (⌘[ / ⌘]) under RTL languages — the system half of
16125                    // shortcut localization; the catalog half is the `.key` attribute
16126                    // (docs/localization.md).
16127                    it.setAllowsAutomaticKeyEquivalentLocalization(true);
16128                    it.setAllowsAutomaticKeyEquivalentMirroring(true);
16129                }
16130                if custom {
16131                    let tobj: &objc2::runtime::AnyObject = target.as_ref();
16132                    unsafe { it.setTarget(Some(tobj)) };
16133                    it.setTag(*action as isize);
16134                }
16135                it.setEnabled(*enabled);
16136                // A checkable item takes NSMenuItem's own state, so macOS draws the ✓ it draws
16137                // everywhere else and reserves the mark's column when it is off (docs/menus.md).
16138                if let Some(on) = checked {
16139                    it.setState(if *on {
16140                        NSControlStateValueOn
16141                    } else {
16142                        NSControlStateValueOff
16143                    });
16144                }
16145                // The item's glyph, drawn the way NSMenuItem draws its own (docs/menus.md):
16146                // template-tinted, sized to the menu's text.
16147                if let Some(icon) = icon
16148                    && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
16149                {
16150                    img.setSize(NSSize::new(16.0, 16.0));
16151                    it.setImage(Some(&img));
16152                }
16153                menu.addItem(&it);
16154            }
16155        }
16156    }
16157    menu
16158}
16159
16160// AppKit's TLS may be destroyed before the reactive arena drops its last Bitmap.
16161// The registry already released the native images in that case.
16162fn release_bitmap(id: day_spec::BitmapId) {
16163    let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
16164}
16165
16166#[cfg(test)]
16167mod splice_tests {
16168    use super::{SpliceRows, splice_fits};
16169    use day_spec::props::RowDelta::{Insert, Move, Remove};
16170
16171    #[test]
16172    fn a_splice_fits_only_the_rows_it_was_made_for() {
16173        // Three rows: insert at the top, move the last to the top, remove from the middle.
16174        let deltas = [Insert(0), Move(3, 0), Remove(2)];
16175        assert!(splice_fits(3, &deltas, 3));
16176        // An append lands one past the end.
16177        assert!(splice_fits(3, &[Insert(3), Insert(4)], 5));
16178        assert!(splice_fits(0, &[], 0));
16179        // The table missed a change: an index past its rows, or the wrong count after.
16180        assert!(!splice_fits(2, &deltas, 2));
16181        assert!(!splice_fits(3, &[Insert(5)], 4));
16182        assert!(!splice_fits(3, &[Remove(3)], 2));
16183        assert!(!splice_fits(3, &[Move(0, 3)], 3));
16184        assert!(!splice_fits(3, &[Insert(0)], 3));
16185    }
16186
16187    #[test]
16188    fn a_splice_in_flight_maps_each_row_to_the_source_row_it_ends_at() {
16189        // A sectioned list [A, a1, B, b1] grows to [A, a1, a2, a3, B, b1, b2, b3, C, c1, c2]:
16190        // day-core inserts from the bottom up, each row above the one placed before it.
16191        let deltas = [
16192            Insert(4),
16193            Insert(4),
16194            Insert(4),
16195            Insert(4),
16196            Insert(4),
16197            Insert(2),
16198            Insert(2),
16199        ];
16200        let mut rows = SpliceRows::new(4, &deltas);
16201        let shown = |rows: &SpliceRows| -> Vec<Option<usize>> {
16202            (0..rows.entries.len())
16203                .map(|r| rows.source_row(r))
16204                .collect()
16205        };
16206        // Before any delta, the rows shown are where they end.
16207        assert!(shown(&rows).into_iter().eq([0, 1, 4, 5].map(Some)));
16208        // The first insert is the last row, c2, at index 4 — where header B ends up.
16209        rows.apply(deltas[0]);
16210        assert!(shown(&rows).into_iter().eq([0, 1, 4, 5, 10].map(Some)));
16211        for delta in &deltas[1..] {
16212            rows.apply(*delta);
16213        }
16214        assert!(shown(&rows).into_iter().eq((0..11).map(Some)));
16215
16216        // Removals first (highest first), then a move: removed rows map to nothing.
16217        let deltas = [Remove(3), Remove(1), Move(1, 0)];
16218        let mut rows = SpliceRows::new(4, &deltas);
16219        assert!(shown(&rows).into_iter().eq([Some(1), None, Some(0), None]));
16220        rows.apply(deltas[0]);
16221        rows.apply(deltas[1]);
16222        assert!(shown(&rows).into_iter().eq([1, 0].map(Some)));
16223        rows.apply(deltas[2]);
16224        assert!(shown(&rows).into_iter().eq([0, 1].map(Some)));
16225    }
16226}
16227
16228#[cfg(test)]
16229mod bitmap_teardown_tests {
16230    use super::*;
16231
16232    #[test]
16233    fn releasing_after_bitmap_registry_teardown_does_not_abort() {
16234        // Isolate destructor panics: Rust aborts the process when a TLS destructor unwinds.
16235        const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
16236        if std::env::var_os(CHILD).is_some() {
16237            struct LateRelease;
16238            impl Drop for LateRelease {
16239                fn drop(&mut self) {
16240                    assert!(BITMAPS.try_with(|_| ()).is_err());
16241                    // Same duty called by Bitmap::drop; no NSApplication is needed.
16242                    release_bitmap(day_spec::BitmapId(1));
16243                }
16244            }
16245            std::thread_local! {
16246                static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
16247            }
16248            std::thread::spawn(|| {
16249                LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
16250                BITMAPS.with(|_| ()); // initialized last, destroyed first
16251            })
16252            .join()
16253            .unwrap();
16254            return;
16255        }
16256        let output = std::process::Command::new(std::env::current_exe().unwrap())
16257            .args([
16258                "--exact",
16259                "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
16260                "--nocapture",
16261            ])
16262            .env(CHILD, "1")
16263            .output()
16264            .unwrap();
16265        assert!(
16266            output.status.success(),
16267            "{}",
16268            String::from_utf8_lossy(&output.stderr)
16269        );
16270    }
16271}
16272
16273#[cfg(test)]
16274mod canvas_ink_tests {
16275    use super::*;
16276    use day_spec::{Affine, BlendMode, Color, ConicGradient, Shadow, Shape};
16277
16278    const RED: Color = Color::rgb(1.0, 0.0, 0.0);
16279    const GREEN: Color = Color::rgb(0.0, 1.0, 0.0);
16280    const BLUE: Color = Color::rgb(0.0, 0.0, 1.0);
16281    const YELLOW: Color = Color::rgb(1.0, 1.0, 0.0);
16282
16283    fn rect(x: f64, y: f64, w: f64, h: f64) -> Shape {
16284        Shape::Rect(day_spec::Rect::new(x, y, w, h))
16285    }
16286
16287    /// Four hard-edged quarters, clockwise from +x: red, green, blue, yellow.
16288    fn quarters() -> ConicGradient {
16289        let stops = [RED, GREEN, BLUE, YELLOW]
16290            .iter()
16291            .enumerate()
16292            .flat_map(|(i, c)| [(i as f64 * 0.25, *c), (i as f64 * 0.25 + 0.25, *c)])
16293            .collect::<Vec<_>>();
16294        ConicGradient::centered(day_spec::Angle::deg(0.0), stops)
16295    }
16296
16297    /// Paint `ops` through the export painter and read back premultiplied RGBA at pixel
16298    /// (`x`, `y`), counted from the top left.
16299    fn painted(ops: &[DrawOp], size: Size, scale: f64, at: &[(usize, usize)]) -> Vec<[u8; 4]> {
16300        let image = render_bitmap_cgimage(ops, size, scale).unwrap();
16301        let rep = unsafe {
16302            objc2_app_kit::NSBitmapImageRep::initWithCGImage(
16303                objc2_app_kit::NSBitmapImageRep::alloc(),
16304                &image,
16305            )
16306        };
16307        let (data, stride) = (rep.bitmapData(), rep.bytesPerRow() as usize);
16308        assert_eq!(rep.bitsPerPixel(), 32);
16309        at.iter()
16310            .map(|(x, y)| {
16311                let mut px = [0u8; 4];
16312                // SAFETY: the rep owns `stride` bytes per row for its pixel height, and every
16313                // sample a test asks for lies inside the image it rendered.
16314                unsafe {
16315                    data.add(y * stride + x * 4)
16316                        .copy_to_nonoverlapping(px.as_mut_ptr(), 4);
16317                };
16318                px
16319            })
16320            .collect()
16321    }
16322
16323    fn near(px: [u8; 4], want: [u8; 4]) -> bool {
16324        px.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 24)
16325    }
16326
16327    #[test]
16328    fn replay_mirrors_save_and_restore() {
16329        let mut replay = Replay::new(1.0);
16330        replay.save();
16331        replay.ink.shadow = true;
16332        replay.save();
16333        replay.ink.blend = BlendMode::Erase;
16334        assert!(replay.restore());
16335        assert_eq!(
16336            replay.ink,
16337            Ink {
16338                shadow: true,
16339                blend: BlendMode::Normal
16340            }
16341        );
16342        assert!(replay.restore());
16343        assert_eq!(replay.ink, Ink::default());
16344        // A restore with no save changes nothing and reports it.
16345        assert!(!replay.restore());
16346        assert_eq!(replay.ink, Ink::default());
16347    }
16348
16349    #[test]
16350    fn pdf_leaves_out_what_erase_draws() {
16351        let plain = [DrawOp::Fill(rect(0.0, 0.0, 9.0, 9.0), RED.into())];
16352        assert!(matches!(pdf_ops(&plain), std::borrow::Cow::Borrowed(_)));
16353        let ops = [
16354            DrawOp::Fill(rect(0.0, 0.0, 9.0, 9.0), RED.into()),
16355            DrawOp::Save,
16356            DrawOp::Blend(BlendMode::Erase),
16357            DrawOp::Fill(rect(1.0, 1.0, 2.0, 2.0), GREEN.into()),
16358            DrawOp::Restore,
16359            DrawOp::Fill(rect(3.0, 3.0, 2.0, 2.0), BLUE.into()),
16360        ];
16361        let kept = pdf_ops(&ops);
16362        assert_eq!(kept.len(), 5);
16363        assert!(!kept.contains(&ops[3]));
16364        assert!(kept.contains(&ops[5]));
16365    }
16366
16367    #[test]
16368    fn conic_pixels_turn_clockwise_from_the_start() {
16369        // A 4 by 4 grid about its own middle: one quarter per quadrant, bottom-right first.
16370        let px = conic_pixels(
16371            &quarters(),
16372            Point::new(2.0, 2.0),
16373            Point::new(0.0, 0.0),
16374            1.0,
16375            4,
16376            4,
16377        );
16378        let at = |x: usize, y: usize| <[u8; 4]>::try_from(&px[(y * 4 + x) * 4..][..4]).unwrap();
16379        assert_eq!(px.len(), 4 * 4 * 4);
16380        assert_eq!(at(3, 3), [255, 0, 0, 255]);
16381        assert_eq!(at(0, 3), [0, 255, 0, 255]);
16382        assert_eq!(at(0, 0), [0, 0, 255, 255]);
16383        assert_eq!(at(3, 0), [255, 255, 0, 255]);
16384        // Alpha premultiplies the color.
16385        let half = Color::rgba(1.0, 0.0, 0.0, 0.5);
16386        let faint =
16387            ConicGradient::centered(day_spec::Angle::deg(90.0), vec![(0.0, half), (1.0, half)]);
16388        let px = conic_pixels(
16389            &faint,
16390            Point::new(0.5, 0.5),
16391            Point::new(0.0, 0.0),
16392            1.0,
16393            1,
16394            1,
16395        );
16396        assert_eq!(px, [128, 0, 0, 128]);
16397        // The start angle turns the whole wheel: from 90°, the first quarter is bottom-left.
16398        let turned = ConicGradient::centered(day_spec::Angle::deg(90.0), quarters().stops);
16399        let px = conic_pixels(
16400            &turned,
16401            Point::new(1.0, 1.0),
16402            Point::new(0.0, 0.0),
16403            1.0,
16404            2,
16405            2,
16406        );
16407        assert_eq!(px[8..12], [255, 0, 0, 255]);
16408    }
16409
16410    #[test]
16411    fn stamp_bounds_join_every_copy() {
16412        let mut stamp = day_spec::Stamp {
16413            shape: Shape::Ellipse(day_spec::Rect::new(-3.0, -3.0, 6.0, 6.0)),
16414            at: vec![Point::new(10.0, 50.0), Point::new(40.0, 20.0)],
16415            paint: RED.into(),
16416            stroke: None,
16417        };
16418        assert_eq!(
16419            stamp_bounds(&stamp),
16420            Some(day_spec::Rect::new(7.0, 17.0, 36.0, 36.0))
16421        );
16422        stamp.at.clear();
16423        assert_eq!(stamp_bounds(&stamp), None);
16424    }
16425
16426    #[test]
16427    fn export_paints_conic_quadrants() {
16428        let size = Size::new(100.0, 100.0);
16429        let ops = [DrawOp::Fill(
16430            rect(0.0, 0.0, 100.0, 100.0),
16431            quarters().into(),
16432        )];
16433        let px = painted(&ops, size, 1.0, &[(75, 75), (25, 75), (25, 25), (75, 25)]);
16434        assert!(near(px[0], [255, 0, 0, 255]), "{px:?}");
16435        assert!(near(px[1], [0, 255, 0, 255]), "{px:?}");
16436        assert!(near(px[2], [0, 0, 255, 255]), "{px:?}");
16437        assert!(near(px[3], [255, 255, 0, 255]), "{px:?}");
16438    }
16439
16440    /// Fill a 100-point disc with `gradient` through the pixel emulation, in the canvas's
16441    /// y-down space, and read back premultiplied RGBA at the pixels asked for.
16442    fn fanned(gradient: &ConicGradient, at: &[(usize, usize)]) -> Vec<[u8; 4]> {
16443        use objc2_core_graphics::{
16444            CGBitmapContextCreate, CGBitmapContextGetBytesPerRow, CGBitmapContextGetData,
16445            CGColorSpace, CGContext, CGImageAlphaInfo,
16446        };
16447        let space =
16448            CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
16449        let cg = unsafe {
16450            CGBitmapContextCreate(
16451                std::ptr::null_mut(),
16452                100,
16453                100,
16454                8,
16455                0,
16456                space.as_deref(),
16457                CGImageAlphaInfo::PremultipliedLast.0,
16458            )
16459        }
16460        .unwrap();
16461        CGContext::translate_ctm(Some(&cg), 0.0, 100.0);
16462        CGContext::scale_ctm(Some(&cg), 1.0, -1.0);
16463        CGContext::add_ellipse_in_rect(
16464            Some(&cg),
16465            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(100.0, 100.0)),
16466        );
16467        CGContext::clip(Some(&cg));
16468        draw_conic_pixels(&cg, gradient, Point::new(50.0, 50.0));
16469        let (data, stride) = (
16470            CGBitmapContextGetData(Some(&cg)).cast::<u8>(),
16471            CGBitmapContextGetBytesPerRow(Some(&cg)),
16472        );
16473        at.iter()
16474            .map(|(x, y)| {
16475                let mut px = [0u8; 4];
16476                // SAFETY: inside the 100 by 100 buffer the context owns.
16477                unsafe {
16478                    data.add(y * stride + x * 4)
16479                        .copy_to_nonoverlapping(px.as_mut_ptr(), 4);
16480                };
16481                px
16482            })
16483            .collect()
16484    }
16485
16486    #[test]
16487    fn emulated_conic_paints_the_same_quadrants() {
16488        let px = fanned(
16489            &quarters(),
16490            &[(75, 75), (25, 75), (25, 25), (75, 25), (2, 2)],
16491        );
16492        assert_eq!(px[0], [255, 0, 0, 255]);
16493        assert_eq!(px[1], [0, 255, 0, 255]);
16494        assert_eq!(px[2], [0, 0, 255, 255]);
16495        assert_eq!(px[3], [255, 255, 0, 255]);
16496        // Outside the clip, nothing.
16497        assert_eq!(px[4], [0, 0, 0, 0]);
16498    }
16499
16500    #[test]
16501    fn emulated_conic_is_one_even_coat() {
16502        // Half-transparent, so a gap would read 0 and an overlap about 191: every pixel
16503        // well inside the disc must read exactly one coat.
16504        let half = Color::rgba(0.0, 0.0, 0.0, 0.5);
16505        let gradient =
16506            ConicGradient::centered(day_spec::Angle::deg(17.0), vec![(0.0, half), (1.0, half)]);
16507        let inside: Vec<(usize, usize)> = (20..80)
16508            .flat_map(|y| (20..80).map(move |x| (x, y)))
16509            .collect();
16510        for (px, at) in fanned(&gradient, &inside).iter().zip(&inside) {
16511            assert!(
16512                px[3].abs_diff(128) <= 1,
16513                "uneven at {at:?}: alpha {}",
16514                px[3]
16515            );
16516        }
16517    }
16518
16519    #[test]
16520    fn export_shadow_is_in_points_and_scoped() {
16521        // The conformance drawing, at two pixels per point: the box lands on (30, 20) to
16522        // (70, 50) points and its shadow 20 points lower, whatever the transform and the scale.
16523        let ops = [
16524            DrawOp::Fill(rect(0.0, 0.0, 200.0, 100.0), Color::WHITE.into()),
16525            DrawOp::Save,
16526            DrawOp::Concat(Affine::scale(2.0, 2.0)),
16527            DrawOp::Save,
16528            DrawOp::Shadow(Some(
16529                Shadow::new(Color::rgb(0.0, 0.0, 0.0), 2.0).offset(0.0, 20.0),
16530            )),
16531            DrawOp::Fill(rect(15.0, 10.0, 20.0, 15.0), BLUE.into()),
16532            DrawOp::Restore,
16533            DrawOp::Restore,
16534            DrawOp::Fill(rect(130.0, 20.0, 40.0, 30.0), BLUE.into()),
16535        ];
16536        let at = [(100, 70), (100, 120), (100, 170), (300, 70), (300, 120)];
16537        let px = painted(&ops, Size::new(200.0, 100.0), 2.0, &at);
16538        assert!(near(px[0], [0, 0, 255, 255]), "{px:?}");
16539        assert!(near(px[1], [0, 0, 0, 255]), "{px:?}");
16540        assert!(near(px[2], [255, 255, 255, 255]), "{px:?}");
16541        assert!(near(px[3], [0, 0, 255, 255]), "{px:?}");
16542        assert!(near(px[4], [255, 255, 255, 255]), "{px:?}");
16543    }
16544
16545    #[test]
16546    fn export_gradient_casts_a_whole_shadow() {
16547        // A gradient is drawn through a clip, which would cut its shadow off too.
16548        let ops = [
16549            DrawOp::Shadow(Some(Shadow::new(BLUE, 0.0).offset(0.0, 30.0))),
16550            DrawOp::Fill(rect(10.0, 10.0, 40.0, 20.0), quarters().into()),
16551        ];
16552        let px = painted(&ops, Size::new(60.0, 80.0), 1.0, &[(30, 50), (30, 70)]);
16553        assert!(near(px[0], [0, 0, 255, 255]), "{px:?}");
16554        assert_eq!(px[1], [0, 0, 0, 0]);
16555    }
16556
16557    #[test]
16558    fn export_blends_path_object_shapes_too() {
16559        // A rounded rectangle takes the `NSBezierPath` route, not the direct context one.
16560        let round = |x: f64| Shape::RoundedRect(day_spec::Rect::new(x, 0.0, 30.0, 30.0), 4.0);
16561        let ops = [
16562            DrawOp::Fill(rect(0.0, 0.0, 60.0, 60.0), YELLOW.into()),
16563            DrawOp::Save,
16564            DrawOp::Blend(BlendMode::Multiply),
16565            DrawOp::Fill(round(0.0), Color::rgb(0.0, 1.0, 1.0).into()),
16566            DrawOp::Blend(BlendMode::Erase),
16567            DrawOp::Fill(round(30.0), RED.into()),
16568            DrawOp::Restore,
16569            DrawOp::Shadow(Some(Shadow::new(BLUE, 0.0).offset(0.0, 30.0))),
16570            DrawOp::Fill(round(0.0), RED.into()),
16571        ];
16572        let px = painted(
16573            &ops,
16574            Size::new(60.0, 60.0),
16575            1.0,
16576            &[(15, 15), (45, 15), (15, 45)],
16577        );
16578        assert!(near(px[0], [255, 0, 0, 255]), "{px:?}");
16579        assert_eq!(px[1], [0, 0, 0, 0], "{px:?}");
16580        assert!(near(px[2], [0, 0, 255, 255]), "{px:?}");
16581    }
16582
16583    #[test]
16584    fn export_blends_and_erases() {
16585        let ops = [
16586            DrawOp::Fill(rect(0.0, 0.0, 90.0, 30.0), Color::WHITE.into()),
16587            DrawOp::Fill(rect(0.0, 0.0, 30.0, 30.0), YELLOW.into()),
16588            DrawOp::Save,
16589            DrawOp::Blend(BlendMode::Multiply),
16590            DrawOp::Fill(rect(0.0, 0.0, 30.0, 30.0), Color::rgb(0.0, 1.0, 1.0).into()),
16591            DrawOp::Restore,
16592            DrawOp::Fill(rect(30.0, 0.0, 30.0, 30.0), RED.into()),
16593            DrawOp::Save,
16594            DrawOp::Blend(BlendMode::Add),
16595            DrawOp::Fill(rect(30.0, 0.0, 30.0, 30.0), BLUE.into()),
16596            DrawOp::Restore,
16597            DrawOp::Save,
16598            DrawOp::Blend(BlendMode::Erase),
16599            DrawOp::Fill(rect(60.0, 0.0, 15.0, 30.0), GREEN.into()),
16600            // A gradient erases by its alpha as one piece, like a solid.
16601            DrawOp::Fill(rect(75.0, 0.0, 15.0, 15.0), quarters().into()),
16602            DrawOp::Restore,
16603            DrawOp::Fill(rect(80.0, 20.0, 10.0, 10.0), BLUE.into()),
16604        ];
16605        let at = [(15, 15), (45, 15), (67, 15), (82, 7), (78, 25), (85, 25)];
16606        let px = painted(&ops, Size::new(90.0, 30.0), 1.0, &at);
16607        assert!(near(px[0], [0, 255, 0, 255]), "{px:?}");
16608        assert!(near(px[1], [255, 0, 255, 255]), "{px:?}");
16609        assert_eq!(px[2], [0, 0, 0, 0], "{px:?}");
16610        assert!(near(px[3], [0, 0, 0, 0]), "{px:?}");
16611        assert!(near(px[4], [255, 255, 255, 255]), "{px:?}");
16612        // The mode ended with its scope: this one simply covers.
16613        assert!(near(px[5], [0, 0, 255, 255]), "{px:?}");
16614    }
16615}