Skip to main content

day_toolkit_appkit/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-appkit: the macos-appkit backend (DESIGN.md §9). objc2, pure Rust, no shim.
5//!
6//! `Handle = Retained<NSView>`. Containers are flipped `NSView`s (top-left origin, so Day's
7//! frames apply directly and survive diffing). One custom target class (`DayTarget`) forwards
8//! target/action + text-delegate callbacks into the Day event sink, node-id keyed (§8.3).
9
10#![allow(unused_unsafe)]
11#![cfg(target_os = "macos")]
12
13mod controls;
14
15mod applications;
16mod nav_progress;
17
18use std::any::Any;
19use std::cell::{Cell, RefCell};
20use std::collections::HashMap;
21use std::rc::Rc;
22
23use linkme::distributed_slice;
24use objc2::Message as _;
25use objc2::rc::Retained;
26use objc2::runtime::{NSObjectProtocol, ProtocolObject};
27use objc2::{
28    AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
29};
30use objc2_app_kit::NSAccessibility as _;
31use objc2_app_kit::NSAppearanceCustomization as _;
32use objc2_app_kit::NSDraggingInfo as _;
33use objc2_app_kit::NSSplitViewDelegate;
34use objc2_app_kit::NSTextContent as _;
35use objc2_app_kit::NSUserInterfaceItemIdentification as _;
36use objc2_app_kit::{
37    NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
38    NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
39};
40use objc2_app_kit::{
41    NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
42    NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
43    NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
44    NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
45    NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
46    NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
47    NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
48    NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
49    NSWindowDelegate, NSWindowStyleMask,
50};
51use objc2_app_kit::{
52    NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
53    NSApplicationWillTerminateNotification,
54};
55use objc2_app_kit::{
56    NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
57};
58use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
59use objc2_core_foundation::CGAffineTransform;
60use objc2_foundation::{
61    NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
62    NSNumber, NSObject, NSPoint, NSRect, NSSize, NSString,
63};
64use objc2_quartz_core::{
65    CAMediaTimingFunction, CATransaction, kCAMediaTimingFunctionEaseIn,
66    kCAMediaTimingFunctionEaseInEaseOut, kCAMediaTimingFunctionEaseOut,
67    kCAMediaTimingFunctionLinear,
68};
69
70use day_spec::ffi_guard;
71use day_spec::present;
72use day_spec::props::*;
73use day_spec::sidetable::SideTable;
74use day_spec::{
75    A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
76    InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
77    Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
78    WindowOptions, kinds, props_of,
79};
80
81pub type Handle = Retained<NSView>;
82
83/// Icon resolution for a piece renderer's own `NSToolbar` items (see `toolbar::image_for`).
84pub use toolbar::image_for as toolbar_image;
85
86// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
87mod dock;
88mod documents;
89mod frame;
90mod picker;
91mod status_item;
92mod textarea;
93mod toolbar;
94mod transfer;
95mod window_chrome;
96use objc2_app_kit::NSDraggingSource;
97
98pub mod ext;
99pub use ext::*;
100
101// ---------------------------------------------------------------------------
102// Event plumbing: node-id keyed sink, thread-local (single UI thread)
103// ---------------------------------------------------------------------------
104
105/// The day-core event sink (node-id keyed).
106type Sink = Rc<dyn Fn(NodeId, Event)>;
107
108day_core::tls_group! {
109    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
110    /// Keeps each control's `DayTarget` alive (target/action holds it weakly).
111    static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
112    /// The style each button currently carries, keyed by its view pointer.
113    ///
114    /// Needed because a tinted title is an attributed string (see `set_button_title`), and
115    /// `ButtonPatch::Title` would otherwise replace it with a plain one and lose the color.
116    static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
117        RefCell::new(HashMap::new());
118    /// Original template images, retained across tint changes and swept on view release.
119    static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
120    /// Each button's selected state (`ButtonProps::selected`), keyed by its view pointer: what
121    /// the `action:` handler restores after a click toggles a push-on/push-off button, and the
122    /// buttons whose `state` `read_native` reports as `checked`.
123    static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
124
125    /// Canvas ptr → its display list. A [`SideTable`], so the release sweep reclaims it
126    /// (replay inserted but nothing ever removed).
127    static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
128    /// Views the app gave an accessibility label (`set_a11y`): a button's title change must then
129    /// leave the label alone (`apply_button_content`). Swept on release like the other tables.
130    static APP_LABELED: SideTable<()> = SideTable::new();
131    /// How each image view renders its glyph (docs/vectors.md "Tint", "Template"): whether it
132    /// was realized as a template, and whether a tint is on it now. Template rendering is a
133    /// property of the NSImage, so a source swap has to re-apply it, and a tint patch of `None`
134    /// keeps a template in the neutral tint rather than returning to the authored art. Swept
135    /// on release.
136    static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
137    /// Each transformed view's `Transform` (`set_transform`). AppKit owns a layer-backed view's
138    /// layer geometry and re-syncs it from the view, so a transform written into the layer
139    /// never showed. It is expressed in the view's own geometry instead (`apply_geometry`).
140    static TRANSFORMS: SideTable<Transform> = SideTable::new();
141    /// Each view's frame as Day laid it out, before any translation, so a translation change can
142    /// move the view without waiting for the next layout.
143    static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
144    static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
145    /// A presented cover sheet's window → its cover node, for Escape (docs/cover.md).
146    static SHEET_NODES: SideTable<NodeId> = SideTable::new();
147    static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
148    /// View ptr → node for `GestureKind::Pan` (docs/shapes.md): macOS pans arrive as trackpad
149    /// scroll events, so `DayCanvas::scrollWheel:` reports them here instead of a recognizer.
150    static PAN_NODES: SideTable<NodeId> = SideTable::new();
151    static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
152    /// View ptr → node for `GestureKind::Hover` (docs/canvas.md "Interaction"). Hover is not a
153    /// recognizer on macOS either: it is an `NSTrackingArea` plus the three mouse methods, so
154    /// like [`PAN_NODES`] this holds the canvases that asked and `DayCanvas` reports for them.
155    static HOVER_NODES: SideTable<NodeId> = SideTable::new();
156    /// Canvas view ptr → its node, so the view's own `keyDown:` knows who to report to. Every
157    /// canvas is registered at realize (unlike [`PAN_NODES`], which only holds the ones that
158    /// asked for a pan) because focus, not a gesture, is what decides who hears a key.
159    static KEY_NODES: SideTable<NodeId> = SideTable::new();
160    /// Focusable container view ptr → its node (docs/focus.md): `Decorate::focusable` opts a
161    /// `DayFlipped` into the canvas contract (accepts first responder, takes focus on a
162    /// press, reports both directions, hears the arrows). Empty for every container that
163    /// never asked, whose behavior is exactly as before.
164    static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
165
166    /// Keeps each view's gesture targets alive + records which gestures are attached (idempotent).
167    static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
168        RefCell::new(HashMap::new());
169
170    static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
171    /// Handles whose frames are native-owned (nav pages): set_frame skips them.
172    static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
173        RefCell::new(std::collections::HashSet::new());
174    /// Each nav page's pane, recorded at realize because `insert` sees only handles
175    /// (docs/size-classes.md). Identity rather than position: a re-present re-homes the pages
176    /// without changing their order, so "index 0 is the sidebar" stops being true the moment a
177    /// host can morph. A [`SideTable`]: `remove` clears it on the normal path, and the release
178    /// sweep catches a page released without one (a stale entry could mis-pane a recycled ptr).
179    static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
180
181    static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
182    /// INSPECTOR_PANE ptr → is-panel, recorded at realize because `insert` sees only handles.
183    /// A [`SideTable`]: the release sweep drops it with the view.
184    static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
185
186    /// Split host (the wrap around an `NSSplitView`, docs/split.md) ptr → its state.
187    static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
188    /// SPLIT_PANE ptr → is-second, recorded at realize because `insert` sees only handles.
189    static SPLIT_PANES: SideTable<bool> = SideTable::new();
190
191    /// Outline ptr → its data source, for [`DayNavOutlineView::menu_for_event`]'s row lookup.
192    /// A [`SideTable`], reclaimed by the outline-keyed auxiliary sweep in `release`: the entry
193    /// used to outlive its host, so a recycled outline address served the dead menu's rows.
194    static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
195
196    static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
197    /// Tree host scroll-view ptr → (outline, data source) (docs/tree.md).
198    static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
199
200    /// `BitmapId` → the decoded image (docs/images.md). Keyed by the id day-core minted, not by
201    /// a view pointer: a bitmap outlives any one view and may be drawn by several at once.
202    /// Entries leave only through `release_image`, which day-core calls when the app drops its
203    /// last `Bitmap` handle.
204    static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
205    /// View ptr → its summon-time context-menu provider (docs/menus.md). Swept on release
206    /// via `day_spec::sidetable`.
207    static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
208
209    /// NAV_MENU scroll-view ptr → (outline, data source) for patches and measure.
210    static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
211
212    /// The app's edit-bridge state (`set_edit_state`), which validateMenuItem consults.
213    static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
214        const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
215    static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
216        const { std::cell::RefCell::new(None) };
217
218    /// Live modal sheets keyed by request id (for programmatic dismissal).
219    static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
220        RefCell::new(HashMap::new());
221    /// Live file-picker sheets (NSOpenPanel is stored via its NSSavePanel supertype).
222    static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
223        RefCell::new(HashMap::new());
224
225    // NSMenuItem does not retain its target, so one shared target is kept alive for the app's
226    // lifetime.
227    static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
228        const { std::cell::RefCell::new(None) };
229    /// The primary window's content view, for call sites without backend access that must
230    /// address the main window specifically (cover re-homing, DAY_DUMP). With secondary
231    /// windows open, `app.windows().firstObject()` is arbitrary (docs/windows.md).
232    static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
233        const { std::cell::RefCell::new(None) };
234
235}
236
237/// Emit an event into day-core's queue (public: external Day Piece renderers use this too).
238pub fn emit(id: NodeId, ev: Event) {
239    let sink = SINK.with(|s| s.borrow().clone());
240    if let Some(sink) = sink {
241        sink(id, ev);
242    }
243}
244
245fn ptr_of(v: &NSView) -> usize {
246    (v as *const NSView).cast::<()>() as usize
247}
248
249/// An image view's rendering (`IMAGE_MODES`).
250#[derive(Clone, Copy)]
251struct ImageMode {
252    template: bool,
253    tinted: bool,
254}
255
256impl ImageMode {
257    /// Template rendering: the glyph's alpha as a mask, filled with the tint or the neutral
258    /// template color.
259    fn renders_template(self) -> bool {
260        self.template || self.tinted
261    }
262}
263
264/// A decoded bitmap (docs/images.md), held until day-core drops its last handle.
265///
266/// The `NSBitmapImageRep` is kept beside the image rather than fetched on demand for two
267/// reasons: it is the only thing here that can re-encode to other formats, and it is the only
268/// accurate source of pixel dimensions, since `NSImage.size` is in points and reports a @2x
269/// asset at half its real width.
270struct AppKitBitmap {
271    image: Retained<objc2_app_kit::NSImage>,
272    rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
273    info: day_spec::BitmapInfo,
274}
275
276/// Draw a decoded image into a fresh bitmap `scale`× its pixel size, for [`day_spec::EncodeSpec`]'s
277/// `fit`.
278///
279/// 8 bits across 4 samples with alpha is the one layout every writer here accepts, and the only
280/// one that carries transparency through a PNG round-trip intact.
281fn scaled_rep(
282    image: &objc2_app_kit::NSImage,
283    pixels: Size,
284    scale: f64,
285) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
286    use objc2::AllocAnyThread as _;
287    let w = (pixels.width * scale).round().max(1.0);
288    let h = (pixels.height * scale).round().max(1.0);
289    let rep = unsafe {
290        objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
291            objc2_app_kit::NSBitmapImageRep::alloc(),
292            std::ptr::null_mut(),
293            w as isize,
294            h as isize,
295            8,
296            4,
297            true,
298            false,
299            objc2_app_kit::NSDeviceRGBColorSpace,
300            0,
301            0,
302        )
303    }?;
304    let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
305    NSGraphicsContext::saveGraphicsState_class();
306    objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
307    unsafe {
308        image.drawInRect_fromRect_operation_fraction(
309            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
310            NSRect::ZERO,
311            objc2_app_kit::NSCompositingOperation::SourceOver,
312            1.0,
313        );
314    }
315    NSGraphicsContext::restoreGraphicsState_class();
316    Some(rep)
317}
318
319/// Re-encode a decoded bitmap (docs/images.md).
320///
321/// A free function rather than the duty's body so each refusal reads as an early return instead
322/// of another copy of the same emit.
323fn encode_bitmap(
324    id: day_spec::BitmapId,
325    spec: &day_spec::EncodeSpec,
326) -> Result<Vec<u8>, day_spec::ImageError> {
327    use day_spec::ImageFormat as F;
328    use objc2_app_kit::NSBitmapImageFileType as T;
329    let file_type = match spec.format {
330        F::Png => T::PNG,
331        F::Jpeg => T::JPEG,
332        F::Tiff => T::TIFF,
333        F::Bmp => T::BMP,
334        F::Gif => T::GIF,
335        // Readable here but not writable: `NSBitmapImageRep` ships no WebP or HEIF writer. That
336        // asymmetry is why `encode_formats` exists instead of letting `Cap::ImageEncode` imply
337        // that everything decodable is also encodable.
338        _ => return Err(day_spec::ImageError::Encode),
339    };
340    let held = BITMAPS.with(|m| {
341        m.borrow()
342            .get(&id.0)
343            .map(|b| (b.rep.clone(), b.image.clone(), b.info))
344    });
345    let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
346    let rep = rep.ok_or(day_spec::ImageError::Encode)?;
347
348    // `fit` scales the longest side down first. A box larger than the original is ignored:
349    // upscaling on an export path inflates the bytes without adding any detail.
350    let rep = match spec.fit {
351        Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
352            let scale = (fit.width / info.pixels.width)
353                .min(fit.height / info.pixels.height)
354                .min(1.0);
355            if scale < 1.0 {
356                scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
357            } else {
358                rep
359            }
360        }
361        _ => rep,
362    };
363
364    let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
365        // AppKit's own compression-factor property; a lossless writer ignores it.
366        Some(q) => {
367            let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
368            let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
369            let value: &objc2::runtime::AnyObject = &number;
370            NSDictionary::from_slices::<NSString>(&[key], &[value])
371        }
372        None => NSDictionary::new(),
373    };
374    let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
375        .ok_or(day_spec::ImageError::Encode)?;
376    Ok(data.to_vec())
377}
378
379/// Replay a display list into the current graphics context. The one painter both the on-screen
380/// `DayCanvas` (its `drawRect:`) and the canvas exports run, so the two cannot drift apart
381/// (docs/canvas.md "Exporting").
382fn paint_ops(ops: &[DrawOp]) {
383    for op in ops {
384        draw_op(op);
385    }
386}
387
388/// Paint `ops` into `cg` with a top-left origin and y down, as the flipped `DayCanvas` sees
389/// them. `height` is the context's own height in its base units (pixels for a bitmap, points for
390/// a PDF page) and `scale` its units per canvas point.
391///
392/// The CTM flip turns the geometry the right way up; wrapping the context as a FLIPPED
393/// `NSGraphicsContext` is what tells AppKit's text and image drawing to keep glyphs and pictures
394/// upright inside that flip, exactly as they are in a flipped view's `drawRect:`.
395fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
396    use objc2_core_graphics::CGContext;
397    CGContext::save_g_state(Some(cg));
398    CGContext::translate_ctm(Some(cg), 0.0, height);
399    CGContext::scale_ctm(Some(cg), scale, -scale);
400    let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
401    NSGraphicsContext::saveGraphicsState_class();
402    NSGraphicsContext::setCurrentContext(Some(&ns));
403    paint_ops(ops);
404    NSGraphicsContext::restoreGraphicsState_class();
405    CGContext::restore_g_state(Some(cg));
406}
407
408/// Render a canvas display list offscreen (docs/canvas.md "Exporting"): `export_pixels` of
409/// transparent sRGB, premultiplied RGBA, painted at `scale` pixels per point.
410///
411/// A `CGBitmapContext` rather than `NSGraphicsContext(bitmapImageRep:)`: it carries a real sRGB
412/// color space, so the `NSBitmapImageRep` built from its image is tagged sRGB like every canvas
413/// color, shows on the display through the same color matching the live canvas gets, and writes
414/// that profile into a PNG.
415fn render_bitmap_image(
416    ops: &[DrawOp],
417    size: Size,
418    scale: f64,
419) -> Result<AppKitBitmap, day_spec::ExportError> {
420    use objc2::AllocAnyThread as _;
421    use objc2_core_graphics::{
422        CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
423    };
424    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
425    let (pw, ph) = day_spec::export_pixels(size, scale);
426    // SAFETY: `kCGColorSpaceSRGB` is an immutable CoreGraphics constant, valid for the process.
427    let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
428        .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
429    // SAFETY: a null data pointer asks CoreGraphics to allocate (and own) the buffer, and a zero
430    // row stride lets it choose one; 8 bits × RGBA premultiplied is a supported layout.
431    let cg = unsafe {
432        CGBitmapContextCreate(
433            std::ptr::null_mut(),
434            pw as usize,
435            ph as usize,
436            8,
437            0,
438            Some(&space),
439            CGImageAlphaInfo::PremultipliedLast.0,
440        )
441    }
442    .ok_or_else(|| {
443        day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
444    })?;
445    // A new bitmap context starts zeroed, which is the transparent background.
446    paint_flipped(&cg, ph as f64, scale, ops);
447    let cg_image = CGBitmapContextCreateImage(Some(&cg))
448        .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))?;
449    let rep = unsafe {
450        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
451            objc2_app_kit::NSBitmapImageRep::alloc(),
452            &cg_image,
453        )
454    };
455    // Sized in POINTS, pixels over scale, so the image draws at the drawing's size and stays
456    // sharp at `scale`× — the same shape as a staged @2x asset.
457    let points = NSSize::new(pw as f64 / scale, ph as f64 / scale);
458    unsafe { rep.setSize(points) };
459    let image =
460        unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
461    unsafe { image.addRepresentation(&rep) };
462    Ok(AppKitBitmap {
463        image,
464        rep: Some(rep),
465        info: day_spec::BitmapInfo {
466            pixels: Size::new(pw as f64, ph as f64),
467            scale,
468            format: None,
469            has_alpha: true,
470        },
471    })
472}
473
474/// Write `pages` as one PDF document (docs/canvas.md "Exporting"): a `CGPDFContext` on a
475/// `CGDataConsumer` over memory, one page per drawing with its own media box, the title and
476/// author in the document info. Shapes and text stay vector: the same painter draws into the PDF
477/// context, and AppKit's string drawing there emits real glyphs from embedded font subsets.
478fn render_pdf_bytes(
479    pages: &[day_spec::PdfPage],
480    info: &day_spec::PdfInfo,
481) -> Result<Vec<u8>, day_spec::ExportError> {
482    use objc2_core_foundation::{
483        CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
484    };
485    use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
486    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
487    let media =
488        |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
489    let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
490    let data = CFMutableData::new(None, 0)
491        .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
492    let consumer = CGDataConsumer::with_cf_data(Some(&data))
493        .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
494
495    let mut keys: Vec<&CFString> = Vec::new();
496    let mut values: Vec<CFRetained<CFString>> = Vec::new();
497    // SAFETY: the auxiliary-info keys are immutable CoreGraphics constants.
498    let (title_key, author_key) = unsafe {
499        (
500            objc2_core_graphics::kCGPDFContextTitle,
501            objc2_core_graphics::kCGPDFContextAuthor,
502        )
503    };
504    for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
505        if let Some(value) = value {
506            keys.push(key);
507            values.push(CFString::from_str(value));
508        }
509    }
510    let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
511    let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
512
513    let first_box = media(first.size);
514    // SAFETY: `first_box` outlives the call, and the dictionary maps the documented
515    // auxiliary-info string keys to strings, which is the type those keys take.
516    let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
517        .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
518    for page in pages {
519        let page_box = media(page.size);
520        // SAFETY: `page_box` outlives the call; in a PDF context it becomes the page's MediaBox.
521        unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
522        paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
523        CGContext::end_page(Some(&pdf));
524    }
525    // Closing flushes the trailer into the consumer; the bytes are complete only after it.
526    CGPDFContextClose(Some(&pdf));
527    drop(pdf);
528    drop(consumer);
529    Ok(data.to_vec())
530}
531
532thread_local! {
533    /// Each realized list item's current props, by its view: a patch updates one part and the
534    /// item is re-dressed from the whole (docs/list.md "List items").
535    static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
536        std::cell::RefCell::new(std::collections::HashMap::new());
537}
538
539/// A list row's standard content (docs/list.md "List items"), as an image-and-text table cell
540/// draws it: a 16pt template image, the title in the system font with a smaller secondary
541/// subtitle under it, a secondary trailing value, and the accent checkmark, in a horizontal
542/// stack at least 28pt tall. Parts that are absent are hidden, and the stack closes up around
543/// them.
544///
545/// The row's width is spoken for explicitly, as an image-and-text cell's is: the stack fills
546/// its frame edge to edge, the words take every spare point and give way first, and the
547/// trailing parts keep their own size. Left to the stack's default gravity areas, the spare
548/// width had two equally weak claims, the words' column and the gap before the trailing parts,
549/// so Auto Layout settled it from whatever the row's last layout had been: a checkmark landed
550/// beside the title in one row and at the trailing edge in the next, and stayed put.
551fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
552    use objc2_app_kit::{
553        NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
554    };
555    let label = |text: &str, size: f64, secondary: bool| {
556        let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
557        unsafe {
558            tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
559            if secondary {
560                tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
561            }
562            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
563        }
564        tf
565    };
566    let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
567    let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
568    const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
569        objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
570    // Hugging: the words stretch (1), the trailing parts hold their size (750), and the stack
571    // keeps its edges on its first and last parts (750), so exactly one part takes the slack.
572    const STRETCH: f32 = 1.0;
573    const HOLD: f32 = 750.0;
574    let stack = NSStackView::new(mtm);
575    stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
576    stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
577    stack.setAlignment(NSLayoutAttribute::CenterY);
578    stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
579    stack.setSpacing(6.0);
580    // A table row's breathing room above and below; the list gives the sides.
581    stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
582        top: 4.0,
583        left: 0.0,
584        bottom: 4.0,
585        right: 0.0,
586    });
587    let icon = unsafe { NSImageView::new(mtm) };
588    unsafe {
589        icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
590        icon.widthAnchor()
591            .constraintEqualToConstant(16.0)
592            .setActive(true);
593        icon.heightAnchor()
594            .constraintEqualToConstant(16.0)
595            .setActive(true);
596    }
597    stack.addArrangedSubview(&icon);
598    // The title and subtitle span the words' column (Width alignment), so the column's width is
599    // theirs and nothing is left over inside it.
600    let texts = NSStackView::new(mtm);
601    texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
602    texts.setAlignment(NSLayoutAttribute::Width);
603    texts.setSpacing(1.0);
604    // Its height is its lines', centered in the row, not the row's height with the lines
605    // floating somewhere inside it.
606    texts.setHuggingPriority_forOrientation(
607        HOLD,
608        objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
609    );
610    let title = label("", size, false);
611    let subtitle = label("", small, true);
612    // The words take the width and give way first, truncating, before the trailing parts.
613    for line in [&title, &subtitle] {
614        line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
615        line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
616    }
617    texts.addArrangedSubview(&title);
618    texts.addArrangedSubview(&subtitle);
619    stack.addArrangedSubview(&texts);
620    let detail = label("", size, true);
621    detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
622    detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
623    stack.addArrangedSubview(&detail);
624    let check = unsafe { NSImageView::new(mtm) };
625    unsafe {
626        check.setImage(
627            objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
628                &NSString::from_str("checkmark"),
629                None,
630            )
631            .as_deref(),
632        );
633        check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
634    }
635    check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
636    check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
637    stack.addArrangedSubview(&check);
638    let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
639    LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
640    dress_list_item(&view, p, mtm);
641    view
642}
643
644/// Show `p` on a list item's stack (see [`make_list_item`]), as one accessibility element.
645fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
646    use objc2_app_kit::{NSImageView, NSStackView};
647    let Some(stack) = view.downcast_ref::<NSStackView>() else {
648        return;
649    };
650    let parts = stack.arrangedSubviews();
651    if parts.len() < 4 {
652        return;
653    }
654    let icon = parts.objectAtIndex(0);
655    if let Some(iv) = icon.downcast_ref::<NSImageView>() {
656        let image = p
657            .icon
658            .as_ref()
659            .and_then(|i| toolbar::image_for(i, &p.title, mtm));
660        unsafe {
661            iv.setImage(image.as_deref());
662            iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
663        }
664    }
665    icon.setHidden(p.icon.is_none());
666    if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
667        let lines = texts.arrangedSubviews();
668        if lines.len() == 2 {
669            if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
670                tf.setStringValue(&NSString::from_str(&p.title));
671            }
672            let sub = lines.objectAtIndex(1);
673            if let Some(tf) = sub.downcast_ref::<NSTextField>() {
674                tf.setStringValue(&NSString::from_str(&p.subtitle));
675            }
676            sub.setHidden(p.subtitle.is_empty());
677        }
678    }
679    let detail = parts.objectAtIndex(2);
680    if let Some(tf) = detail.downcast_ref::<NSTextField>() {
681        tf.setStringValue(&NSString::from_str(&p.detail));
682    }
683    detail.setHidden(p.detail.is_empty());
684    parts.objectAtIndex(3).setHidden(!p.checked);
685    let words = [&p.title, &p.subtitle, &p.detail]
686        .into_iter()
687        .filter(|w| !w.is_empty())
688        .map(String::as_str)
689        .collect::<Vec<_>>()
690        .join(", ");
691    unsafe {
692        view.setAccessibilityElement(true);
693        view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
694        view.setAccessibilitySelected(p.checked);
695    }
696}
697
698/// The `NSImage` behind an [`day_spec::ImageSource`] (docs/images.md).
699///
700/// Shared by realize and the `Source` patch: a swapped source must load exactly what a fresh
701/// realize would have, or a piece would show different pixels depending on whether it was
702/// built or updated.
703fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
704    use objc2::AllocAnyThread as _;
705    match source {
706        // A vector glyph's SVG first (docs/vectors.md): NSImage renders SVG at display size
707        // (macOS 11+), so vectors stay vector with no build-time raster resampling. Then the
708        // shared image-file resolver (images/ then assets/ then bundle), which is macOS's native
709        // path: a bundle file loaded straight into NSImage (§18.3).
710        day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
711            .or_else(|| day_spec::resource::resolve_image_file(name))
712            .and_then(|path| unsafe {
713                objc2_app_kit::NSImage::initWithContentsOfFile(
714                    objc2_app_kit::NSImage::alloc(),
715                    &NSString::from_str(&path.to_string_lossy()),
716                )
717            }),
718        // Bytes the app already holds (a download, a picked file, a paste) with no staged
719        // resource behind them.
720        day_spec::ImageSource::Bytes(bytes) => unsafe {
721            objc2_app_kit::NSImage::initWithData(
722                objc2_app_kit::NSImage::alloc(),
723                &NSData::with_bytes(bytes),
724            )
725        },
726        // Already decoded: share the one NSImage rather than parsing the same bytes twice.
727        day_spec::ImageSource::Decoded(id) => {
728            BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
729        }
730    }
731}
732
733/// Day `Role` → the `NSAccessibilityRole` constant to apply (§13). `None` for `Role::None`:
734/// Day leaves native controls' roles untouched and only applies explicit canvas/custom roles.
735fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
736    use day_spec::Role;
737    use objc2_app_kit::{
738        NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
739        NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
740        NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
741        NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
742    };
743    unsafe {
744        Some(match role {
745            Role::Button => NSAccessibilityButtonRole,
746            Role::Toggle => NSAccessibilityCheckBoxRole,
747            // A tab is a radio button with the tab-button subrole (`set_a11y` adds it), which
748            // is how NSTabView's own tabs read to VoiceOver; the strip is a tab group.
749            Role::Tab => NSAccessibilityRadioButtonRole,
750            Role::TabList => NSAccessibilityTabGroupRole,
751            Role::Slider => NSAccessibilitySliderRole,
752            Role::TextInput => NSAccessibilityTextFieldRole,
753            // `AXHeading` lands the label in VoiceOver's headings rotor. The level has no
754            // AppKit attribute of its own: the only convention (the level as `AXValue`) would
755            // displace the text an NSTextField reports as its value, so the level stays
756            // unspoken.
757            Role::Heading(_) => NSAccessibilityHeadingRole,
758            Role::Image => NSAccessibilityImageRole,
759            Role::Meter => NSAccessibilityLevelIndicatorRole,
760            Role::Group => NSAccessibilityGroupRole,
761            // NSOutlineView already reports these itself; the mapping is for the audit's
762            // expectation and for any composed stand-in (docs/tree.md).
763            Role::Tree => NSAccessibilityOutlineRole,
764            Role::TreeItem => NSAccessibilityRowRole,
765            Role::None => return None,
766        })
767    }
768}
769
770/// Native `AXRole` string → Day `Role` (best-effort, for `read_native`/`a11y_audit`).
771fn day_role_from_ns(ax: &str) -> day_spec::Role {
772    use day_spec::Role;
773    match ax {
774        "AXButton" => Role::Button,
775        "AXCheckBox" => Role::Toggle,
776        "AXSlider" => Role::Slider,
777        "AXTextField" => Role::TextInput,
778        // Plain text is ambiguous with a heading, and neither carries a level; the audit
779        // ignores the level either way.
780        "AXStaticText" | "AXHeading" => Role::Heading(0),
781        "AXOutline" => Role::Tree,
782        "AXImage" => Role::Image,
783        "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
784        "AXGroup" => Role::Group,
785        "AXRadioButton" => Role::Tab,
786        "AXTabGroup" => Role::TabList,
787        _ => Role::None,
788    }
789}
790
791// ---------------------------------------------------------------------------
792// DayTarget: target/action + text delegate trampoline
793// ---------------------------------------------------------------------------
794
795struct TargetIvars {
796    node: NodeId,
797}
798
799define_class!(
800    #[unsafe(super(NSObject))]
801    #[thread_kind = MainThreadOnly]
802    #[name = "DayTarget"]
803    #[ivars = TargetIvars]
804    struct DayTarget;
805
806    unsafe impl NSObjectProtocol for DayTarget {}
807    unsafe impl NSTextFieldDelegate for DayTarget {}
808
809    /// A tabs host's `NSTabView` (docs/navigation.md). A pick emits against the NAV_MENU's
810    /// node, exactly as the sidebar's outline view does, so as far as everything above this
811    /// backend is concerned, picking a tab and clicking a sidebar row are the same event, and
812    /// neither the pieces layer nor dayscript needs to know which chrome the window wears.
813    unsafe impl NSTabViewDelegate for DayTarget {
814        #[unsafe(method(tabView:didSelectTabViewItem:))]
815        fn tab_view_did_select(
816            &self,
817            tab_view: &objc2_app_kit::NSTabView,
818            item: Option<&objc2_app_kit::NSTabViewItem>,
819        ) {
820            ffi_guard::contain((), || {
821                if TAB_PICK_SUPPRESS.with(|s| s.get()) {
822                    return;
823                }
824                if let Some(item) = item {
825                    let idx = unsafe { tab_view.indexOfTabViewItem(item) };
826                    if idx >= 0 {
827                        emit(self.ivars().node, Event::SelectionChanged(idx as i64));
828                    }
829                }
830            })
831        }
832    }
833
834    impl DayTarget {
835        // Every trampoline that dispatches into the sink (and through it, app handlers) runs
836        // its body through `ffi_guard::contain` (§8.5): a Rust panic unwinding out of an ObjC
837        // frame is an abort, so it is caught, reported, and the reactive runtime recovered.
838        // The same guard wraps every other target/delegate entry in this backend.
839        #[unsafe(method(action:))]
840        fn action(&self, sender: &NSControl) {
841            ffi_guard::contain((), || {
842                let node = self.ivars().node;
843                if sender.downcast_ref::<NSSwitch>().is_some() {
844                    emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
845                } else if sender.downcast_ref::<NSSlider>().is_some() {
846                    let value = unsafe { sender.doubleValue() };
847                    // The live value first: bindings follow this, so the UI tracks the thumb.
848                    emit(node, Event::ValueChanged(value));
849                    // Then, once, the value the user settled on. The slider is `continuous`, so
850                    // this action fires on every tick of a drag; AppKit's way to tell where in the
851                    // gesture you are is the event that provoked it. A mouse-up ends a drag; a key
852                    // press (arrow keys) moves the value by one discrete step and is already settled;
853                    // anything else (mouse-down, mouse-dragged) is mid-gesture and commits nothing.
854                    if slider_value_settled() {
855                        emit(node, Event::ValueCommitted(value));
856                    }
857                } else {
858                    emit(node, Event::Pressed);
859                    // A push-on/push-off button toggled its state on the click; Day owns the
860                    // selected state (`set_button_selected`), so put back what it last asked.
861                    let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
862                    if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
863                        unsafe {
864                            btn.setState(if on {
865                                NSControlStateValueOn
866                            } else {
867                                NSControlStateValueOff
868                            })
869                        };
870                    }
871                }
872            })
873        }
874
875        /// The stack-nav back header's button (docs/navigation.md): a day-initiated pop. The
876        /// nav host's handler writes it into the path signal, which reconciles the pop.
877        #[unsafe(method(navBack:))]
878        fn nav_back(&self, _sender: &NSControl) {
879            ffi_guard::contain((), || {
880                emit(
881                    self.ivars().node,
882                    Event::NavBack {
883                        already_popped: false,
884                    },
885                );
886            })
887        }
888    }
889
890    unsafe impl NSControlTextEditingDelegate for DayTarget {
891        #[unsafe(method(controlTextDidChange:))]
892        fn control_text_did_change(&self, notification: &NSNotification) {
893            ffi_guard::contain((), || {
894                let node = self.ivars().node;
895                if let Some(obj) = unsafe { notification.object() }
896                    && let Ok(tf) = obj.downcast::<NSTextField>() {
897                        emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
898                    }
899            })
900        }
901
902        /// End of an editing session (docs/focus.md). Return submits: AppKit keeps the field
903        /// first responder and re-selects, so it is not a focus loss; every other movement
904        /// (tab, click-away, cancel) reports `FocusChanged(false)`.
905        #[unsafe(method(controlTextDidEndEditing:))]
906        fn control_text_did_end_editing(&self, notification: &NSNotification) {
907            ffi_guard::contain((), || {
908                let node = self.ivars().node;
909                let movement = unsafe { notification.userInfo() }
910                    .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
911                    .and_then(|n| n.downcast::<NSNumber>().ok())
912                    .map(|n| NSTextMovement(n.integerValue()))
913                    .unwrap_or(NSTextMovement::Other);
914                if movement == NSTextMovement::Return {
915                    emit(node, Event::Submitted);
916                } else {
917                    emit(node, Event::FocusChanged(false));
918                }
919            })
920        }
921    }
922);
923
924impl DayTarget {
925    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
926        let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
927        unsafe { msg_send![super(this), init] }
928    }
929}
930
931// ---------------------------------------------------------------------------
932// DayCursorOwner: the `.cursor()` decorator's tracking-area owner (docs/cursor.md)
933// ---------------------------------------------------------------------------
934
935struct CursorIvars {
936    /// The shape to set on `cursorUpdate:`; `None` leaves the platform's own choice.
937    cursor: RefCell<Option<Retained<NSCursor>>>,
938    /// `Cursor::None`: hide the pointer while it is inside, unhide on exit.
939    hidden: Cell<bool>,
940    /// Whether this owner is the one that hid the pointer (balanced by `unhide`).
941    hiding: Cell<bool>,
942}
943
944// AppKit only re-evaluates the pointer's shape on `cursorUpdate:`, which it sends to a
945// tracking area's owner when the pointer enters the area (and on request through
946// `invalidateCursorRectsForView:`). One owner per view keeps the view class untouched: a label,
947// a button, or a plain container all get the same treatment without subclassing. Nested areas
948// resolve by entry order: the innermost is entered last, so its shape is the one that stays.
949define_class!(
950    #[unsafe(super(NSObject))]
951    #[thread_kind = MainThreadOnly]
952    #[name = "DayCursorOwner"]
953    #[ivars = CursorIvars]
954    struct DayCursorOwner;
955
956    unsafe impl NSObjectProtocol for DayCursorOwner {}
957
958    impl DayCursorOwner {
959        #[unsafe(method(cursorUpdate:))]
960        fn cursor_update(&self, _event: &NSEvent) {
961            let iv = self.ivars();
962            if iv.hidden.get() {
963                if !iv.hiding.replace(true) {
964                    NSCursor::hide();
965                }
966                return;
967            }
968            if let Some(c) = iv.cursor.borrow().as_ref() {
969                c.set();
970            }
971        }
972
973        #[unsafe(method(mouseExited:))]
974        fn mouse_exited(&self, _event: &NSEvent) {
975            if self.ivars().hiding.replace(false) {
976                NSCursor::unhide();
977            }
978        }
979    }
980);
981
982impl DayCursorOwner {
983    fn new(mtm: MainThreadMarker) -> Retained<Self> {
984        let this = Self::alloc(mtm).set_ivars(CursorIvars {
985            cursor: RefCell::new(None),
986            hidden: Cell::new(false),
987            hiding: Cell::new(false),
988        });
989        unsafe { msg_send![super(this), init] }
990    }
991}
992
993/// The `NSCursor` for a [`Cursor`], or `None` where the platform's own choice should stand
994/// (`Cursor::None`, which the owner hides instead, and a native name AppKit does not have).
995/// AppKit has no wait, progress, help, or move shape, so those take the arrow; the zoom, frame
996/// (diagonal) resize, and column/row resize cursors arrived in macOS 15 and are probed by
997/// nav host, with the nearest older shape below it.
998// `resizeLeftRightCursor` and `resizeUpDownCursor` are deprecated in favor of the macOS 15
999// column/row resize cursors, which are probed above them; below 15 they are the shape.
1000#[allow(deprecated)]
1001fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1002    let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1003    Some(match c {
1004        Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1005        Cursor::Pointer => NSCursor::pointingHandCursor(),
1006        Cursor::Text => NSCursor::IBeamCursor(),
1007        Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1008        Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1009        Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1010        Cursor::Grabbing => NSCursor::closedHandCursor(),
1011        Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1012        Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1013        Cursor::Copy => NSCursor::dragCopyCursor(),
1014        Cursor::Alias => NSCursor::dragLinkCursor(),
1015        Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1016        Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1017        Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1018        Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1019        Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1020        Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1021            NSCursor::frameResizeCursorFromPosition_inDirections(
1022                NSCursorFrameResizePosition::TopRight,
1023                NSCursorFrameResizeDirections::All,
1024            )
1025        }
1026        Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1027            NSCursor::frameResizeCursorFromPosition_inDirections(
1028                NSCursorFrameResizePosition::TopLeft,
1029                NSCursorFrameResizeDirections::All,
1030            )
1031        }
1032        Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1033        Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1034        Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1035        Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1036        Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1037        Cursor::None => return None,
1038        Cursor::Native(name) => match &**name {
1039            "disappearingItem" => NSCursor::disappearingItemCursor(),
1040            "dragCopy" => NSCursor::dragCopyCursor(),
1041            "dragLink" => NSCursor::dragLinkCursor(),
1042            "contextualMenu" => NSCursor::contextualMenuCursor(),
1043            "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1044            _ => return None,
1045        },
1046    })
1047}
1048
1049/// Whether the NSEvent currently being dispatched ends a slider's interaction (see the
1050/// `ValueCommitted` emission in `DayTarget::action:`). AppKit gives a continuous slider no
1051/// "drag ended" callback, so the event that provoked the action is what says where in the gesture
1052/// we are: a mouse-up ends a drag, an arrow key moves one discrete step and is already settled,
1053/// and mouse-down/mouse-dragged are mid-gesture. No current event at all (a programmatic
1054/// `setDoubleValue:` that fires the action) is not a user commit either.
1055fn slider_value_settled() -> bool {
1056    let Some(mtm) = MainThreadMarker::new() else {
1057        return false;
1058    };
1059    let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1060        return false;
1061    };
1062    matches!(
1063        unsafe { event.r#type() },
1064        NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1065    )
1066}
1067
1068// ---------------------------------------------------------------------------
1069// DayTextField: NSTextField that reports focus gain (docs/focus.md)
1070// ---------------------------------------------------------------------------
1071
1072struct FieldIvars {
1073    node: NodeId,
1074}
1075
1076define_class!(
1077    #[unsafe(super(NSTextField))]
1078    #[thread_kind = MainThreadOnly]
1079    #[name = "DayTextField"]
1080    #[ivars = FieldIvars]
1081    struct DayTextField;
1082
1083    impl DayTextField {
1084        /// Focus gain. Key events go to the shared field editor, but the field itself receives
1085        /// `becomeFirstResponder` first, the reliable gain hook (`controlTextDidBeginEditing:`
1086        /// waits for the first keystroke). Loss comes from `controlTextDidEndEditing:` on the
1087        /// delegate.
1088        #[unsafe(method(becomeFirstResponder))]
1089        fn become_first_responder(&self) -> bool {
1090            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1091            if ok {
1092                field_gained_focus(self.ivars().node);
1093            }
1094            ok
1095        }
1096    }
1097);
1098
1099impl DayTextField {
1100    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1101        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1102        unsafe { msg_send![super(this), init] }
1103    }
1104}
1105
1106// The secure twin (docs/textfield.md). AppKit hides characters with a class, not a property:
1107// `NSSecureTextField` brings its own cell and field editor, which keep the text out of the
1108// pasteboard, the spelling checker and the accessibility value. A `text_field` that turns
1109// `secure` is rebuilt as this class (`set_input_traits`), with the same focus hook.
1110define_class!(
1111    #[unsafe(super(NSSecureTextField))]
1112    #[thread_kind = MainThreadOnly]
1113    #[name = "DaySecureTextField"]
1114    #[ivars = FieldIvars]
1115    struct DaySecureTextField;
1116
1117    impl DaySecureTextField {
1118        /// Focus gain, as on `DayTextField`.
1119        #[unsafe(method(becomeFirstResponder))]
1120        fn become_first_responder(&self) -> bool {
1121            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1122            if ok {
1123                field_gained_focus(self.ivars().node);
1124            }
1125            ok
1126        }
1127    }
1128);
1129
1130impl DaySecureTextField {
1131    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1132        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1133        unsafe { msg_send![super(this), init] }
1134    }
1135}
1136
1137thread_local! {
1138    /// A plain/secure class swap in flight (`set_input_traits`): focus moves from the old
1139    /// field to its replacement, which the app must not see as a focus change.
1140    static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1141}
1142
1143/// Report a text field's focus gain, unless it is a class swap handing focus to the
1144/// replacement of a field that already had it.
1145fn field_gained_focus(node: NodeId) {
1146    if FIELD_SWAP.with(|s| s.get()) {
1147        return;
1148    }
1149    // Guard only the sink dispatch: the responder change already happened, so a contained
1150    // panic must not flip the answer AppKit acts on.
1151    ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1152}
1153
1154/// The node a `text_field`'s view reports against, or `None` when the view is not one
1155/// (a label is an `NSTextField` too).
1156fn text_field_node(v: &NSView) -> Option<NodeId> {
1157    v.downcast_ref::<DayTextField>()
1158        .map(|f| f.ivars().node)
1159        .or_else(|| {
1160            v.downcast_ref::<DaySecureTextField>()
1161                .map(|f| f.ivars().node)
1162        })
1163}
1164
1165/// Build a `text_field`'s view, plain or secure, with its delegate wired and registered.
1166/// `realize` and the class swap in `set_input_traits` both come through here, so both classes
1167/// report text, submit and focus the same way against the same node.
1168fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1169    let target = DayTarget::new(mtm, node);
1170    // Up to `NSTextField` (the declared superclass of both), so the AsRef<NSView> bound on
1171    // `view_of` resolves and every `NSTextField` downcast sees either class.
1172    let tf: Retained<NSTextField> = if secure {
1173        Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1174    } else {
1175        Retained::into_super(DayTextField::new(mtm, node))
1176    };
1177    unsafe {
1178        tf.setEditable(true);
1179        tf.setBezeled(true);
1180        tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1181    }
1182    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1183    tf
1184}
1185
1186/// Whether `h` (a text field, or the field editor's client) holds its window's focus. A
1187/// focused `NSTextField`'s first responder is the shared field editor, so unwrap it back to
1188/// the field via its delegate.
1189fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1190    window.firstResponder().is_some_and(|fr| {
1191        if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
1192            return true;
1193        }
1194        fr.downcast::<NSText>().is_ok_and(|text| {
1195            unsafe { text.delegate() }
1196                .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
1197        })
1198    })
1199}
1200
1201/// An `NSTextContentType` constant by symbol name, or `None` on a system that predates it.
1202/// Looked up at run time because most of the vocabulary arrived in macOS 14: a direct
1203/// reference binds at launch, and one missing symbol would keep the whole app from starting
1204/// on an older system.
1205fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1206    unsafe extern "C" {
1207        fn dlsym(
1208            handle: *mut std::ffi::c_void,
1209            symbol: *const std::ffi::c_char,
1210        ) -> *mut std::ffi::c_void;
1211    }
1212    // <dlfcn.h>: search every image loaded in the process.
1213    const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1214    // SAFETY: `symbol` is NUL-terminated. Each name passed here is an AppKit
1215    // `NSString * const`, so a non-null result is the address of a pointer to an immortal
1216    // constant string.
1217    unsafe {
1218        let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1219        if slot.is_null() {
1220            None
1221        } else {
1222            (*slot).as_ref()
1223        }
1224    }
1225}
1226
1227/// Move a view-keyed entry to the view that replaces it.
1228fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1229    if let Some(v) = table.take(old) {
1230        table.insert(new, v);
1231    }
1232}
1233
1234/// A label is the shared field editor's delegate. AppKit does not forward
1235/// `textView:clickedOnLink:atIndex:` to an NSTextField's separate control delegate, so the
1236/// label itself must handle it to prevent the field editor from opening the target externally.
1237/// See Apple's "Working With the Field Editor" and docs/text-runs.md.
1238struct LabelIvars {
1239    node: NodeId,
1240    has_links: Cell<bool>,
1241    has_runs: Cell<bool>,
1242    selectable: Cell<bool>,
1243}
1244
1245define_class!(
1246    #[unsafe(super(NSTextField))]
1247    #[thread_kind = MainThreadOnly]
1248    #[name = "DayLabel"]
1249    #[ivars = LabelIvars]
1250    struct DayLabel;
1251
1252    impl DayLabel {
1253        #[unsafe(method_id(menuForEvent:))]
1254        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1255            ffi_guard::contain(None, || {
1256                if !self.isSelectable()
1257                    && let Some(menu) = inherited_context_menu(self, event)
1258                {
1259                    return menu;
1260                }
1261                unsafe { msg_send![super(self), menuForEvent: event] }
1262            })
1263        }
1264
1265        #[unsafe(method(drawRect:))]
1266        fn draw_rect(&self, dirty: NSRect) {
1267            // AppKit cannot propagate a table cell's background style through arbitrary
1268            // Day containers. Resolve selection at paint time so keyboard focus, window
1269            // activation, and cell reuse all use the actual native row state.
1270            let mut ancestor = unsafe { self.superview() };
1271            let mut selection_color = None;
1272            if !self.ivars().has_runs.get() {
1273                while let Some(view) = ancestor {
1274                    if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1275                        if unsafe { row.isSelected() } {
1276                            selection_color = Some(unsafe {
1277                                if row.isEmphasized() {
1278                                    objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1279                                } else {
1280                                    objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1281                                }
1282                            });
1283                        }
1284                        break;
1285                    }
1286                    ancestor = unsafe { view.superview() };
1287                }
1288            }
1289            let cell = unsafe { self.cell() }
1290                .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1291            if let (Some(color), Some(cell)) = (selection_color, cell) {
1292                let original = unsafe { cell.textColor() };
1293                // Mutate the cell only for this paint; changing the field would invalidate
1294                // the view again. Keep the app's normal color for deselection and reuse.
1295                unsafe {
1296                    cell.setTextColor(Some(&color));
1297                    let _: () = msg_send![super(self), drawRect: dirty];
1298                    cell.setTextColor(original.as_deref());
1299                }
1300            } else {
1301                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1302            }
1303        }
1304    }
1305
1306    unsafe impl NSObjectProtocol for DayLabel {}
1307    unsafe impl NSTextDelegate for DayLabel {}
1308
1309    unsafe impl NSTextViewDelegate for DayLabel {
1310        #[unsafe(method(textView:clickedOnLink:atIndex:))]
1311        fn clicked_on_link(
1312            &self,
1313            _tv: &NSTextView,
1314            link: &objc2::runtime::AnyObject,
1315            _index: usize,
1316        ) -> bool {
1317            ffi_guard::contain(true, || {
1318                // NSString targets stay verbatim (including #route); accept NSURL too.
1319                let url: Retained<NSString> = unsafe { msg_send![link, description] };
1320                emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1321                true // Handled: AppKit must never also open the target itself.
1322            })
1323        }
1324    }
1325);
1326
1327impl DayLabel {
1328    fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1329        let this = Self::alloc(mtm).set_ivars(LabelIvars {
1330            node,
1331            has_links: Cell::new(false),
1332            has_runs: Cell::new(false),
1333            selectable: Cell::new(false),
1334        });
1335        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1336        unsafe {
1337            this.setStringValue(&NSString::from_str(text));
1338            this.setEditable(false);
1339            this.setSelectable(false);
1340            this.setBordered(false);
1341            this.setBezeled(false);
1342            this.setDrawsBackground(false);
1343        }
1344        this
1345    }
1346
1347    fn set_links(&self, has_links: bool) {
1348        self.ivars().has_links.set(has_links);
1349        unsafe {
1350            self.setSelectable(has_links || self.ivars().selectable.get());
1351            self.setAllowsEditingTextAttributes(has_links);
1352        }
1353    }
1354}
1355
1356struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1357impl Drop for PanMonitor {
1358    fn drop(&mut self) {
1359        unsafe { NSEvent::removeMonitor(&self.0) };
1360    }
1361}
1362
1363// Escape closes a cover's window sheet, as it cancels any sheet on macOS (docs/cover.md
1364// "Modal sheet"): the cover hears it as its back request. A local monitor, because the key
1365// window's first responder may be a web view or a field that keeps Escape to itself. A sheet
1366// with its own sheet or alert over it, and app-modal panels, keep their Escape.
1367fn install_sheet_escape_monitor() {
1368    SHEET_ESCAPE_MONITOR.with(|slot| {
1369        if slot.borrow().is_some() {
1370            return;
1371        }
1372        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1373            let event = unsafe { raw.as_ref() };
1374            ffi_guard::contain(raw.as_ptr(), || {
1375                let Some(mtm) = MainThreadMarker::new() else {
1376                    return raw.as_ptr();
1377                };
1378                let escape = unsafe { event.charactersIgnoringModifiers() }
1379                    .is_some_and(|s| s.to_string() == "\u{1b}");
1380                let Some(window) = event.window(mtm).filter(|_| escape) else {
1381                    return raw.as_ptr();
1382                };
1383                let app = NSApplication::sharedApplication(mtm);
1384                if app.modalWindow().is_some() || window.attachedSheet().is_some() {
1385                    return raw.as_ptr();
1386                }
1387                match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
1388                    Some(node) => {
1389                        emit(
1390                            node,
1391                            Event::NavBack {
1392                                already_popped: false,
1393                            },
1394                        );
1395                        std::ptr::null_mut()
1396                    }
1397                    None => raw.as_ptr(),
1398                }
1399            })
1400        });
1401        let monitor = unsafe {
1402            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1403                objc2_app_kit::NSEventMask::KeyDown,
1404                &block,
1405            )
1406        };
1407        *slot.borrow_mut() = monitor.map(PanMonitor);
1408    });
1409}
1410
1411// A container pan observes horizontal wheel events over its descendants, including native
1412// scroll views. Leave vertical scrolling and canvas 2D pans to their existing handlers.
1413fn install_container_pan_monitor() {
1414    PAN_MONITOR.with(|slot| {
1415        if slot.borrow().is_some() {
1416            return;
1417        }
1418        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1419            let event = unsafe { raw.as_ref() };
1420            ffi_guard::contain(raw.as_ptr(), || {
1421                let dx = unsafe { event.scrollingDeltaX() };
1422                let dy = unsafe { event.scrollingDeltaY() };
1423                if dx.abs() <= dy.abs() {
1424                    return raw.as_ptr();
1425                }
1426                let Some(mtm) = MainThreadMarker::new() else {
1427                    return raw.as_ptr();
1428                };
1429                let Some(window) = event.window(mtm) else {
1430                    return raw.as_ptr();
1431                };
1432                let Some(content) = window.contentView() else {
1433                    return raw.as_ptr();
1434                };
1435                let point =
1436                    content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1437                let mut view = content.hitTest(point);
1438                while let Some(v) = view {
1439                    if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1440                        if v.downcast_ref::<DayCanvas>().is_some() {
1441                            return raw.as_ptr();
1442                        }
1443                        let raw_phase = unsafe { event.phase() };
1444                        let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1445                            day_spec::DragPhase::Began
1446                        } else if raw_phase.intersects(
1447                            objc2_app_kit::NSEventPhase::Ended
1448                                | objc2_app_kit::NSEventPhase::Cancelled,
1449                        ) {
1450                            day_spec::DragPhase::Ended
1451                        } else {
1452                            day_spec::DragPhase::Changed
1453                        };
1454                        let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1455                        emit(
1456                            node,
1457                            Event::Pan {
1458                                phase,
1459                                delta: Point::new(dx, dy),
1460                                location: Point::new(p.x, p.y),
1461                            },
1462                        );
1463                        return std::ptr::null_mut();
1464                    }
1465                    view = unsafe { v.superview() };
1466                }
1467                raw.as_ptr()
1468            })
1469        });
1470        *slot.borrow_mut() = unsafe {
1471            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1472                objc2_app_kit::NSEventMask::ScrollWheel,
1473                &block,
1474            )
1475        }
1476        .map(PanMonitor);
1477    });
1478}
1479
1480// ---------------------------------------------------------------------------
1481// DayFlipped: top-left-origin container view
1482// ---------------------------------------------------------------------------
1483
1484/// A `background(..)` fill: `(r, g, b, a, corner_radius)`, painted in `drawRect` with NSColor.
1485type Surface = (f64, f64, f64, f64, f64);
1486
1487#[derive(Default)]
1488struct FlippedIvars {
1489    surface: Cell<Option<Surface>>,
1490    /// SurfaceRole::SectionCard: `(radius,)`, drawn with a dynamic system fill resolved at
1491    /// draw time, so the card tracks light/dark appearance changes automatically.
1492    section_card: Cell<Option<f64>>,
1493    /// Paint the whole view with the dynamic window background before anything else: the
1494    /// inspector panel wrap (docs/inspector.md). The inspector NSSplitViewItem backs its pane
1495    /// with a vibrancy material, and the section cards' thin quaternary fill composites over
1496    /// it into near-black in dark mode (and the material itself captures black offscreen; see
1497    /// the sidebar-screenshot rule, docs/navigation.md). An opaque appearance-resolved
1498    /// backdrop gives the cards the same ground System Settings draws them on.
1499    pane_backdrop: Cell<bool>,
1500}
1501
1502define_class!(
1503    #[unsafe(super(NSView))]
1504    #[thread_kind = MainThreadOnly]
1505    #[name = "DayFlipped"]
1506    #[ivars = FlippedIvars]
1507    struct DayFlipped;
1508
1509    impl DayFlipped {
1510        #[unsafe(method_id(menuForEvent:))]
1511        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1512            ffi_guard::contain(None, || {
1513                inherited_context_menu(self, event)
1514                    .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1515            })
1516        }
1517
1518        #[unsafe(method(isFlipped))]
1519        fn is_flipped(&self) -> bool {
1520            true
1521        }
1522
1523        // Focus, and with it the keyboard (docs/focus.md): the canvas contract, opted into by
1524        // `Decorate::focusable`. A container never in FOCUSABLE_NODES behaves exactly as
1525        // before (refuses first responder, forwards every key).
1526        #[unsafe(method(acceptsFirstResponder))]
1527        fn accepts_first_responder(&self) -> bool {
1528            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1529            FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1530        }
1531
1532        // Clicking a focusable container focuses it, the way clicking a table does. The
1533        // gesture recognizers still see the press: this runs before `super`, which is what
1534        // forwards it to them.
1535        #[unsafe(method(mouseDown:))]
1536        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1537            if transfer::pressed(self, event) { return; }
1538            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1539            if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1540                && let Some(window) = self.window()
1541            {
1542                window.makeFirstResponder(Some(self));
1543            }
1544            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1545        }
1546
1547        #[unsafe(method(becomeFirstResponder))]
1548        fn become_first_responder(&self) -> bool {
1549            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1550            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1551                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1552            }
1553            true
1554        }
1555
1556        #[unsafe(method(resignFirstResponder))]
1557        fn resign_first_responder(&self) -> bool {
1558            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1559            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1560                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1561            }
1562            true
1563        }
1564
1565        /// The arrows, delivered here while this container is the first responder. Anything
1566        /// else (and every arrow when the app registered no key handler for the node) goes
1567        /// to `super`, which walks the responder chain exactly as it would have without us.
1568        #[unsafe(method(keyDown:))]
1569        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1570            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1571            let handled = ffi_guard::contain(false, || {
1572                let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
1573                    return false;
1574                };
1575                let Some(key) = key_name(event) else {
1576                    return false;
1577                };
1578                if !day_spec::keys::handled(node) {
1579                    return false;
1580                }
1581                emit(
1582                    node,
1583                    Event::Key(day_spec::KeyEvent {
1584                        key: key.to_string(),
1585                        modifiers: key_modifiers(event.modifierFlags()),
1586                    }),
1587                );
1588                true
1589            });
1590            if !handled {
1591                let _: () = unsafe { msg_send![super(self), keyDown: event] };
1592            }
1593        }
1594
1595        /// Show the attached context menu (docs/menus.md) explicitly rather than relying on
1596        /// `NSResponder`'s default `.menu` display: popping it ourselves is deterministic
1597        /// regardless of how the click threads through Day's container hierarchy.
1598        #[unsafe(method(rightMouseDown:))]
1599        fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1600            if let Some(menu) = self.menuForEvent(event) {
1601                unsafe {
1602                    objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
1603                };
1604            } else {
1605                let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
1606            }
1607        }
1608
1609        #[unsafe(method(drawRect:))]
1610        fn draw_rect(&self, _dirty: NSRect) {
1611            let paint = || {
1612                if self.ivars().pane_backdrop.get() {
1613                    let bounds = self.bounds();
1614                    unsafe {
1615                        // Resolved at draw time, like the section fill below, so the backdrop
1616                        // follows light/dark appearance changes automatically.
1617                        NSColor::windowBackgroundColor().setFill();
1618                        objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
1619                    }
1620                }
1621                if let Some(radius) = self.ivars().section_card.get() {
1622                    let bounds = self.bounds();
1623                    unsafe {
1624                        // quaternarySystemFill (macOS 14+) is the grouped-card material System
1625                        // Settings uses; older systems fall back to the control background.
1626                        let cls = objc2::class!(NSColor);
1627                        let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
1628                        let color: objc2::rc::Retained<NSColor> = if has {
1629                            msg_send![cls, quaternarySystemFillColor]
1630                        } else {
1631                            msg_send![cls, controlBackgroundColor]
1632                        };
1633                        color.setFill();
1634                        let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1635                            bounds, radius, radius,
1636                        );
1637                        path.fill();
1638                    }
1639                }
1640                if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
1641                    let bounds = self.bounds();
1642                    unsafe {
1643                        NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
1644                        let path = if radius > 0.0 {
1645                            objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1646                                bounds, radius, radius,
1647                            )
1648                        } else {
1649                            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
1650                        };
1651                        path.fill();
1652                    }
1653                }
1654            };
1655            // Paint under the standard counterpart of this view's appearance. Inside an
1656            // NSVisualEffectView subtree (the inspector pane) the effective appearance is
1657            // a vibrant one (NSAppearanceNameVibrantDark/-Light), and the system fills'
1658            // vibrant variants are opaque blend colors that only composite correctly in an
1659            // `allowsVibrancy` view: drawn plainly, dark-mode quaternary fill comes out
1660            // near-black instead of lightening. Resolving under aqua/darkAqua gives exactly
1661            // the fills System Settings draws with, and re-resolves on every theme change
1662            // (this runs per draw, and appearance flips redraw).
1663            unsafe {
1664                let names = objc2_foundation::NSArray::from_slice(&[
1665                    objc2_app_kit::NSAppearanceNameAqua,
1666                    objc2_app_kit::NSAppearanceNameDarkAqua,
1667                ]);
1668                let standard = self
1669                    .effectiveAppearance()
1670                    .bestMatchFromAppearancesWithNames(&names)
1671                    .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
1672                match standard {
1673                    Some(appearance) => {
1674                        let block = block2::StackBlock::new(paint);
1675                        appearance.performAsCurrentDrawingAppearance(&block);
1676                    }
1677                    None => paint(),
1678                }
1679            }
1680        }
1681    }
1682    unsafe impl NSObjectProtocol for DayFlipped {}
1683    unsafe impl NSDraggingSource for DayFlipped {
1684        #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
1685        fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
1686    }
1687    impl DayFlipped {
1688        #[unsafe(method(mouseDragged:))]
1689        fn transfer_dragged(&self, event: &NSEvent) {
1690            if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
1691        }
1692        #[unsafe(method(draggingEntered:))]
1693        fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1694        #[unsafe(method(draggingUpdated:))]
1695        fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1696        #[unsafe(method(performDragOperation:))]
1697        fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
1698    }
1699
1700);
1701
1702impl DayFlipped {
1703    fn new(mtm: MainThreadMarker) -> Retained<Self> {
1704        let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
1705        unsafe { msg_send![super(this), init] }
1706    }
1707
1708    /// Apply a `background`/`corner_radius` surface. The fill (rounded by `corner_radius`) is
1709    /// drawn in `drawRect` with NSColor, not via the layer's `backgroundColor`, whose CGColorRef
1710    /// argument objc2's `msg_send` cannot type-check. A rounded child clip does use the CALayer
1711    /// (`cornerRadius` + `masksToBounds` are a CGFloat + `BOOL`, which are fine).
1712    /// SurfaceRole::SectionCard: the fill resolves dynamically in drawRect (theme-adaptive).
1713    fn set_section_card(&self, corner_radius: f64) {
1714        self.ivars().section_card.set(Some(corner_radius));
1715        unsafe {
1716            let _: () = msg_send![self, setNeedsDisplay: true];
1717        }
1718    }
1719
1720    /// Opaque window-background backdrop (the inspector panel wrap; see `FlippedIvars`).
1721    fn set_pane_backdrop(&self) {
1722        self.ivars().pane_backdrop.set(true);
1723        unsafe {
1724            let _: () = msg_send![self, setNeedsDisplay: true];
1725        }
1726    }
1727
1728    fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
1729        self.ivars()
1730            .surface
1731            .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
1732        unsafe {
1733            let _: () = msg_send![self, setNeedsDisplay: true];
1734            if clips || corner_radius > 0.0 {
1735                let _: () = msg_send![self, setWantsLayer: true];
1736                let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
1737                if !layer.is_null() {
1738                    let _: () = msg_send![layer, setCornerRadius: corner_radius];
1739                    let _: () = msg_send![layer, setMasksToBounds: true];
1740                }
1741            }
1742        }
1743    }
1744}
1745
1746// ---------------------------------------------------------------------------
1747// DayCanvas — a flipped view replaying the Day display list in drawRect (§11)
1748// ---------------------------------------------------------------------------
1749
1750struct CanvasIvars;
1751
1752define_class!(
1753    #[unsafe(super(NSView))]
1754    #[thread_kind = MainThreadOnly]
1755    #[name = "DayCanvas"]
1756    #[ivars = CanvasIvars]
1757    struct DayCanvas;
1758
1759    impl DayCanvas {
1760        #[unsafe(method(isFlipped))]
1761        fn is_flipped(&self) -> bool {
1762            true
1763        }
1764
1765        /// A summon-time context menu (docs/menus.md): built when the right-click lands,
1766        /// from the provider `set_context_menu_fn` registered — so a canvas can select what
1767        /// is under the pointer and offer commands for that selection.
1768        #[unsafe(method_id(menuForEvent:))]
1769        fn menu_for_event(
1770            &self,
1771            event: &objc2_app_kit::NSEvent,
1772        ) -> Option<Retained<NSMenu>> {
1773            let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
1774            let Some(f) = f else {
1775                return unsafe { msg_send![super(self), menuForEvent: event] };
1776            };
1777            // Guarded: the provider is app code (it usually re-selects, then builds).
1778            ffi_guard::contain(None, || {
1779                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1780                let items = f(day_spec::Point::new(p.x, p.y));
1781                if items.is_empty() {
1782                    return None;
1783                }
1784                Some(build_ns_menu(self.mtm(), "", &items))
1785            })
1786        }
1787
1788        // Focus, and with it the keyboard (docs/focus.md, docs/menus.md). A canvas is the one
1789        // built-in piece with no native control under it, so nothing else would ever make it
1790        // the first responder — and without that, arrow keys aimed at what it draws could only
1791        // be caught by watching the whole app.
1792        #[unsafe(method(acceptsFirstResponder))]
1793        fn accepts_first_responder(&self) -> bool {
1794            true
1795        }
1796
1797        // Clicking a canvas focuses it, the way clicking a table or a text field does. The
1798        // gesture recognizers (tap/drag) still see the press — this runs before `super`, which
1799        // is what forwards it to them.
1800        #[unsafe(method(mouseDown:))]
1801        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1802            if let Some(window) = self.window() {
1803                window.makeFirstResponder(Some(self));
1804            }
1805            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1806        }
1807
1808        // Report focus both ways, so `.focused(signal)` binds two-way and dayscript's
1809        // `assert_focused` can see it.
1810        #[unsafe(method(becomeFirstResponder))]
1811        fn become_first_responder(&self) -> bool {
1812            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1813            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1814                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1815            }
1816            true
1817        }
1818
1819        #[unsafe(method(resignFirstResponder))]
1820        fn resign_first_responder(&self) -> bool {
1821            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1822            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1823                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1824            }
1825            true
1826        }
1827
1828        /// The arrows, delivered to this canvas because it is the first responder. Anything
1829        /// else — and every arrow when the app registered no handler for this node — goes to
1830        /// `super`, which walks the responder chain exactly as it would have without us.
1831        #[unsafe(method(keyDown:))]
1832        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1833            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1834            let handled = ffi_guard::contain(false, || {
1835                let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
1836                    return false;
1837                };
1838                let Some(key) = key_name(event) else {
1839                    return false;
1840                };
1841                // A canvas nobody asked keys from does not get to keep them: an enclosing
1842                // scroll view still scrolls, and an unclaimed key still beeps the way the
1843                // platform means it to.
1844                if !day_spec::keys::handled(node) {
1845                    return false;
1846                }
1847                emit(
1848                    node,
1849                    Event::Key(day_spec::KeyEvent {
1850                        key: key.to_string(),
1851                        modifiers: key_modifiers(event.modifierFlags()),
1852                    }),
1853                );
1854                true
1855            });
1856            if !handled {
1857                let _: () = unsafe { msg_send![super(self), keyDown: event] };
1858            }
1859        }
1860
1861        #[unsafe(method(drawRect:))]
1862        fn draw_rect(&self, _dirty: NSRect) {
1863            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1864            let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
1865            paint_ops(&ops);
1866        }
1867
1868        /// Hover entry/motion/exit (docs/canvas.md "Interaction"). The tracking area is installed
1869        /// by `enable_gesture`; `updateTrackingAreas` below keeps it the size of the view.
1870        #[unsafe(method(mouseEntered:))]
1871        fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
1872            self.report_hover(event, day_spec::DragPhase::Began);
1873        }
1874
1875        #[unsafe(method(mouseMoved:))]
1876        fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
1877            self.report_hover(event, day_spec::DragPhase::Changed);
1878        }
1879
1880        #[unsafe(method(mouseExited:))]
1881        fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
1882            self.report_hover(event, day_spec::DragPhase::Ended);
1883        }
1884
1885        #[unsafe(method(scrollWheel:))]
1886        fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
1887            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1888            let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
1889                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
1890                return;
1891            };
1892            ffi_guard::contain((), || {
1893                // Trackpads bracket a pan with phases; a discrete wheel tick has none and
1894                // arrives as a lone Changed — exactly the Event::Pan contract.
1895                let raw = unsafe { event.phase() };
1896                let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
1897                    day_spec::DragPhase::Began
1898                } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
1899                    || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
1900                {
1901                    day_spec::DragPhase::Ended
1902                } else {
1903                    day_spec::DragPhase::Changed
1904                };
1905                let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
1906                    event.scrollingDeltaY()
1907                });
1908                let win = unsafe { event.locationInWindow() };
1909                let loc = self.convertPoint_fromView(win, None);
1910                emit(
1911                    node,
1912                    Event::Pan {
1913                        phase,
1914                        delta,
1915                        location: Point::new(loc.x, loc.y),
1916                    },
1917                );
1918            })
1919        }
1920    }
1921);
1922
1923impl DayCanvas {
1924    fn new(mtm: MainThreadMarker) -> Retained<Self> {
1925        let this = Self::alloc(mtm).set_ivars(CanvasIvars);
1926        unsafe { msg_send![super(this), init] }
1927    }
1928
1929    /// One hover phase, reported to whichever node asked for it (docs/canvas.md "Interaction").
1930    ///
1931    /// `mouseEntered:`/`mouseExited:` are scoped by the tracking area, but **`mouseMoved:` is
1932    /// not**: it walks the responder chain, so a focused canvas hears about motion anywhere in
1933    /// its window — including outside itself. Hence the bounds test, without which a canvas
1934    /// reports a hover for a pointer that is nowhere near it (measured: a pointer parked outside
1935    /// the window entirely still produced hover positions).
1936    fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
1937        let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1938        let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
1939            return;
1940        };
1941        ffi_guard::contain((), || {
1942            let win = unsafe { event.locationInWindow() };
1943            let loc = self.convertPoint_fromView(win, None);
1944            let b = self.bounds();
1945            let inside = loc.x >= b.origin.x
1946                && loc.x <= b.origin.x + b.size.width
1947                && loc.y >= b.origin.y
1948                && loc.y <= b.origin.y + b.size.height;
1949            // An exit is reported wherever it happens — that is the point of it — but a move
1950            // outside the view is not this view's hover.
1951            if !inside && phase != day_spec::DragPhase::Ended {
1952                return;
1953            }
1954            emit(
1955                node,
1956                Event::Hover {
1957                    phase,
1958                    location: Point::new(loc.x, loc.y),
1959                },
1960            );
1961        });
1962    }
1963}
1964
1965/// The tracking area a hovering canvas needs. `InVisibleRect` makes it follow the view's bounds,
1966/// so there is no rect to keep in step with layout; `ActiveInKeyWindow` matches the cursor areas
1967/// already installed here — a background window does not report hovers.
1968fn install_tracking_area(h: &NSView) {
1969    let opts = NSTrackingAreaOptions::MouseEnteredAndExited
1970        | NSTrackingAreaOptions::MouseMoved
1971        | NSTrackingAreaOptions::ActiveInKeyWindow
1972        | NSTrackingAreaOptions::InVisibleRect;
1973    let any: &objc2::runtime::AnyObject = h;
1974    let area = unsafe {
1975        NSTrackingArea::initWithRect_options_owner_userInfo(
1976            NSTrackingArea::alloc(),
1977            NSRect::ZERO,
1978            opts,
1979            Some(any),
1980            None,
1981        )
1982    };
1983    unsafe { h.addTrackingArea(&area) };
1984}
1985
1986// ---------------------------------------------------------------------------
1987// DayGesture — tap/drag recognizer target, node-id keyed (docs/shapes.md)
1988// ---------------------------------------------------------------------------
1989
1990struct GestureIvars {
1991    node: NodeId,
1992    kind: day_spec::GestureKind,
1993}
1994
1995define_class!(
1996    #[unsafe(super(NSObject))]
1997    #[thread_kind = MainThreadOnly]
1998    #[name = "DayGesture"]
1999    #[ivars = GestureIvars]
2000    struct DayGesture;
2001
2002    unsafe impl NSObjectProtocol for DayGesture {}
2003
2004    impl DayGesture {
2005        #[unsafe(method(fire:))]
2006        fn fire(&self, g: &NSGestureRecognizer) {
2007            ffi_guard::contain((), || {
2008                let node = self.ivars().node;
2009                let view = g.view();
2010                let loc = g.locationInView(view.as_deref());
2011                let at = Point::new(loc.x, loc.y);
2012                let phase = match g.state() {
2013                    NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
2014                    NSGestureRecognizerState::Ended
2015                    | NSGestureRecognizerState::Cancelled
2016                    | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
2017                    _ => day_spec::DragPhase::Changed,
2018                };
2019                let obj: &objc2::runtime::AnyObject = g.as_ref();
2020                match self.ivars().kind {
2021                    day_spec::GestureKind::Drag => {
2022                        let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
2023                            let t = unsafe { pan.translationInView(view.as_deref()) };
2024                            Point::new(t.x, t.y)
2025                        } else {
2026                            Point::ZERO
2027                        };
2028                        emit(node, Event::Drag { phase, location: at, translation });
2029                    }
2030                    day_spec::GestureKind::Pinch => {
2031                        // Cumulative since Began: `magnification` is the total delta (0 =
2032                        // unchanged), and Day's contract wants a factor.
2033                        let scale = if let Some(m) =
2034                            obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
2035                        {
2036                            1.0 + unsafe { m.magnification() }
2037                        } else {
2038                            1.0
2039                        };
2040                        emit(node, Event::Pinch { phase, scale, location: at });
2041                    }
2042                    _ => emit(node, Event::Tap(at)),
2043                }
2044            })
2045        }
2046    }
2047);
2048
2049impl DayGesture {
2050    fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2051        let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2052        unsafe { msg_send![super(this), init] }
2053    }
2054}
2055
2056// ---------------------------------------------------------------------------
2057// Navigation (docs/navigation.md): NSSplitView host, sidebar + detail panes.
2058// Page FRAMES are pane-owned (autoresized); Day lays content inside the size each
2059// page reports from setFrameSize:. Day's set_frame on pages is skipped.
2060// ---------------------------------------------------------------------------
2061
2062/// The stack presentation's back header (desktop has no system back affordance — this bar
2063/// gives a pushed page its way out, like AdwNavigationView's header on GTK). Hidden at root.
2064struct NavHeader {
2065    bar: Retained<NSView>,
2066    title: Retained<NSTextField>,
2067    /// Title per stack level (index 0 = root); the field shows the last.
2068    titles: Vec<String>,
2069    _target: Retained<DayTarget>,
2070}
2071
2072/// Height of the stack-nav back header while a pushed page is showing.
2073const NAV_HEADER_H: f64 = 34.0;
2074
2075// Drag limits for both draggable panes come from day-spec (`NAV_SIDEBAR_MIN_W` and friends): a
2076// sidebar NSSplitViewItem enforces them itself, which is why the divider no longer needs
2077// restoring by hand after every window resize.
2078use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2079
2080/// The content-list width to place divider 1 at, once, the first time the pane is showing —
2081/// `None` when the pane is collapsed or has already been placed. Latches on the way out, so the
2082/// two callers (the first frame pass, and the patch that reveals the pane) cannot both spend it.
2083fn take_list_placement(state: &mut NavState) -> Option<f64> {
2084    if !state.list_visible || state.list_positioned {
2085        return None;
2086    }
2087    state.list_positioned = true;
2088    state.list_width
2089}
2090
2091/// A tabs host's `NSTabView` margins inside its pane: the sides and the foot, and the top —
2092/// deeper, since the tabs themselves stand about a segment's height above the bezel.
2093const NAV_TABVIEW_INSET: f64 = 12.0;
2094const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2095
2096/// The `NavPresentation::Tabs` container: a real `NSTabView` — the Mac's own tab control, top
2097/// tabs on a bezel — whose items own the detail pages. The page frames stay native-owned
2098/// exactly as in a split: the tab view frames the selected item's view, and the page's
2099/// `setFrameSize:` reports it. The labels come from the NAV_MENU's rows, which arrive after
2100/// the pages' host (day-core mounts top-down: the rows page joins the host before its menu is
2101/// built), so `adopt_menu_for_tabs` runs when the menu is inserted and whenever its rows are
2102/// rebuilt.
2103///
2104/// Until 2026-09-12 this was an `NSSegmentedControl` docked at the foot, built from the rows
2105/// page's menu at the moment that page was inserted — before the menu existed — so no bar was
2106/// ever built and a tabs host showed its first page alone.
2107struct TabHost {
2108    view: Retained<objc2_app_kit::NSTabView>,
2109    /// The delegate reporting a native tab pick against the NAV_MENU's node; set once the menu
2110    /// is known.
2111    target: Option<Retained<DayTarget>>,
2112}
2113
2114thread_local! {
2115    /// A Day-driven tab selection in flight (`NavPatch::Select`, a label sync): the tab view's
2116    /// delegate must not echo it back as `SelectionChanged`.
2117    static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2118}
2119
2120/// Give the tab view its labels from the rows, and its selection. Rows and items are
2121/// index-aligned (destination `i` is item `i`); a count mismatch mid-rebuild labels what both
2122/// have.
2123fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2124    unsafe {
2125        let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2126        for (i, title) in titles.iter().enumerate().take(n) {
2127            tabs.view
2128                .tabViewItemAtIndex(i as isize)
2129                .setLabel(&NSString::from_str(title));
2130        }
2131        if n > 0 {
2132            TAB_PICK_SUPPRESS.with(|s| s.set(true));
2133            tabs.view
2134                .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2135            TAB_PICK_SUPPRESS.with(|s| s.set(false));
2136        }
2137    }
2138}
2139
2140/// A NAV_MENU reached a tabs host (its rows page sits in the host's collapsed sidebar pane):
2141/// the menu's rows become the tab labels and its node the delegate's target. Walks up from the
2142/// menu, so the innermost host — the one whose rows these are — is the one that takes them.
2143fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2144    let Some((titles, node)) = NAV_MENUS.with(|m| {
2145        m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2146            let ivars = d.ivars();
2147            (
2148                ivars
2149                    .items
2150                    .borrow()
2151                    .iter()
2152                    .map(|s| s.to_string())
2153                    .collect::<Vec<String>>(),
2154                ivars.node,
2155            )
2156        })
2157    }) else {
2158        return;
2159    };
2160    let mut up = unsafe { menu.superview() };
2161    while let Some(v) = up {
2162        let reached = NAV_STATE.with(|m| {
2163            let mut m = m.borrow_mut();
2164            let Some(s) = m.get_mut(&ptr_of(&v)) else {
2165                return false;
2166            };
2167            let selected = s.selected;
2168            if let Some(tabs) = s.tabs.as_mut() {
2169                if tabs.target.is_none() {
2170                    let target = DayTarget::new(mtm, node);
2171                    unsafe {
2172                        tabs.view
2173                            .setDelegate(Some(ProtocolObject::from_ref(&*target)))
2174                    };
2175                    tabs.target = Some(target);
2176                }
2177                sync_tab_labels(tabs, &titles, selected);
2178            }
2179            true
2180        });
2181        if reached {
2182            return;
2183        }
2184        up = unsafe { v.superview() };
2185    }
2186}
2187
2188struct NavState {
2189    sidebar_wrap: Retained<NSView>,
2190    detail_wrap: Retained<NSView>,
2191    /// The container behind the host view. A view holds NO strong reference to its controller,
2192    /// and the split view controller is what owns the items, their holding priorities, the
2193    /// sidebar's material and the split's delegate duties — so it has to be retained here or
2194    /// the sidebar loses its treatment the moment this realize returns.
2195    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2196    /// The sidebar item, for the `SidebarToggle` duty (docs/toolbars.md). AppKit's own
2197    /// `NSToolbarToggleSidebarItem` reaches the controller through the responder chain; this is
2198    /// the path dayscript and any non-toolbar caller take.
2199    sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2200    /// The content-list pane (docs/navigation.md), `Some` only on a host whose
2201    /// `NavProps::list_width` was set: the wrap its `Pane::List` page fills, and the
2202    /// `contentList` split item `NavPatch::ListVisible` collapses. The pane PERSISTS through
2203    /// every presentation (`Cap::NavContentList` = Native) — a narrow window collapses the
2204    /// sidebar and keeps the list, exactly as a narrow Mail.app does.
2205    list_wrap: Option<Retained<NSView>>,
2206    list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2207    /// The app's requested content-list width (`NavProps::list_width`) — applied once, at the
2208    /// first frame pass, by placing divider 1 (see `set_frame`).
2209    list_width: Option<f64>,
2210    /// Whether the content-list pane is showing (`NavProps::list_visible`, then
2211    /// `NavPatch::ListVisible`). Placing divider 1 for a pane that is collapsed is what re-opens
2212    /// it, so both placement paths ask first.
2213    list_visible: bool,
2214    /// Whether divider 1 has been placed at the app's requested width yet. Separate from
2215    /// `positioned` because the pane may not exist on screen when the first frame pass runs: an
2216    /// app opening on a full-width destination has nothing to size then, and spending the
2217    /// one-time placement there is what left the list at the solver's own width when it did
2218    /// appear.
2219    list_positioned: bool,
2220    /// Detail pages in stack order (the sidebar page is not in here in split mode; in stack
2221    /// mode `split == false`, the root page is here too, so push/pop visibility covers it).
2222    pages: Vec<Retained<NSView>>,
2223    /// The host's sidebar page, once it has one — what a re-present moves between the sidebar
2224    /// pane and the head of `pages` (docs/size-classes.md).
2225    sidebar_page: Option<Retained<NSView>>,
2226    /// The content-list pane's page, re-framed when the pane is first revealed: it was inserted
2227    /// into a collapsed wrap, where autoresizing can only keep it at zero.
2228    list_page: Option<Retained<NSView>>,
2229    positioned: bool,
2230    /// Which of the four presentations is drawn right now (docs/size-classes.md). All of them are
2231    /// the same `NSSplitViewController`: a stack is that split with its sidebar collapsed, a rail
2232    /// is it with a narrow one, and a tab bar is a collapsed sidebar plus the bottom bar below.
2233    presentation: NavPresentation,
2234    /// The detail page on screen, as an index into `pages`. Maintained by every patch that
2235    /// changes it — push, pop and select alike — so a re-present can carry it across.
2236    selected: usize,
2237    /// The tab view (`NavPresentation::Tabs` only), holding the detail pages as its items and
2238    /// labeled from the same rows the sidebar's outline view shows; a pick emits
2239    /// `SelectionChanged` against the same NAV_MENU node.
2240    tabs: Option<TabHost>,
2241    /// Back header (stack presentation only).
2242    header: Option<NavHeader>,
2243    /// The host's own title, kept so a re-present into a stack can seed a fresh back header
2244    /// with the same root title the initial build would have used.
2245    root_title: String,
2246    /// The host's node, for the same reason — a back header's button targets it.
2247    node: NodeId,
2248    /// How far the host reaches up under the window's title bar (see `pane_under_title_bar`):
2249    /// the strip each pane's wrap is kept below. Zero for a host that does not start at the top
2250    /// of a pinned window.
2251    title_strip: f64,
2252}
2253
2254/// A split item's view: a transparent pane that runs the item's full height, with `wrap` (the
2255/// view Day's pages and the rest of this backend frame themselves against) inside it.
2256///
2257/// `NSSplitViewController` expects its split view to reach the top of a full-size-content window
2258/// and lays its title-bar treatment over the top of every item: a title-bar background, and on
2259/// macOS 26 and later the frosted scroll pocket. Day pins its content below the title bar
2260/// (`pin_below_title_bar`), so a split framed where Day lays it out put that treatment over the
2261/// first strip of every page instead, blurring a detail page's heading. The host is framed up
2262/// under the bar instead (`set_frame`), and each wrap is held below the strip inside its pane, so
2263/// the treatment lands on the bar, the sidebar's material runs to the top of the window as
2264/// `allowsFullHeightLayout` intends, and every page still starts where Day laid it out.
2265fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2266    let pane = view_of(DayFlipped::new(mtm));
2267    unsafe {
2268        wrap.setFrame(pane.bounds());
2269        wrap.setAutoresizingMask(
2270            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2271                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2272        );
2273        pane.addSubview(wrap);
2274    }
2275    pane
2276}
2277
2278/// Hold `wrap` `strip` points below the top of the pane that holds it.
2279fn place_below_strip(wrap: &NSView, strip: f64) {
2280    let Some(pane) = (unsafe { wrap.superview() }) else {
2281        return;
2282    };
2283    let b = pane.bounds();
2284    unsafe {
2285        wrap.setFrame(NSRect::new(
2286            NSPoint::new(0.0, strip),
2287            NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2288        ))
2289    };
2290}
2291
2292/// The stack presentation's back header: a chevron + centered title docked above the pages,
2293/// hidden at the root. Desktop has no system back affordance, so a pushed page carries its own
2294/// way out (docs/navigation.md).
2295///
2296/// Built here rather than inline because a host that RE-PRESENTS into a stack needs one at that
2297/// moment (docs/size-classes.md), and a header that differed from the one a stack-at-launch host
2298/// gets would be a second shape to keep in step.
2299fn build_nav_header(
2300    mtm: MainThreadMarker,
2301    id: NodeId,
2302    detail_wrap: &NSView,
2303    root_title: &str,
2304) -> NavHeader {
2305    let bar = view_of(DayFlipped::new(mtm));
2306    let target = DayTarget::new(mtm, id);
2307    let back = unsafe {
2308        // Invariant: NSImageNameGoBackTemplate is one of AppKit's own named images, present
2309        // on every macOS release this backend builds for.
2310        let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2311            .expect("NSGoBackTemplate");
2312        let tobj: &objc2::runtime::AnyObject = target.as_ref();
2313        objc2_app_kit::NSButton::buttonWithImage_target_action(
2314            &img,
2315            Some(tobj),
2316            Some(sel!(navBack:)),
2317            mtm,
2318        )
2319    };
2320    let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2321    unsafe {
2322        back.setFrame(NSRect::new(
2323            NSPoint::new(6.0, 4.0),
2324            NSSize::new(30.0, NAV_HEADER_H - 8.0),
2325        ));
2326        title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2327        title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2328        title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2329        title.setFrame(NSRect::new(
2330            NSPoint::new(44.0, 9.0),
2331            NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2332        ));
2333        title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2334        bar.setFrame(NSRect::new(
2335            NSPoint::new(0.0, 0.0),
2336            NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2337        ));
2338        bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2339        bar.addSubview(&back);
2340        bar.addSubview(&title);
2341        bar.setHidden(true);
2342        detail_wrap.addSubview(&bar);
2343    }
2344    NavHeader {
2345        bar,
2346        title,
2347        titles: vec![root_title.to_string()],
2348        _target: target,
2349    }
2350}
2351
2352/// The frame a stack page occupies inside the detail wrap: full bounds at the root, inset below
2353/// the back header while a pushed page is showing. (A tabs host's pages are framed by its
2354/// `NSTabView`, never through here.)
2355fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
2356    let b = wrap.bounds();
2357    let top = if header_visible { NAV_HEADER_H } else { 0.0 };
2358    NSRect::new(
2359        NSPoint::new(0.0, top),
2360        NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
2361    )
2362}
2363
2364/// The row titles and the NAV_MENU node of the menu inside `page`, if it has one.
2365///
2366/// The tab bar needs the same rows the sidebar shows, and they arrive at the NAV_MENU rather
2367/// than at the host. Rather than plumb a second copy through the props, this walks down to the
2368/// menu that is already there — the sidebar page is Day-built and shallow, so the search is a
2369/// handful of views — and reads the titles it has stored for its own outline view.
2370fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
2371    fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
2372        if out.is_some() {
2373            return;
2374        }
2375        let found = NAV_MENUS.with(|m| {
2376            m.borrow()
2377                .get(&(v as *const NSView as usize))
2378                .map(|(_, d)| {
2379                    let ivars = d.ivars();
2380                    (
2381                        ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
2382                        ivars.node,
2383                    )
2384                })
2385        });
2386        if found.is_some() {
2387            *out = found;
2388            return;
2389        }
2390        for sub in unsafe { v.subviews() }.iter() {
2391            walk(&sub, out);
2392        }
2393    }
2394    let mut out = None;
2395    walk(page, &mut out);
2396    out
2397}
2398
2399/// Apply a presentation to the sidebar split item. All four are the same item at a different
2400/// thickness or collapsed outright, which is why a morph never rebuilds the split.
2401fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
2402    let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
2403    unsafe {
2404        item.setCanCollapse(shown);
2405        item.setCollapsed(!shown);
2406        match pres {
2407            NavPresentation::Split => {
2408                item.setAllowsFullHeightLayout(true);
2409                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2410                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2411            }
2412            // macOS has no rail: nothing in AppKit is a vertical strip of icon-only
2413            // destinations, and a source list pinned to icon width just truncates every row to an
2414            // ellipsis. `NavPresentation::Rail` is explicitly ROUNDABLE for exactly this case, so
2415            // it lands on the neighbor a Mac does have — an ordinary sidebar. Windows rounds the
2416            // other way (`PaneDisplayMode = LeftCompact` is a real rail there).
2417            NavPresentation::Rail => {
2418                item.setAllowsFullHeightLayout(true);
2419                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2420                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2421            }
2422            // Zero the thickness bounds before collapsing takes effect, or the pane keeps a
2423            // minimum width and the detail never reaches the window edge.
2424            NavPresentation::Stack | NavPresentation::Tabs => {
2425                item.setMinimumThickness(0.0);
2426                item.setMaximumThickness(0.0);
2427            }
2428        }
2429    }
2430}
2431
2432/// Show/hide the stack-nav back header for the given page stack and re-frame the pages under
2433/// it. The header shows exactly while a pushed page (depth ≥ 1 above the root) is on top; each
2434/// page's `DayNavPage::setFrameSize` reports the new size so Day re-lays its content.
2435/// The split view of the navigation host in `window` that has a content-list pane, for the
2436/// tracking separator pinned to its second divider (docs/toolbars.md).
2437pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
2438    NAV_STATE.with(|m| {
2439        m.borrow()
2440            .values()
2441            .find(|st| {
2442                st.list_item.is_some()
2443                    && st
2444                        .sidebar_wrap
2445                        .window()
2446                        .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
2447            })
2448            .map(|st| unsafe { st._split_vc.splitView() })
2449    })
2450}
2451
2452fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
2453    let visible = pages.len() >= 2;
2454    hdr.bar.setHidden(!visible);
2455    unsafe {
2456        hdr.title.setStringValue(&NSString::from_str(
2457            hdr.titles.last().map(String::as_str).unwrap_or(""),
2458        ));
2459    }
2460    let frame = nav_page_frame(wrap, visible);
2461    for page in pages {
2462        unsafe { page.setFrame(frame) };
2463    }
2464}
2465
2466/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
2467/// chrome changes but the pages do not.
2468///
2469/// Both presentations already share one `NSSplitViewController` — a stack is the same split with
2470/// its sidebar item collapsed to zero thickness — so the morph is three moves, and none of them
2471/// touches a page's CONTENT:
2472///
2473/// 1. the sidebar item collapses or expands (AppKit animates it and re-runs the titlebar
2474///    separator on its own),
2475/// 2. the sidebar PAGE moves between the sidebar wrap and the head of the detail stack,
2476/// 3. the back header appears or hides, since only a stack has one.
2477///
2478/// `addSubview` re-parents a view rather than rebuilding it, so every page keeps its subtree,
2479/// its scroll position, and its first responder across the move.
2480fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
2481    let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
2482        NAV_STATE.with(|m| {
2483            let st = m.borrow();
2484            let s = st.get(&ptr_of(host))?;
2485            Some((
2486                s.sidebar_page.clone(),
2487                s.detail_wrap.clone(),
2488                s.sidebar_wrap.clone(),
2489                s.sidebar_item.clone(),
2490                s.presentation,
2491                s.root_title.clone(),
2492                s.node,
2493                s.selected,
2494            ))
2495        })
2496    else {
2497        return;
2498    };
2499    if was == next {
2500        return;
2501    }
2502    apply_sidebar_item(&sidebar_item, next);
2503    // Settle the split now rather than at the next natural layout pass. `setCollapsed` marks the
2504    // split view as needing layout; without this the pane keeps its old width for one more frame,
2505    // which the dayscript screenshot seam captures (it renders the window offscreen the instant
2506    // the patch returns) and which a user crossing a breakpoint sees as a stutter.
2507    NAV_STATE.with(|m| {
2508        if let Some(s) = m.borrow().get(&ptr_of(host)) {
2509            unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
2510        }
2511    });
2512    // A stack needs a back header; nothing else may show one. Built on demand and kept
2513    // afterwards — rebuilding it on every morph would leak a target per crossing.
2514    let stacked = next == NavPresentation::Stack;
2515    let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
2516    if stacked && header.is_none() {
2517        header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
2518    }
2519    if let Some(hdr) = header.as_ref() {
2520        hdr.bar.setHidden(true);
2521    }
2522    // No tab view here: `Tabs` is a PINNED style on this backend (`Cap::NavTabsAdaptive` is
2523    // off), resolved the same at every width, so a host never morphs into or out of it — its
2524    // `NSTabView` is built at realize and lives for the host.
2525    // Which page is on screen, by IDENTITY: moving the sidebar page in or out of the detail list
2526    // shifts every index past it, so an index captured now would name the wrong page after.
2527    let mut pages = NAV_STATE.with(|m| {
2528        m.borrow()
2529            .get(&ptr_of(host))
2530            .map(|s| s.pages.clone())
2531            .unwrap_or_default()
2532    });
2533    let shown_page = pages.get(sel).cloned();
2534    // The sidebar page is a stack ROOT only while stacked; otherwise it lives in its own pane,
2535    // which is the sidebar in `Split`/`Rail` and a collapsed one behind a tab bar in `Tabs`.
2536    if let Some(page) = sidebar_page {
2537        pages.retain(|p| ptr_of(p) != ptr_of(&page));
2538        unsafe {
2539            if stacked {
2540                detail_wrap.addSubview(&page);
2541                pages.insert(0, page.clone());
2542            } else {
2543                page.setFrame(sidebar_wrap.bounds());
2544                sidebar_wrap.addSubview(&page);
2545            }
2546        }
2547        // A pane always shows its page; as a stack root it may have been hidden under a push.
2548        page.setHidden(false);
2549    }
2550    let shown = shown_page
2551        .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
2552        .unwrap_or_else(|| pages.len().saturating_sub(1));
2553    for (i, page) in pages.iter().enumerate() {
2554        page.setHidden(i != shown);
2555    }
2556    NAV_STATE.with(|m| {
2557        let mut m = m.borrow_mut();
2558        if let Some(s) = m.get_mut(&ptr_of(host)) {
2559            s.presentation = next;
2560            s.pages = pages;
2561            s.selected = shown;
2562            s.header = header;
2563            if let Some(hdr) = s.header.as_ref() {
2564                // Depth drives visibility, and the header is meaningless anywhere but a stack.
2565                if stacked {
2566                    sync_nav_header(hdr, &s.detail_wrap, &s.pages);
2567                } else {
2568                    hdr.bar.setHidden(true);
2569                }
2570            }
2571            if !stacked {
2572                // Leaving the stack: the pages were inset below the header, so give them the
2573                // pane back.
2574                let frame = nav_page_frame(&s.detail_wrap, false);
2575                for page in &s.pages {
2576                    unsafe { page.setFrame(frame) };
2577                }
2578            }
2579        }
2580    });
2581}
2582
2583// ---------------------------------------------------------------------------
2584// The sidebar pane holds its width through NSSplitViewController's own holding priorities
2585// (docs/navigation.md) — a sidebar NSSplitViewItem pins its thickness and lets the detail
2586// absorb a window resize, which is exactly the Finder/Mail behavior the hand-rolled
2587// `splitView:shouldAdjustSizeOfSubview:` delegate used to approximate. The controller IS the
2588// split's delegate, so Day must not install one of its own.
2589// ---------------------------------------------------------------------------
2590
2591struct CoverSheet(Retained<NSWindow>);
2592impl Drop for CoverSheet {
2593    fn drop(&mut self) {
2594        // try_with: the table may already be gone when the thread's locals tear down.
2595        let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
2596        // Sheet transitions may run a nested AppKit update cycle. Defer them until the
2597        // core's tree borrow has ended; this retained pointer travels only to the main queue.
2598        let raw = Retained::into_raw(self.0.clone()) as usize;
2599        dispatch2::DispatchQueue::main().exec_async(move || {
2600            ffi_guard::contain((), || unsafe {
2601                let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
2602                if let Some(parent) = window.sheetParent() {
2603                    parent.endSheet(&window);
2604                }
2605                window.orderOut(None);
2606                window.setContentView(None);
2607            });
2608        });
2609    }
2610}
2611struct NavPageIvars {
2612    node: NodeId,
2613    /// A presented cover's strip under the window's title bar: the page paints it (its frame
2614    /// starts above the layout area) but lays its content out below it, and reports the
2615    /// remaining height (see `pin_below_title_bar`).
2616    top_inset: Cell<f64>,
2617    sheet: Cell<bool>,
2618    /// A half sheet (docs/cover.md): the window sheet stands half the parent's height.
2619    half: Cell<bool>,
2620    /// A large sheet (docs/cover.md "Large sheet"): the window sheet grows to
2621    /// `LARGE_SHEET_MAX`.
2622    large: Cell<bool>,
2623}
2624
2625define_class!(
2626    #[unsafe(super(NSView))]
2627    #[thread_kind = MainThreadOnly]
2628    #[name = "DayNavPage"]
2629    #[ivars = NavPageIvars]
2630    struct DayNavPage;
2631
2632    impl DayNavPage {
2633        #[unsafe(method(isFlipped))]
2634        fn is_flipped(&self) -> bool {
2635            true
2636        }
2637
2638        #[unsafe(method(setFrameSize:))]
2639        fn set_frame_size(&self, size: NSSize) {
2640            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
2641            // Pane-driven resize (splitter drag, window resize): report the usable size
2642            // so NavLayout re-lays this page's content (enqueue-only, §8.3).
2643            ffi_guard::contain((), || {
2644                let inset = self.ivars().top_inset.get();
2645                emit(
2646                    self.ivars().node,
2647                    Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
2648                );
2649            })
2650        }
2651    }
2652);
2653
2654impl DayNavPage {
2655    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2656        let this = Self::alloc(mtm).set_ivars(NavPageIvars {
2657            node,
2658            top_inset: Cell::new(0.0),
2659            sheet: Cell::new(false),
2660            half: Cell::new(false),
2661            large: Cell::new(false),
2662        });
2663        unsafe { msg_send![super(this), init] }
2664    }
2665}
2666
2667// ---------------------------------------------------------------------------
2668// Inspector (docs/inspector.md): an NSSplitViewController whose trailing pane is a REAL
2669// inspector item (`inspectorWithViewController:`) — the system treatment for exactly this
2670// surface: its own backing material, the standard thickness handling, full-height layout
2671// under the titlebar. Day's bound signal is the only visibility driver (the item cannot be
2672// user-collapsed), so this backend never emits `Event::InspectorChanged`.
2673// ---------------------------------------------------------------------------
2674
2675struct InspectorState {
2676    content_wrap: Handle,
2677    panel_wrap: Handle,
2678    /// Retained so the controller (the split's delegate) lives as long as its split.
2679    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2680    panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
2681}
2682
2683// ---------------------------------------------------------------------------
2684// Split (docs/split.md): a plain `NSSplitView` inside a flipped wrap (the wrap is the handle,
2685// so `set_frame`'s nav-host treatment of split views never sees it), two arranged flipped
2686// subviews as the panes, and a delegate that places the divider by the bound share, keeps
2687// both panes above the minimum, and reports a drag back as the new share.
2688// ---------------------------------------------------------------------------
2689
2690struct SplitState {
2691    split: Retained<objc2_app_kit::NSSplitView>,
2692    first_wrap: Handle,
2693    second_wrap: Handle,
2694    delegate: Retained<DaySplitDelegate>,
2695}
2696
2697struct SplitDelegateIvars {
2698    node: NodeId,
2699    min_pane: f64,
2700    /// The share as last patched or reported: what a report is compared against, and where
2701    /// the divider goes when the split first has a size or turns.
2702    share: Cell<f64>,
2703    /// The divider has been placed once; before that the split has no size to place it in.
2704    positioned: Cell<bool>,
2705    /// Day is moving the divider itself: the resize that follows is not a report.
2706    suppress: Cell<bool>,
2707}
2708
2709define_class!(
2710    #[unsafe(super(NSObject))]
2711    #[thread_kind = MainThreadOnly]
2712    #[name = "DaySplitDelegate"]
2713    #[ivars = SplitDelegateIvars]
2714    struct DaySplitDelegate;
2715
2716    unsafe impl NSObjectProtocol for DaySplitDelegate {}
2717
2718    unsafe impl NSSplitViewDelegate for DaySplitDelegate {
2719        #[unsafe(method(splitViewDidResizeSubviews:))]
2720        fn did_resize(&self, notification: &NSNotification) {
2721            ffi_guard::contain((), || {
2722                let Some(obj) = notification.object() else {
2723                    return;
2724                };
2725                let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
2726                    return;
2727                };
2728                let iv = self.ivars();
2729                let usable = split_usable(&sv);
2730                if usable <= 0.0 {
2731                    return;
2732                }
2733                // The first resize with a size: place the divider by the share, once.
2734                if !iv.positioned.replace(true) {
2735                    split_place(&sv, iv);
2736                    return;
2737                }
2738                if iv.suppress.get() {
2739                    return;
2740                }
2741                let Some(first) = sv.subviews().iter().next() else {
2742                    return;
2743                };
2744                let f = first.frame();
2745                let a = if sv.isVertical() {
2746                    f.size.width
2747                } else {
2748                    f.size.height
2749                };
2750                let share = (a / usable).clamp(0.0, 1.0);
2751                if (share - iv.share.get()).abs() > 1e-4 {
2752                    iv.share.set(share);
2753                    emit(iv.node, Event::ValueChanged(share));
2754                }
2755            })
2756        }
2757
2758        #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
2759        fn constrain_min(
2760            &self,
2761            _sv: &objc2_app_kit::NSSplitView,
2762            proposed: f64,
2763            _index: isize,
2764        ) -> f64 {
2765            proposed.max(self.ivars().min_pane)
2766        }
2767
2768        #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
2769        fn constrain_max(
2770            &self,
2771            sv: &objc2_app_kit::NSSplitView,
2772            proposed: f64,
2773            _index: isize,
2774        ) -> f64 {
2775            proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
2776        }
2777    }
2778);
2779
2780impl DaySplitDelegate {
2781    fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
2782        let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
2783            node,
2784            min_pane,
2785            share: Cell::new(share.clamp(0.0, 1.0)),
2786            positioned: Cell::new(false),
2787            suppress: Cell::new(false),
2788        });
2789        unsafe { msg_send![super(this), init] }
2790    }
2791}
2792
2793/// The length the two panes share along the split's axis: the frame minus the divider.
2794fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
2795    let frame = sv.frame();
2796    let len = if sv.isVertical() {
2797        frame.size.width
2798    } else {
2799        frame.size.height
2800    };
2801    (len - sv.dividerThickness()).max(0.0)
2802}
2803
2804/// Move the divider so the first pane takes the share, silently (Day's own write, not a drag).
2805fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
2806    let usable = split_usable(sv);
2807    if usable <= 0.0 {
2808        return;
2809    }
2810    iv.suppress.set(true);
2811    unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
2812    iv.suppress.set(false);
2813}
2814
2815// ---------------------------------------------------------------------------
2816
2817// ---------------------------------------------------------------------------
2818// DayNavMenuData — flat NSOutlineView source list for nav_menu() (docs/navigation.md)
2819// ---------------------------------------------------------------------------
2820
2821struct NavMenuIvars {
2822    node: NodeId,
2823    items: RefCell<Vec<Retained<NSString>>>,
2824    /// Pre-resolved template icons per row (docs/navigation.md), `None` where a row has no icon.
2825    /// Template images tint with the source-list's selection/appearance, so they read in light,
2826    /// dark, and while selected — the macOS-idiomatic sidebar look (Finder/Mail).
2827    icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2828    /// How much of each icon's box its drawing spans (`nav_icon_fill`), index-aligned with
2829    /// `icons`: the cell sizes the icon so the drawing matches a system sidebar glyph.
2830    icon_fills: RefCell<Vec<f64>>,
2831    /// Per-row icon tint (docs/vectors.md): recolors the template glyph via contentTintColor;
2832    /// `None` keeps the source-list's neutral template tint.
2833    tints: RefCell<Vec<Option<day_spec::Color>>>,
2834    /// Trailing accessory per item row (an unread count), `None` where a row has none.
2835    badges: RefCell<Vec<Option<Retained<NSString>>>>,
2836    /// Trailing accessory GLYPH per row, in the same slot as `badges` and drawn after it —
2837    /// a starred page's star. Resolved to images once per rebuild, like `icons`.
2838    icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
2839    badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2840    /// Tint for `badge_icons`; `None` keeps the neutral template tint.
2841    badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
2842    /// Per-row context menu (docs/menus.md), empty = none. Built into an NSMenu and attached
2843    /// to the row's cell view, so a secondary click pops it like any native sidebar menu.
2844    menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
2845    /// Which items drag to reorder (`NavMenuProps::movable`); empty when none do.
2846    movable: RefCell<Vec<bool>>,
2847    /// Movable rows may cross section headers (`NavMenuProps::regroup`); set at creation.
2848    regroup: std::cell::Cell<bool>,
2849    /// Which movable items keep their section's sorted order (`NavMenuProps::sorted`).
2850    sorted: RefCell<Vec<bool>>,
2851    /// The outline's rows, in display order: `Some(i)` is item `i`, `None` is a section
2852    /// header. Day addresses rows by ITEM index, so every selection crossing the boundary
2853    /// goes through this map — a header must never shift what index 3 means.
2854    rows: RefCell<Vec<Option<usize>>>,
2855    /// One retained NSString per outline row: the row's text (a header's or an item's).
2856    row_objects: RefCell<Vec<Retained<NSString>>>,
2857    /// One NSNumber per outline row, holding the row's index: the outline's item IDENTITY.
2858    /// NSOutlineView matches items with `isEqual:`, so an NSString cannot be the identity —
2859    /// a section header titled "Controls" and an item titled "Controls" would collapse into one
2860    /// row, and the header would wear the item's icon. Row indexes are unique by construction.
2861    row_ids: RefCell<Vec<Retained<NSNumber>>>,
2862    /// Programmatic selection in flight: don't re-emit SelectionChanged.
2863    suppress: std::cell::Cell<bool>,
2864}
2865
2866struct NavCellIvars {
2867    /// The trailing accessories (an unread count, a status glyph), when the row has any: the
2868    /// label ends before them.
2869    accessory: RefCell<Option<Retained<NSView>>>,
2870    /// The unread count among them, sized to follow the row's text.
2871    count: RefCell<Option<Retained<NSTextField>>>,
2872    /// How much of the icon's box its drawing spans (`nav_icon_fill`).
2873    icon_fill: std::cell::Cell<f64>,
2874}
2875
2876define_class!(
2877    /// A sidebar row's cell. `NSTableCellView` lays out its icon and label itself, at the
2878    /// size the outline's row size style gives them: the system's Sidebar icon size setting,
2879    /// followed live (docs/navigation.md). This only makes room for the trailing accessories,
2880    /// which AppKit knows nothing about.
2881    #[unsafe(super(objc2_app_kit::NSTableCellView))]
2882    #[thread_kind = MainThreadOnly]
2883    #[name = "DayNavCell"]
2884    #[ivars = NavCellIvars]
2885    struct DayNavCell;
2886
2887    unsafe impl NSObjectProtocol for DayNavCell {}
2888
2889    impl DayNavCell {
2890        #[unsafe(method(layout))]
2891        fn layout(&self) {
2892            let _: () = unsafe { msg_send![super(self), layout] };
2893            ffi_guard::contain((), || self.fit_accessories());
2894        }
2895    }
2896);
2897
2898impl DayNavCell {
2899    fn new(mtm: MainThreadMarker) -> Retained<Self> {
2900        let this = Self::alloc(mtm).set_ivars(NavCellIvars {
2901            accessory: RefCell::new(None),
2902            count: RefCell::new(None),
2903            icon_fill: std::cell::Cell::new(1.0),
2904        });
2905        unsafe { msg_send![super(this), init] }
2906    }
2907
2908    /// After AppKit's layout: the count takes a size two points under the label's, and the
2909    /// label, which AppKit stretches to the cell's trailing edge, ends 6pt before the
2910    /// accessories so a long title truncates instead of running under its count. A showing
2911    /// progress ring re-fits the icon AppKit just sized.
2912    fn fit_accessories(&self) {
2913        let label = unsafe { self.textField() };
2914        if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
2915            let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
2916                (f.pointSize() - 2.0).max(9.0)
2917            });
2918            if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
2919                unsafe {
2920                    count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
2921                        size,
2922                        objc2_app_kit::NSFontWeightRegular,
2923                    )));
2924                }
2925                self.layoutSubtreeIfNeeded();
2926            }
2927        }
2928        if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
2929            let mut frame = label.frame();
2930            let end = accessory.frame().origin.x - 6.0;
2931            if frame.origin.x + frame.size.width > end {
2932                frame.size.width = (end - frame.origin.x).max(0.0);
2933                label.setFrame(frame);
2934            }
2935        }
2936        if let Some(icon) = unsafe { self.imageView() } {
2937            fit_nav_icon(&icon, self.ivars().icon_fill.get());
2938            nav_progress::fit(&icon);
2939        }
2940    }
2941}
2942
2943thread_local! {
2944    /// The side of a system sidebar glyph per symbol configuration (see `fit_nav_icon`).
2945    static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
2946}
2947
2948/// Draw a sidebar row's icon so its drawing is the size a system sidebar draws its SF Symbol,
2949/// centered in the slot AppKit lays out for it; `fill` is how much of the image's box the
2950/// drawing spans (`nav_icon_fill`). The slot is wider than the glyph AppKit puts there (22pt for a
2951/// 16pt glyph at Medium), and Day's icons are artwork that fills whatever frame it gets, so
2952/// left at the slot's size they read a third larger and heavier than Finder's or Mail's.
2953/// The side is measured, not tabled: a square symbol (`gearshape`) drawn with the symbol
2954/// configuration the row size style gave this image view, so it tracks the Sidebar icon size
2955/// setting and whatever a later macOS draws.
2956fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
2957    let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
2958        return;
2959    };
2960    let slot = icon.frame();
2961    // Configurations compare by value, and AppKit gives every cell of a row size style an
2962    // equal one, so the hash names the style.
2963    let key = config.hash() as u64;
2964    let side = NAV_GLYPH_SIDES
2965        .with(|m| m.borrow().get(&key).copied())
2966        .or_else(|| {
2967            let symbol =
2968                objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
2969                    &NSString::from_str("gearshape"),
2970                    None,
2971                )?;
2972            let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
2973            NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
2974            Some(side)
2975        });
2976    // The box that puts the drawing itself at the glyph's size: a Material Symbols icon keeps
2977    // the margin of its grid inside the box, so its box is that much larger.
2978    let Some(side) = side
2979        .filter(|s| *s > 0.0)
2980        .map(|s| (s / fill.clamp(0.25, 1.0)).round())
2981    else {
2982        return;
2983    };
2984    if slot.size.width <= side && slot.size.height <= side {
2985        return;
2986    }
2987    icon.setFrame(NSRect::new(
2988        NSPoint::new(
2989            (slot.origin.x + (slot.size.width - side) / 2.0).round(),
2990            (slot.origin.y + (slot.size.height - side) / 2.0).round(),
2991        ),
2992        NSSize::new(side, side),
2993    ));
2994}
2995
2996define_class!(
2997    #[unsafe(super(objc2_app_kit::NSTableRowView))]
2998    #[thread_kind = MainThreadOnly]
2999    #[name = "DayNavRowView"]
3000    struct DayNavRowView;
3001
3002    unsafe impl NSObjectProtocol for DayNavRowView {}
3003
3004    impl DayNavRowView {
3005        /// Always report the emphasized (key-window) state, so the selected sidebar row draws
3006        /// the accent pill with auto-whitened label/icon in both themes. Without this, a run
3007        /// whose window never becomes key (scripted screenshot captures) falls back to the
3008        /// unemphasized selection fill, which under a forced appearance rendered as a
3009        /// near-black pill that swallowed the row's label.
3010        #[unsafe(method(isEmphasized))]
3011        fn is_emphasized(&self) -> bool {
3012            true
3013        }
3014    }
3015);
3016
3017define_class!(
3018    #[unsafe(super(objc2_app_kit::NSOutlineView))]
3019    #[thread_kind = MainThreadOnly]
3020    #[name = "DayNavOutlineView"]
3021    struct DayNavOutlineView;
3022
3023    unsafe impl NSObjectProtocol for DayNavOutlineView {}
3024
3025    impl DayNavOutlineView {
3026        /// The clicked row's context menu (docs/menus.md): NSTableView-family views consume
3027        /// right-clicks themselves, so per-row menus are served here — resolve the row under
3028        /// the click, then build the same NSMenu the piece decorator would.
3029        #[unsafe(method_id(menuForEvent:))]
3030        fn menu_for_event(
3031            &self,
3032            event: &objc2_app_kit::NSEvent,
3033        ) -> Option<Retained<NSMenu>> {
3034            ffi_guard::contain(None, || {
3035                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3036                let row = unsafe { self.rowAtPoint(point) };
3037                let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
3038                // `define_class!` rewrites the return, so no early `return` — one expression.
3039                match data {
3040                    None => None,
3041                    Some(d) => {
3042                        let items = d
3043                            .item_of_row(row)
3044                            .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
3045                            .unwrap_or_default();
3046                        if items.is_empty() {
3047                            None
3048                        } else {
3049                            Some(build_ns_menu(d.mtm(), "", &items))
3050                        }
3051                    }
3052                }
3053            })
3054        }
3055    }
3056);
3057
3058define_class!(
3059    #[unsafe(super(NSObject))]
3060    #[thread_kind = MainThreadOnly]
3061    #[name = "DayNavMenuData"]
3062    #[ivars = NavMenuIvars]
3063    struct DayNavMenuData;
3064
3065    unsafe impl NSObjectProtocol for DayNavMenuData {}
3066
3067    unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3068        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3069        fn number_of_children(
3070            &self,
3071            _ov: &objc2_app_kit::NSOutlineView,
3072            item: Option<&objc2::runtime::AnyObject>,
3073        ) -> isize {
3074            if item.is_none() {
3075                self.ivars().row_objects.borrow().len() as isize
3076            } else {
3077                0
3078            }
3079        }
3080
3081        #[unsafe(method_id(outlineView:child:ofItem:))]
3082        fn child_of_item(
3083            &self,
3084            _ov: &objc2_app_kit::NSOutlineView,
3085            index: isize,
3086            _item: Option<&objc2::runtime::AnyObject>,
3087        ) -> Retained<objc2::runtime::AnyObject> {
3088            let ids = self.ivars().row_ids.borrow();
3089            // AppKit only asks for children it was told exist, but a stale query racing a
3090            // reload must degrade (an unmatched identity) rather than index out of bounds —
3091            // a panic here unwinds into an ObjC frame and aborts.
3092            let id = ids
3093                .get(index as usize)
3094                .cloned()
3095                .unwrap_or_else(|| NSNumber::new_isize(-1));
3096            unsafe { objc2::rc::Retained::cast_unchecked(id) }
3097        }
3098
3099        #[unsafe(method(outlineView:isItemExpandable:))]
3100        fn is_expandable(
3101            &self,
3102            _ov: &objc2_app_kit::NSOutlineView,
3103            _item: &objc2::runtime::AnyObject,
3104        ) -> bool {
3105            false
3106        }
3107
3108        // --- drag-to-reorder (docs/navigation.md "Reordering sidebar destinations"): the
3109        // outline's own drag pipeline, with the Gap placeholder Finder's sidebar shows. A row
3110        // moves within the run of movable rows around it, or, regrouping, into any section of
3111        // movable rows (`regroup_gap`); the app's data change brings the new order back as
3112        // `NavMenuPatch::Items`.
3113
3114        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3115        fn pasteboard_writer_for_item(
3116            &self,
3117            _ov: &objc2_app_kit::NSOutlineView,
3118            item: &objc2::runtime::AnyObject,
3119        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3120            let make = || {
3121                let row = Self::outline_row(item);
3122                let index = self.item_of_row(row)?;
3123                if !self.is_movable(index) {
3124                    return None;
3125                }
3126                let pbitem = objc2_app_kit::NSPasteboardItem::new();
3127                unsafe {
3128                    pbitem.setString_forType(
3129                        &NSString::from_str(&row.to_string()),
3130                        &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3131                    );
3132                }
3133                Some(ProtocolObject::from_retained(pbitem))
3134            };
3135            ffi_guard::contain(None, make)
3136        }
3137
3138        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3139        fn validate_drop(
3140            &self,
3141            ov: &objc2_app_kit::NSOutlineView,
3142            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3143            item: Option<&objc2::runtime::AnyObject>,
3144            child_index: isize,
3145        ) -> objc2_app_kit::NSDragOperation {
3146            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3147                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3148                    return objc2_app_kit::NSDragOperation::None;
3149                };
3150                // A drop past the run's end lands at that end: move the gap there.
3151                if drop.retarget {
3152                    unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3153                }
3154                objc2_app_kit::NSDragOperation::Move
3155            })
3156        }
3157
3158        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3159        fn accept_drop(
3160            &self,
3161            ov: &objc2_app_kit::NSOutlineView,
3162            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3163            item: Option<&objc2::runtime::AnyObject>,
3164            child_index: isize,
3165        ) -> bool {
3166            ffi_guard::contain(false, || {
3167                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3168                    return false;
3169                };
3170                // Deferred through the event queue: the app's callback never runs inside
3171                // AppKit's drop, and its data change reloads the rows in the new order.
3172                match drop.moves {
3173                    Some(NavMove::Reorder { from, to }) => {
3174                        emit(self.ivars().node, Event::ListReorder { from, to });
3175                    }
3176                    Some(NavMove::Regroup {
3177                        from,
3178                        section,
3179                        before,
3180                    }) => emit(
3181                        self.ivars().node,
3182                        Event::NavRegroup {
3183                            from,
3184                            section,
3185                            before,
3186                        },
3187                    ),
3188                    None => {}
3189                }
3190                true
3191            })
3192        }
3193    }
3194
3195    unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3196
3197    unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3198        /// Section headers are AppKit group rows: the source-list treatment (small, bold,
3199        /// secondary) comes free, and they are excluded from selection below.
3200        #[unsafe(method(outlineView:isGroupItem:))]
3201        fn is_group_item(
3202            &self,
3203            _ov: &objc2_app_kit::NSOutlineView,
3204            item: &objc2::runtime::AnyObject,
3205        ) -> bool {
3206            let row = Self::outline_row(item);
3207            row >= 0 && self.item_of_row(row).is_none()
3208        }
3209
3210        #[unsafe(method(outlineView:shouldSelectItem:))]
3211        fn should_select(
3212            &self,
3213            _ov: &objc2_app_kit::NSOutlineView,
3214            item: &objc2::runtime::AnyObject,
3215        ) -> bool {
3216            self.item_of_row(Self::outline_row(item)).is_some()
3217        }
3218
3219        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3220        fn view_for(
3221            &self,
3222            ov: &objc2_app_kit::NSOutlineView,
3223            _col: Option<&objc2_app_kit::NSTableColumn>,
3224            item: &objc2::runtime::AnyObject,
3225        ) -> Option<Retained<NSView>> {
3226            let mtm = self.mtm();
3227            let row = Self::outline_row(item);
3228            let text = self
3229                .ivars()
3230                .row_objects
3231                .borrow()
3232                .get(usize::try_from(row).unwrap_or(usize::MAX))
3233                .cloned();
3234            // No early returns: the method_id macro owns the return conversion.
3235            text.map(|text| {
3236                let text: &NSString = &text;
3237                let Some(index) = self.item_of_row(row) else {
3238                    // A section header: a plain label. AppKit gives group rows their own
3239                    // typography and places the text, so this only supplies it.
3240                    let cell = DayNavCell::new(mtm);
3241                    let label = unsafe { NSTextField::labelWithString(text, mtm) };
3242                    unsafe {
3243                        label.cell().inspect(|c| {
3244                            c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3245                        });
3246                        cell.addSubview(&label);
3247                        cell.setTextField(Some(&label));
3248                    }
3249                    return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3250                };
3251                let icon = self
3252                    .ivars()
3253                    .icons
3254                    .borrow()
3255                    .get(index)
3256                    .and_then(|o| o.clone());
3257                let badge = self
3258                    .ivars()
3259                    .badges
3260                    .borrow()
3261                    .get(index)
3262                    .and_then(|o| o.clone());
3263                let badge_icon = self
3264                    .ivars()
3265                    .badge_icons
3266                    .borrow()
3267                    .get(index)
3268                    .and_then(|o| o.clone());
3269                let badge_tint = self
3270                    .ivars()
3271                    .badge_tints
3272                    .borrow()
3273                    .get(index)
3274                    .copied()
3275                    .flatten();
3276                // The cell places the icon and the label itself, at the row size style's size
3277                // (the system's Sidebar icon size); `DayNavCell` keeps the label clear of the
3278                // trailing accessories.
3279                let cell = DayNavCell::new(mtm);
3280                let label = unsafe { NSTextField::labelWithString(text, mtm) };
3281                unsafe {
3282                    // Feed titles are arbitrarily long, so the label truncates with an
3283                    // ellipsis within the frame the cell gives it.
3284                    label.cell().inspect(|c| {
3285                        c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3286                    });
3287                    cell.addSubview(&label);
3288                    cell.setTextField(Some(&label));
3289                    // The badge sits at the trailing edge and keeps its intrinsic width; the
3290                    // label truncates into whatever is left, so a long feed name never pushes
3291                    // its own unread count off the pane.
3292                    // Both accessories share the trailing slot: the count (if any) and then
3293                    // the status glyph (if any), in a stack so a row can carry either or both
3294                    // without the constraints below caring which it got.
3295                    let accessory = objc2_app_kit::NSStackView::new(mtm);
3296                    accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3297                    accessory.setOrientation(
3298                        objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3299                    );
3300                    accessory.setSpacing(4.0);
3301                    let mut has_accessory = false;
3302                    let trailing: Retained<NSView> = match &badge {
3303                        Some(text) => {
3304                            let b = NSTextField::labelWithString(text, mtm);
3305                            b.setTranslatesAutoresizingMaskIntoConstraints(false);
3306                            b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3307                            b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3308                            b.setFont(Some(
3309                                &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3310                                    objc2_app_kit::NSFont::smallSystemFontSize(),
3311                                    objc2_app_kit::NSFontWeightRegular,
3312                                ),
3313                            ));
3314                            b.setContentCompressionResistancePriority_forOrientation(
3315                                objc2_app_kit::NSLayoutPriorityRequired,
3316                                objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3317                            );
3318                            *cell.ivars().count.borrow_mut() = Some(b.clone());
3319                            accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3320                                objc2::rc::Retained::into_super(b),
3321                            ));
3322                            has_accessory = true;
3323                            let v: Retained<NSView> =
3324                                objc2::rc::Retained::into_super(accessory.clone());
3325                            v
3326                        }
3327                        None => objc2::rc::Retained::into_super(accessory.clone()),
3328                    };
3329                    // The status glyph, tinted where the app gave it a meaning-bearing color
3330                    // (a star is yellow because that is what a star IS, not because the theme
3331                    // says so). Template images take contentTintColor exactly as the row's
3332                    // leading icon does.
3333                    if let Some(img) = &badge_icon {
3334                        let iv = objc2_app_kit::NSImageView::new(mtm);
3335                        iv.setImage(Some(img));
3336                        iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3337                        if let Some(c) = badge_tint {
3338                            iv.setContentTintColor(Some(&nscolor(c)));
3339                        }
3340                        iv.setContentCompressionResistancePriority_forOrientation(
3341                            objc2_app_kit::NSLayoutPriorityRequired,
3342                            objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3343                        );
3344                        accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
3345                        has_accessory = true;
3346                    }
3347                    cell.addSubview(&trailing);
3348                    if has_accessory {
3349                        *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
3350                    }
3351                    objc2_app_kit::NSLayoutConstraint::activateConstraints(
3352                        &objc2_foundation::NSArray::from_retained_slice(&[
3353                            trailing
3354                                .trailingAnchor()
3355                                .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
3356                            trailing
3357                                .centerYAnchor()
3358                                .constraintEqualToAnchor(&cell.centerYAnchor()),
3359                        ]),
3360                    );
3361                }
3362                if let Some(img) = icon {
3363                    let fill = self.ivars().icon_fills.borrow().get(index).copied();
3364                    cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
3365                    let tint = self.ivars().tints.borrow().get(index).copied().flatten();
3366                    let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
3367                    unsafe {
3368                        iv.setImage(Some(&img));
3369                        // Per-row tint (docs/vectors.md): the icons are template images, so
3370                        // contentTintColor recolors the alpha mask; None keeps the neutral look.
3371                        if let Some(t) = tint {
3372                            iv.setContentTintColor(Some(&nscolor(t)));
3373                        }
3374                        iv.setImageScaling(
3375                            objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
3376                        );
3377                        cell.addSubview(&iv);
3378                        cell.setImageView(Some(&iv));
3379                        let progress = self
3380                            .ivars()
3381                            .icon_progress
3382                            .borrow()
3383                            .iter()
3384                            .find(|(row, _)| *row == index)
3385                            .map(|(_, f)| *f);
3386                        nav_progress::update(&iv, progress);
3387                    }
3388                }
3389                objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
3390            })
3391        }
3392
3393        #[unsafe(method_id(outlineView:rowViewForItem:))]
3394        fn row_view_for(
3395            &self,
3396            _ov: &objc2_app_kit::NSOutlineView,
3397            _item: &objc2::runtime::AnyObject,
3398        ) -> Retained<objc2_app_kit::NSTableRowView> {
3399            let row: Retained<DayNavRowView> =
3400                unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
3401            objc2::rc::Retained::into_super(row)
3402        }
3403
3404        #[unsafe(method(outlineViewSelectionDidChange:))]
3405        fn selection_did_change(&self, notification: &NSNotification) {
3406            ffi_guard::contain((), || {
3407                if self.ivars().suppress.get() {
3408                    return;
3409                }
3410                let Some(obj) = (unsafe { notification.object() }) else {
3411                    return;
3412                };
3413                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
3414                    return;
3415                };
3416                let row = unsafe { ov.selectedRow() };
3417                if let Some(item) = self.item_of_row(row) {
3418                    emit(self.ivars().node, Event::SelectionChanged(item as i64));
3419                }
3420            })
3421        }
3422    }
3423);
3424
3425thread_local! {
3426    /// `nav_icon_fill` per icon name: a sidebar rebuilds its rows on every count change, and an
3427    /// icon's drawing does not change with them.
3428    static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
3429}
3430
3431/// `nav_icon_fill` for each resolved icon, by name; 1 where a row has none.
3432fn nav_icon_fills(
3433    names: &[Option<String>],
3434    images: &[Option<Retained<objc2_app_kit::NSImage>>],
3435) -> Vec<f64> {
3436    names
3437        .iter()
3438        .zip(images)
3439        .map(|(name, image)| match (name, image) {
3440            (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
3441                *m.borrow_mut()
3442                    .entry(name.clone())
3443                    .or_insert_with(|| nav_icon_fill(image))
3444            }),
3445            _ => 1.0,
3446        })
3447        .collect()
3448}
3449
3450/// How much of an icon's box its drawing spans along its longer side, in (0, 1]: a Material
3451/// Symbols glyph keeps the 80-unit margin of its 960-unit grid (about 0.83), an SF Symbol export
3452/// is boxed to its content (1), and artwork usually fills its square. Measured from the alpha of
3453/// one small render, since a plain SVG says nothing about where its drawing sits.
3454fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
3455    const PX: f64 = 64.0;
3456    let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
3457        return 1.0;
3458    };
3459    let (w, h) = (
3460        rep.pixelsWide().max(0) as usize,
3461        rep.pixelsHigh().max(0) as usize,
3462    );
3463    let stride = rep.bytesPerRow().max(0) as usize;
3464    let data = unsafe { rep.bitmapData() };
3465    if data.is_null() || stride < w * 4 {
3466        return 1.0;
3467    }
3468    // SAFETY: `scaled_rep` made a meshed 8-bit RGBA bitmap of `h` rows of `stride` bytes, which
3469    // `rep` owns and keeps alive for this borrow.
3470    let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
3471    let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
3472    for y in 0..h {
3473        for x in 0..w {
3474            if bytes[y * stride + x * 4 + 3] > 24 {
3475                (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
3476            }
3477        }
3478    }
3479    if x1 <= x0 || y1 <= y0 {
3480        return 1.0;
3481    }
3482    // The render stretched the image to a square; back in the image's own proportions, the
3483    // drawing's longer extent over the image's longer side is what proportional scaling keeps.
3484    let size = image.size();
3485    let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
3486    let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
3487    ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
3488}
3489
3490fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
3491    // A bundled icon name → a template NSImage (tinted by the source list); `None` per iconless row.
3492    icons
3493        .iter()
3494        .map(|ic| {
3495            let name = ic.as_deref()?;
3496            // Prefer the glyph SVG (docs/vectors.md): NSImage renders it at display size.
3497            let path = day_spec::resource::resolve_vector_svg(name)
3498                .or_else(|| day_spec::resource::resolve_image_file(name))?;
3499            use objc2::AllocAnyThread as _;
3500            let img = unsafe {
3501                objc2_app_kit::NSImage::initWithContentsOfFile(
3502                    objc2_app_kit::NSImage::alloc(),
3503                    &NSString::from_str(&path.to_string_lossy()),
3504                )
3505            }?;
3506            // Downloaded/user-file icons are artwork; bundled glyphs remain templates.
3507            unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
3508            Some(img)
3509        })
3510        .collect()
3511}
3512
3513impl DayNavMenuData {
3514    #[allow(clippy::too_many_arguments)]
3515    fn new(
3516        mtm: MainThreadMarker,
3517        node: NodeId,
3518        items: &[String],
3519        icons: &[Option<String>],
3520        badges: &[Option<String>],
3521        badge_icons: &[Option<String>],
3522        badge_tints: &[Option<day_spec::Color>],
3523        sections: &[Option<String>],
3524        tints: &[Option<day_spec::Color>],
3525        menus: &[Vec<day_spec::MenuItem>],
3526    ) -> Retained<Self> {
3527        let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
3528            node,
3529            items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
3530            icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
3531            icons: RefCell::new(resolve_nav_icons(icons)),
3532            tints: RefCell::new(tints.to_vec()),
3533            menus: RefCell::new(menus.to_vec()),
3534            movable: RefCell::new(Vec::new()),
3535            regroup: std::cell::Cell::new(false),
3536            sorted: RefCell::new(Vec::new()),
3537            badges: RefCell::new(ns_badges(badges)),
3538            icon_progress: RefCell::new(Vec::new()),
3539            badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
3540            badge_tints: RefCell::new(badge_tints.to_vec()),
3541            rows: RefCell::new(Vec::new()),
3542            row_objects: RefCell::new(Vec::new()),
3543            row_ids: RefCell::new(Vec::new()),
3544            suppress: std::cell::Cell::new(false),
3545        });
3546        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
3547        this.rebuild_rows(items, sections);
3548        this
3549    }
3550
3551    /// Data-driven rows changed (`NavMenuPatch::Items`): swap the stored decorations in place.
3552    // The parameters are the patch's payload: index-aligned per-row decoration arrays, each
3553    // landing in its own ivar. Bundling them would just move the same eight fields.
3554    #[allow(clippy::too_many_arguments)]
3555    fn set_items(
3556        &self,
3557        items: &[String],
3558        icons: &[Option<String>],
3559        badges: &[Option<String>],
3560        badge_icons: &[Option<String>],
3561        badge_tints: &[Option<day_spec::Color>],
3562        sections: &[Option<String>],
3563        tints: &[Option<day_spec::Color>],
3564        menus: &[Vec<day_spec::MenuItem>],
3565    ) {
3566        *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
3567        let resolved = resolve_nav_icons(icons);
3568        *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
3569        *self.ivars().icons.borrow_mut() = resolved;
3570        *self.ivars().tints.borrow_mut() = tints.to_vec();
3571        *self.ivars().menus.borrow_mut() = menus.to_vec();
3572        *self.ivars().badges.borrow_mut() = ns_badges(badges);
3573        self.ivars().icon_progress.borrow_mut().clear();
3574        *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
3575        *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
3576        self.rebuild_rows(items, sections);
3577    }
3578
3579    /// Flatten items + section headers into the outline's display rows. Each row gets its own
3580    /// retained NSString so the outline can tell two rows apart by identity even when their
3581    /// labels match (two feeds legitimately share a title).
3582    fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
3583        let mut rows = Vec::with_capacity(items.len());
3584        let mut objects = Vec::with_capacity(items.len());
3585        for (i, label) in items.iter().enumerate() {
3586            if let Some(Some(header)) = sections.get(i) {
3587                rows.push(None);
3588                objects.push(NSString::from_str(header));
3589            }
3590            rows.push(Some(i));
3591            objects.push(NSString::from_str(label));
3592        }
3593        let ids = (0..objects.len())
3594            .map(|i| NSNumber::new_isize(i as isize))
3595            .collect();
3596        *self.ivars().rows.borrow_mut() = rows;
3597        *self.ivars().row_objects.borrow_mut() = objects;
3598        *self.ivars().row_ids.borrow_mut() = ids;
3599    }
3600
3601    /// The outline row an item object names — the index its NSNumber identity carries — or
3602    /// `-1` for anything that is not one of ours (a stale query racing a reload).
3603    fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
3604        item.downcast_ref::<NSNumber>()
3605            .map(|n| n.integerValue())
3606            .unwrap_or(-1)
3607    }
3608
3609    /// Outline row → day item index.
3610    fn item_of_row(&self, row: isize) -> Option<usize> {
3611        if row < 0 {
3612            return None;
3613        }
3614        self.ivars()
3615            .rows
3616            .borrow()
3617            .get(row as usize)
3618            .copied()
3619            .flatten()
3620    }
3621
3622    /// Day item index → outline row.
3623    fn row_of_item(&self, item: usize) -> Option<usize> {
3624        self.ivars()
3625            .rows
3626            .borrow()
3627            .iter()
3628            .position(|r| *r == Some(item))
3629    }
3630
3631    fn is_movable(&self, item: usize) -> bool {
3632        self.ivars()
3633            .movable
3634            .borrow()
3635            .get(item)
3636            .copied()
3637            .unwrap_or(false)
3638    }
3639
3640    /// What a drop proposal means for a reorder, or `None` when it is no drop of ours: a drag
3641    /// from another view, of a row that cannot move, or (regrouping) to a gap no rule allows.
3642    /// Reordering, the gap clamps to the run of movable rows around the dragged one, which
3643    /// section headers and fixed rows end ([`reorder_gap`]); regrouping, see [`regroup_gap`].
3644    fn nav_drop(
3645        &self,
3646        ov: &objc2_app_kit::NSOutlineView,
3647        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3648        item: Option<&objc2::runtime::AnyObject>,
3649        child_index: isize,
3650    ) -> Option<NavDrop> {
3651        let src = unsafe { info.draggingSource() }?;
3652        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
3653            != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
3654        {
3655            return None;
3656        }
3657        let pb = unsafe { info.draggingPasteboard() };
3658        let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
3659            .to_string()
3660            .parse::<usize>()
3661            .ok()?;
3662        let rows = self.ivars().rows.borrow();
3663        // The flat outline proposes a gap among the root's children, or a row itself (a drop
3664        // ONTO it, index -1).
3665        let proposed = match item {
3666            Some(item) => Self::outline_row(item),
3667            None => child_index,
3668        };
3669        let proposed = usize::try_from(proposed).unwrap_or(rows.len());
3670        if self.ivars().regroup.get() {
3671            regroup_gap(
3672                &rows,
3673                &self.ivars().movable.borrow(),
3674                &self.ivars().sorted.borrow(),
3675                from_row,
3676                proposed,
3677                item.is_some(),
3678            )
3679        } else {
3680            reorder_gap(
3681                &rows,
3682                &self.ivars().movable.borrow(),
3683                from_row,
3684                proposed,
3685                item.is_some(),
3686            )
3687        }
3688    }
3689}
3690
3691/// A drop in a sidebar outline (`DayNavMenuData::nav_drop`).
3692#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3693struct NavDrop {
3694    /// The gap the row drops into, among the outline's rows.
3695    gap: usize,
3696    /// The proposal named some other place, and the gap moves here.
3697    retarget: bool,
3698    /// What the drop reports, or `None` for a drop back in place.
3699    moves: Option<NavMove>,
3700}
3701
3702/// What a sidebar drop reports, in item indices (the rows before the move).
3703#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3704enum NavMove {
3705    /// `Event::ListReorder`: `from` takes `to`'s place.
3706    Reorder { from: usize, to: usize },
3707    /// `Event::NavRegroup`: `from` joins the section whose first row is `section`, before
3708    /// `before` or at the section's end.
3709    Regroup {
3710        from: usize,
3711        section: usize,
3712        before: Option<usize>,
3713    },
3714}
3715
3716/// A reorder drop at `proposed`, a gap among the outline's `rows` (`None` a header, `Some(i)`
3717/// item `i`), for the row at `from_row`; `onto` when the proposal named a row itself, which
3718/// reads as the gap above it. The gap clamps to the run of movable rows around the dragged
3719/// one, which section headers and fixed rows end. `None` when that row cannot move.
3720fn reorder_gap(
3721    rows: &[Option<usize>],
3722    movable: &[bool],
3723    from_row: usize,
3724    proposed: usize,
3725    onto: bool,
3726) -> Option<NavDrop> {
3727    let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
3728    let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
3729    let in_run = |r: usize| rows[r].is_some_and(is_movable);
3730    let first = (0..from_row)
3731        .rev()
3732        .take_while(|r| in_run(*r))
3733        .last()
3734        .unwrap_or(from_row);
3735    let last = (from_row + 1..rows.len())
3736        .take_while(|r| in_run(*r))
3737        .last()
3738        .unwrap_or(from_row);
3739    let gap = proposed.clamp(first, last + 1);
3740    // The row's place once it has left its own: the row whose position it takes.
3741    let target_row = if gap > from_row { gap - 1 } else { gap };
3742    let moves = (target_row != from_row)
3743        .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
3744        .flatten();
3745    Some(NavDrop {
3746        gap,
3747        retarget: gap != proposed || onto,
3748        moves,
3749    })
3750}
3751
3752/// A regroup drop at `proposed`, a gap among the outline's `rows` (as [`reorder_gap`]'s), for
3753/// the row at `from_row` (docs/navigation.md "Moving rows between sections"). The gap's section
3754/// is the nearest header above it, or the rows above the first header; `before` is the item
3755/// right below the gap when that row is in the same section. A drop ONTO a header reads as
3756/// that section's first gap, onto an item as the gap above it. `None` when the row cannot
3757/// move, the gap is above the first header with no rows there, the section holds a fixed row,
3758/// or the gap is in the row's own section and the row is sorted. Gaps are never clamped.
3759fn regroup_gap(
3760    rows: &[Option<usize>],
3761    movable: &[bool],
3762    sorted: &[bool],
3763    from_row: usize,
3764    proposed: usize,
3765    onto: bool,
3766) -> Option<NavDrop> {
3767    let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
3768    let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
3769    let gap = match rows.get(proposed) {
3770        Some(None) if onto => proposed + 1,
3771        _ => proposed.min(rows.len()),
3772    };
3773    // The first outline row of the section a gap (or a row, as the gap above it) sits in.
3774    let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
3775        Some(header) => Some(header + 1),
3776        None => rows.first().copied().flatten().map(|_| 0),
3777    };
3778    let first = section_start(gap)?;
3779    let end = (first..rows.len())
3780        .find(|r| rows[*r].is_none())
3781        .unwrap_or(rows.len());
3782    let section = rows.get(first).copied().flatten()?;
3783    if !rows[first..end]
3784        .iter()
3785        .all(|r| r.is_some_and(|i| flag(movable, i)))
3786    {
3787        return None;
3788    }
3789    let own = section_start(from_row) == Some(first);
3790    if own && flag(sorted, from) {
3791        return None;
3792    }
3793    let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
3794        from,
3795        section,
3796        before: rows.get(gap).copied().flatten(),
3797    });
3798    Some(NavDrop {
3799        gap,
3800        retarget: gap != proposed || onto,
3801        moves,
3802    })
3803}
3804
3805#[cfg(test)]
3806mod nav_gap_tests {
3807    use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
3808
3809    /// 0 today, 1 [news], 2 a, 3 b, 4 e, 5 [tech], 6 c, 7 d, 8 [smart], 9 starred: items 0..=6.
3810    const ROWS: [Option<usize>; 10] = [
3811        Some(0),
3812        None,
3813        Some(1),
3814        Some(2),
3815        Some(3),
3816        None,
3817        Some(4),
3818        Some(5),
3819        None,
3820        Some(6),
3821    ];
3822    /// The feeds move; today and starred are fixed.
3823    const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
3824    const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
3825    const UNSORTED: [bool; 7] = [false; 7];
3826
3827    fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
3828        Some(NavMove::Regroup {
3829            from,
3830            section,
3831            before,
3832        })
3833    }
3834
3835    #[test]
3836    fn regroup_gaps_name_the_section_above_and_the_row_below() {
3837        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3838        // a, into tech's first gap: before c.
3839        assert_eq!(
3840            at(2, 6),
3841            Some(NavDrop {
3842                gap: 6,
3843                retarget: false,
3844                moves: regroup(1, 4, Some(4)),
3845            })
3846        );
3847        // c, into the gap above tech's header: the end of news.
3848        assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
3849        // a, between c and d, and at tech's end above smart's header.
3850        assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
3851        assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
3852    }
3853
3854    #[test]
3855    fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
3856        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3857        // Smart holds starred, and the rows above the first header hold today.
3858        for gap in [0, 1, 9, 10] {
3859            assert_eq!(at(2, gap), None, "gap {gap}");
3860        }
3861        // A sorted row's own section offers no gap, its own place included.
3862        for gap in [2, 3, 4, 5] {
3863            assert_eq!(at(2, gap), None, "gap {gap}");
3864        }
3865        // Fixed rows and headers never drag.
3866        assert_eq!(at(0, 6), None);
3867        assert_eq!(at(1, 6), None);
3868        assert_eq!(at(9, 6), None);
3869    }
3870
3871    #[test]
3872    fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
3873        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
3874        // a, between b and e.
3875        assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
3876        // a, at news's end above tech's header.
3877        assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
3878        // Back in place, either side of itself: a drop that reports nothing.
3879        for gap in [2, 3] {
3880            let drop = at(2, gap).expect("offered");
3881            assert_eq!(drop.moves, None, "gap {gap}");
3882        }
3883    }
3884
3885    #[test]
3886    fn regroup_drops_onto_a_row_move_to_a_gap() {
3887        // Onto tech's header: its first gap. Onto d: the gap above d.
3888        assert_eq!(
3889            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
3890            Some(NavDrop {
3891                gap: 6,
3892                retarget: true,
3893                moves: regroup(1, 4, Some(4)),
3894            })
3895        );
3896        assert_eq!(
3897            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
3898            Some(NavDrop {
3899                gap: 7,
3900                retarget: true,
3901                moves: regroup(1, 4, Some(5)),
3902            })
3903        );
3904    }
3905
3906    #[test]
3907    fn regroup_offers_nothing_above_a_leading_header() {
3908        // 0 [news], 1 a, 2 [tech], 3 b.
3909        let rows = [None, Some(0), None, Some(1)];
3910        let movable = [true, true];
3911        let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
3912        assert_eq!(at(0), None);
3913        assert_eq!(at(1).map(|d| d.moves), Some(None));
3914        assert_eq!(at(2).map(|d| d.moves), Some(None));
3915        assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
3916        assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
3917    }
3918
3919    #[test]
3920    fn reorder_gaps_clamp_to_the_run() {
3921        // a past the run's end lands at its end: e's place.
3922        assert_eq!(
3923            reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
3924            Some(NavDrop {
3925                gap: 5,
3926                retarget: true,
3927                moves: Some(NavMove::Reorder { from: 1, to: 3 }),
3928            })
3929        );
3930        // Back in place.
3931        assert_eq!(
3932            reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
3933            Some(None)
3934        );
3935        // b above the run's start lands at a's place; a fixed row offers nothing.
3936        assert_eq!(
3937            reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
3938            Some(NavMove::Reorder { from: 2, to: 1 })
3939        );
3940        assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
3941    }
3942}
3943
3944/// The private pasteboard type carrying a dragged sidebar row (local reorder only).
3945const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
3946
3947/// Badge strings, retained once per rebuild rather than per cell.
3948fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
3949    badges
3950        .iter()
3951        .map(|b| b.as_deref().map(NSString::from_str))
3952        .collect()
3953}
3954
3955// ---------------------------------------------------------------------------
3956/// Force the table's visible rows to exist on the next main-loop turn — outside any `with_tree`
3957/// borrow, so `bind_row` may build them. `layoutSubtreeIfNeeded` is not enough: an occluded
3958/// window's table skips row tiling entirely, so `viewAtColumn:row:makeIfNecessary:` is the only
3959/// reliable way to realize rows without a draw pass (§10; see the Reload patch for why).
3960fn post_realize_visible_rows(key: usize) {
3961    <AppKit as Platform>::post(Box::new(move || {
3962        if let Some((table, data)) = list_entry(key) {
3963            unsafe { table.layoutSubtreeIfNeeded() };
3964            let range = unsafe { table.rowsInRect(table.visibleRect()) };
3965            if let Some(source) = data.ivars().source.borrow().clone()
3966                && let Some(report) = &source.first_visible
3967            {
3968                report(range.location.min((source.len)().saturating_sub(1)));
3969            }
3970            for row in range.location..range.location + range.length {
3971                let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
3972                // A snapshot/layout can have requested this cell while day-core held its
3973                // tree borrow. The delegate then returned an empty container; AppKit caches
3974                // it and will not ask viewForRow again. Complete that skipped bind here.
3975                if let Some(cell) = cell
3976                    && cell.subviews().is_empty()
3977                {
3978                    let source = data.ivars().source.borrow().clone();
3979                    if let Some(source) = source {
3980                        (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
3981                    }
3982                }
3983            }
3984        }
3985        // The builds above queued their styling effects; drain them now — outside the pump, no
3986        // event may arrive for a while (idle app), and a snapshot would capture bare rows.
3987        day_core::pump_events();
3988    }));
3989}
3990
3991/// A native drop changes the snapshot synchronously and suppresses the app's echo Reload.
3992/// Once AppKit has unwound its drop/gap tracking, reconcile the table with that snapshot:
3993/// the incremental move alone can leave its row tiling and scroll extent out of sync.
3994/// Preserve the user's viewport and selection; never force a jump to the moved row.
3995fn post_settle_list_drop(key: usize) {
3996    <AppKit as Platform>::post(Box::new(move || {
3997        // Publish the deferred on_reorder before reading the final row set. App code may
3998        // remove rows or close the list, so resolve the native handles only after the drain.
3999        day_core::pump_events();
4000        let Some((table, data)) = list_entry(key) else {
4001            return;
4002        };
4003        let Some(scroll) = table.enclosingScrollView() else {
4004            return;
4005        };
4006        let clip = scroll.contentView();
4007        let origin = clip.bounds().origin;
4008        let selected = table.selectedRowIndexes();
4009        let suppressed = data.ivars().suppress.replace(true);
4010        table.reloadData();
4011        // Outside with_tree: tiling is allowed to bind/rebind Day's cell contents here.
4012        table.layoutSubtreeIfNeeded();
4013        let restored = objc2_foundation::NSMutableIndexSet::new();
4014        for row in 0..table.numberOfRows().max(0) as usize {
4015            if selected.containsIndex(row) {
4016                restored.addIndex(row);
4017            }
4018        }
4019        table.selectRowIndexes_byExtendingSelection(&restored, false);
4020        let mut bounds = clip.bounds();
4021        bounds.origin = origin;
4022        clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
4023        scroll.reflectScrolledClipView(&clip);
4024        data.ivars().suppress.set(suppressed);
4025        post_realize_visible_rows(key);
4026    }));
4027}
4028
4029// DayListData — NSTableView data-source + delegate for the recycling list (docs/list.md, §10)
4030//
4031// No custom NSTableRowView: the table runs the PLAIN style, whose standard row view lays cell
4032// views out at the full row bounds — no inset to pin away — and whose cell-frame slide is what
4033// animates a row-action swipe. (A `layout`-override pin lived here under FullWidth until
4034// 2026-08; it also froze row content mid-swipe, revealing actions behind a motionless row.)
4035// ---------------------------------------------------------------------------
4036
4037define_class!(
4038    #[unsafe(super(NSTableView))]
4039    #[thread_kind = MainThreadOnly]
4040    #[name = "DayListView"]
4041    struct DayListView;
4042    unsafe impl NSObjectProtocol for DayListView {}
4043    impl DayListView {
4044        /// NSTableView consumes right-clicks before the row's container sees them. Resolve
4045        /// its summon-time provider from the visible cell, never from the selected row.
4046        #[unsafe(method_id(menuForEvent:))]
4047        fn menu_for_event(
4048            &self,
4049            event: &objc2_app_kit::NSEvent,
4050        ) -> Option<Retained<NSMenu>> {
4051            ffi_guard::contain(None, || {
4052                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4053                let row = unsafe { self.rowAtPoint(point) };
4054                let provider = if row >= 0 {
4055                    unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
4056                        .and_then(|cell| list_row_menu_provider(&cell))
4057                } else {
4058                    None
4059                };
4060                match provider {
4061                    Some((view, provider)) => {
4062                        let point = view.convertPoint_fromView(
4063                            unsafe { event.locationInWindow() }, None,
4064                        );
4065                        let items = provider(day_spec::Point::new(point.x, point.y));
4066                        if items.is_empty() {
4067                            None
4068                        } else {
4069                            Some(build_ns_menu(self.mtm(), "", &items))
4070                        }
4071                    }
4072                    None => unsafe { msg_send![super(self), menuForEvent: event] },
4073                }
4074            })
4075        }
4076
4077        #[unsafe(method(becomeFirstResponder))]
4078        fn become_first_responder(&self) -> bool {
4079            let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4080            if accepted {
4081                self.report_focus(true);
4082            }
4083            accepted
4084        }
4085
4086        #[unsafe(method(resignFirstResponder))]
4087        fn resign_first_responder(&self) -> bool {
4088            let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4089            if accepted {
4090                self.report_focus(false);
4091            }
4092            accepted
4093        }
4094
4095        #[unsafe(method(keyDown:))]
4096        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4097            ffi_guard::contain((), || {
4098                let key = unsafe { event.keyCode() };
4099                if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4100                    let row = unsafe { self.selectedRow() };
4101                    if row >= 0 && let Some(target) = unsafe { self.target() } {
4102                        let _: () = unsafe { msg_send![&*target, activateRow: self] };
4103                        return;
4104                    }
4105                }
4106                let _: () = unsafe { msg_send![super(self), keyDown: event] };
4107            });
4108        }
4109    }
4110);
4111
4112/// The cell can wrap its decorated row in layout containers. Search only this visible
4113/// cell, not other rows; cloning the provider releases the registry borrow before app code.
4114fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4115    if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
4116        return Some((view.retain(), provider));
4117    }
4118    view.subviews()
4119        .iter()
4120        .find_map(|view| list_row_menu_provider(&view))
4121}
4122
4123/// Plain labels receive the mouse event before their row does. Resolve the nearest dynamic
4124/// owner without copying providers onto descendants (which would go stale on recycling).
4125/// `Some(None)` means an owner deliberately returned no menu; do not fall through to a parent.
4126fn inherited_context_menu(
4127    view: &NSView,
4128    event: &objc2_app_kit::NSEvent,
4129) -> Option<Option<Retained<NSMenu>>> {
4130    let mut current = Some(view.retain());
4131    while let Some(view) = current {
4132        if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4133            let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4134            let items = provider(day_spec::Point::new(point.x, point.y));
4135            return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4136        }
4137        current = unsafe { view.superview() };
4138    }
4139    None
4140}
4141
4142impl DayListView {
4143    fn report_focus(&self, focused: bool) {
4144        ffi_guard::contain((), || {
4145            if let Some(target) = unsafe { self.target() }
4146                && let Some(data) = target.downcast_ref::<DayListData>()
4147            {
4148                emit(data.ivars().node, Event::FocusChanged(focused));
4149            }
4150        });
4151    }
4152}
4153
4154struct ListIvars {
4155    node: NodeId,
4156    /// Injected by `attach_list` once day-core wires the driver.
4157    source: RefCell<Option<ListSource>>,
4158    selectable: std::cell::Cell<bool>,
4159    /// Multi-select mode (docs/list.md): every change reports the FULL selected set.
4160    multi: std::cell::Cell<bool>,
4161    /// Programmatic selection in flight: don't re-emit SelectionChanged.
4162    suppress: std::cell::Cell<bool>,
4163    /// The row-token order this table currently displays — the baseline `permutation_moves`
4164    /// diffs a Reload against (docs/list.md: a same-set reorder animates as row moves).
4165    tokens: RefCell<Vec<u64>>,
4166    /// `RowHeight::Automatic` (docs/list.md "Row heights"): each row is as tall as Day laid
4167    /// it, through `tableView:heightOfRow:`. A uniform list never answers that selector, so
4168    /// NSTableView keeps its fixed-pitch fast path.
4169    automatic: bool,
4170    /// The list has section headers (docs/list.md "Sections"): AppKit group rows, which float
4171    /// at the top as their section scrolls under them. A header sizes to its content in any
4172    /// list, so a sectioned list answers `tableView:heightOfRow:` even when it is uniform.
4173    sections: bool,
4174    /// The height a header nobody has bound yet is given, like `estimate` for rows.
4175    header_estimate: std::cell::Cell<f64>,
4176    /// Each self-sizing row's height by row token, as Day last laid it. By token, not row: a
4177    /// splice or a drag moves rows without rebinding them.
4178    heights: RefCell<std::collections::HashMap<u64, f64>>,
4179    /// The row token each bound cell shows, so `RowSizeInvalidated` (which names the cell)
4180    /// finds the height it corrects.
4181    cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4182    /// The height a row nobody has bound yet is given: the last one Day measured, so a list
4183    /// of like rows scrolls without its rows jumping as they arrive.
4184    estimate: std::cell::Cell<f64>,
4185    /// A height pass is posted and not yet run (`post_row_heights` coalesces).
4186    heights_pending: std::cell::Cell<bool>,
4187}
4188
4189define_class!(
4190    #[unsafe(super(NSObject))]
4191    #[thread_kind = MainThreadOnly]
4192    #[name = "DayListData"]
4193    #[ivars = ListIvars]
4194    struct DayListData;
4195
4196    unsafe impl NSObjectProtocol for DayListData {}
4197    unsafe impl NSControlTextEditingDelegate for DayListData {}
4198
4199    impl DayListData {
4200        /// Only a self-sizing list answers `tableView:heightOfRow:`: NSTableView asks that
4201        /// of every row on each reload, and a uniform list's fixed `rowHeight` is the fast
4202        /// path. NSTableView reads this once, at `setDelegate:`, after `automatic` is set.
4203        #[unsafe(method(respondsToSelector:))]
4204        fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4205            if selector == objc2::sel!(tableView:heightOfRow:)
4206                && !self.ivars().automatic
4207                && !self.ivars().sections
4208            {
4209                false
4210            } else {
4211                unsafe { msg_send![super(self), respondsToSelector: selector] }
4212            }
4213        }
4214
4215        #[unsafe(method(listViewportChanged:))]
4216        fn list_viewport_changed(&self, notification: &NSNotification) {
4217            ffi_guard::contain((), || {
4218                let source = self.ivars().source.borrow().clone();
4219                if let Some(source) = source && let Some(report) = &source.first_visible
4220                    && let Some(object) = notification.object()
4221                    && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4222                    && let Some(document) = clip.documentView()
4223                    && let Some(table) = document.downcast_ref::<NSTableView>() {
4224                    let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4225                    report(visible.location.min((source.len)().saturating_sub(1)));
4226                }
4227            });
4228        }
4229
4230        #[unsafe(method(activateRow:))]
4231        fn activate_row(&self, table: &NSTableView) {
4232            ffi_guard::contain((), || {
4233                let row = unsafe { table.selectedRow() };
4234                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4235            });
4236        }
4237        #[unsafe(method(doubleClickRow:))]
4238        fn double_click_row(&self, table: &NSTableView) {
4239            ffi_guard::contain((), || {
4240                let row = unsafe { table.clickedRow() };
4241                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4242            });
4243        }
4244    }
4245
4246    unsafe impl NSTableViewDataSource for DayListData {
4247        #[unsafe(method(numberOfRowsInTableView:))]
4248        fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4249            // Reads the piece's snapshot only (no tree access) — safe even when called
4250            // synchronously from reloadData inside a with_tree borrow. Guarded because
4251            // `len` is a day-core closure.
4252            ffi_guard::contain(0, || {
4253                self.ivars()
4254                    .source
4255                    .borrow()
4256                    .as_ref()
4257                    .map(|s| (s.len)() as isize)
4258                    .unwrap_or(0)
4259            })
4260        }
4261
4262        // --- drag-to-reorder (docs/list.md): NSTableView's native drag pipeline. The dragged
4263        // row rides the pasteboard as a private-typed string; `validateDrop` consults the app's
4264        // guard live (the `.gap` feedback style opens the placeholder gap only where the guard
4265        // allows), and `acceptDrop` commits through the sync seam, then animates the native move.
4266
4267        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4268        fn pasteboard_writer_for_row(
4269            &self,
4270            _tv: &NSTableView,
4271            row: isize,
4272        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4273            // (Closure body: define_class converts only the TAIL expression, so early `return`s
4274            // must not escape the method itself.)
4275            let make = || {
4276                // Only reorderable lists write drag items — no seam, no drag.
4277                let reorderable = self
4278                    .ivars()
4279                    .source
4280                    .borrow()
4281                    .as_ref()
4282                    .is_some_and(|s| s.reorder.is_some());
4283                // A group row (a section header) never lifts (docs/list.md "Sections").
4284                if !reorderable || row < 0 || self.is_header(row) {
4285                    return None;
4286                }
4287                let item = objc2_app_kit::NSPasteboardItem::new();
4288                unsafe {
4289                    item.setString_forType(
4290                        &NSString::from_str(&row.to_string()),
4291                        &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4292                    );
4293                }
4294                Some(ProtocolObject::from_retained(item))
4295            };
4296            ffi_guard::contain(None, make)
4297        }
4298
4299        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4300        fn validate_drop(
4301            &self,
4302            tv: &NSTableView,
4303            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4304            row: isize,
4305            _op: objc2_app_kit::NSTableViewDropOperation,
4306        ) -> objc2_app_kit::NSDragOperation {
4307            // Guarded: `can_move` consults the app's reorder guard closure.
4308            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4309                let Some((from, len)) = self.drag_context(tv, info) else {
4310                    return objc2_app_kit::NSDragOperation::None;
4311                };
4312                // Normalize to an above insertion point (the gap style's semantics), convert to
4313                // the post-removal target index, and ask the guard.
4314                let ins = row.clamp(0, len as isize) as usize;
4315                let to = insertion_to_target(from, ins, len);
4316                let accepted = self.can_move(from, to);
4317                if accepted < 0 {
4318                    return objc2_app_kit::NSDragOperation::None;
4319                }
4320                let accepted = (accepted as usize).min(len.saturating_sub(1));
4321                if accepted != to {
4322                    // The guard retargeted: move the gap to where the drop would actually land.
4323                    unsafe {
4324                        tv.setDropRow_dropOperation(
4325                            target_to_insertion(from, accepted) as isize,
4326                            objc2_app_kit::NSTableViewDropOperation::Above,
4327                        );
4328                    }
4329                }
4330                objc2_app_kit::NSDragOperation::Move
4331            })
4332        }
4333
4334        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4335        fn accept_drop(
4336            &self,
4337            tv: &NSTableView,
4338            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4339            row: isize,
4340            _op: objc2_app_kit::NSTableViewDropOperation,
4341        ) -> bool {
4342            // (Closure body: early `return`s must not escape the define_class method itself.)
4343            let drop = || {
4344                let Some((from, len)) = self.drag_context(tv, info) else {
4345                    return false;
4346                };
4347                let ins = row.clamp(0, len as isize) as usize;
4348                let to = insertion_to_target(from, ins, len);
4349                let accepted = self.can_move(from, to);
4350                if accepted < 0 {
4351                    return false;
4352                }
4353                let accepted = (accepted as usize).min(len.saturating_sub(1));
4354                if accepted == from {
4355                    return true; // dropped back home — nothing to commit
4356                }
4357                // Commit through the sync seam (rotates Day's snapshot, defers the app
4358                // callback), THEN animate the native move — the data source already answers in
4359                // the new order.
4360                let mv = self
4361                    .ivars()
4362                    .source
4363                    .borrow()
4364                    .as_ref()
4365                    .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
4366                let Some(mv) = mv else { return false };
4367                mv(from, accepted);
4368                // Keep the displayed-order cache in step (the commit's echo skips the Reload
4369                // that would otherwise refresh it — see `permutation_moves`).
4370                {
4371                    let mut toks = self.ivars().tokens.borrow_mut();
4372                    if from < toks.len() && accepted < toks.len() {
4373                        let t = toks.remove(from);
4374                        toks.insert(accepted, t);
4375                    }
4376                }
4377                unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
4378                if let Some(scroll) = tv.enclosingScrollView() {
4379                    post_settle_list_drop(ptr_of(&scroll));
4380                }
4381                true
4382            };
4383            // Guarded: the commit runs the seam's move closure into day-core and the app.
4384            ffi_guard::contain(false, drop)
4385        }
4386    }
4387
4388    unsafe impl NSTableViewDelegate for DayListData {
4389        /// A self-sizing row's height (docs/list.md "Row heights"): the height Day laid it at
4390        /// once it has been bound, the running estimate until then. Asked before the row's view
4391        /// exists, often from inside `reloadData` under a day-core borrow, so it reads only this
4392        /// table's own record and the source's token snapshot.
4393        #[unsafe(method(tableView:heightOfRow:))]
4394        fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
4395            ffi_guard::contain(44.0, || {
4396                let ivars = self.ivars();
4397                let header = self.is_header(row);
4398                // A uniform sectioned list: rows keep the fixed pitch, headers size themselves.
4399                if !header && !ivars.automatic {
4400                    return unsafe { tv.rowHeight() };
4401                }
4402                let token = ivars
4403                    .source
4404                    .borrow()
4405                    .as_ref()
4406                    .filter(|s| row >= 0 && (row as usize) < (s.len)())
4407                    .map(|s| (s.token_at)(row as usize));
4408                token
4409                    .and_then(|t| ivars.heights.borrow().get(&t).copied())
4410                    .unwrap_or_else(|| {
4411                        if header {
4412                            ivars.header_estimate.get()
4413                        } else {
4414                            ivars.estimate.get()
4415                        }
4416                    })
4417            })
4418        }
4419
4420        /// Section headers are AppKit group rows (docs/list.md "Sections"): drawn in the
4421        /// group style, spanning the row, and floated over their section by
4422        /// `floatsGroupRows`.
4423        #[unsafe(method(tableView:isGroupRow:))]
4424        fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
4425            ffi_guard::contain(false, || self.is_header(row))
4426        }
4427
4428        /// A header is not an item: clicks and arrow keys pass over it.
4429        #[unsafe(method(tableView:shouldSelectRow:))]
4430        fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
4431            ffi_guard::contain(true, || !self.is_header(row))
4432        }
4433
4434        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
4435        fn view_for_row(
4436            &self,
4437            tv: &NSTableView,
4438            _col: Option<&NSTableColumn>,
4439            row: isize,
4440        ) -> Option<Retained<NSView>> {
4441            // Guarded: `bind_row` builds the app's row content.
4442            ffi_guard::contain(None, || {
4443                let mtm = self.mtm();
4444                // Headers pool apart from rows, so a recycled cell keeps its kind and rebinds.
4445                let header = self.is_header(row);
4446                let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
4447                // Recycle a cell view if one is free; else make a fresh flipped container.
4448                let cell: Retained<NSView> =
4449                    unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
4450                        let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
4451                        unsafe { v.setIdentifier(Some(&ident)) };
4452                        v
4453                    });
4454                // Day builds row content the first time it sees this cell, and rebinds
4455                // (slot-write) when the cell is recycled. NSTableView calls this outside
4456                // reloadData's stack, so the re-entry into with_tree is safe.
4457                let source = self.ivars().source.borrow().clone();
4458                if let Some(source) = source {
4459                    let raw = Retained::as_ptr(&cell) as RawHandle;
4460                    (source.bind_row)(row as usize, raw);
4461                    if self.ivars().automatic || header {
4462                        self.note_row_height(tv, &source, row, raw, header);
4463                    }
4464                }
4465                Some(cell)
4466            })
4467        }
4468
4469        #[unsafe(method(tableView:didRemoveRowView:forRow:))]
4470        fn did_remove_row_view(
4471            &self,
4472            _tv: &NSTableView,
4473            row_view: &objc2_app_kit::NSTableRowView,
4474            _row: isize,
4475        ) {
4476            // The row went back to the reuse pool (a reload dropping it past a shrunk source, a
4477            // scroll): clear its day element ids so it stops answering lookups, as the tree's
4478            // `outlineView:didRemoveRowView:forRow:` does. Deferred, since this fires inside
4479            // reload stacks that hold the day-core borrow, and re-checked: a cell the same
4480            // turn's reload already reused has a window again, and its fresh ids must survive.
4481            ffi_guard::contain((), || {
4482                let Some(cell) = row_view.subviews().iter().find(|sub| {
4483                    sub.identifier()
4484                        .map(|i| {
4485                            let i = i.to_string();
4486                            i == DAY_ROW_CELL || i == DAY_HEADER_CELL
4487                        })
4488                        .unwrap_or(false)
4489                }) else {
4490                    return;
4491                };
4492                // Raw +1 pointers across the post (the closure must be Send, which Retained is
4493                // not; everything stays on the main thread). AppKit may free a removed row view.
4494                let cell = Retained::into_raw(cell) as usize;
4495                let Some(this) = (unsafe {
4496                    Retained::retain(self as *const DayListData as *mut DayListData)
4497                }) else {
4498                    return;
4499                };
4500                let this = Retained::into_raw(this) as usize;
4501                <AppKit as Platform>::post(Box::new(move || {
4502                    // Reclaim both +1s first, so every early return balances them.
4503                    let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4504                    let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
4505                    let (Some(this), Some(cell)) = (this, cell) else {
4506                        return;
4507                    };
4508                    if cell.window().is_some() {
4509                        return; // reused already: its ids are the live row's
4510                    }
4511                    let recycle = this
4512                        .ivars()
4513                        .source
4514                        .borrow()
4515                        .as_ref()
4516                        .map(|s| s.recycle.clone());
4517                    if let Some(recycle) = recycle {
4518                        recycle(Retained::as_ptr(&cell) as RawHandle);
4519                    }
4520                }));
4521            })
4522        }
4523
4524        #[unsafe(method(tableViewSelectionDidChange:))]
4525        fn selection_did_change(&self, notification: &NSNotification) {
4526            ffi_guard::contain((), || {
4527                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
4528                    return;
4529                }
4530                let Some(obj) = (unsafe { notification.object() }) else {
4531                    return;
4532                };
4533                let Ok(tv) = obj.downcast::<NSTableView>() else {
4534                    return;
4535                };
4536                if self.ivars().multi.get() {
4537                    // Multi-select: report the FULL set (ascending; empty = cleared).
4538                    let idx = unsafe { tv.selectedRowIndexes() };
4539                    let mut rows = Vec::with_capacity(idx.count());
4540                    let mut i = idx.firstIndex();
4541                    while i != objc2_foundation::NSNotFound as usize {
4542                        rows.push(i as i64);
4543                        i = unsafe { idx.indexGreaterThanIndex(i) };
4544                    }
4545                    emit(self.ivars().node, Event::SelectionSet(rows));
4546                } else {
4547                    let row = unsafe { tv.selectedRow() };
4548                    if row >= 0 {
4549                        emit(self.ivars().node, Event::SelectionChanged(row as i64));
4550                    } else {
4551                        // CLEARED. `selectedRow()` answers -1, which is not a row, so there is
4552                        // nothing for `SelectionChanged` to carry and nothing for `on_select` to
4553                        // be called with — but the app still has to hear about it, or a detail
4554                        // pane goes on showing the row the user just deselected. The empty set is
4555                        // how that is said (`on_selection`, docs/list.md); reporting nothing was
4556                        // a silent contract break, since single-selection backends are documented
4557                        // as firing it with a one-element OR EMPTY set.
4558                        emit(self.ivars().node, Event::SelectionSet(Vec::new()));
4559                    }
4560                }
4561            })
4562        }
4563
4564        // --- swipe actions (docs/list.md): NSTableView's row-action pipeline. AppKit calls
4565        // this as the two-finger swipe starts, so the offer reflects the row's state at
4566        // GESTURE time; a full swipe across activates the first action (AppKit's own
4567        // full-slide behavior). The handler commits through the seam, which defers the app's
4568        // callback to the event drain.
4569        #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
4570        fn row_actions_for_row(
4571            &self,
4572            tv: &NSTableView,
4573            row: isize,
4574            edge: objc2_app_kit::NSTableRowActionEdge,
4575        ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
4576            // Guarded: `actions_at` runs the app's provider closure.
4577            ffi_guard::contain(NSArray::new(), || {
4578                let sw = self
4579                    .ivars()
4580                    .source
4581                    .borrow()
4582                    .as_ref()
4583                    .and_then(|s| s.swipe.clone());
4584                let Some(sw) = sw else {
4585                    return NSArray::new();
4586                };
4587                if row < 0 {
4588                    return NSArray::new();
4589                }
4590                // AppKit's Leading/Trailing already speak reading direction, same as ours.
4591                let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
4592                    day_spec::SwipeEdge::Leading
4593                } else {
4594                    day_spec::SwipeEdge::Trailing
4595                };
4596                let offer = (sw.actions_at)(row as usize, day_edge);
4597                let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
4598                    .iter()
4599                    .enumerate()
4600                    .map(|(i, a)| {
4601                        let style = if a.destructive {
4602                            objc2_app_kit::NSTableViewRowActionStyle::Destructive
4603                        } else {
4604                            objc2_app_kit::NSTableViewRowActionStyle::Regular
4605                        };
4606                        let perform = sw.perform.clone();
4607                        // Retained only for the swipe session: AppKit releases the actions
4608                        // (and this block) when the revealed buttons close.
4609                        let table = tv.retain();
4610                        let handler = block2::RcBlock::new(
4611                            move |_action: std::ptr::NonNull<
4612                                objc2_app_kit::NSTableViewRowAction,
4613                            >,
4614                                  row: isize| {
4615                                ffi_guard::contain((), || {
4616                                    perform(row as usize, day_edge, i);
4617                                    // A button press leaves the buttons revealed; close
4618                                    // them (a full slide already closed itself).
4619                                    unsafe { table.setRowActionsVisible(false) };
4620                                })
4621                            },
4622                        );
4623                        let action =
4624                            objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
4625                                style,
4626                                &NSString::from_str(&a.label),
4627                                &handler,
4628                            );
4629                        if let Some(t) = a.tint {
4630                            unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
4631                        }
4632                        // Glyph above the label — the Mail row-action look. The SF symbol
4633                        // resolves per OS release; an unknown name yields no image and the
4634                        // button keeps its label alone.
4635                        if let Some(sym) = a.symbol {
4636                            let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
4637                                &NSString::from_str(day_spec::sf_symbol_name(sym)),
4638                                None,
4639                            );
4640                            if let Some(img) = img {
4641                                unsafe { action.setImage(Some(&img)) };
4642                            }
4643                        }
4644                        action
4645                    })
4646                    .collect();
4647                NSArray::from_retained_slice(&actions)
4648            })
4649        }
4650    }
4651);
4652
4653impl DayListData {
4654    fn new(
4655        mtm: MainThreadMarker,
4656        node: NodeId,
4657        selectable: bool,
4658        multi: bool,
4659        automatic: bool,
4660        sections: bool,
4661    ) -> Retained<Self> {
4662        let this = Self::alloc(mtm).set_ivars(ListIvars {
4663            node,
4664            source: RefCell::new(None),
4665            selectable: std::cell::Cell::new(selectable),
4666            multi: std::cell::Cell::new(multi),
4667            suppress: std::cell::Cell::new(false),
4668            tokens: RefCell::new(Vec::new()),
4669            automatic,
4670            sections,
4671            header_estimate: std::cell::Cell::new(28.0),
4672            heights: RefCell::new(std::collections::HashMap::new()),
4673            cell_tokens: RefCell::new(std::collections::HashMap::new()),
4674            estimate: std::cell::Cell::new(44.0),
4675            heights_pending: std::cell::Cell::new(false),
4676        });
4677        unsafe { msg_send![super(this), init] }
4678    }
4679
4680    /// A self-sizing row was just bound to `cell`: record the height Day laid it at, and if
4681    /// the table drew the row at another height (the estimate, or the row's old content),
4682    /// correct it on the next turn. Not here: this runs inside NSTableView's own tiling.
4683    fn note_row_height(
4684        &self,
4685        table: &NSTableView,
4686        source: &ListSource,
4687        row: isize,
4688        cell: RawHandle,
4689        header: bool,
4690    ) {
4691        let height = (source.cell_height)(cell);
4692        if height <= 0.0 || row < 0 {
4693            return;
4694        }
4695        let token = (source.token_at)(row as usize);
4696        self.ivars()
4697            .cell_tokens
4698            .borrow_mut()
4699            .insert(cell as usize, token);
4700        self.ivars().heights.borrow_mut().insert(token, height);
4701        if header {
4702            self.ivars().header_estimate.set(height);
4703        } else {
4704            self.ivars().estimate.set(height);
4705        }
4706        let drawn = unsafe { table.rectOfRow(row) }.size.height;
4707        if (drawn - height).abs() > 0.5 {
4708            self.post_row_heights(table);
4709        }
4710    }
4711
4712    /// Whether display row `row` is a section header (docs/list.md "Sections").
4713    fn is_header(&self, row: isize) -> bool {
4714        row >= 0
4715            && self
4716                .ivars()
4717                .source
4718                .borrow()
4719                .as_ref()
4720                .and_then(|s| s.is_header.clone())
4721                .is_some_and(|is_header| is_header(row as usize))
4722    }
4723
4724    /// `ListPatch::RowSizeInvalidated`: the row in `cell` was re-laid at `height`. Arrives under
4725    /// the day-core borrow, so it only records the height; the table is told after the pass.
4726    fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
4727        let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
4728        if let Some(token) = token {
4729            self.ivars().heights.borrow_mut().insert(token, height);
4730            self.post_row_heights(table);
4731        }
4732    }
4733
4734    /// Tell the table, on the next main-loop turn, about every row near the viewport whose drawn
4735    /// height differs from the one Day laid it at. Coalesced: a pass that re-lays many rows
4736    /// posts one correction.
4737    fn post_row_heights(&self, table: &NSTableView) {
4738        if self.ivars().heights_pending.replace(true) {
4739            return;
4740        }
4741        // Raw +1 pointers across the post (the closure must be Send, which Retained is not;
4742        // everything stays on the main thread).
4743        let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
4744            return;
4745        };
4746        let this = Retained::into_raw(this) as usize;
4747        let table = Retained::into_raw(table.retain()) as usize;
4748        <AppKit as Platform>::post(Box::new(move || {
4749            // Reclaim both +1s first, so every early return balances them.
4750            let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4751            let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
4752            let (Some(this), Some(table)) = (this, table) else {
4753                return;
4754            };
4755            this.ivars().heights_pending.set(false);
4756            ffi_guard::contain((), || this.apply_row_heights(&table));
4757        }));
4758    }
4759
4760    fn apply_row_heights(&self, table: &NSTableView) {
4761        let Some(source) = self.ivars().source.borrow().clone() else {
4762            return;
4763        };
4764        let count = unsafe { table.numberOfRows() }.max(0) as usize;
4765        let shown = unsafe { table.rowsInRect(table.visibleRect()) };
4766        // The viewport and the rows AppKit prepares around it.
4767        let first = shown.location.saturating_sub(8);
4768        let last = (shown.location + shown.length + 8)
4769            .min(count)
4770            .min((source.len)());
4771        let changed = objc2_foundation::NSMutableIndexSet::new();
4772        {
4773            let heights = self.ivars().heights.borrow();
4774            for row in first..last {
4775                if let Some(&height) = heights.get(&(source.token_at)(row)) {
4776                    let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
4777                    if (drawn - height).abs() > 0.5 {
4778                        unsafe { changed.addIndex(row) };
4779                    }
4780                }
4781            }
4782        }
4783        if changed.count() == 0 {
4784            return;
4785        }
4786        // Unanimated: the row takes its content's height, it does not grow into it.
4787        NSAnimationContext::beginGrouping();
4788        NSAnimationContext::currentContext().setDuration(0.0);
4789        unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
4790        NSAnimationContext::endGrouping();
4791    }
4792
4793    /// If this Reload is the same row set in a new order, the incremental `moveRowAtIndex`
4794    /// steps (each `(from, to)` interpreted against the already-moved rows, NSTableView's
4795    /// semantics) that transform the displayed order into the new one — and `None` for
4796    /// anything else (insert/remove/content change/no change), which reloads flat. Always
4797    /// refreshes the displayed-order cache.
4798    ///
4799    /// Every row that changes position must have a REALIZED row view (`table`): moving a
4800    /// viewless row (its old position sat outside the viewport, so it was never bound)
4801    /// animates nothing and leaves the row unbound at its new position — its content, and any
4802    /// element ids inside it, would simply not exist. Such a reorder returns `None` and
4803    /// reloads flat, which realizes and binds the row at its new position.
4804    fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
4805        let source = self.ivars().source.borrow();
4806        let source = source.as_ref()?;
4807        let n = (source.len)();
4808        let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
4809        let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
4810        if old.len() != n || n == 0 || old == new {
4811            return None;
4812        }
4813        let (mut so, mut sn) = (old.clone(), new.clone());
4814        so.sort_unstable();
4815        sn.sort_unstable();
4816        if so != sn {
4817            return None;
4818        }
4819        for i in 0..n {
4820            if old[i] != new[i]
4821                && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
4822            {
4823                return None;
4824            }
4825        }
4826        let mut work = old;
4827        let mut moves = Vec::new();
4828        for i in 0..n {
4829            if work[i] == new[i] {
4830                continue;
4831            }
4832            let j = (i + 1..n).find(|&j| work[j] == new[i])?;
4833            let t = work.remove(j);
4834            work.insert(i, t);
4835            moves.push((j, i));
4836        }
4837        Some(moves)
4838    }
4839
4840    /// The dragged row + current row count for an in-flight LOCAL reorder drag — `None` when the
4841    /// drag came from anywhere but this table (day never accepts foreign drops into a list) or
4842    /// the pasteboard doesn't carry the day row type.
4843    fn drag_context(
4844        &self,
4845        tv: &NSTableView,
4846        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4847    ) -> Option<(usize, usize)> {
4848        let src = unsafe { info.draggingSource() }?;
4849        if Retained::as_ptr(&src) as *const std::ffi::c_void
4850            != tv as *const NSTableView as *const std::ffi::c_void
4851        {
4852            return None;
4853        }
4854        let pb = unsafe { info.draggingPasteboard() };
4855        let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
4856            .to_string()
4857            .parse::<usize>()
4858            .ok()?;
4859        let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
4860        (from < len).then_some((from, len))
4861    }
4862
4863    /// The guard's verdict for `from -> to` (accepted index, or -1), through the sync seam.
4864    fn can_move(&self, from: usize, to: usize) -> i64 {
4865        self.ivars()
4866            .source
4867            .borrow()
4868            .as_ref()
4869            .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
4870            .unwrap_or(-1)
4871    }
4872}
4873
4874/// The reuse identifiers of a list's row cells and its section-header cells.
4875const DAY_ROW_CELL: &str = "day.cell";
4876const DAY_HEADER_CELL: &str = "day.header";
4877
4878/// The private pasteboard type carrying a dragged day list row's index (local reorder only).
4879const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
4880
4881/// An NSTableView drop lands at an INSERTION point (`row` with `.Above` semantics, 0..=len);
4882/// day's seam speaks post-removal target indices. Dropping `from` at insertion `ins`:
4883fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
4884    let to = if ins > from { ins - 1 } else { ins };
4885    to.min(len.saturating_sub(1))
4886}
4887
4888/// The inverse, for retargeting the drop gap: where the gap sits for a post-removal target.
4889fn target_to_insertion(from: usize, to: usize) -> usize {
4890    if to > from { to + 1 } else { to }
4891}
4892
4893/// A realized LIST's scroll view ptr → (table, data source) for attach_list / update / measure.
4894type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
4895
4896/// Clone a list's (table, data) out of `LIST_STATE` under a SHORT borrow. Every caller then
4897/// talks to AppKit with the map free: table calls that look innocuous (`endUpdates`, a scroll's
4898/// tiling, `viewAtColumn:row:makeIfNecessary:`, even `layoutSubtreeIfNeeded`) can synchronously
4899/// re-enter `viewForRow` → `bind_row` → a flush that tears nodes down — and `release` must be
4900/// able to take its own borrow at that depth. Holding the map across any of them was the
4901/// "RefCell already borrowed" contained panic every list walkthrough used to log, 24 a run.
4902fn list_entry(key: usize) -> Option<ListEntry> {
4903    LIST_STATE.with(|m| m.borrow().get(&key).cloned())
4904}
4905
4906// ---------------------------------------------------------------------------
4907// DayTreeData — NSOutlineView data-source + delegate for the hierarchical tree (docs/tree.md)
4908// ---------------------------------------------------------------------------
4909
4910struct TreeIvars {
4911    node: NodeId,
4912    /// Injected by `attach_tree` once day-core wires the driver.
4913    source: RefCell<Option<TreeSource>>,
4914    selectable: std::cell::Cell<bool>,
4915    /// Programmatic selection/disclosure in flight: don't re-emit the event (echo rule).
4916    suppress: std::cell::Cell<bool>,
4917    /// token → its interned NSNumber. NSOutlineView tracks items (selection, expansion,
4918    /// rowForItem) by object identity/equality, so every query for a token must answer with
4919    /// the same object — which is also what preserves expansion across reloadData.
4920    items: RefCell<HashMap<u64, Retained<NSNumber>>>,
4921}
4922
4923define_class!(
4924    #[unsafe(super(NSObject))]
4925    #[thread_kind = MainThreadOnly]
4926    #[name = "DayTreeData"]
4927    #[ivars = TreeIvars]
4928    struct DayTreeData;
4929
4930    unsafe impl NSObjectProtocol for DayTreeData {}
4931
4932    unsafe impl NSOutlineViewDataSource for DayTreeData {
4933        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
4934        fn number_of_children(
4935            &self,
4936            _ov: &objc2_app_kit::NSOutlineView,
4937            item: Option<&objc2::runtime::AnyObject>,
4938        ) -> isize {
4939            // Reads the piece's snapshot only (no tree access) — safe even when called
4940            // synchronously from reloadData inside a with_tree borrow. Guarded because
4941            // the closures are day-core's.
4942            ffi_guard::contain(0, || {
4943                let parent = item.and_then(Self::token_of_item);
4944                if item.is_some() && parent.is_none() {
4945                    return 0; // not one of ours (stale query racing a reload)
4946                }
4947                self.ivars()
4948                    .source
4949                    .borrow()
4950                    .as_ref()
4951                    .map(|s| (s.children_len)(parent) as isize)
4952                    .unwrap_or(0)
4953            })
4954        }
4955
4956        #[unsafe(method_id(outlineView:child:ofItem:))]
4957        fn child_of_item(
4958            &self,
4959            _ov: &objc2_app_kit::NSOutlineView,
4960            index: isize,
4961            item: Option<&objc2::runtime::AnyObject>,
4962        ) -> Retained<objc2::runtime::AnyObject> {
4963            // AppKit only asks for children it was told exist, but a stale query racing a
4964            // reload must degrade (token 0, an unmatched identity) rather than panic — an
4965            // unwind here crosses an ObjC frame and aborts.
4966            let token = ffi_guard::contain(0, || {
4967                let parent = item.and_then(Self::token_of_item);
4968                self.ivars()
4969                    .source
4970                    .borrow()
4971                    .as_ref()
4972                    .map(|s| (s.child_token)(parent, index.max(0) as usize))
4973                    .unwrap_or(0)
4974            });
4975            let ns = self.intern(token);
4976            unsafe { objc2::rc::Retained::cast_unchecked(ns) }
4977        }
4978
4979        #[unsafe(method(outlineView:isItemExpandable:))]
4980        fn is_expandable(
4981            &self,
4982            _ov: &objc2_app_kit::NSOutlineView,
4983            item: &objc2::runtime::AnyObject,
4984        ) -> bool {
4985            ffi_guard::contain(false, || {
4986                let Some(token) = Self::token_of_item(item) else {
4987                    return false;
4988                };
4989                self.ivars()
4990                    .source
4991                    .borrow()
4992                    .as_ref()
4993                    .map(|s| (s.expandable)(token))
4994                    .unwrap_or(false)
4995            })
4996        }
4997
4998        // --- drag-to-move (docs/tree.md): the dragged node rides the pasteboard as a
4999        // private-typed token string; `validateDrop` consults the guard live (forbidden
5000        // cursor where it denies, including ONTO-a-row drops via childIndex -1), and
5001        // `acceptDrop` commits through the sync seam — the app's own data write reloads.
5002
5003        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
5004        fn pasteboard_writer_for_item(
5005            &self,
5006            _ov: &objc2_app_kit::NSOutlineView,
5007            item: &objc2::runtime::AnyObject,
5008        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
5009            let make = || {
5010                let movable = self
5011                    .ivars()
5012                    .source
5013                    .borrow()
5014                    .as_ref()
5015                    .is_some_and(|s| s.moves.is_some());
5016                let token = Self::token_of_item(item)?;
5017                if !movable {
5018                    return None;
5019                }
5020                let pbitem = objc2_app_kit::NSPasteboardItem::new();
5021                unsafe {
5022                    pbitem.setString_forType(
5023                        &NSString::from_str(&token.to_string()),
5024                        &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
5025                    );
5026                }
5027                Some(ProtocolObject::from_retained(pbitem))
5028            };
5029            ffi_guard::contain(None, make)
5030        }
5031
5032        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
5033        fn validate_drop(
5034            &self,
5035            ov: &objc2_app_kit::NSOutlineView,
5036            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5037            item: Option<&objc2::runtime::AnyObject>,
5038            child_index: isize,
5039        ) -> objc2_app_kit::NSDragOperation {
5040            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
5041                match self.drop_proposal(ov, info, item, child_index) {
5042                    Some((token, parent, index)) if self.can_move(token, parent, index) => {
5043                        objc2_app_kit::NSDragOperation::Move
5044                    }
5045                    _ => objc2_app_kit::NSDragOperation::None,
5046                }
5047            })
5048        }
5049
5050        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
5051        fn accept_drop(
5052            &self,
5053            ov: &objc2_app_kit::NSOutlineView,
5054            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5055            item: Option<&objc2::runtime::AnyObject>,
5056            child_index: isize,
5057        ) -> bool {
5058            let drop = || {
5059                let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
5060                else {
5061                    return false;
5062                };
5063                if !self.can_move(token, parent, index) {
5064                    return false;
5065                }
5066                // Commit through the sync seam: defers the app's `on_move`; the app's own
5067                // data write drives the Reload (no native row animation on this path).
5068                let mv = self
5069                    .ivars()
5070                    .source
5071                    .borrow()
5072                    .as_ref()
5073                    .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5074                let Some(mv) = mv else { return false };
5075                mv(token, parent, index);
5076                true
5077            };
5078            ffi_guard::contain(false, drop)
5079        }
5080    }
5081
5082    unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5083
5084    unsafe impl NSOutlineViewDelegate for DayTreeData {
5085        #[unsafe(method(outlineView:isGroupItem:))]
5086        fn is_group_item(
5087            &self,
5088            _ov: &objc2_app_kit::NSOutlineView,
5089            item: &objc2::runtime::AnyObject,
5090        ) -> bool {
5091            Self::token_of_item(item).is_some_and(|t| {
5092                self.ivars()
5093                    .source
5094                    .borrow()
5095                    .as_ref()
5096                    .is_some_and(|s| (s.section_header)(t))
5097            })
5098        }
5099        #[unsafe(method(outlineView:shouldSelectItem:))]
5100        fn should_select_item(
5101            &self,
5102            _ov: &objc2_app_kit::NSOutlineView,
5103            item: &objc2::runtime::AnyObject,
5104        ) -> bool {
5105            Self::token_of_item(item).is_some_and(|t| {
5106                self.ivars()
5107                    .source
5108                    .borrow()
5109                    .as_ref()
5110                    .is_some_and(|s| !(s.section_header)(t))
5111            })
5112        }
5113
5114        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5115        fn view_for_item(
5116            &self,
5117            ov: &objc2_app_kit::NSOutlineView,
5118            _col: Option<&NSTableColumn>,
5119            item: &objc2::runtime::AnyObject,
5120        ) -> Option<Retained<NSView>> {
5121            // Guarded: `bind_row` builds the app's row content.
5122            ffi_guard::contain(None, || {
5123                let mtm = self.mtm();
5124                let token = Self::token_of_item(item)?;
5125                let ident = NSString::from_str("day.tree.cell");
5126                // Recycle a cell view if one is free; else make a fresh flipped container
5127                // (DayTreeCell re-lays its Day row at its own width — indentation makes
5128                // every tree cell's width per-row).
5129                let cell: Retained<NSView> =
5130                    unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5131                        let v: Retained<NSView> =
5132                            Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5133                        unsafe { v.setIdentifier(Some(&ident)) };
5134                        v
5135                    });
5136                if let Some(source) = self.ivars().source.borrow().as_ref() {
5137                    let raw = Retained::as_ptr(&cell) as RawHandle;
5138                    if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5139                        unsafe {
5140                            cell.setTextField(None);
5141                        }
5142                    }
5143                    (source.bind_row)(token, raw);
5144                    // Associate the actual Day label with NSTableCellView so AppKit can
5145                    // apply group typography and source-list background styles normally.
5146                    if (source.section_header)(token) {
5147                        fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5148                            for child in unsafe { view.subviews() }.iter() {
5149                                if let Ok(label) = child.clone().downcast::<NSTextField>() {
5150                                    return Some(label);
5151                                }
5152                                if let Some(label) = label_in(&child) {
5153                                    return Some(label);
5154                                }
5155                            }
5156                            None
5157                        }
5158                        if let Some(label) = label_in(&cell) {
5159                            let cell = cell.downcast_ref::<DayTreeCell>()?;
5160                            unsafe {
5161                                cell.setTextField(Some(&label));
5162                            }
5163                        }
5164                    }
5165                }
5166                Some(cell)
5167            })
5168        }
5169
5170        #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5171        fn type_select_string(
5172            &self,
5173            _ov: &objc2_app_kit::NSOutlineView,
5174            _col: Option<&NSTableColumn>,
5175            item: &objc2::runtime::AnyObject,
5176        ) -> Option<Retained<NSString>> {
5177            ffi_guard::contain(None, || {
5178                let token = Self::token_of_item(item)?;
5179                let text = self
5180                    .ivars()
5181                    .source
5182                    .borrow()
5183                    .as_ref()
5184                    .map(|s| (s.type_select_text)(token))
5185                    .unwrap_or_default();
5186                // Empty = this row doesn't participate in type-select.
5187                (!text.is_empty()).then(|| NSString::from_str(&text))
5188            })
5189        }
5190
5191        #[unsafe(method_id(outlineView:rowViewForItem:))]
5192        fn row_view_for_item(
5193            &self,
5194            ov: &objc2_app_kit::NSOutlineView,
5195            _item: &objc2::runtime::AnyObject,
5196        ) -> Retained<objc2_app_kit::NSTableRowView> {
5197            if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5198                // AppKit owns source-list group backgrounds, floating headers and selection.
5199                unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5200            } else {
5201                // The rounded-selection row (see DayTreeRowView).
5202                let rv: Retained<DayTreeRowView> =
5203                    unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5204                Retained::into_super(rv)
5205            }
5206        }
5207
5208        #[unsafe(method(outlineViewSelectionDidChange:))]
5209        fn selection_did_change(&self, notification: &NSNotification) {
5210            ffi_guard::contain((), || {
5211                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5212                    return;
5213                }
5214                let Some(obj) = (unsafe { notification.object() }) else {
5215                    return;
5216                };
5217                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5218                    return;
5219                };
5220                // Always the FULL token set (docs/tree.md): a tree cannot speak row indices.
5221                let idx = unsafe { ov.selectedRowIndexes() };
5222                let mut tokens = Vec::with_capacity(idx.count());
5223                let mut i = idx.firstIndex();
5224                while i != objc2_foundation::NSNotFound as usize {
5225                    if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5226                        && let Some(tok) = Self::token_of_item(&item)
5227                    {
5228                        tokens.push(tok);
5229                    }
5230                    i = unsafe { idx.indexGreaterThanIndex(i) };
5231                }
5232                emit(self.ivars().node, Event::TreeSelection(tokens));
5233            })
5234        }
5235
5236        #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5237        fn did_remove_row_view(
5238            &self,
5239            ov: &objc2_app_kit::NSOutlineView,
5240            row_view: &objc2_app_kit::NSTableRowView,
5241            _row: isize,
5242        ) {
5243            // The row went back to the reuse pool (a collapse, a reload dropping it): clear
5244            // its day element ids so it stops answering `find_by_id`. DEFERRED — this fires
5245            // inside collapse/reload stacks that hold the day-core borrow — and re-checked:
5246            // a cell already reused by the same turn's reload has a window again, and its
5247            // fresh ids must survive.
5248            ffi_guard::contain((), || {
5249                let mut cell_ptr: Option<usize> = None;
5250                for sub in row_view.subviews().iter() {
5251                    let is_cell = sub
5252                        .identifier()
5253                        .map(|i| i.to_string() == "day.tree.cell")
5254                        .unwrap_or(false);
5255                    if is_cell {
5256                        cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5257                    }
5258                }
5259                let Some(cell) = cell_ptr else { return };
5260                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5261                    return;
5262                };
5263                let key = Retained::as_ptr(&scroll) as usize;
5264                // Carry a RETAIN across the post as a raw +1 pointer (the boxed closure must
5265                // be Send, which Retained is not; we stay on the main thread throughout).
5266                // AppKit is free to dealloc removed row views — a bare pointer died here once.
5267                let retained =
5268                    unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5269                        as usize;
5270                <AppKit as Platform>::post(Box::new(move || {
5271                    // Reclaim the +1 first, unconditionally — every early return below must
5272                    // still balance the retain.
5273                    let cell_view: Retained<NSView> =
5274                        match unsafe { Retained::from_raw(retained as *mut NSView) } {
5275                            Some(v) => v,
5276                            None => return,
5277                        };
5278                    let recycle = tree_entry(key).and_then(|(_, data)| {
5279                        data.ivars()
5280                            .source
5281                            .borrow()
5282                            .as_ref()
5283                            .map(|s| s.recycle.clone())
5284                    });
5285                    let Some(recycle) = recycle else { return };
5286                    if cell_view.window().is_some() {
5287                        return; // reused already — its ids are the live row's
5288                    }
5289                    recycle(cell as RawHandle);
5290                }));
5291            })
5292        }
5293
5294        #[unsafe(method(outlineViewItemDidExpand:))]
5295        fn item_did_expand(&self, notification: &NSNotification) {
5296            self.report_disclosure(notification, true);
5297        }
5298
5299        #[unsafe(method(outlineViewItemDidCollapse:))]
5300        fn item_did_collapse(&self, notification: &NSNotification) {
5301            self.report_disclosure(notification, false);
5302        }
5303    }
5304);
5305
5306impl DayTreeData {
5307    fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5308        let this = Self::alloc(mtm).set_ivars(TreeIvars {
5309            node,
5310            source: RefCell::new(None),
5311            selectable: std::cell::Cell::new(selectable),
5312            suppress: std::cell::Cell::new(false),
5313            items: RefCell::new(HashMap::new()),
5314        });
5315        unsafe { msg_send![super(this), init] }
5316    }
5317
5318    /// The same NSNumber for a token, every time — NSOutlineView's item identity.
5319    fn intern(&self, token: u64) -> Retained<NSNumber> {
5320        self.ivars()
5321            .items
5322            .borrow_mut()
5323            .entry(token)
5324            .or_insert_with(|| NSNumber::new_u64(token))
5325            .clone()
5326    }
5327
5328    fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5329        item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
5330    }
5331
5332    /// A native disclosure (user click, keyboard left/right) → `Event::TreeExpanded`.
5333    /// Programmatic `TreePatch::Expand` applications are suppressed (the echo rule).
5334    fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5335        ffi_guard::contain((), || {
5336            if self.ivars().suppress.get() {
5337                return;
5338            }
5339            let token = unsafe { notification.userInfo() }
5340                .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
5341                .and_then(|item| Self::token_of_item(&item));
5342            if let Some(token) = token {
5343                emit(self.ivars().node, Event::TreeExpanded { token, expanded });
5344            }
5345        })
5346    }
5347
5348    /// The full drop proposal — `(dragged token, parent token, index)` — for a LOCAL drag
5349    /// from this outline; `None` for a foreign drag or an unparseable one. `index: None`
5350    /// means "ONTO the parent" (NSOutlineView's childIndex -1, `NSOutlineViewDropOnItemIndex`).
5351    fn drop_proposal(
5352        &self,
5353        ov: &objc2_app_kit::NSOutlineView,
5354        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5355        item: Option<&objc2::runtime::AnyObject>,
5356        child_index: isize,
5357    ) -> Option<(u64, Option<u64>, Option<usize>)> {
5358        let src = unsafe { info.draggingSource() }?;
5359        if Retained::as_ptr(&src) as *const std::ffi::c_void
5360            != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
5361        {
5362            return None;
5363        }
5364        let pb = unsafe { info.draggingPasteboard() };
5365        let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
5366            .to_string()
5367            .parse::<u64>()
5368            .ok()?;
5369        let parent = match item {
5370            Some(i) => Some(Self::token_of_item(i)?), // a non-token item is not ours
5371            None => None,
5372        };
5373        let index = (child_index >= 0).then_some(child_index as usize);
5374        Some((token, parent, index))
5375    }
5376
5377    /// The guard's live verdict through the sync seam.
5378    fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
5379        self.ivars()
5380            .source
5381            .borrow()
5382            .as_ref()
5383            .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
5384            .map(|v| v == MoveVerdict::Allow)
5385            .unwrap_or(false)
5386    }
5387}
5388
5389// DayOutlineView — an NSOutlineView that PINS its width to its clip on every layout pass.
5390// A table sizes itself from its COLUMNS, and the autoresizing mask only tracks deltas, so
5391// any early pass at a different pane width leaves a permanent offset (a 233pt table in a
5392// 220pt pane, whose selection pill then clips mid-corner). Enforcing it in `layout` — not
5393// in occasional deferred posts — closes every window where a stale width could draw.
5394define_class!(
5395    #[unsafe(super(objc2_app_kit::NSOutlineView))]
5396    #[thread_kind = MainThreadOnly]
5397    #[name = "DayOutlineView"]
5398    struct DayOutlineView;
5399
5400    impl DayOutlineView {
5401        #[unsafe(method(layout))]
5402        fn layout(&self) {
5403            sync_tree_width(self);
5404            let _: () = unsafe { msg_send![super(self), layout] };
5405        }
5406
5407        /// A summon-time ROW context menu (docs/menus.md, docs/tree.md): right-click asks
5408        /// the tree's `row_menu` provider for the row under the pointer.
5409        #[unsafe(method_id(menuForEvent:))]
5410        fn menu_for_event(
5411            &self,
5412            event: &objc2_app_kit::NSEvent,
5413        ) -> Option<Retained<NSMenu>> {
5414            ffi_guard::contain(None, || {
5415                let scroll = unsafe { self.enclosingScrollView() }?;
5416                let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
5417                let row_menu = data
5418                    .ivars()
5419                    .source
5420                    .borrow()
5421                    .as_ref()
5422                    .and_then(|s| s.row_menu.clone())?;
5423                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
5424                let row = unsafe { self.rowAtPoint(p) };
5425                if row < 0 {
5426                    return None;
5427                }
5428                let token =
5429                    unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
5430                let items = row_menu(token);
5431                if items.is_empty() {
5432                    return None;
5433                }
5434                Some(build_ns_menu(self.mtm(), "", &items))
5435            })
5436        }
5437    }
5438);
5439
5440// DayTreeRowView — a tree row with the MODERN selection: a rounded pill, inset from the
5441// pane's edges, in the system's semantic selection colors (accent when the tree has focus,
5442// the quiet gray otherwise). Drawn by hand rather than through `NSTableViewStyle::Inset`,
5443// whose machinery pads the table wider than its clip and fights day's fixed-frame layout —
5444// and a hand-drawn plain color also captures correctly offscreen, where materials go black
5445// (docs/navigation.md's sidebar-screenshot rule).
5446define_class!(
5447    #[unsafe(super(objc2_app_kit::NSTableRowView))]
5448    #[thread_kind = MainThreadOnly]
5449    #[name = "DayTreeRowView"]
5450    struct DayTreeRowView;
5451
5452    impl DayTreeRowView {
5453        #[unsafe(method(drawSelectionInRect:))]
5454        fn draw_selection_in_rect(&self, _dirty: NSRect) {
5455            if !unsafe { self.isSelected() } {
5456                return;
5457            }
5458            let color = if unsafe { self.isEmphasized() } {
5459                unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
5460            } else {
5461                unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
5462            };
5463            let b = self.bounds();
5464            let pill = NSRect::new(
5465                NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
5466                NSSize::new(
5467                    (b.size.width - 10.0).max(0.0),
5468                    (b.size.height - 2.0).max(0.0),
5469                ),
5470            );
5471            unsafe {
5472                color.setFill();
5473                objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
5474                    pill, 5.0, 5.0,
5475                )
5476                .fill();
5477            }
5478        }
5479    }
5480);
5481
5482// DayTreeCell — a tree row's flipped cell container. NSOutlineView frames it at the row's
5483// INDENTED position, so its width is per-row; every native layout pass re-lays the Day row
5484// content inside it at that width through the seam's `layout_cell`.
5485define_class!(
5486    #[unsafe(super(objc2_app_kit::NSTableCellView))]
5487    #[thread_kind = MainThreadOnly]
5488    #[name = "DayTreeCell"]
5489    struct DayTreeCell;
5490
5491    impl DayTreeCell {
5492        #[unsafe(method(isFlipped))]
5493        fn is_flipped(&self) -> bool {
5494            true
5495        }
5496
5497        #[unsafe(method(layout))]
5498        fn layout(&self) {
5499            let _: () = unsafe { msg_send![super(self), layout] };
5500            ffi_guard::contain((), || {
5501                let width = self.bounds().size.width;
5502                if width <= 0.0 {
5503                    return;
5504                }
5505                // This cell's tree: walk up to the outline, then to its scroll host, which
5506                // keys TREE_STATE. (The cell may be in the reuse pool — no outline — or the
5507                // tree may be mid-teardown; both just skip.)
5508                let mut cur = unsafe { self.superview() };
5509                let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
5510                while let Some(v) = cur {
5511                    cur = unsafe { v.superview() };
5512                    if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
5513                        outline = Some(ov);
5514                        break;
5515                    }
5516                }
5517                let Some(ov) = outline else { return };
5518                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5519                    return;
5520                };
5521                let f = tree_entry(Retained::as_ptr(&scroll) as usize)
5522                    .and_then(|(_, data)| {
5523                        data.ivars()
5524                            .source
5525                            .borrow()
5526                            .as_ref()
5527                            .map(|s| s.layout_cell_size.clone())
5528                    });
5529                if let Some(f) = f {
5530                    f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
5531                }
5532            })
5533        }
5534    }
5535);
5536
5537impl DayTreeCell {
5538    fn new(mtm: MainThreadMarker) -> Retained<Self> {
5539        unsafe { msg_send![Self::alloc(mtm), init] }
5540    }
5541}
5542
5543/// The private pasteboard type carrying a dragged day tree node's token (local moves only).
5544const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
5545
5546/// A realized TREE's scroll view ptr → (outline, data source).
5547type TreeEntry = (
5548    Retained<objc2_app_kit::NSOutlineView>,
5549    Retained<DayTreeData>,
5550);
5551
5552/// Clone a tree's (outline, data) out of `TREE_STATE` under a SHORT borrow — the same
5553/// re-entrancy rule as `list_entry` (its comment has the war story).
5554fn tree_entry(key: usize) -> Option<TreeEntry> {
5555    TREE_STATE.with(|m| m.borrow().get(&key).cloned())
5556}
5557
5558/// Keep the outline exactly as wide as its clip — DayOutlineView calls this on every layout
5559/// pass (its comment has the why). The list never noticed the width drift because it lays
5560/// row content at the HOST's width; tree rows lay out at the CELL's, which exposes it.
5561fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
5562    let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
5563        return;
5564    };
5565    let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
5566    let f = outline.frame();
5567    if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
5568        unsafe {
5569            outline.setFrameSize(NSSize::new(clip_w, f.size.height));
5570            outline.sizeLastColumnToFit();
5571        }
5572    }
5573}
5574
5575/// Realize the tree's visible rows on the next main-loop turn, outside any borrow — the
5576/// tree twin of `post_realize_visible_rows` (its comment explains the occluded-window trap).
5577fn post_realize_visible_tree_rows(key: usize) {
5578    <AppKit as Platform>::post(Box::new(move || {
5579        if let Some((outline, _)) = tree_entry(key) {
5580            let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
5581            for row in range.location..range.location + range.length {
5582                let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
5583            }
5584        }
5585        day_core::pump_events();
5586    }));
5587}
5588
5589/// A realized NAV_MENU's native outline view paired with its data-source object.
5590type NavMenuEntry = (
5591    Retained<objc2_app_kit::NSOutlineView>,
5592    Retained<DayNavMenuData>,
5593);
5594
5595fn ns_rect(r: day_spec::Rect) -> NSRect {
5596    NSRect::new(
5597        NSPoint::new(r.origin.x, r.origin.y),
5598        NSSize::new(r.size.width, r.size.height),
5599    )
5600}
5601
5602fn draw_op(op: &DrawOp) {
5603    unsafe {
5604        match op {
5605            // One path for the whole batch, then one fill or stroke: the template is appended
5606            // once per position, so the rasterizer is entered once however many copies there are
5607            // (docs/canvas.md "Stamping"). A gradient resolves against the batch's own bounds,
5608            // which is what makes a stamped scatter shade across the group rather than repeating
5609            // the ramp inside every dot.
5610            DrawOp::Stamp(st) => {
5611                let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
5612                for p in &st.at {
5613                    if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
5614                        unsafe { batch.appendBezierPath(&copy) };
5615                    }
5616                }
5617                let color = match &st.paint {
5618                    day_spec::Paint::Solid(c) => *c,
5619                    // A gradient over a stamped batch clips to the whole batch path; the solid
5620                    // fallback below keeps the marks visible on a backend path that cannot.
5621                    _ => day_spec::Color::WHITE,
5622                };
5623                match &st.stroke {
5624                    None => {
5625                        nscolor(color).setFill();
5626                        unsafe { batch.fill() };
5627                    }
5628                    Some(style) => {
5629                        nscolor(color).setStroke();
5630                        apply_stroke_style(&batch, style);
5631                        unsafe { batch.stroke() };
5632                    }
5633                }
5634            }
5635            DrawOp::Fill(shape, paint) => match paint {
5636                day_spec::Paint::Solid(color) => {
5637                    nscolor(*color).setFill();
5638                    if let Some(p) = bezier(shape) {
5639                        p.fill();
5640                    }
5641                }
5642                day_spec::Paint::Linear(g) => {
5643                    // Native linear gradient: clip to the shape's path, then NSGradient along
5644                    // the line resolved from the gradient's unit points in the shape's bounds.
5645                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5646                        let b = shape.bounds();
5647                        let (s, e) = (g.start.resolve(b), g.end.resolve(b));
5648                        NSGraphicsContext::saveGraphicsState_class();
5649                        p.addClip();
5650                        grad.drawFromPoint_toPoint_options(
5651                            NSPoint::new(s.x, s.y),
5652                            NSPoint::new(e.x, e.y),
5653                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5654                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5655                        );
5656                        NSGraphicsContext::restoreGraphicsState_class();
5657                    }
5658                }
5659                day_spec::Paint::Radial(g) => {
5660                    // Native radial gradient: clip to the path, map unit space onto the bounds
5661                    // (elliptical in non-square bounds), draw circular in unit coordinates.
5662                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5663                        let b = shape.bounds();
5664                        NSGraphicsContext::saveGraphicsState_class();
5665                        p.addClip();
5666                        concat_unit_to_bounds(b);
5667                        let c = NSPoint::new(g.center.x, g.center.y);
5668                        grad.drawFromCenter_radius_toCenter_radius_options(
5669                            c,
5670                            0.0,
5671                            c,
5672                            g.radius,
5673                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5674                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5675                        );
5676                        NSGraphicsContext::restoreGraphicsState_class();
5677                    }
5678                }
5679            },
5680            DrawOp::Stroke(shape, paint, style) => {
5681                if let Some(p) = bezier(shape) {
5682                    apply_stroke_style(&p, style);
5683                    match paint {
5684                        day_spec::Paint::Solid(color) => {
5685                            nscolor(*color).setStroke();
5686                            p.stroke();
5687                        }
5688                        // No gradient-stroke primitive here either: turn the stroke into the
5689                        // region it covers and draw the gradient through that clip.
5690                        // No gradient-stroke primitive: convert the stroke into the REGION it
5691                        // covers (CoreGraphics can, and NSGraphicsContext hands us its context),
5692                        // clip to that, then draw the gradient through it.
5693                        _ => {
5694                            let Some(ctx) = NSGraphicsContext::currentContext() else {
5695                                return;
5696                            };
5697                            let cg = ctx.CGContext();
5698                            NSGraphicsContext::saveGraphicsState_class();
5699                            objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
5700                            objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
5701                                &cg,
5702                            ));
5703                            objc2_core_graphics::CGContext::clip(Some(&cg));
5704                            draw_gradient_in(paint, shape.bounds());
5705                            NSGraphicsContext::restoreGraphicsState_class();
5706                        }
5707                    }
5708                }
5709            }
5710            DrawOp::Clip(shape) => {
5711                // `addClip` intersects with the current clip and honors the path's winding rule.
5712                if let Some(p) = bezier(shape) {
5713                    p.addClip();
5714                }
5715            }
5716            DrawOp::Text {
5717                text,
5718                at,
5719                size,
5720                color,
5721                anchor,
5722                font,
5723            } => {
5724                let font = canvas_nsfont(*size, font);
5725                let attrs = canvas_text_attrs(&font, *color);
5726                let ns = NSString::from_str(text);
5727                let mut origin = NSPoint::new(at.x, at.y);
5728                // `drawAtPoint:` takes the top-leading corner of the line box, so any other
5729                // anchor is an offset from it. The size comes from the attributes the draw is
5730                // about to use, which is why the alignment belongs here and not in the app: the
5731                // caller would have to ask for these same metrics through `measure_text` first.
5732                if *anchor != day_spec::TextAnchor::LEADING {
5733                    let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
5734                    let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
5735                    origin.x += dx;
5736                    origin.y += dy;
5737                }
5738                let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
5739            }
5740            // A released bitmap draws nothing rather than a placeholder: the canvas re-records
5741            // on every tracked read, so a handle can be dropped between the record and the
5742            // replay, and a frame that flashes a grey box is worse than one that omits the image.
5743            DrawOp::Image {
5744                image,
5745                rect,
5746                opacity,
5747            } => {
5748                let img = BITMAPS.with(|m| m.borrow().get(&image.0).map(|b| b.image.clone()));
5749                if let Some(img) = img {
5750                    let dest = NSRect::new(
5751                        NSPoint::new(rect.origin.x, rect.origin.y),
5752                        NSSize::new(rect.size.width, rect.size.height),
5753                    );
5754                    // DayCanvas is flipped (top-left origin). Respect that context so image
5755                    // rows stay upright, including under the canvas's rotation/zoom transforms.
5756                    // A zero `fromRect` means the whole image; `fraction` multiplies its alpha.
5757                    img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
5758                        dest,
5759                        NSRect::ZERO,
5760                        objc2_app_kit::NSCompositingOperation::SourceOver,
5761                        *opacity,
5762                        true,
5763                        None,
5764                    );
5765                }
5766            }
5767            DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
5768            DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
5769            DrawOp::Concat(m) => {
5770                let t = NSAffineTransform::new();
5771                t.setTransformStruct(NSAffineTransformStruct {
5772                    m11: m.a,
5773                    m12: m.b,
5774                    m21: m.c,
5775                    m22: m.d,
5776                    tX: m.tx,
5777                    tY: m.ty,
5778                });
5779                t.concat();
5780            }
5781        }
5782    }
5783}
5784
5785/// An `NSGradient` from a display-list gradient's stops (sRGB, like every canvas color).
5786fn nsgradient(
5787    stops: &[(f64, day_spec::Color)],
5788) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
5789    if stops.is_empty() {
5790        return None;
5791    }
5792    let colors = objc2_foundation::NSArray::from_retained_slice(
5793        &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
5794    );
5795    let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
5796    unsafe {
5797        objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
5798            objc2_app_kit::NSGradient::alloc(),
5799            &colors,
5800            locations.as_ptr(),
5801            &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
5802        )
5803    }
5804}
5805
5806/// Concat a bounds-mapping transform (unit gradient space → `b`) onto the current context, so a
5807/// circular gradient drawn in unit coordinates renders elliptically stretched to the bounds.
5808fn concat_unit_to_bounds(b: day_spec::Rect) {
5809    let t = NSAffineTransform::new();
5810    t.setTransformStruct(NSAffineTransformStruct {
5811        m11: b.size.width,
5812        m12: 0.0,
5813        m21: 0.0,
5814        m22: b.size.height,
5815        tX: b.origin.x,
5816        tY: b.origin.y,
5817    });
5818    unsafe { t.concat() };
5819}
5820
5821/// Put a [`day_spec::StrokeStyle`] onto a path.
5822///
5823/// NOTE: this backend used to force ROUND caps on every stroke. It now honors the style, whose
5824/// default is BUTT — the same default the spec and every other backend use. A line that wants
5825/// round ends asks for `StrokeStyle::round`.
5826fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
5827    use day_spec::{LineCap, LineJoin};
5828    unsafe {
5829        p.setLineWidth(style.width);
5830        p.setLineCapStyle(match style.cap {
5831            LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
5832            LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
5833            LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
5834        });
5835        if style.is_plain() {
5836            return;
5837        }
5838        p.setLineJoinStyle(match style.join {
5839            LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
5840            LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
5841            LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
5842        });
5843        p.setMiterLimit(style.miter_limit);
5844        if !style.dash.is_empty() {
5845            let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
5846            p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
5847        }
5848    }
5849}
5850
5851/// Draw a gradient through whatever clip is installed, in AppKit's own NSGradient terms.
5852/// Shared by the gradient FILL arms and the gradient STROKE arm, which differ only in what they
5853/// clipped to first.
5854fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
5855    let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5856        | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
5857    match paint {
5858        day_spec::Paint::Linear(g) => {
5859            if let Some(grad) = nsgradient(&g.stops) {
5860                let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
5861                unsafe {
5862                    grad.drawFromPoint_toPoint_options(
5863                        NSPoint::new(s.x, s.y),
5864                        NSPoint::new(e.x, e.y),
5865                        opts,
5866                    )
5867                };
5868            }
5869        }
5870        day_spec::Paint::Radial(g) => {
5871            if let Some(grad) = nsgradient(&g.stops) {
5872                NSGraphicsContext::saveGraphicsState_class();
5873                concat_unit_to_bounds(bounds);
5874                let c = NSPoint::new(g.center.x, g.center.y);
5875                unsafe {
5876                    grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
5877                };
5878                NSGraphicsContext::restoreGraphicsState_class();
5879            }
5880        }
5881        day_spec::Paint::Solid(_) => {}
5882    }
5883}
5884
5885fn apply_button_content(
5886    btn: &NSButton,
5887    title: &str,
5888    icon: Option<&day_spec::Icon>,
5889    icon_only: bool,
5890) {
5891    let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
5892    if let Some(image) = &image {
5893        let size = image.size();
5894        let longest = size.width.max(size.height);
5895        if longest > 0.0 {
5896            image.setSize(objc2_foundation::NSSize::new(
5897                size.width * 20.0 / longest,
5898                size.height * 20.0 / longest,
5899            ));
5900        }
5901    }
5902    let style = BUTTON_STYLES
5903        .with(|m| m.borrow().get(&ptr_of(btn)).copied())
5904        .unwrap_or_default();
5905    BUTTON_IMAGES.with(|images| {
5906        images.remove(ptr_of(btn));
5907        if let Some(image) = &image {
5908            images.insert(ptr_of(btn), image.clone());
5909        }
5910    });
5911    set_button_title(btn, title, style);
5912    // The position first: the image setter pads a glyph that sits beside a title, and leaves
5913    // an icon-only one alone, by reading it.
5914    unsafe {
5915        btn.setImagePosition(if image.is_none() {
5916            objc2_app_kit::NSCellImagePosition::NoImage
5917        } else if icon_only {
5918            objc2_app_kit::NSCellImagePosition::ImageOnly
5919        } else {
5920            objc2_app_kit::NSCellImagePosition::ImageLeading
5921        });
5922    }
5923    set_button_image(btn, style);
5924    unsafe {
5925        // The title is the spoken name (an icon-only button shows none), unless the app named
5926        // the button itself; overwriting that here replaced app labels on every title change.
5927        if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
5928            btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
5929        }
5930        let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
5931        btn.setToolTip(tooltip.as_deref());
5932    }
5933}
5934
5935/// Bordered buttons do not reliably apply contentTintColor to template images. Keep
5936/// the native button, but supply an image that draws the original vector's alpha in
5937/// the requested contrast color at the destination resolution.
5938fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
5939    use day_spec::props::ButtonStyleSpec as S;
5940    let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
5941    let image = image.map(|source| {
5942        let S::Tinted(fill) = style else {
5943            return source;
5944        };
5945        let size = source.size();
5946        let ink = nscolor(S::on_tint(fill));
5947        let draw = block2::RcBlock::new(move |rect: NSRect| {
5948            source.drawInRect_fromRect_operation_fraction(
5949                rect,
5950                NSRect::ZERO,
5951                objc2_app_kit::NSCompositingOperation::SourceOver,
5952                1.0,
5953            );
5954            unsafe {
5955                ink.setFill();
5956                objc2_app_kit::NSRectFillUsingOperation(
5957                    rect,
5958                    objc2_app_kit::NSCompositingOperation::SourceIn,
5959                );
5960            }
5961            objc2::runtime::Bool::YES
5962        });
5963        objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
5964    });
5965    unsafe {
5966        let position = btn.imagePosition();
5967        // Beside a title, the glyph gets a clear gap: AppKit draws a leading image flush
5968        // against the text, so the image carries the space itself (a template stays one, so
5969        // the label color still tints it). The cell centers the image in its slot, so half
5970        // the extra width lands on each side.
5971        let image = image.map(|source| {
5972            // The position is set after this on a fresh button, so an unset one counts as
5973            // "beside a title"; only an icon-only button keeps the glyph as drawn.
5974            if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
5975                return source;
5976            }
5977            let size = source.size();
5978            let template = source.isTemplate();
5979            let padded = NSSize::new(size.width + 8.0, size.height);
5980            let draw = block2::RcBlock::new(move |_rect: NSRect| {
5981                source.drawInRect_fromRect_operation_fraction(
5982                    NSRect::new(NSPoint::new(0.0, 0.0), size),
5983                    NSRect::ZERO,
5984                    objc2_app_kit::NSCompositingOperation::SourceOver,
5985                    1.0,
5986                );
5987                objc2::runtime::Bool::YES
5988            });
5989            let out =
5990                objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
5991            out.setTemplate(template);
5992            out
5993        });
5994        btn.setImage(image.as_deref());
5995        btn.setImagePosition(position);
5996        btn.setImageHugsTitle(true);
5997    }
5998}
5999
6000/// Put `ButtonProps::selected` on an `NSButton`, keeping it an NSButton. A momentary button
6001/// shows no state, so the first `true` makes it push-on/push-off, whose on state AppKit draws
6002/// as the bezel's highlighted fill and VoiceOver reads as selected; a button that never
6003/// selects keeps its momentary type. A click toggles the state natively before the action
6004/// runs, so the `action:` handler restores the value recorded here.
6005fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
6006    BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
6007    unsafe {
6008        if on {
6009            btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
6010        }
6011        btn.setState(if on {
6012            NSControlStateValueOn
6013        } else {
6014            NSControlStateValueOff
6015        });
6016    }
6017}
6018
6019/// The corner radius of the tint painted behind a tinted button's bezel: the rounded push
6020/// bezel's own, so the fill reads as the bezel rather than as a box around it.
6021const TINT_CORNER_RADIUS: f64 = 6.0;
6022
6023/// Put a [`day_spec::props::ButtonStyleSpec`] on an `NSButton`, keeping it an NSButton.
6024///
6025/// Prominent = the return-key default button. Tinted = `bezelColor`, which AppKit composites
6026/// through the button's own bezel — so the pressed darkening, the focus ring and the disabled
6027/// look all still come from the control rather than from us painting a rectangle. macOS 26
6028/// composites the push bezel as a system material that ignores `bezelColor` on screen (an
6029/// offscreen `cacheDisplay` still honors it), so the tint is also painted on the control's
6030/// backing layer, where the translucent material lets it through; on older systems the opaque
6031/// tinted bezel covers that layer, so nothing changes there.
6032fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
6033    use day_spec::props::ButtonStyleSpec as S;
6034    let title = unsafe { btn.title() }.to_string();
6035    unsafe {
6036        // Reset first, so a patch from one style to another leaves nothing of the old one.
6037        btn.setKeyEquivalent(&NSString::from_str(""));
6038        btn.setBezelColor(None);
6039        btn.setBordered(!matches!(style, S::Plain));
6040        match style {
6041            S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
6042            S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
6043            // Bordered is the stock NSButton look already; Automatic asks for nothing, and an
6044            // NSButton hugs a one-glyph title already, so Compact asks for nothing either.
6045            S::Bordered | S::Automatic | S::Compact | S::Plain => {}
6046        }
6047        btn.setWantsLayer(true);
6048        if let Some(layer) = btn.layer() {
6049            match style {
6050                S::Tinted(c) => {
6051                    layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
6052                    layer.setCornerRadius(TINT_CORNER_RADIUS);
6053                }
6054                _ => layer.setBackgroundColor(None),
6055            }
6056        }
6057    }
6058    BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6059    let ink = match style {
6060        S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6061        _ => None,
6062    };
6063    unsafe {
6064        btn.setContentTintColor(ink.as_deref());
6065    }
6066    set_button_title(btn, &title, style);
6067    set_button_image(btn, style);
6068}
6069
6070/// Set a button's title, coloring it for the tint where there is one.
6071///
6072/// `contentTintColor` is NOT the seam for this: on a bordered `NSButton`,
6073/// AppKit keeps drawing the title in its own control text color — which is how a
6074/// white-on-rust button came out black-on-rust. An ATTRIBUTED title is the documented way to
6075/// control the text color, so that is what a tinted button gets.
6076///
6077/// The button's own font is carried into the attributes: an attributed title supplies the whole
6078/// run, so leaving the font out would drop the control font and render at the system default.
6079fn set_button_title(
6080    btn: &objc2_app_kit::NSButton,
6081    title: &str,
6082    style: day_spec::props::ButtonStyleSpec,
6083) {
6084    use day_spec::props::ButtonStyleSpec as S;
6085    // Changing an attributed title can reset NSButton's image placement. A reactive
6086    // tint must keep an icon-only button icon-only, including its native template tint.
6087    let position = unsafe { btn.imagePosition() };
6088    let S::Tinted(fill) = style else {
6089        // Plain title: AppKit picks the label color that suits the bezel it is drawing.
6090        unsafe {
6091            btn.setTitle(&NSString::from_str(title));
6092            btn.setImagePosition(position);
6093        }
6094        return;
6095    };
6096    unsafe {
6097        let col = nscolor(S::on_tint(fill));
6098        let font = btn
6099            .font()
6100            .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6101        // Centered, matching a plain NSButton title: an attributed title carries its own
6102        // paragraph style, and the default is left-aligned.
6103        let para = objc2_app_kit::NSMutableParagraphStyle::new();
6104        para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6105        let keys: [&NSString; 3] = [
6106            objc2_app_kit::NSFontAttributeName,
6107            objc2_app_kit::NSForegroundColorAttributeName,
6108            objc2_app_kit::NSParagraphStyleAttributeName,
6109        ];
6110        let objs: [&objc2::runtime::AnyObject; 3] = [
6111            font.as_ref() as &objc2::runtime::AnyObject,
6112            col.as_ref() as &objc2::runtime::AnyObject,
6113            para.as_ref() as &objc2::runtime::AnyObject,
6114        ];
6115        let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6116        let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6117            objc2_foundation::NSAttributedString::alloc(),
6118            &NSString::from_str(title),
6119            Some(&attrs),
6120        );
6121        btn.setAttributedTitle(&s);
6122        btn.setImagePosition(position);
6123    }
6124}
6125
6126// NSImageView supports aspect-fit but not aspect-fill. Expand its native drawing about
6127// the center and clip to the view; this retains vector rendering and template tinting.
6128define_class!(
6129    #[unsafe(super(objc2_app_kit::NSImageView))]
6130    #[thread_kind = MainThreadOnly]
6131    #[name = "DayFillImageView"]
6132    struct FillImageView;
6133
6134    impl FillImageView {
6135        #[unsafe(method(drawRect:))]
6136        fn draw_rect(&self, dirty: NSRect) {
6137            let bounds = self.bounds();
6138            let image = unsafe { self.image() };
6139            let Some(size) = image.map(|image| image.size()).filter(|size| {
6140                size.width > 0.0 && size.height > 0.0
6141                    && bounds.size.width > 0.0 && bounds.size.height > 0.0
6142            }) else {
6143                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6144                return;
6145            };
6146            let x = bounds.size.width / size.width;
6147            let y = bounds.size.height / size.height;
6148            let scale = x.max(y) / x.min(y);
6149            let cx = bounds.origin.x + bounds.size.width / 2.0;
6150            let cy = bounds.origin.y + bounds.size.height / 2.0;
6151            NSGraphicsContext::saveGraphicsState_class();
6152            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6153            let transform = NSAffineTransform::transform();
6154            transform.translateXBy_yBy(cx, cy);
6155            transform.scaleBy(scale);
6156            transform.translateXBy_yBy(-cx, -cy);
6157            transform.concat();
6158            let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6159            NSGraphicsContext::restoreGraphicsState_class();
6160        }
6161
6162        #[unsafe(method(setFrameSize:))]
6163        fn set_frame_size(&self, size: NSSize) {
6164            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6165            NSView::setNeedsDisplay(self, true);
6166        }
6167    }
6168);
6169
6170fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6171    use day_spec::Shape;
6172    use objc2_app_kit::NSBezierPath;
6173    unsafe {
6174        Some(match shape {
6175            Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6176            Shape::RoundedRect(r, rad) => {
6177                NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6178            }
6179            Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6180            Shape::Arc {
6181                rect,
6182                start_deg,
6183                sweep_deg,
6184            } => {
6185                let p = NSBezierPath::new();
6186                let center = NSPoint::new(
6187                    rect.origin.x + rect.size.width / 2.0,
6188                    rect.origin.y + rect.size.height / 2.0,
6189                );
6190                let radius = rect.size.width.min(rect.size.height) / 2.0;
6191                // Flipped view: increasing angle is visually clockwise, matching the spec.
6192                p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6193                    center,
6194                    radius,
6195                    *start_deg,
6196                    *start_deg + *sweep_deg,
6197                );
6198                p
6199            }
6200            Shape::Line(a, b) => {
6201                let p = NSBezierPath::new();
6202                p.moveToPoint(NSPoint::new(a.x, a.y));
6203                p.lineToPoint(NSPoint::new(b.x, b.y));
6204                p
6205            }
6206            Shape::Polygon(pts) => {
6207                if pts.len() < 2 {
6208                    return None;
6209                }
6210                let p = NSBezierPath::new();
6211                p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6212                for pt in &pts[1..] {
6213                    p.lineToPoint(NSPoint::new(pt.x, pt.y));
6214                }
6215                p.closePath();
6216                p
6217            }
6218            Shape::Path(path) => {
6219                use day_spec::PathSeg;
6220                if path.segs.is_empty() {
6221                    return None;
6222                }
6223                let p = NSBezierPath::new();
6224                // NSBezierPath's own quadratic API is macOS 14+, so quads are ELEVATED to
6225                // cubics with the standard formula (c1 = p0 + 2/3(c - p0), c2 = p1 + 2/3(c -
6226                // p1)), which is exact rather than an approximation.
6227                let mut cur = NSPoint::new(0.0, 0.0);
6228                for seg in &path.segs {
6229                    match seg {
6230                        PathSeg::Move(a) => {
6231                            cur = NSPoint::new(a.x, a.y);
6232                            p.moveToPoint(cur);
6233                        }
6234                        PathSeg::Line(a) => {
6235                            cur = NSPoint::new(a.x, a.y);
6236                            p.lineToPoint(cur);
6237                        }
6238                        PathSeg::Quad(c, a) => {
6239                            let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6240                            let c1 = NSPoint::new(
6241                                cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6242                                cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6243                            );
6244                            let c2 = NSPoint::new(
6245                                end.x + 2.0 / 3.0 * (ctl.x - end.x),
6246                                end.y + 2.0 / 3.0 * (ctl.y - end.y),
6247                            );
6248                            p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6249                            cur = end;
6250                        }
6251                        PathSeg::Cubic(c1, c2, a) => {
6252                            cur = NSPoint::new(a.x, a.y);
6253                            p.curveToPoint_controlPoint1_controlPoint2(
6254                                cur,
6255                                NSPoint::new(c1.x, c1.y),
6256                                NSPoint::new(c2.x, c2.y),
6257                            );
6258                        }
6259                        PathSeg::Close => p.closePath(),
6260                    }
6261                }
6262                p.setWindingRule(match path.rule {
6263                    day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6264                    day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6265                });
6266                p
6267            }
6268        })
6269    }
6270}
6271
6272// ---------------------------------------------------------------------------
6273// DayUndoManager — the native FRONT of the app's one undo stack (docs/model.md)
6274// ---------------------------------------------------------------------------
6275
6276/// The mirrored [`day_spec::UndoState`]: what the stock Edit menu reads through the standard
6277/// `undo:`/`redo:` validation. The stack itself lives in day-model; this object only answers
6278/// questions and forwards invocations — two histories can never fork.
6279struct UndoIvars {
6280    state: std::cell::RefCell<day_spec::UndoState>,
6281}
6282
6283define_class!(
6284    #[unsafe(super(objc2_foundation::NSUndoManager))]
6285    #[thread_kind = MainThreadOnly]
6286    #[name = "DayUndoManager"]
6287    #[ivars = UndoIvars]
6288    struct DayUndoManager;
6289
6290    /// Overrides of the questions AppKit's menu validation asks, answered from the mirrored
6291    /// state — and of the two verbs, forwarded as `Event::Undo` (enqueue-only, like every
6292    /// other event). Registration/grouping machinery of the superclass is never used.
6293    impl DayUndoManager {
6294        #[unsafe(method(canUndo))]
6295        fn can_undo(&self) -> bool {
6296            self.ivars().state.borrow().can_undo
6297        }
6298
6299        #[unsafe(method(canRedo))]
6300        fn can_redo(&self) -> bool {
6301            self.ivars().state.borrow().can_redo
6302        }
6303
6304        #[unsafe(method(undo))]
6305        fn do_undo(&self) {
6306            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
6307        }
6308
6309        #[unsafe(method(redo))]
6310        fn do_redo(&self) {
6311            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
6312        }
6313
6314        #[unsafe(method_id(undoMenuItemTitle))]
6315        fn undo_menu_item_title(&self) -> Retained<NSString> {
6316            // Route through the superclass's own title former, so "Undo" itself comes out in
6317            // the system language; the action label arrived already localized from the app.
6318            let label = self.ivars().state.borrow().undo_label.clone();
6319            unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6320        }
6321
6322        #[unsafe(method_id(redoMenuItemTitle))]
6323        fn redo_menu_item_title(&self) -> Retained<NSString> {
6324            let label = self.ivars().state.borrow().redo_label.clone();
6325            unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6326        }
6327    }
6328);
6329
6330fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
6331    UNDO_FRONT.with(|u| {
6332        u.borrow_mut()
6333            .get_or_insert_with(|| {
6334                let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
6335                    state: std::cell::RefCell::new(day_spec::UndoState::default()),
6336                });
6337                unsafe { msg_send![super(this), init] }
6338            })
6339            .clone()
6340    })
6341}
6342
6343// ---------------------------------------------------------------------------
6344// DayWinDelegate — resize + close + key tracking, per window
6345// ---------------------------------------------------------------------------
6346
6347/// `node`: the day window-root id this delegate's window reports to. `None` = the PRIMARY
6348/// window — resize goes to `WINDOW_NODE` and close terminates the app; a secondary window
6349/// (docs/windows.md) reports to its own root and close tears down just that window.
6350struct WinIvars {
6351    node: Option<NodeId>,
6352    /// The tab group this window was opened in (`WindowTabbing::Group`/`Preferred`): the
6353    /// tab bar's "+" opens another window of the same group.
6354    group: Option<String>,
6355    /// The last display state reported (`WindowState::code`), so a resize that does not change
6356    /// the zoom state reports nothing.
6357    last_state: Cell<i32>,
6358}
6359
6360define_class!(
6361    #[unsafe(super(NSObject))]
6362    #[thread_kind = MainThreadOnly]
6363    #[name = "DayWinDelegate"]
6364    #[ivars = WinIvars]
6365    struct DayWinDelegate;
6366
6367    unsafe impl NSObjectProtocol for DayWinDelegate {}
6368
6369    /// The responder chain's last stop for the standard edit nav hosts: a focused text view
6370    /// answered `cut:`/`copy:`/`paste:` long before the window asked its delegate, so what
6371    /// arrives here is the app's to handle — the same precedence the undo manager route uses.
6372    impl DayWinDelegate {
6373        /// Edit ▸ Undo. The stock item's nil-target `undo:` finds no implementor among Day's
6374        /// plain views, so the delegate is where the chain lands — resolving through the
6375        /// acting manager keeps a focused field's typing undo ahead of the document stack.
6376        #[unsafe(method(undo:))]
6377        fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6378            ffi_guard::contain((), || {
6379                if let Some(m) = self.acting_undo_manager() {
6380                    unsafe { m.undo() };
6381                }
6382            });
6383        }
6384
6385        /// Edit ▸ Redo.
6386        #[unsafe(method(redo:))]
6387        fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6388            ffi_guard::contain((), || {
6389                if let Some(m) = self.acting_undo_manager() {
6390                    unsafe { m.redo() };
6391                }
6392            });
6393        }
6394
6395        #[unsafe(method(cut:))]
6396        fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6397            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
6398        }
6399
6400        #[unsafe(method(copy:))]
6401        fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6402            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
6403        }
6404
6405        #[unsafe(method(paste:))]
6406        fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6407            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
6408        }
6409
6410        #[unsafe(method(selectAll:))]
6411        fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6412            ffi_guard::contain((), || {
6413                emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
6414            });
6415        }
6416
6417        /// AppKit's menu validation, the same machinery that greys Edit items for text views:
6418        /// the bridge state answers for cut/copy, and paste additionally requires the
6419        /// pasteboard to actually hold text.
6420        #[unsafe(method(validateMenuItem:))]
6421        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
6422            ffi_guard::contain(false, || {
6423                let state = EDIT_STATE.with(|s| s.get());
6424                match unsafe { item.action() } {
6425                    // The undo pair enables from the acting manager and takes its titles
6426                    // ("Undo Move Shape"), exactly as AppKit's own windows do.
6427                    Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
6428                        Some(m) => {
6429                            item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
6430                            unsafe { m.canUndo() }
6431                        }
6432                        None => false,
6433                    },
6434                    Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
6435                        Some(m) => {
6436                            item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
6437                            unsafe { m.canRedo() }
6438                        }
6439                        None => false,
6440                    },
6441                    Some(a) if a == sel!(selectAll:) => state.can_select_all,
6442                    Some(a) if a == sel!(cut:) => state.can_cut,
6443                    Some(a) if a == sel!(copy:) => state.can_copy,
6444                    Some(a) if a == sel!(paste:) => {
6445                        state.can_paste && {
6446                            let pb = unsafe { NSPasteboard::generalPasteboard() };
6447                            pb.types().is_some_and(|types| !types.is_empty())
6448                        }
6449                    }
6450                    _ => true,
6451                }
6452            })
6453        }
6454    }
6455
6456    unsafe impl NSWindowDelegate for DayWinDelegate {
6457        #[unsafe(method(windowDidResize:))]
6458        fn window_did_resize(&self, notification: &NSNotification) {
6459            ffi_guard::contain((), || {
6460                if let Some(obj) = unsafe { notification.object() }
6461                    && let Ok(win) = obj.downcast::<NSWindow>()
6462                    && let Some(size) = pin_below_title_bar(&win)
6463                {
6464                    let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6465                    emit(target, Event::WindowResized(size));
6466                }
6467                // Zooming is a resize with no notification of its own.
6468                self.report_state_of(notification);
6469            })
6470        }
6471
6472        #[unsafe(method(windowShouldClose:))]
6473        fn window_should_close(&self, _window: &NSWindow) -> bool {
6474            ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
6475        }
6476
6477        #[unsafe(method(windowWillClose:))]
6478        fn window_will_close(&self, _notification: &NSNotification) {
6479            ffi_guard::contain((), || {
6480                match self.ivars().node {
6481                    // Secondary window: confirm the close to day-core, which tears the
6482                    // subtree down on a DEFERRED hop (never inside this AppKit close frame).
6483                    Some(node) => emit(node, Event::WindowClosed),
6484                    // Primary window: closing it quits, taking secondaries with it
6485                    // (docs/windows.md close policy), unless the app keeps running without a
6486                    // window (a status item, `KeepRunning::Always`): then it closes like any
6487                    // other window and day-core decides.
6488                    None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
6489                    None => {
6490                        let app = NSApplication::sharedApplication(self.mtm());
6491                        unsafe { app.terminate(None) };
6492                    }
6493                }
6494            })
6495        }
6496
6497        #[unsafe(method_id(windowWillReturnUndoManager:))]
6498        fn window_will_return_undo_manager(
6499            &self,
6500            _window: &NSWindow,
6501        ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6502            // The responder chain already gave a focused text field its OWN manager before
6503            // asking the window — typing undo stays the field's, the model stack gets the
6504            // rest, exactly the precedence the plan's typing rule wants.
6505            ffi_guard::contain(None, || {
6506                UNDO_FRONT.with(|u| {
6507                    u.borrow()
6508                        .as_ref()
6509                        .map(|m| Retained::into_super(m.clone()))
6510                })
6511            })
6512        }
6513
6514        #[unsafe(method(windowDidBecomeKey:))]
6515        fn window_did_become_key(&self, _notification: &NSNotification) {
6516            ffi_guard::contain((), || {
6517                if let Some(node) = self.ivars().node {
6518                    emit(node, Event::WindowFocused(true));
6519                }
6520            })
6521        }
6522
6523        #[unsafe(method(windowDidResignKey:))]
6524        fn window_did_resign_key(&self, _notification: &NSNotification) {
6525            ffi_guard::contain((), || {
6526                if let Some(node) = self.ivars().node {
6527                    emit(node, Event::WindowFocused(false));
6528                }
6529            })
6530        }
6531
6532        #[unsafe(method(windowDidMiniaturize:))]
6533        fn window_did_miniaturize(&self, notification: &NSNotification) {
6534            ffi_guard::contain((), || self.report_state_of(notification))
6535        }
6536
6537        #[unsafe(method(windowDidDeminiaturize:))]
6538        fn window_did_deminiaturize(&self, notification: &NSNotification) {
6539            ffi_guard::contain((), || self.report_state_of(notification))
6540        }
6541
6542        #[unsafe(method(windowDidEnterFullScreen:))]
6543        fn window_did_enter_full_screen(&self, notification: &NSNotification) {
6544            ffi_guard::contain((), || self.report_state_of(notification))
6545        }
6546
6547        #[unsafe(method(windowDidExitFullScreen:))]
6548        fn window_did_exit_full_screen(&self, notification: &NSNotification) {
6549            ffi_guard::contain((), || self.report_state_of(notification))
6550        }
6551    }
6552
6553    // The tab bar's "+" button walks the responder chain (window → delegate) for
6554    // `newWindowForTab:` — present only when the app registered a new-window builder
6555    // (otherwise automatic tabbing is off and no "+" exists).
6556    impl DayWinDelegate {
6557        #[unsafe(method(newWindowForTab:))]
6558        fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
6559            ffi_guard::contain((), || {
6560                // A window in a tab group of its own gets another window of that group
6561                // (`register_new_window_for`); everything else gets File ▸ New Window's.
6562                let _ = match self.ivars().group.as_deref() {
6563                    Some(group) => day_core::windows::open_new_window_for_group(group),
6564                    None => day_core::windows::open_new_window(),
6565                };
6566            })
6567        }
6568    }
6569);
6570
6571impl DayWinDelegate {
6572    fn report_state_of(&self, notification: &NSNotification) {
6573        if let Some(obj) = unsafe { notification.object() }
6574            && let Ok(win) = obj.downcast::<NSWindow>()
6575        {
6576            self.report_state(&win);
6577        }
6578    }
6579}
6580
6581/// The day name for a key press, or `None` for every key the route does not carry — the
6582/// [`day_spec::KeyEvent`] names (docs/menus.md).
6583fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
6584    match unsafe { event.keyCode() } {
6585        123 => Some("ArrowLeft"),
6586        124 => Some("ArrowRight"),
6587        125 => Some("ArrowDown"),
6588        126 => Some("ArrowUp"),
6589        // Not the delete keys. This backend draws a menu bar, so a Delete accelerator on a
6590        // menu item owns them (docs/menus.md) — and a focused piece that CLAIMS a key stops
6591        // that accelerator from ever seeing it, which is how a canvas ends up swallowing the
6592        // Delete its own Edit menu was going to act on.
6593        //
6594        // A digit, main row or keypad, named by what it types. Never under ⌘, ⌥ or ⌃: those
6595        // combinations are accelerators, and claiming one would starve the menu the same way.
6596        _ => {
6597            let held = NSEventModifierFlags::Command
6598                | NSEventModifierFlags::Option
6599                | NSEventModifierFlags::Control;
6600            if event.modifierFlags().intersects(held) {
6601                return None;
6602            }
6603            let typed = event.characters()?.to_string();
6604            let mut chars = typed.chars();
6605            match (chars.next(), chars.next()) {
6606                (Some(c), None) => day_spec::KeyEvent::digit_name(c),
6607                _ => None,
6608            }
6609        }
6610    }
6611}
6612
6613/// AppKit's modifier flags as day's mask.
6614fn key_modifiers(f: NSEventModifierFlags) -> u8 {
6615    let mut modifiers = 0u8;
6616    if f.contains(NSEventModifierFlags::Shift) {
6617        modifiers |= day_spec::KeyEvent::SHIFT;
6618    }
6619    if f.contains(NSEventModifierFlags::Command) {
6620        modifiers |= day_spec::KeyEvent::PRIMARY;
6621    }
6622    if f.contains(NSEventModifierFlags::Option) {
6623        modifiers |= day_spec::KeyEvent::ALT;
6624    }
6625    modifiers
6626}
6627
6628impl DayWinDelegate {
6629    /// The manager AppKit's own undo mechanics act on: ask the FIRST RESPONDER, whose
6630    /// `undoManager` walks the chain itself — a field editor answers with its typing
6631    /// history, everything else falls through to `windowWillReturnUndoManager` and lands on
6632    /// the app's front. Falls back to the front when no window is key yet.
6633    fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6634        let responder = NSApplication::sharedApplication(self.mtm())
6635            .keyWindow()
6636            .and_then(|w| w.firstResponder());
6637        responder
6638            .and_then(|r| unsafe { r.undoManager() })
6639            .or_else(|| {
6640                UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
6641            })
6642    }
6643}
6644
6645impl DayWinDelegate {
6646    fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
6647        let this = Self::alloc(mtm).set_ivars(WinIvars {
6648            node,
6649            group,
6650            last_state: Cell::new(day_spec::WindowState::Normal.code()),
6651        });
6652        unsafe { msg_send![super(this), init] }
6653    }
6654
6655    /// Report the window's display state if it changed since the last report
6656    /// (docs/windows.md "Window properties"): to the window's root node, or `WINDOW_NODE` for the
6657    /// primary, the same routing as `WindowResized`.
6658    fn report_state(&self, window: &NSWindow) {
6659        let state = ns_window_state(window);
6660        if self.ivars().last_state.replace(state.code()) != state.code() {
6661            log::debug!("appkit: window state now {state:?}");
6662            let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6663            emit(target, Event::WindowStateChanged(state));
6664        }
6665    }
6666}
6667
6668/// What AppKit says a window is showing as: miniaturized wins (a fullscreen window can be
6669/// neither), then fullscreen (whose frame also reads as zoomed), then zoomed.
6670fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
6671    if window.isMiniaturized() {
6672        day_spec::WindowState::Minimized
6673    } else if window
6674        .styleMask()
6675        .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
6676    {
6677        day_spec::WindowState::Fullscreen
6678    } else if window.isZoomed() {
6679        day_spec::WindowState::Maximized
6680    } else {
6681        day_spec::WindowState::Normal
6682    }
6683}
6684
6685/// Ask AppKit for `state`, undoing whatever the window is in first: fullscreen and miniaturized
6686/// have to be left before a window can zoom, and each is its own toggle.
6687fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
6688    use day_spec::WindowState as S;
6689    let current = ns_window_state(window);
6690    if current == state {
6691        return;
6692    }
6693    unsafe {
6694        match current {
6695            S::Minimized => window.deminiaturize(None),
6696            // Leaving fullscreen animates; asking for another state in the same turn would be
6697            // dropped by AppKit mid-transition, so the request stops at leaving it. The state
6698            // signal reads back `Normal`, and a second request takes it from there.
6699            S::Fullscreen => {
6700                window.toggleFullScreen(None);
6701                return;
6702            }
6703            S::Maximized if state != S::Minimized => window.zoom(None),
6704            _ => {}
6705        }
6706        match state {
6707            S::Normal => {}
6708            S::Minimized => window.miniaturize(None),
6709            S::Maximized => {
6710                if !window.isZoomed() {
6711                    window.zoom(None)
6712                }
6713            }
6714            S::Fullscreen => window.toggleFullScreen(None),
6715        }
6716    }
6717}
6718
6719// ---------------------------------------------------------------------------
6720// The backend
6721// ---------------------------------------------------------------------------
6722
6723/// Renderers registered by external Day Piece crates (§8.2 layer 3 — linkme convenience).
6724#[distributed_slice]
6725pub static RENDERERS: [fn() -> Renderer<AppKit>];
6726
6727/// A live secondary window (docs/windows.md). The delegate is RETAINED here —
6728/// `setDelegate:` holds it weakly, and unlike the primary's (kept alive because `run`
6729/// never returns) a secondary's delegate would die at the end of `open_window` otherwise.
6730struct SecondaryWin {
6731    window: Retained<NSWindow>,
6732    #[allow(dead_code)] // held for lifetime only; AppKit talks to it via the weak delegate ref
6733    delegate: Retained<DayWinDelegate>,
6734    content: Handle,
6735}
6736
6737/// Deliver an explicitly registered Escape accelerator before a field editor swallows it.
6738/// The monitor is local to this process and removed with the backend.
6739struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
6740impl Drop for MenuEscapeMonitor {
6741    fn drop(&mut self) {
6742        unsafe { NSEvent::removeMonitor(&self.0) };
6743    }
6744}
6745
6746pub struct AppKit {
6747    menu_escape_monitor: Option<MenuEscapeMonitor>,
6748    sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
6749
6750    mtm: MainThreadMarker,
6751    registry: Registry<AppKit>,
6752    window: Option<Retained<NSWindow>>,
6753    content: Option<Handle>,
6754    secondary: Vec<SecondaryWin>,
6755    app_name: String,
6756    /// Where the next secondary window's top-left goes (docs/windows.md). macOS staggers new
6757    /// windows rather than stacking them: `cascadeTopLeftFromPoint:` places the window and
6758    /// answers the point after it, so threading that answer through here is the whole
6759    /// mechanism. `None` until the primary exists — the cascade starts from its corner.
6760    cascade: Option<NSPoint>,
6761    /// One tracking-area owner per view carrying a `.cursor()` (docs/cursor.md), keyed by the
6762    /// view pointer. Removed when the cursor goes back to `Default`.
6763    cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
6764}
6765
6766impl AppKit {
6767    /// Rebuild a `text_field` as the other class (plain ⇄ secure) and put the replacement
6768    /// where the old view was: same text, look and place among its siblings, same focus and
6769    /// selection, and every view-keyed entry moved to it. day-core drops the old handle
6770    /// without a `release`, so nothing keyed by it may stay behind.
6771    fn swap_text_field(
6772        &mut self,
6773        h: &Handle,
6774        old: &NSTextField,
6775        node: NodeId,
6776        secure: bool,
6777    ) -> Retained<NSTextField> {
6778        let new = new_text_field(self.mtm, node, secure);
6779        let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
6780        // Focus and selection first: reading them is only meaningful while the old field
6781        // still edits. `stringValue` below answers the field editor's live text.
6782        let window = h.window();
6783        let focused = window
6784            .as_deref()
6785            .is_some_and(|w| owns_first_responder(w, h));
6786        let selection = old.currentEditor().map(|e| e.selectedRange());
6787        unsafe {
6788            new.setStringValue(&old.stringValue());
6789            new.setPlaceholderString(old.placeholderString().as_deref());
6790            new.setEnabled(old.isEnabled());
6791            new.setFont(old.font().as_deref());
6792            new.setFrame(h.frame());
6793            new.setHidden(h.isHidden());
6794            new.setMenu(h.menu().as_deref());
6795            new.setToolTip(h.toolTip().as_deref());
6796            // Opacity and transform ride the layer (`set_opacity` / `set_transform`).
6797            if h.wantsLayer() {
6798                new.setWantsLayer(true);
6799                new.setAlphaValue(h.alphaValue());
6800                let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
6801                let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
6802                if !from.is_null() && !to.is_null() {
6803                    let t: CGAffineTransform = msg_send![from, affineTransform];
6804                    let _: () = msg_send![to, setAffineTransform: t];
6805                }
6806            }
6807            // Accessibility (`set_a11y`): only what was set explicitly, so the new class
6808            // keeps its own defaults (a secure field's role and hidden value) for the rest.
6809            if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
6810                new.setAccessibilityIdentifier(Some(&id));
6811            }
6812            if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
6813                new.setAccessibilityLabel(Some(&label));
6814            }
6815            if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
6816                new.setAccessibilityHelp(Some(&help));
6817            }
6818            if !h.isAccessibilityElement() {
6819                new.setAccessibilityElement(false);
6820            }
6821        }
6822        // Recognizers and the cursor's tracking area move as objects, keeping their targets.
6823        for r in unsafe { h.gestureRecognizers() }.iter() {
6824            unsafe {
6825                h.removeGestureRecognizer(&r);
6826                new.addGestureRecognizer(&r);
6827            }
6828        }
6829        GESTURES.with(|m| {
6830            let mut m = m.borrow_mut();
6831            if let Some(targets) = m.remove(&old_key) {
6832                m.insert(new_key, targets);
6833            }
6834        });
6835        if let Some((owner, area)) = self.cursors.remove(&old_key) {
6836            unsafe {
6837                h.removeTrackingArea(&area);
6838                new.addTrackingArea(&area);
6839            }
6840            self.cursors.insert(new_key, (owner, area));
6841        }
6842        PAN_NODES.with(|t| rekey(t, old_key, new_key));
6843        HOVER_NODES.with(|t| rekey(t, old_key, new_key));
6844        KEY_NODES.with(|t| rekey(t, old_key, new_key));
6845        FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
6846        CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
6847        transfer::moved(h, &new);
6848        // The old field goes silent before it leaves: ending its editing session would
6849        // otherwise report a focus loss for a node that keeps its focus.
6850        unsafe { old.setDelegate(None) };
6851        TARGETS.with(|m| {
6852            m.borrow_mut().remove(&old_key);
6853        });
6854        if let Some(parent) = unsafe { h.superview() } {
6855            unsafe {
6856                parent.addSubview_positioned_relativeTo(
6857                    &new,
6858                    objc2_app_kit::NSWindowOrderingMode::Above,
6859                    Some(h),
6860                );
6861                h.removeFromSuperview();
6862            }
6863        }
6864        if focused && let Some(window) = window {
6865            FIELD_SWAP.with(|s| s.set(true));
6866            let taken = window.makeFirstResponder(Some(&new));
6867            FIELD_SWAP.with(|s| s.set(false));
6868            // Taking focus selects the whole text; put back what was selected (the caret,
6869            // usually). Both classes count in UTF-16 units, so the range carries over.
6870            if taken && let Some(editor) = new.currentEditor() {
6871                let len = unsafe { new.stringValue() }.length();
6872                let range = selection
6873                    .filter(|r| r.location.saturating_add(r.length) <= len)
6874                    .unwrap_or(objc2_foundation::NSRange::new(len, 0));
6875                editor.setSelectedRange(range);
6876            }
6877        }
6878        // Whatever else was keyed by the old view goes with it.
6879        day_spec::sidetable::sweep(old_key);
6880        new
6881    }
6882
6883    pub fn new() -> Self {
6884        let mtm =
6885            MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
6886        let mut registry = Registry::default();
6887        for f in RENDERERS {
6888            registry.register(f());
6889        }
6890        AppKit {
6891            menu_escape_monitor: None,
6892            mtm,
6893            registry,
6894            window: None,
6895            sharing: None,
6896            content: None,
6897            secondary: Vec::new(),
6898            app_name: "Day".into(),
6899            cascade: None,
6900            cursors: HashMap::new(),
6901        }
6902    }
6903
6904    /// Public helper for external renderers.
6905    pub fn mtm(&self) -> MainThreadMarker {
6906        self.mtm
6907    }
6908
6909    /// The `NSWindow` whose content container is `host`: a secondary window, or the primary.
6910    fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
6911        if let Some(w) = self
6912            .secondary
6913            .iter()
6914            .find(|w| ptr_of(&w.content) == ptr_of(host))
6915        {
6916            return Some(w.window.clone());
6917        }
6918        self.content
6919            .as_ref()
6920            .filter(|c| ptr_of(c) == ptr_of(host))
6921            .and(self.window.clone())
6922    }
6923
6924    /// Build a Day window: titled + closable (Preferences kind drops resize/minimize and
6925    /// disallows tabbing per macOS convention; Normal windows share the `day.normal`
6926    /// tabbing group), a flipped content view, and a per-window delegate (`node`: `None` =
6927    /// primary). The window is NOT released-when-closed — Rust's `Retained` owns it, and
6928    /// the AppKit default would double-release under us on close.
6929    fn make_window(
6930        &self,
6931        options: &WindowOptions,
6932        prefs_style: bool,
6933        node: Option<NodeId>,
6934    ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
6935        let mtm = self.mtm;
6936        let (title, size, min_size, tabbing) = (
6937            options.title.as_str(),
6938            options.size,
6939            options.min_size,
6940            &options.tabbing,
6941        );
6942        let content_rect =
6943            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
6944        // The kind decides the controls, the chrome decides the frame (docs/window-chrome.md).
6945        let style = window_chrome::style_mask(options, prefs_style);
6946        let window = window_chrome::alloc_window(
6947            mtm,
6948            content_rect,
6949            style,
6950            options.chrome == day_spec::WindowChrome::Frameless,
6951        );
6952        unsafe { window.setReleasedWhenClosed(false) };
6953        window.setTitle(&NSString::from_str(title));
6954        if let Some(min) = min_size {
6955            unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
6956        }
6957        if let Some(max) = options.max_size {
6958            unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
6959        }
6960        use day_spec::WindowTabbing as T;
6961        use objc2_app_kit::NSWindowTabbingMode as M;
6962        let group = match tabbing {
6963            T::Group(g) | T::Preferred(g) => Some(g.clone()),
6964            T::Automatic | T::Disallowed => None,
6965        };
6966        match tabbing {
6967            _ if prefs_style => window.setTabbingMode(M::Disallowed),
6968            T::Disallowed => window.setTabbingMode(M::Disallowed),
6969            // Same-kind Day windows group as native tabs (System Settings "prefer tabs",
6970            // View ▸ Show Tab Bar, Merge All Windows) — meaningful once a second Normal
6971            // window can exist; inert while automatic tabbing is globally off (see `run`).
6972            T::Automatic => unsafe {
6973                window.setTabbingIdentifier(&NSString::from_str("day.normal"))
6974            },
6975            T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
6976            T::Preferred(g) => {
6977                unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
6978                window.setTabbingMode(M::Preferred);
6979            }
6980        }
6981        if group.is_some() {
6982            // A named group is the app asking for tabs, so the class-wide switch `run` may have
6983            // turned off (no New Window builder) goes back on for it.
6984            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
6985        }
6986        let delegate = DayWinDelegate::new(mtm, node, group);
6987        window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
6988        let content = view_of(DayFlipped::new(mtm));
6989        window.setContentView(Some(&content));
6990        window_chrome::apply(&window, &content, options);
6991        // Tab / Shift-Tab (docs/focus.md). AppKit does NOT derive the key view loop from the view
6992        // hierarchy: `nextKeyView` is nil on a programmatically built window and the loop stays
6993        // empty, so Tab moves focus OUT of a text field and onto nothing — measured on the
6994        // showcase's Focus page, where three Tabs in a row left every field unfocused. Every other
6995        // Day backend gets traversal from its widget order for free; this is the one that has to
6996        // ask. Autorecalculation rather than a call at the end of each layout because Day's tree
6997        // is reactive: fields appear, move, and vanish between passes, and AppKit rebuilding the
6998        // loop on hierarchy changes is the same rule expressed once.
6999        window.setAutorecalculatesKeyViewLoop(true);
7000        (window, delegate, content)
7001    }
7002}
7003
7004impl Default for AppKit {
7005    fn default() -> Self {
7006        Self::new()
7007    }
7008}
7009
7010fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
7011    Retained::from(x.as_ref())
7012}
7013
7014fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
7015    unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
7016}
7017
7018/// The macOS native semantic text style for a logical [`Font`] (`None` for a custom size).
7019/// `NSFont.preferredFont(forTextStyle:)` gives the OS's own typography, tracking the system settings.
7020fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
7021    use objc2_app_kit::*;
7022    unsafe {
7023        Some(match f {
7024            Font::LargeTitle => NSFontTextStyleLargeTitle,
7025            Font::Title => NSFontTextStyleTitle1,
7026            Font::Title2 => NSFontTextStyleTitle2,
7027            Font::Title3 => NSFontTextStyleTitle3,
7028            Font::Headline => NSFontTextStyleHeadline,
7029            Font::Subheadline => NSFontTextStyleSubheadline,
7030            Font::Body => NSFontTextStyleBody,
7031            Font::Callout => NSFontTextStyleCallout,
7032            Font::Footnote => NSFontTextStyleFootnote,
7033            Font::Caption => NSFontTextStyleCaption1,
7034            Font::Caption2 => NSFontTextStyleCaption2,
7035            Font::System(_) | Font::Custom(..) => return None,
7036        })
7037    }
7038}
7039
7040fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
7041    use day_spec::FontWeight as W;
7042    use objc2_app_kit::*;
7043    unsafe {
7044        match w {
7045            W::UltraLight => NSFontWeightUltraLight,
7046            W::Thin => NSFontWeightThin,
7047            W::Light => NSFontWeightLight,
7048            W::Regular => NSFontWeightRegular,
7049            W::Medium => NSFontWeightMedium,
7050            W::Semibold => NSFontWeightSemibold,
7051            W::Bold => NSFontWeightBold,
7052            W::Heavy => NSFontWeightHeavy,
7053            W::Black => NSFontWeightBlack,
7054        }
7055    }
7056}
7057
7058/// The `NSFontManager` weight rung (0 … 15) for a Day weight — the scale
7059/// `fontWithFamily:traits:weight:size:` matches faces on (5 = regular, 9 = bold).
7060fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7061    use day_spec::FontWeight as W;
7062    match w {
7063        W::UltraLight => 2,
7064        W::Thin => 3,
7065        W::Light => 4,
7066        W::Regular => 5,
7067        W::Medium => 6,
7068        W::Semibold => 8,
7069        W::Bold => 9,
7070        W::Heavy => 10,
7071        W::Black => 12,
7072    }
7073}
7074
7075/// Resolve a canvas font (docs/fonts.md) at an absolute size: the system face for `None`,
7076/// else the family's nearest member through `NSFontManager` (which also synthesizes a bold or
7077/// italic the family lacks), falling back to a PostScript/full-name lookup (a bundled font
7078/// registered in `run`) and then to the system font with one warning.
7079fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7080    use objc2_app_kit::*;
7081    let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7082    let mtm = objc2::MainThreadMarker::new().expect("canvas draws on the main thread");
7083    let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7084    let mut traits = NSFontTraitMask::empty();
7085    if weight >= day_spec::FontWeight::Semibold {
7086        traits |= NSFontTraitMask::BoldFontMask;
7087    }
7088    if font.italic {
7089        traits |= NSFontTraitMask::ItalicFontMask;
7090    }
7091    let Some(family) = font.family.as_deref() else {
7092        let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7093        return if font.italic {
7094            unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7095        } else {
7096            base
7097        };
7098    };
7099    let ns_family = NSString::from_str(family);
7100    if let Some(f) = unsafe {
7101        manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7102    } {
7103        return f;
7104    }
7105    if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7106        return if traits.is_empty() {
7107            f
7108        } else {
7109            unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7110        };
7111    }
7112    log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7113    unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7114}
7115
7116/// The attribute dictionary canvas text draws and measures with (the same one, so
7117/// `measure_text` and `replay` agree on the line box).
7118fn canvas_text_attrs(
7119    font: &NSFont,
7120    color: day_spec::Color,
7121) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7122    let col = nscolor(color);
7123    // SAFETY: both are AppKit's own attribute-name constants, valid for the process lifetime.
7124    let keys: [&NSString; 2] = unsafe {
7125        [
7126            objc2_app_kit::NSFontAttributeName,
7127            objc2_app_kit::NSForegroundColorAttributeName,
7128        ]
7129    };
7130    let objs: [&objc2::runtime::AnyObject; 2] = [
7131        font as &objc2::runtime::AnyObject,
7132        col.as_ref() as &objc2::runtime::AnyObject,
7133    ];
7134    objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7135}
7136
7137/// Resolve a [`FontSpec`] to a native `NSFont`: a semantic style via `preferredFont(forTextStyle:)`
7138/// (or a custom system size), then an optional weight override (at the same size) and italic trait.
7139fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7140    use objc2_app_kit::*;
7141    let base: Retained<NSFont> = match spec.style {
7142        Font::System(pt) => {
7143            let w = spec
7144                .weight
7145                .map(ns_weight)
7146                .unwrap_or(unsafe { NSFontWeightRegular });
7147            unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7148        }
7149        // A bundled family (§18.4), registered with CoreText in run(). fontWithName resolves
7150        // family, full, and PostScript names. A weight override maps to the bold trait (the
7151        // family decides what it can supply); unknown families fall back to the system font.
7152        Font::Custom(name, pt) => {
7153            match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7154                Some(f) => {
7155                    if spec
7156                        .weight
7157                        .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7158                    {
7159                        let mtm = objc2::MainThreadMarker::new()
7160                            .expect("labels realize on the main thread");
7161                        unsafe {
7162                            NSFontManager::sharedFontManager(mtm)
7163                                .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
7164                        }
7165                    } else {
7166                        f
7167                    }
7168                }
7169                None => {
7170                    log::warn!(
7171                        "unknown font family {name:?} — falling back to the system font \
7172                         (is the file in the project's fonts/ directory?)"
7173                    );
7174                    let w = spec
7175                        .weight
7176                        .map(ns_weight)
7177                        .unwrap_or(unsafe { NSFontWeightRegular });
7178                    unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7179                }
7180            }
7181        }
7182        style => {
7183            // Invariant: System/Custom matched above, so only the semantic styles — which
7184            // `ns_text_style` maps exhaustively — can reach this arm.
7185            let ts = ns_text_style(style).expect("semantic style");
7186            let opts = objc2_foundation::NSDictionary::new();
7187            let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
7188            match spec.weight {
7189                // A weight override keeps the style's (system-resolved) size but re-picks the weight.
7190                Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
7191                None => f,
7192            }
7193        }
7194    };
7195    // Tabular figures. Cocoa exposes them as a whole font, not a trait, so this re-picks the
7196    // system font at the resolved size/weight rather than converting — which is why it only
7197    // applies to the system styles: a bundled `Font::Custom` family keeps its own figures (asking
7198    // for the system's monospaced-digit face there would silently swap the typeface).
7199    let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
7200        let w = spec
7201            .weight
7202            .map(ns_weight)
7203            .unwrap_or(unsafe { NSFontWeightRegular });
7204        unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
7205    } else {
7206        base
7207    };
7208    // Monospace, by the same rule as tabular: Cocoa ships it as a whole font, so this re-picks
7209    // the system's monospaced face at the resolved size and weight. Skipped for a bundled family
7210    // — swapping a chosen typeface for the system mono would be a surprise, not a refinement.
7211    let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
7212        let w = spec
7213            .weight
7214            .map(ns_weight)
7215            .unwrap_or(unsafe { NSFontWeightRegular });
7216        unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
7217    } else {
7218        base
7219    };
7220    // Relative size (`FontSpec::scale`). Applied last, over whatever face the traits above
7221    // settled on, and through `convertFont_toSize` so a bundled family keeps its typeface —
7222    // re-picking the system font here would undo the Custom/monospace/tabular work above.
7223    let base = if spec.scale != 1.0 {
7224        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7225        let pts = spec.resolved_points(base.pointSize());
7226        unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
7227    } else {
7228        base
7229    };
7230    if spec.italic {
7231        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7232        unsafe {
7233            NSFontManager::sharedFontManager(mtm)
7234                .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
7235        }
7236    } else {
7237        base
7238    }
7239}
7240
7241/// Build an `NSAttributedString` for a label's text + runs (docs/text-runs.md).
7242///
7243/// Ranges arrive as BYTE offsets into a Rust `str`; `NSAttributedString` indexes UTF-16. The
7244/// conversion is per-run rather than a blanket assumption: any text with an emoji or a CJK
7245/// character makes the two disagree, and an off-by-N range there styles the wrong words.
7246/// Stamp a paragraph alignment across a label's whole attributed string.
7247///
7248/// Separate from `setAlignment:` because the two live in different places: the cell has a
7249/// paragraph style, the attributed string carries its own, and the string's wins.
7250fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
7251    use objc2_foundation::{NSMutableAttributedString, NSRange};
7252    unsafe {
7253        let cur = tf.attributedStringValue();
7254        let m = NSMutableAttributedString::initWithAttributedString(
7255            NSMutableAttributedString::alloc(),
7256            &cur,
7257        );
7258        let style = objc2_app_kit::NSMutableParagraphStyle::new();
7259        style.setAlignment(align);
7260        // Wrapping is what makes alignment observable at all, and the default paragraph style a
7261        // fresh NSMutableParagraphStyle carries would otherwise reset it to clipping.
7262        style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
7263        m.addAttribute_value_range(
7264            objc2_app_kit::NSParagraphStyleAttributeName,
7265            &style,
7266            NSRange::new(0, cur.length()),
7267        );
7268        tf.setAttributedStringValue(&m);
7269    }
7270}
7271
7272fn attributed_label(
7273    text: &str,
7274    base_font: &NSFont,
7275    color: Option<day_spec::Color>,
7276    role: day_spec::props::TextRole,
7277    runs: &[day_spec::TextRun],
7278) -> Retained<objc2_foundation::NSAttributedString> {
7279    use objc2_foundation::{NSMutableAttributedString, NSRange};
7280    let ns = NSString::from_str(text);
7281    let s = unsafe {
7282        NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
7283    };
7284    let whole = NSRange::new(0, ns.length());
7285    unsafe {
7286        s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
7287        // Always a foreground: an attributed range with no color attribute draws in black,
7288        // which is unreadable in dark mode. `labelColor` is the adaptive default the field
7289        // would have used on its own.
7290        // An explicit color wins; otherwise the ROLE picks which adaptive system color to use.
7291        // Both are adaptive, which is the point of asking for a role instead of a grey: the
7292        // secondary label is legible against either appearance's background, and a literal one
7293        // cannot be.
7294        let fg = color.map(nscolor).unwrap_or_else(|| match role {
7295            day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
7296            day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
7297        });
7298        s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
7299    }
7300    for r in runs {
7301        let Some(range) = utf16_range(text, &r.range) else {
7302            continue;
7303        };
7304        unsafe {
7305            s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
7306            if let Some(c) = r.color {
7307                s.addAttribute_value_range(
7308                    objc2_app_kit::NSForegroundColorAttributeName,
7309                    &nscolor(c),
7310                    range,
7311                );
7312            }
7313            if let Some(c) = r.background {
7314                s.addAttribute_value_range(
7315                    objc2_app_kit::NSBackgroundColorAttributeName,
7316                    &nscolor(c),
7317                    range,
7318                );
7319            }
7320            if r.underline.is_on() {
7321                let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
7322                s.addAttribute_value_range(
7323                    objc2_app_kit::NSUnderlineStyleAttributeName,
7324                    &style,
7325                    range,
7326                );
7327            }
7328            if r.strikethrough {
7329                let one = objc2_foundation::NSNumber::new_i64(1);
7330                s.addAttribute_value_range(
7331                    objc2_app_kit::NSStrikethroughStyleAttributeName,
7332                    &one,
7333                    range,
7334                );
7335            }
7336            if let Some(url) = r.link.as_deref() {
7337                // The native field editor hit-tests this attribute; DayLabel handles its
7338                // delegate callback and reports LinkActivated without opening the URL itself.
7339                let value = NSString::from_str(url);
7340                s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
7341            }
7342        }
7343    }
7344    s.into_super()
7345}
7346
7347/// [`Underline`](day_spec::Underline) as an `NSUnderlineStyle` bitmask: the line style in the low
7348/// byte, the pattern in the second. `Dotted`/`Wavy` are patterns over a single line, which is
7349/// exactly how AppKit spells them.
7350fn ns_underline(u: day_spec::Underline) -> i64 {
7351    use day_spec::Underline as U;
7352    match u {
7353        U::None => 0,
7354        U::Single => 0x01,
7355        U::Double => 0x09,
7356        U::Dotted => 0x01 | 0x0100,
7357        U::Wavy => 0x01 | 0x0400,
7358    }
7359}
7360
7361/// A byte range in `text` as an `NSRange` in UTF-16 units, or `None` if it is out of bounds.
7362fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
7363    let start = text.get(..r.start)?.encode_utf16().count();
7364    let len = text.get(r.clone())?.encode_utf16().count();
7365    Some(objc2_foundation::NSRange::new(start, len))
7366}
7367
7368/// Register every bundled font file (the project's `fonts/`, staged per §18.4) with CoreText for
7369/// this process, so `Font::Custom` family names resolve through `NSFont::fontWithName`. Called
7370/// once from `run()`; a failure (already registered on a hot relaunch, or a broken file) only
7371/// means that family won't resolve, so it logs and moves on.
7372fn register_bundled_fonts() {
7373    // CFURLRef is toll-free bridged with NSURL, so the NSURL pointer passes straight through.
7374    #[link(name = "CoreText", kind = "framework")]
7375    unsafe extern "C" {
7376        fn CTFontManagerRegisterFontsForURL(
7377            font_url: *const std::ffi::c_void,
7378            scope: u32, // kCTFontManagerScopeProcess = 1
7379            error: *mut *const std::ffi::c_void,
7380        ) -> bool;
7381    }
7382    for path in day_spec::fonts::bundled_fonts() {
7383        let url = unsafe {
7384            objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
7385        };
7386        let ok = unsafe {
7387            CTFontManagerRegisterFontsForURL(
7388                Retained::as_ptr(&url) as *const std::ffi::c_void,
7389                1,
7390                std::ptr::null_mut(),
7391            )
7392        };
7393        if !ok {
7394            log::warn!("could not register bundled font {}", path.display());
7395        }
7396    }
7397}
7398
7399/// `TextAlign` → AppKit. `Natural` rather than `Left` for the leading case: it follows the
7400/// writing direction, so an RTL locale aligns right without the app asking (docs/localization.md).
7401fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
7402    match a {
7403        day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
7404        day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
7405        day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
7406    }
7407}
7408
7409fn configure_label_cell(tf: &NSTextField) {
7410    if let Some(cell) = unsafe { tf.cell() } {
7411        unsafe {
7412            cell.setWraps(true);
7413            cell.setUsesSingleLineMode(false);
7414            cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
7415        }
7416    }
7417}
7418
7419/// If `parent` is a scroll view, children go into its (flipped) document view.
7420fn content_of(parent: &Handle) -> Retained<NSView> {
7421    if let Some(sv) = parent.downcast_ref::<NSScrollView>()
7422        && let Some(doc) = unsafe { sv.documentView() }
7423    {
7424        return doc;
7425    }
7426    parent.clone()
7427}
7428
7429/// Run `body` (which sets animatable properties on a layer-backed view) inside an
7430/// `NSAnimationContext` group so AppKit interpolates the change on the render server with the
7431/// curve's timing function, or immediately when `anim` is `None` (§8.4). `allowsImplicitAnimation`
7432/// makes direct property changes on layer-backed views animate. A spring maps to an overshooting
7433/// cubic-bezier timing function (a visible bounce without an explicit `CASpringAnimation`).
7434fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
7435    let Some(a) = anim else {
7436        body();
7437        return;
7438    };
7439    let (dur, timing) = appkit_timing(a);
7440    unsafe {
7441        NSAnimationContext::beginGrouping();
7442        let ctx = NSAnimationContext::currentContext();
7443        ctx.setDuration(dur);
7444        ctx.setTimingFunction(Some(&timing));
7445        ctx.setAllowsImplicitAnimation(true);
7446        body();
7447        NSAnimationContext::endGrouping();
7448    }
7449}
7450
7451/// The `(duration_secs, timing function)` for a curve. Springs render as an overshooting bezier
7452/// (control point y > 1) whose overshoot grows as damping falls, over a response-derived duration.
7453fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
7454    unsafe {
7455        let named = |n| {
7456            (
7457                a.duration_secs().max(0.01),
7458                CAMediaTimingFunction::functionWithName(n),
7459            )
7460        };
7461        match a.curve {
7462            Curve::Linear => named(kCAMediaTimingFunctionLinear),
7463            Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
7464            Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
7465            Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
7466            Curve::Spring { damping, .. } => {
7467                // Overshoot bezier over exactly the specified duration (authoritative timing).
7468                let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
7469                (
7470                    a.duration_secs().max(0.05),
7471                    CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
7472                )
7473            }
7474        }
7475    }
7476}
7477
7478/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
7479/// a visible placeholder. A missing renderer usually means the piece's `appkit` feature wasn't enabled
7480/// (Tier A.2 derives it automatically under `day build`; a bare `cargo` build may miss it). Deduped
7481/// per kind so a placeholder rendered every frame doesn't spam the log.
7482fn warn_missing_renderer(kind: PieceKind) {
7483    day_spec::placeholder::report(kind, "appkit");
7484}
7485
7486/// The visible-but-harmless placeholder label the unregistered-kind arm renders. Shared with
7487/// the [`props_of`] mismatch fallback, so a wrong props payload degrades to the same surface
7488/// (the warning is already reported by `props_of` itself).
7489pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
7490    view_of(unsafe {
7491        NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
7492    })
7493}
7494
7495impl Toolkit for AppKit {
7496    /// Settled unless a toolbar edit is still painting (toolbar.rs `CHROME_SETTLE`); AppKit's
7497    /// own transitions (sheets, nav pushes) complete within the turn that starts them.
7498    fn ui_idle(&mut self) -> bool {
7499        toolbar::chrome_settled()
7500    }
7501
7502    type Handle = Handle;
7503
7504    fn dark_mode(&mut self) -> bool {
7505        // The app's EFFECTIVE appearance — one source for the system setting, the DAY_THEME
7506        // launch force (applied as an NSApp override at startup), and a set_appearance call.
7507        let app = NSApplication::sharedApplication(self.mtm());
7508        app.effectiveAppearance()
7509            .name()
7510            .to_string()
7511            .contains("Dark")
7512    }
7513
7514    /// System Settings › Accessibility › Display › "Reduce motion", as NSWorkspace reports it
7515    /// (docs/accessibility.md). `install_reduce_motion_observer` re-reads it on a flip.
7516    fn reduce_motion(&mut self) -> bool {
7517        objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
7518    }
7519
7520    /// macOS is the one platform whose badge takes arbitrary text: `NSDockTile.badgeLabel` is a
7521    /// `String`, so `Text` renders literally and a count is just its decimal form. A nil label
7522    /// clears it (docs/badge.md).
7523    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
7524        use day_spec::AppBadge;
7525        let label = match badge {
7526            AppBadge::None => None,
7527            // Zero clears, matching the platform convention the doc states.
7528            AppBadge::Count(0) => None,
7529            AppBadge::Count(n) => Some(n.to_string()),
7530            AppBadge::Text(t) if t.is_empty() => None,
7531            AppBadge::Text(t) => Some(t.clone()),
7532            // No dedicated dot on the Dock; the smallest honest mark is a single bullet.
7533            AppBadge::Dot => Some("\u{2022}".to_string()),
7534        };
7535        let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
7536        let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
7537        unsafe { tile.setBadgeLabel(ns.as_deref()) };
7538        tile.display();
7539    }
7540
7541    fn set_appearance(&mut self, dark: Option<bool>) {
7542        let app = NSApplication::sharedApplication(self.mtm());
7543        let appearance = dark.and_then(|d| {
7544            objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
7545                if d {
7546                    objc2_app_kit::NSAppearanceNameDarkAqua
7547                } else {
7548                    objc2_app_kit::NSAppearanceNameAqua
7549                }
7550            })
7551        });
7552        // `None` clears the override — back to the system appearance.
7553        unsafe { app.setAppearance(appearance.as_deref()) };
7554    }
7555
7556    fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
7557        controls::refresh_gesture::attach(handle, host);
7558    }
7559
7560    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
7561        unsafe {
7562            handle.setHidden(!visible);
7563        }
7564    }
7565
7566    fn capability(&self, cap: Cap) -> Support {
7567        match cap {
7568            Cap::SearchField => Support::Native,
7569            Cap::ComboBox => Support::Native,
7570            Cap::Stepper => Support::Native,
7571            Cap::DateTimePicker => Support::Native,
7572            Cap::ColorPicker => Support::Native,
7573            Cap::PullRefresh => Support::Emulated,
7574            Cap::Pager => Support::Emulated,
7575            Cap::PullRefreshGesture => Support::Emulated,
7576            // A tracking-area owner sets an `NSCursor` per view (docs/cursor.md). Wait, progress,
7577            // help, and move take the arrow — AppKit draws no such shapes — and the zoom and
7578            // diagonal-resize cursors need macOS 15.
7579            Cap::Cursor => Support::Native,
7580            // `NSFontManager` enumerates every family and member (docs/fonts.md).
7581            Cap::FontList => Support::Native,
7582            // An image-and-text table cell's content (docs/list.md "List items").
7583            Cap::ListItem => Support::Native,
7584            // ImageIO behind `NSBitmapImageRep` reads every container macOS knows and writes
7585            // back PNG/JPEG/TIFF/BMP/GIF, and carries the container's own metadata dictionary
7586            // (docs/images.md).
7587            Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
7588            // Canvas export (docs/canvas.md "Exporting"): the canvas painter replayed into a
7589            // CGBitmapContext, or a CGPDFContext that keeps shapes and text vector.
7590            Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
7591            // The announcement-requested notification, posted from the primary window
7592            // (docs/accessibility.md).
7593            Cap::Announce => Support::Native,
7594            // `NSWorkspace.accessibilityDisplayShouldReduceMotion`, re-read when the workspace
7595            // posts its display-options change (docs/accessibility.md).
7596            Cap::ReduceMotion => Support::Native,
7597            Cap::Snapshot
7598            | Cap::NativeSymbols
7599            // The rows as chrome: `Rail` is the same source list pinned narrow, `Tabs` an
7600            // NSSegmentedControl docked below the pages. AppKit has no app-level tab bar —
7601            // NSTabView owns its own page content, the opposite of Day's model — so the bar
7602            // is composed from the control a Mac uses for a one-of-N switch this size.
7603            //
7604            // `Cap::NavTabsAdaptive` is deliberately NOT here: a Mac app may PIN a tab bar, but
7605            // a narrow Mac window hides its sidebar and pushes rather than growing one. It falls
7606            // through to the `Unsupported` arm below.
7607            | Cap::NavTabs
7608            | Cap::NavSplit
7609            // Both presentations are the same NSSplitViewController — a stack is that split with
7610            // its sidebar item collapsed — so re-presenting is a collapse plus one `addSubview`
7611            // that re-parents the sidebar page (docs/size-classes.md).
7612            | Cap::NavRepresent
7613            // A REAL `contentList` NSSplitViewItem between sidebar and detail; the pane
7614            // persists through every presentation (docs/navigation.md).
7615            | Cap::NavContentList
7616            | Cap::Dialogs
7617            | Cap::FileDialogs
7618            // NSOpenPanel with `canChooseDirectories` (docs/files.md).
7619            | Cap::FolderDialog
7620            | Cap::Animation
7621            // NSTextView natively honors all three text-area attributes.
7622            | Cap::TextEditable
7623            | Cap::TextSelectable
7624            | Cap::TextSpellCheck
7625            // NSTableView's own drag pipeline, with the `.gap` placeholder (docs/list.md), in
7626            // lists and in the source-list sidebar itself (docs/navigation.md).
7627            | Cap::NavReorder | Cap::ListReorder
7628            // NSTableView's view-based reuse queue (`makeViewWithIdentifier`) hands Day's cells
7629            // back for new rows; `didRemoveRowView` recycles them (docs/list.md).
7630            | Cap::ListRecycling
7631            // NSTableView row actions: reveal-as-you-swipe buttons with the native full-slide
7632            // activation (docs/list.md).
7633            | Cap::ListSwipeActions
7634            // NSTableView group rows with `floatsGroupRows` (docs/list.md "Sections").
7635            | Cap::ListSections
7636            // NSOutlineView hosts Day-built rows natively, drag-reparent included
7637            // (docs/tree.md).
7638            | Cap::Tree
7639            | Cap::TreeSections
7640            | Cap::TreeMove
7641            // Real NSWindows with native tabbing + the Windows menu (docs/windows.md).
7642            | Cap::MultiWindow
7643            // `miniaturize:` / `zoom:` / `toggleFullScreen:`, reported back through the window
7644            // delegate's notifications (docs/windows.md "Window properties").
7645            | Cap::WindowStates
7646            | Cap::WindowFullscreen
7647            // `NSWindowSharingNone`: captures, recordings and screen sharing see an empty window.
7648            | Cap::ContentProtection
7649            // Per-window `tabbingIdentifier` / `tabbingMode`, with the "+" opening the group's
7650            // own builder.
7651            | Cap::WindowTabbing
7652            // `applicationDockMenu:` on the app delegate (docs/menus.md).
7653            | Cap::DockMenu
7654            // Borderless windows that still take key, a transparent title bar over the
7655            // content, a clear window background, and `NSVisualEffectView` materials behind the
7656            // content (docs/window-chrome.md).
7657            | Cap::FramelessWindow
7658            | Cap::OverlayTitleBar
7659            | Cap::TransparentWindow
7660            | Cap::WindowMaterial
7661            // `performWindowDragWithEvent:` from a press on the region's own background.
7662            | Cap::DragRegion
7663            // `NSStatusItem`s in the menu bar, a progress bar drawn on the Dock tile, and the
7664            // accessory activation policy (docs/status-item.md).
7665            | Cap::StatusItem
7666            | Cap::AppProgress
7667            | Cap::DockVisibility
7668            // Frame, limits, level, Spaces, style-mask controls, per-window appearance, Dock
7669            // bounces, and `NSScreen` (docs/windows.md "Window properties").
7670            | Cap::WindowGeometry
7671            | Cap::WindowPosition
7672            | Cap::WindowLevel
7673            | Cap::WindowAppearance
7674            | Cap::RequestAttention
7675            | Cap::Monitors
7676            // Run-time shortcuts appear in the Dock menu beside the declared ones.
7677            | Cap::DynamicShortcuts
7678            // A real NSToolbar in the title bar (docs/toolbars.md).
7679            | Cap::Toolbar
7680            // The bar holds a native search field (docs/search.md).
7681            | Cap::ToolbarSearch
7682            | Cap::AppMenu
7683            // NSDockTile.badgeLabel is an arbitrary String, so all three payloads render — the
7684            // only backend where Text is real (docs/badge.md).
7685            | Cap::AppBadgeCount
7686            | Cap::AppBadgeText
7687            // NSUndoManager fronted by DayUndoManager: the stock Edit menu retitles and
7688            // enables itself, ⌘Z/⇧⌘Z land through the responder chain (docs/model.md).
7689            | Cap::UndoBridge
7690            | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
7691            | Cap::AppBadgeDot
7692            | Cap::Appearance
7693            // firstBaselineOffsetFromTop — the platform's own answer (docs/baseline.md).
7694            | Cap::BaselineAlignment
7695            // A REAL inspector NSSplitViewItem (`inspectorWithViewController:`): the system
7696            // trailing-pane material and full-height layout (docs/inspector.md).
7697            | Cap::Inspector
7698            // A plain NSSplitView with two arranged panes (docs/split.md).
7699            | Cap::Split
7700            | Cap::TextRuns
7701            | Cap::TextLinks => Support::Native,
7702            // A topmost autoresizing child of the content view — not a system modal
7703            // (docs/cover.md's ArkUI tier).
7704            Cap::Cover => Support::Emulated,
7705            // `.sheet()` is a window sheet on the primary window (docs/cover.md "Modal sheet").
7706            Cap::CoverSheet => Support::Native,
7707            _ => Support::Unsupported,
7708        }
7709    }
7710
7711    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
7712        let mtm = self.mtm;
7713        match Builtin::from_key(kind) {
7714            Some(Builtin::Container) => {
7715                let v = DayFlipped::new(mtm);
7716                if let Some(p) = props.downcast_ref::<ContainerProps>() {
7717                    if p.role == Some(day_spec::SurfaceRole::SectionCard) {
7718                        v.set_section_card(p.corner_radius);
7719                    } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
7720                        v.set_surface(p.background, p.corner_radius, p.clips);
7721                    }
7722                }
7723                view_of(v)
7724            }
7725            Some(Builtin::Scroll) => {
7726                let horizontal = props
7727                    .downcast_ref::<day_spec::props::ScrollProps>()
7728                    .map(|p| p.horizontal)
7729                    .unwrap_or(false);
7730                let sv = unsafe { NSScrollView::new(mtm) };
7731                unsafe {
7732                    sv.setHasVerticalScroller(!horizontal);
7733                    sv.setHasHorizontalScroller(horizontal);
7734                    sv.setDrawsBackground(false);
7735                    // Overlay scrollers ALWAYS: day lays content out at the scroll's full frame
7736                    // width, and a legacy scroller (the "always show scroll bars" system
7737                    // setting, or a mouse attached) would reserve ~15pt and clip trailing
7738                    // content. Overlay floats above content instead — and matches the GTK/Qt
7739                    // backends.
7740                    sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
7741                }
7742                let doc = DayFlipped::new(mtm);
7743                unsafe { sv.setDocumentView(Some(doc.as_ref())) };
7744                view_of(sv)
7745            }
7746            Some(Builtin::Label) => {
7747                // `props_of`, not a panicking downcast, for every typed-props arm: a mismatch
7748                // (a piece registered under a builtin key, or a day-core regression) warns once
7749                // per kind and degrades to the placeholder — realize runs inside native
7750                // up-calls, where a panic is a process kill.
7751                let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
7752                    return placeholder_view(mtm, kind);
7753                };
7754                let tf = DayLabel::new(mtm, id, &p.text);
7755                configure_label_cell(&tf);
7756                if !p.wraps || p.max_lines > 0 {
7757                    unsafe {
7758                        tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
7759                        if !p.wraps || p.max_lines == 1 {
7760                            tf.setUsesSingleLineMode(true);
7761                            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
7762                        }
7763                    }
7764                }
7765                unsafe { tf.setFont(Some(&nsfont(p.font))) };
7766                // The PLAIN path needs the role as much as the attributed one below: a label
7767                // with no runs never reaches `attributed_label`, and reading the role only there
7768                // left every ordinary `.secondary()` label rendering in the primary color.
7769                match (p.color, p.role) {
7770                    (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
7771                    (None, day_spec::props::TextRole::Secondary) => unsafe {
7772                        tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
7773                    },
7774                    (None, day_spec::props::TextRole::Primary) => {}
7775                }
7776                if !p.runs.is_empty() {
7777                    let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
7778                    unsafe { tf.setAttributedStringValue(&s) };
7779                }
7780                tf.ivars().has_runs.set(!p.runs.is_empty());
7781                tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
7782                // Alignment goes on last and, for a runs label, has to reach inside the
7783                // attributed string. `setAlignment:` writes the cell's paragraph style, which an
7784                // attributed string then overrides wholesale with its own — so a markdown label
7785                // set only through the cell comes out leading-aligned no matter what was asked.
7786                if p.align != day_spec::props::TextAlign::Leading {
7787                    unsafe { tf.setAlignment(nstextalign(p.align)) };
7788                    if !p.runs.is_empty() {
7789                        set_paragraph_alignment(&tf, nstextalign(p.align));
7790                    }
7791                }
7792                view_of(Retained::into_super(tf))
7793            }
7794            Some(Builtin::Button) => {
7795                let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
7796                    return placeholder_view(mtm, kind);
7797                };
7798                let target = DayTarget::new(mtm, id);
7799                let btn = unsafe {
7800                    NSButton::buttonWithTitle_target_action(
7801                        &NSString::from_str(&p.title),
7802                        Some(&*target),
7803                        Some(sel!(action:)),
7804                        mtm,
7805                    )
7806                };
7807                apply_button_style(&btn, p.style);
7808                if p.icon.is_some() {
7809                    apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
7810                }
7811                unsafe { btn.setEnabled(p.enabled) };
7812                set_button_selected(&btn, p.selected);
7813                let view = view_of(btn);
7814                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7815                view
7816            }
7817            Some(Builtin::Toggle) => {
7818                let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
7819                    return placeholder_view(mtm, kind);
7820                };
7821                let target = DayTarget::new(mtm, id);
7822                let sw = unsafe { NSSwitch::new(mtm) };
7823                unsafe {
7824                    sw.setState(if p.on { 1 } else { 0 });
7825                    sw.setEnabled(p.enabled);
7826                    sw.setTarget(Some(&*target));
7827                    sw.setAction(Some(sel!(action:)));
7828                }
7829                let view = view_of(sw);
7830                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7831                view
7832            }
7833            Some(Builtin::Slider) => {
7834                let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
7835                    return placeholder_view(mtm, kind);
7836                };
7837                let target = DayTarget::new(mtm, id);
7838                let sl = unsafe {
7839                    NSSlider::sliderWithValue_minValue_maxValue_target_action(
7840                        p.value,
7841                        p.min,
7842                        p.max,
7843                        Some(&*target),
7844                        Some(sel!(action:)),
7845                        mtm,
7846                    )
7847                };
7848                unsafe { sl.setContinuous(true) };
7849                let view = view_of(sl);
7850                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7851                view
7852            }
7853            Some(Builtin::Picker) => picker::realize_any(self, props, id),
7854            Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
7855            Some(Builtin::TextField) => {
7856                let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
7857                    return placeholder_view(mtm, kind);
7858                };
7859                let tf = new_text_field(mtm, id, false);
7860                unsafe {
7861                    tf.setStringValue(&NSString::from_str(&p.text));
7862                    tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
7863                }
7864                view_of(tf)
7865            }
7866            Some(Builtin::Divider) => {
7867                let b = unsafe { NSBox::new(mtm) };
7868                unsafe { b.setBoxType(NSBoxType::Separator) };
7869                view_of(b)
7870            }
7871            Some(Builtin::Progress) => {
7872                let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
7873                    return placeholder_view(mtm, kind);
7874                };
7875                if p.value.is_none() {
7876                    return crate::controls::spinner::make(self, p, id);
7877                }
7878                let pi = unsafe { NSProgressIndicator::new(mtm) };
7879                unsafe {
7880                    match p.value {
7881                        Some(v) => {
7882                            pi.setStyle(NSProgressIndicatorStyle::Bar);
7883                            pi.setIndeterminate(false);
7884                            pi.setMinValue(0.0);
7885                            pi.setMaxValue(1.0);
7886                            pi.setDoubleValue(v);
7887                        }
7888                        None => {
7889                            pi.setStyle(NSProgressIndicatorStyle::Spinning);
7890                            pi.setIndeterminate(true);
7891                            pi.startAnimation(None);
7892                        }
7893                    }
7894                }
7895                view_of(pi)
7896            }
7897            Some(Builtin::Canvas) => {
7898                let canvas = DayCanvas::new(mtm);
7899                KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
7900                view_of(canvas)
7901            }
7902            Some(Builtin::Inspector) => {
7903                let (visible, width, leading) = props
7904                    .downcast_ref::<InspectorProps>()
7905                    .map(|p| {
7906                        (
7907                            p.visible,
7908                            p.width,
7909                            p.edge == day_spec::props::PaneEdge::Leading,
7910                        )
7911                    })
7912                    .unwrap_or((false, 280.0, false));
7913                let content_wrap = view_of(DayFlipped::new(mtm));
7914                let panel_flipped = DayFlipped::new(mtm);
7915                // The panel draws an opaque window-background backdrop over the item's
7916                // vibrancy material — without it the section cards' thin quaternary fill
7917                // composites into near-black in dark mode (see `FlippedIvars`).
7918                panel_flipped.set_pane_backdrop();
7919                let panel_wrap = view_of(panel_flipped);
7920                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
7921                // Force loadView before the items go in — the same lifecycle rule the nav
7922                // host below documents.
7923                let _ = unsafe { split_vc.view() };
7924                let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
7925                let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
7926                unsafe {
7927                    content_vc.setView(&content_wrap);
7928                    panel_vc.setView(&panel_wrap);
7929                }
7930                let content_item = unsafe {
7931                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
7932                };
7933                // A TRAILING pane is a real inspector item (the system treatment). A LEADING
7934                // one is a plain item placed first: `sidebarWithViewController:` would bring
7935                // sidebar material, which captures black offscreen (docs/navigation.md), and
7936                // the panel wrap already paints its own backdrop.
7937                let panel_item = unsafe {
7938                    if leading {
7939                        objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
7940                    } else {
7941                        objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
7942                    }
7943                };
7944                unsafe {
7945                    // Day's signal is the only visibility driver: with the pinned width the
7946                    // divider has nothing to drag and the pane cannot be user-collapsed, so
7947                    // there is no native-initiated change to report back.
7948                    panel_item.setCanCollapse(false);
7949                    panel_item.setCollapsed(!visible);
7950                    panel_item.setMinimumThickness(width);
7951                    panel_item.setMaximumThickness(width);
7952                    panel_item.setAllowsFullHeightLayout(true);
7953                    if leading {
7954                        split_vc.addSplitViewItem(&panel_item);
7955                        split_vc.addSplitViewItem(&content_item);
7956                    } else {
7957                        split_vc.addSplitViewItem(&content_item);
7958                        split_vc.addSplitViewItem(&panel_item);
7959                    }
7960                }
7961                let split = unsafe { split_vc.splitView() };
7962                unsafe {
7963                    split.setVertical(true);
7964                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
7965                    // The same Auto Layout hand-back as the nav host below: Day owns this
7966                    // view's frame outside the split; the controller's own constraints keep
7967                    // doing the pane sizing inside it.
7968                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
7969                }
7970                let view = view_of(split);
7971                INSPECTOR_STATE.with(|m| {
7972                    m.borrow_mut().insert(
7973                        ptr_of(&view),
7974                        InspectorState {
7975                            content_wrap,
7976                            panel_wrap,
7977                            _split_vc: split_vc,
7978                            panel_item,
7979                        },
7980                    )
7981                });
7982                view
7983            }
7984            Some(Builtin::InspectorPane) => {
7985                // A DayNavPage for its `setFrameSize:` → `FrameChanged` report: the pane's
7986                // frame is native-owned (the split sizes it), exactly like a nav page —
7987                // NAV_PAGES membership is what makes `set_frame` skip it.
7988                let pane = view_of(DayNavPage::new(mtm, id));
7989                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
7990                let panel = props
7991                    .downcast_ref::<InspectorPaneProps>()
7992                    .map(|p| p.panel)
7993                    .unwrap_or(false);
7994                INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
7995                pane
7996            }
7997            Some(Builtin::Split) => {
7998                let (axis, fraction, min_pane) = props
7999                    .downcast_ref::<SplitProps>()
8000                    .map(|p| (p.axis, p.fraction, p.min_pane))
8001                    .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
8002                let wrap = view_of(DayFlipped::new(mtm));
8003                let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
8004                let first_wrap = view_of(DayFlipped::new(mtm));
8005                let second_wrap = view_of(DayFlipped::new(mtm));
8006                unsafe {
8007                    // AppKit's "vertical" is the divider's orientation: panes side by side.
8008                    split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
8009                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8010                    split.addArrangedSubview(&first_wrap);
8011                    split.addArrangedSubview(&second_wrap);
8012                    split.setFrame(wrap.bounds());
8013                    split.setAutoresizingMask(
8014                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8015                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8016                    );
8017                    wrap.addSubview(&split);
8018                }
8019                let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
8020                split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
8021                SPLIT_STATE.with(|m| {
8022                    m.borrow_mut().insert(
8023                        ptr_of(&wrap),
8024                        SplitState {
8025                            split,
8026                            first_wrap,
8027                            second_wrap,
8028                            delegate,
8029                        },
8030                    )
8031                });
8032                wrap
8033            }
8034            Some(Builtin::SplitPane) => {
8035                // A DayNavPage, as an inspector pane: the splitter owns its frame, and its
8036                // `setFrameSize:` reports `FrameChanged`.
8037                let pane = view_of(DayNavPage::new(mtm, id));
8038                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8039                let second = props
8040                    .downcast_ref::<SplitPaneProps>()
8041                    .map(|p| p.second)
8042                    .unwrap_or(false);
8043                SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
8044                pane
8045            }
8046            Some(Builtin::Nav) => {
8047                let presentation = props
8048                    .downcast_ref::<NavProps>()
8049                    .map(|p| p.presentation)
8050                    .unwrap_or(NavPresentation::Split);
8051                let is_split = presentation.is_split();
8052                // The host is an NSSplitViewController, not a bare NSSplitView. Handing the
8053                // sidebar pane to `NSSplitViewItem::sidebarWithViewController:` is what buys
8054                // the system treatment: AppKit installs its own backing material and vibrancy
8055                // (so no hand-rolled NSVisualEffectView), pins the thickness with a sidebar
8056                // holding priority, animates collapse/expand, and drives the window's titlebar
8057                // separator. Day still owns the CONTENT of each pane — the two wraps below are
8058                // the item view controllers' views, so `insert`/`remove`/the NAV patches are
8059                // unchanged.
8060                let sidebar_wrap = view_of(DayFlipped::new(mtm));
8061                let detail_wrap = view_of(DayFlipped::new(mtm));
8062                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8063                // Force loadView/viewDidLoad before the items go in. NSSplitViewController
8064                // installs an item's view into the split as the item is added, which it can
8065                // only do once its own view exists — and reading `splitView` does not trigger
8066                // the lifecycle the way reading `view` does. Skipping this leaves a split view
8067                // with zero subviews: correct frame, nothing in it.
8068                let _ = unsafe { split_vc.view() };
8069                // Plain NSViewControllers with their view set explicitly: setting `view` up
8070                // front is what stops NSViewController looking for a nib named after itself.
8071                let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8072                let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8073                unsafe {
8074                    sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8075                    detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8076                }
8077                let sidebar_item = unsafe {
8078                    objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8079                };
8080                let detail_item = unsafe {
8081                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8082                };
8083                // The content-list pane (docs/navigation.md): a REAL `contentList`
8084                // NSSplitViewItem between the sidebar and the detail — Mail's own machinery,
8085                // holding priorities included. Its `Pane::List` page fills `list_wrap` exactly
8086                // as the sidebar page fills its own wrap, and the pane persists through every
8087                // presentation (only `NavPatch::ListVisible` collapses it).
8088                let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8089                // Set before the item joins the split, exactly as the sidebar's is below. A
8090                // collapsed state applied afterwards — by `NavPatch::ListVisible`, on a window
8091                // that has not been displayed — reports as collapsed and is then laid back out
8092                // from the item's holding priorities, which is how an app whose first
8093                // destination has no list opened with one beside it anyway.
8094                let list_visible = props
8095                    .downcast_ref::<NavProps>()
8096                    .is_none_or(|p| p.list_visible);
8097                let (list_wrap, list_item) = match list_width {
8098                    Some(w) => {
8099                        let wrap = view_of(DayFlipped::new(mtm));
8100                        let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8101                        unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8102                        let item = unsafe {
8103                            objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8104                        };
8105                        unsafe {
8106                            item.setCanCollapse(true);
8107                            item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8108                            item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8109                            item.setCollapsed(!list_visible);
8110                        }
8111                        (Some(wrap), Some(item))
8112                    }
8113                    None => (None, None),
8114                };
8115                unsafe {
8116                    // A stack presentation has no sidebar to show: collapse the (empty) pane
8117                    // and refuse the drag, so the detail owns the full width.
8118                    sidebar_item.setCanCollapse(is_split);
8119                    sidebar_item.setCollapsed(!is_split);
8120                    if is_split {
8121                        // Run the sidebar's material to the top of the window, under the
8122                        // titlebar, the way Mail and Finder do. Pairs with the unified toolbar
8123                        // style the window already uses (toolbar.rs).
8124                        sidebar_item.setAllowsFullHeightLayout(true);
8125                        sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8126                        sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8127                    } else {
8128                        sidebar_item.setMinimumThickness(0.0);
8129                        sidebar_item.setMaximumThickness(0.0);
8130                    }
8131                    split_vc.addSplitViewItem(&sidebar_item);
8132                    if let Some(item) = list_item.as_ref() {
8133                        split_vc.addSplitViewItem(item);
8134                    }
8135                    split_vc.addSplitViewItem(&detail_item);
8136                }
8137                let split = unsafe { split_vc.splitView() };
8138                // NSToolbarToggleSidebarItem sends `toggleSidebar:` down the RESPONDER chain,
8139                // and NSSplitViewController implements it — but a view controller only patches
8140                // itself into that chain when it is parented (a window's contentViewController
8141                // or another controller's child), and Day's tree is view-based all the way to
8142                // the window. Insert it by hand, directly after the split view, so a first
8143                // responder anywhere inside either pane walks up through it.
8144                unsafe {
8145                    let after = split.nextResponder();
8146                    split.setNextResponder(Some(&split_vc));
8147                    // The controller must never end up aiming at itself or at its OWN view,
8148                    // or its dealloc aborts the process: `-[NSViewController dealloc]`
8149                    // splices itself out with `view.nextResponder = self.nextResponder`, and
8150                    // if that lands the view on itself AppKit raises "The next responder
8151                    // should never be yourself!" — an NSException that unwinds into Rust and
8152                    // aborts. Both shapes occur here naturally: before macOS 15 the freshly
8153                    // loaded split view's next IS the controller, and on 15+ `view` is a
8154                    // WRAPPER above `splitView` whose auto-wiring makes the split's next
8155                    // that wrapper. Neither is a real upstream hop, so drop them.
8156                    let own_view = split_vc.view();
8157                    let vc_resp: *const objc2_app_kit::NSResponder = {
8158                        let r: &objc2_app_kit::NSResponder = &split_vc;
8159                        r
8160                    };
8161                    let view_resp: *const objc2_app_kit::NSResponder = {
8162                        let r: &objc2_app_kit::NSResponder = &own_view;
8163                        r
8164                    };
8165                    let upstream = after.filter(|a| {
8166                        let p: *const objc2_app_kit::NSResponder = &**a;
8167                        p != vc_resp && p != view_resp
8168                    });
8169                    split_vc.setNextResponder(upstream.as_deref());
8170                }
8171                unsafe {
8172                    split.setVertical(true);
8173                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8174                    // Day owns this view's frame (`set_frame`). A split view vended by
8175                    // NSSplitViewController arrives switched over to Auto Layout, which
8176                    // ignores that frame and lays the split out at zero — a window with
8177                    // chrome and nothing under it. Hand it back to autoresizing translation
8178                    // so Day stays the layout owner outside the split; the constraints the
8179                    // controller installs BETWEEN the split and its panes are untouched and
8180                    // keep doing the pane sizing.
8181                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
8182                }
8183                let root_title = props
8184                    .downcast_ref::<NavProps>()
8185                    .map(|p| p.title.clone())
8186                    .unwrap_or_default();
8187                // Stack presentation: a back header (hidden at root) — desktop has no system
8188                // back affordance, so a pushed page needs its own way out (docs/navigation.md).
8189                let header = if presentation == NavPresentation::Stack {
8190                    Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
8191                } else {
8192                    None
8193                };
8194                // A tabs host: the Mac's own tab control fills the detail pane and takes the
8195                // detail pages as its items (`TabHost`).
8196                let tabs = (presentation == NavPresentation::Tabs).then(|| {
8197                    let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
8198                    // Inset from the pane, the way a tab view sits in any Mac window: its
8199                    // tabs stand above the bezel, so flush to the top they run into the
8200                    // toolbar's edge, and flush to the sides the bezel hugs the sidebar. The
8201                    // autoresizing mask keeps the margins as the pane resizes.
8202                    let b = detail_wrap.bounds();
8203                    let frame = NSRect::new(
8204                        NSPoint::new(NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP),
8205                        NSSize::new(
8206                            (b.size.width - 2.0 * NAV_TABVIEW_INSET).max(0.0),
8207                            (b.size.height - NAV_TABVIEW_INSET_TOP - NAV_TABVIEW_INSET).max(0.0),
8208                        ),
8209                    );
8210                    unsafe {
8211                        tv.setTabViewType(
8212                            if props
8213                                .downcast_ref::<NavProps>()
8214                                .is_some_and(|p| p.documents.is_some())
8215                            {
8216                                objc2_app_kit::NSTabViewType::NoTabsNoBorder
8217                            } else {
8218                                objc2_app_kit::NSTabViewType::TopTabsBezelBorder
8219                            },
8220                        );
8221                        tv.setFrame(frame);
8222                        tv.setAutoresizingMask(
8223                            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8224                                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8225                        );
8226                        detail_wrap.addSubview(&tv);
8227                    }
8228                    TabHost {
8229                        view: tv,
8230                        target: None,
8231                    }
8232                });
8233                let view = view_of(split);
8234                NAV_STATE.with(|m| {
8235                    m.borrow_mut().insert(
8236                        ptr_of(&view),
8237                        NavState {
8238                            sidebar_wrap,
8239                            detail_wrap,
8240                            _split_vc: split_vc,
8241                            sidebar_item,
8242                            list_wrap,
8243                            list_item,
8244                            pages: Vec::new(),
8245                            list_page: None,
8246                            sidebar_page: None,
8247                            list_width,
8248                            list_visible,
8249                            list_positioned: false,
8250                            positioned: false,
8251                            presentation,
8252                            selected: 0,
8253                            tabs,
8254                            header,
8255                            root_title,
8256                            node: id,
8257                            title_strip: 0.0,
8258                        },
8259                    )
8260                });
8261                view
8262            }
8263            Some(Builtin::NavPage) => {
8264                let page = view_of(DayNavPage::new(mtm, id));
8265                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
8266                if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
8267                    PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
8268                }
8269                page
8270            }
8271            // Emulated fullscreen cover (docs/cover.md, the ArkUI tier): a DayNavPage — its
8272            // setFrameSize: override reports FrameChanged, so a window resize re-lays the cover
8273            // content for free — parked hidden until CoverPatch::Present re-homes it on top.
8274            Some(Builtin::Cover) => {
8275                let page = DayNavPage::new(mtm, id);
8276                let cover_props = props.downcast_ref::<CoverProps>();
8277                // A half sheet is a sheet here: macOS has no half-height presentation of its
8278                // own, so the window sheet stands in, at half the parent's height.
8279                page.ivars()
8280                    .sheet
8281                    .set(cover_props.is_some_and(|p| p.sheet || p.half));
8282                page.ivars().half.set(cover_props.is_some_and(|p| p.half));
8283                page.ivars().large.set(cover_props.is_some_and(|p| p.large));
8284                unsafe { page.setHidden(true) };
8285                view_of(page)
8286            }
8287            Some(Builtin::NavMenu) => {
8288                let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
8289                    return placeholder_view(mtm, kind);
8290                };
8291                let data = DayNavMenuData::new(
8292                    mtm,
8293                    id,
8294                    &p.items,
8295                    &p.icons,
8296                    &p.badges,
8297                    &p.badge_icons,
8298                    &p.badge_tints,
8299                    &p.sections,
8300                    &p.tints,
8301                    &p.menus,
8302                );
8303                *data.ivars().movable.borrow_mut() = p.movable.clone();
8304                data.ivars().regroup.set(p.regroup);
8305                *data.ivars().sorted.borrow_mut() = p.sorted.clone();
8306                // The Day subclass serves per-row context menus via menuForEvent:.
8307                let outline: Retained<objc2_app_kit::NSOutlineView> = {
8308                    let o: Retained<DayNavOutlineView> =
8309                        unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
8310                    NAV_OUTLINE_MENUS
8311                        .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
8312                    unsafe { msg_send![&*o, self] }
8313                };
8314                let col = unsafe {
8315                    objc2_app_kit::NSTableColumn::initWithIdentifier(
8316                        objc2_app_kit::NSTableColumn::alloc(mtm),
8317                        &NSString::from_str("item"),
8318                    )
8319                };
8320                unsafe {
8321                    outline.addTableColumn(&col);
8322                    outline.setOutlineTableColumn(Some(&col));
8323                    outline.setHeaderView(None);
8324                    // SourceList: the real sidebar treatment (Finder/Mail). The outline now
8325                    // lives inside a sidebar NSSplitViewItem, so AppKit supplies the backing
8326                    // material and the vibrancy the source-list selection composites through.
8327                    // This was Inset until 2026-08 because the earlier hand-rolled
8328                    // NSVisualEffectView blended behind the window, and an offscreen capture
8329                    // (`cacheDisplayInRect`) has no backdrop to sample — the selection came out
8330                    // a black pill that swallowed the row label. The material is AppKit's own
8331                    // now, and captures go through the window server (`snapshot_view`), which
8332                    // composites the material for real instead of guessing at it.
8333                    // `style = SourceList` is the whole switch: the matching
8334                    // `selectionHighlightStyle` constant is deprecated precisely because the
8335                    // style property now implies it.
8336                    outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8337                    // The default row size style follows the system's Sidebar icon size
8338                    // (Small, Medium, Large), live, as Finder's and Mail's sidebars do: AppKit
8339                    // sets the row height, the label's font and the icon's size. A table made
8340                    // in code starts at Custom, which ignores the setting.
8341                    outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
8342                    // Section headers pin to the top of the scroll as their group passes under
8343                    // it, the way Finder's sidebar groups do.
8344                    outline.setFloatsGroupRows(true);
8345                    outline.setIndentationPerLevel(0.0);
8346                    // Drag-to-reorder within this sidebar only (docs/navigation.md): rows that
8347                    // cannot move offer no drag, so registering costs a plain sidebar nothing.
8348                    outline.registerForDraggedTypes(
8349                        &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8350                            DAY_NAV_PASTEBOARD_TYPE,
8351                        )]),
8352                    );
8353                    outline.setDraggingSourceOperationMask_forLocal(
8354                        objc2_app_kit::NSDragOperation::Move,
8355                        true,
8356                    );
8357                    outline.setDraggingSourceOperationMask_forLocal(
8358                        objc2_app_kit::NSDragOperation::None,
8359                        false,
8360                    );
8361                    outline.setDraggingDestinationFeedbackStyle(
8362                        objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8363                    );
8364                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8365                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8366                    outline.reloadData();
8367                }
8368                let scroll = unsafe { NSScrollView::new(mtm) };
8369                unsafe {
8370                    scroll.setDrawsBackground(false);
8371                    scroll.setHasVerticalScroller(true);
8372                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
8373                    // clip the trailing edge of rows laid out at the full frame width (see
8374                    // the SCROLL realize).
8375                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8376                    // One column, sized to the pane: a sidebar never scrolls sideways.
8377                    scroll.setHasHorizontalScroller(false);
8378                    outline.setAutoresizingMask(
8379                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8380                    );
8381                    outline.setColumnAutoresizingStyle(
8382                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8383                    );
8384                    scroll.setDocumentView(Some(&outline));
8385                }
8386                let view = view_of(scroll);
8387                // Day selects by ITEM index; section headers make that differ from the
8388                // outline's row index, so every programmatic selection maps through `rows`.
8389                if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
8390                    data.ivars().suppress.set(true);
8391                    unsafe {
8392                        outline.selectRowIndexes_byExtendingSelection(
8393                            &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8394                            false,
8395                        )
8396                    };
8397                    data.ivars().suppress.set(false);
8398                }
8399                NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8400                view
8401            }
8402            Some(Builtin::List) => {
8403                let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
8404                    return placeholder_view(mtm, kind);
8405                };
8406                // Every list reports responder changes, even without an activation handler.
8407                let table: Retained<DayListView> =
8408                    unsafe { msg_send![DayListView::alloc(mtm), init] };
8409                let table = Retained::into_super(table);
8410                let col = unsafe {
8411                    NSTableColumn::initWithIdentifier(
8412                        NSTableColumn::alloc(mtm),
8413                        &NSString::from_str("day.list.col"),
8414                    )
8415                };
8416                let data = DayListData::new(
8417                    mtm,
8418                    id,
8419                    p.selectable,
8420                    p.multi_select,
8421                    p.row_height == RowHeight::Automatic,
8422                    p.sections,
8423                );
8424                unsafe {
8425                    if p.multi_select {
8426                        table.setAllowsMultipleSelection(true);
8427                    }
8428                    table.addTableColumn(&col);
8429                    table.setHeaderView(None);
8430                    // PLAIN, the classic edge-to-edge style: the macOS 11+ decorated styles
8431                    // (automatic ~14pt, FullWidth ~6pt) inset every cell view, clipping day
8432                    // row content laid out at the host's full frame width. This table ran
8433                    // FullWidth with a custom NSTableRowView pinning cells back to the row
8434                    // bounds until 2026-08 — and that pin also clobbered the cell-frame slide
8435                    // AppKit performs for row-action swipes, so the actions revealed behind a
8436                    // row whose CONTENT never moved. Plain has no inset to fight: standard
8437                    // row views, standard cell frames, and the swipe slide works untouched.
8438                    table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
8439                    // ...and the default intercell spacing (3pt × 2pt) shaves the column the
8440                    // same way — the last few points of a trailing control. Day rows own all
8441                    // of their spacing.
8442                    table.setIntercellSpacing(NSSize::new(0.0, 0.0));
8443                    // Host-drawn row separators (docs/list.md): the native horizontal grid
8444                    // line, which sits exactly at the row boundary — aligned with the
8445                    // selection, stationary under a row-action swipe, the Mail look.
8446                    if p.separators == Some(true) {
8447                        table.setGridStyleMask(
8448                            objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
8449                        );
8450                        table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
8451                    }
8452                    table.setColumnAutoresizingStyle(
8453                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8454                    );
8455                    // Section headers pin to the top while their section scrolls under them,
8456                    // the way Mail's and Finder's group rows do (docs/list.md "Sections").
8457                    table.setFloatsGroupRows(p.sections);
8458                    match p.row_height {
8459                        RowHeight::Uniform(h) => table.setRowHeight(h),
8460                        RowHeight::Automatic => table.setRowHeight(44.0),
8461                    }
8462                    if !p.selectable {
8463                        table.setSelectionHighlightStyle(
8464                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8465                        );
8466                    }
8467                    // Transparent: day panes own their backgrounds — the stock
8468                    // controlBackgroundColor would paint an appearance-colored slab that
8469                    // fights a themed app (visible whenever rows don't fill the viewport).
8470                    table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8471                    table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8472                    table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8473                    table.setTarget(Some(&*data));
8474                    if p.activatable {
8475                        table.setDoubleAction(Some(sel!(doubleClickRow:)));
8476                    }
8477                    if p.reorderable {
8478                        // Native drag-to-reorder (docs/list.md): rows drag within this table
8479                        // only (move locally, nothing leaves the app), and the drop target shows
8480                        // macOS's temporary placeholder GAP while the drag is over the table.
8481                        table.registerForDraggedTypes(
8482                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8483                                DAY_ROW_PASTEBOARD_TYPE,
8484                            )]),
8485                        );
8486                        table.setDraggingSourceOperationMask_forLocal(
8487                            objc2_app_kit::NSDragOperation::Move,
8488                            true,
8489                        );
8490                        table.setDraggingSourceOperationMask_forLocal(
8491                            objc2_app_kit::NSDragOperation::None,
8492                            false,
8493                        );
8494                        table.setDraggingDestinationFeedbackStyle(
8495                            objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8496                        );
8497                    }
8498                }
8499                let scroll = unsafe { NSScrollView::new(mtm) };
8500                unsafe {
8501                    scroll.setDrawsBackground(false);
8502                    scroll.setHasVerticalScroller(true);
8503                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
8504                    // clip the trailing edge of rows laid out at the full frame width (see
8505                    // the SCROLL realize).
8506                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8507                    scroll.setDocumentView(Some(&table));
8508                    let clip = scroll.contentView();
8509                    clip.setPostsBoundsChangedNotifications(true);
8510                    objc2_foundation::NSNotificationCenter::defaultCenter()
8511                        .addObserver_selector_name_object(
8512                            &data,
8513                            sel!(listViewportChanged:),
8514                            Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
8515                            Some(&clip),
8516                        );
8517                }
8518                let view = view_of(scroll);
8519                LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
8520                view
8521            }
8522            Some(Builtin::Tree) => {
8523                let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
8524                    return placeholder_view(mtm, kind);
8525                };
8526                // The width-pinning subclass (see DayOutlineView).
8527                let outline: Retained<objc2_app_kit::NSOutlineView> = {
8528                    let o: Retained<DayOutlineView> =
8529                        unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
8530                    unsafe { msg_send![&*o, self] }
8531                };
8532                let col = unsafe {
8533                    NSTableColumn::initWithIdentifier(
8534                        NSTableColumn::alloc(mtm),
8535                        &NSString::from_str("day.tree.col"),
8536                    )
8537                };
8538                let data = DayTreeData::new(mtm, id, p.selectable);
8539                unsafe {
8540                    if p.multi_select {
8541                        outline.setAllowsMultipleSelection(true);
8542                    }
8543                    outline.addTableColumn(&col);
8544                    outline.setOutlineTableColumn(Some(&col));
8545                    outline.setHeaderView(None);
8546                    if p.section_headers {
8547                        // Real source-list groups use AppKit's trailing, hover-revealed
8548                        // show/hide button and float over their children while scrolling.
8549                        outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8550                        outline.setFloatsGroupRows(true);
8551                    } else {
8552                        // Generic trees keep their existing full-width cells and rounded
8553                        // DayTreeRowView selection. Source lists use native row drawing.
8554                        outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
8555                        outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
8556                    }
8557                    outline.setColumnAutoresizingStyle(
8558                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8559                    );
8560                    outline.setAutoresizesOutlineColumn(true);
8561                    if let Some(indent) = p.indent {
8562                        outline.setIndentationPerLevel(indent);
8563                    }
8564                    match p.row_height {
8565                        RowHeight::Uniform(h) => outline.setRowHeight(h),
8566                        RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
8567                        RowHeight::Automatic => {}
8568                    }
8569                    if !p.selectable {
8570                        outline.setSelectionHighlightStyle(
8571                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8572                        );
8573                    }
8574                    outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8575                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8576                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8577                    if p.movable {
8578                        // Native drag-to-move (docs/tree.md): nodes drag within this outline
8579                        // only. The REGULAR feedback style (not the list's Gap): a tree drop
8580                        // must distinguish "between rows" (insertion line) from "ONTO a row"
8581                        // (the highlighted-parent drop), and Gap has no onto affordance.
8582                        outline.registerForDraggedTypes(
8583                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8584                                DAY_TREE_PASTEBOARD_TYPE,
8585                            )]),
8586                        );
8587                        outline.setDraggingSourceOperationMask_forLocal(
8588                            objc2_app_kit::NSDragOperation::Move,
8589                            true,
8590                        );
8591                        outline.setDraggingSourceOperationMask_forLocal(
8592                            objc2_app_kit::NSDragOperation::None,
8593                            false,
8594                        );
8595                    }
8596                }
8597                let scroll = unsafe { NSScrollView::new(mtm) };
8598                unsafe {
8599                    scroll.setDrawsBackground(false);
8600                    scroll.setHasVerticalScroller(true);
8601                    scroll.setHasHorizontalScroller(false);
8602                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8603                    outline.setAutoresizingMask(
8604                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8605                    );
8606                    scroll.setDocumentView(Some(&outline));
8607                }
8608                let view = view_of(scroll);
8609                TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8610                view
8611            }
8612            Some(Builtin::Image) => {
8613                let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
8614                    return placeholder_view(mtm, kind);
8615                };
8616                let iv: Retained<objc2_app_kit::NSImageView> =
8617                    if p.content_mode == ContentMode::Fill {
8618                        let view: Retained<FillImageView> =
8619                            unsafe { msg_send![FillImageView::alloc(mtm), init] };
8620                        Retained::from(
8621                            <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
8622                        )
8623                    } else {
8624                        unsafe { objc2_app_kit::NSImageView::new(mtm) }
8625                    };
8626                // Fill expands the native aspect-fit drawing in FillImageView; Stretch
8627                // scales each axis independently, and Fit keeps the stock image view.
8628                let scaling = match p.content_mode {
8629                    ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
8630                    _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
8631                };
8632                unsafe { iv.setImageScaling(scaling) };
8633                if let Some(img) = appkit_image_for(&p.source) {
8634                    // Vector-glyph tint (docs/vectors.md): template rendering + the view's
8635                    // content tint — AppKit recolors the alpha mask natively. A template with
8636                    // no tint keeps the view's nil tint: the neutral template color the nav
8637                    // menu's own rows draw with, light in dark mode, dark in light.
8638                    if p.tint.is_some() || p.template {
8639                        unsafe { img.setTemplate(true) };
8640                    }
8641                    unsafe { iv.setImage(Some(&img)) };
8642                }
8643                if let Some(t) = p.tint {
8644                    unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
8645                }
8646                IMAGE_MODES.with(|t| {
8647                    t.insert(
8648                        ptr_of(&iv),
8649                        ImageMode {
8650                            template: p.template,
8651                            tinted: p.tint.is_some(),
8652                        },
8653                    )
8654                });
8655                view_of(iv)
8656            }
8657            Some(Builtin::ListItem) => {
8658                let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
8659                else {
8660                    return placeholder_view(mtm, kind);
8661                };
8662                make_list_item(p, mtm)
8663            }
8664            // A recycled list cell is ADOPTED from the native list, never realized
8665            // through this path; anything else is an extension piece.
8666            Some(Builtin::ListCell) | None => {
8667                if let Some(make) = self.registry.get(kind).map(|r| r.make) {
8668                    return make(self, props, id);
8669                }
8670                // Unregistered kind: LOUD once-per-kind warning, then a visible-but-harmless
8671                // placeholder (§8.2's debug check will panic first in debug builds once the
8672                // required-kinds set lands).
8673                warn_missing_renderer(kind);
8674                placeholder_view(mtm, kind)
8675            }
8676        }
8677    }
8678
8679    fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
8680        match kind {
8681            kinds::LIST_ITEM => {
8682                let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
8683                    return;
8684                };
8685                let props = LIST_ITEMS.with(|m| {
8686                    let mut m = m.borrow_mut();
8687                    let props = m.get_mut(&ptr_of(h))?;
8688                    use day_spec::props::ListItemPatch as P;
8689                    match p {
8690                        P::Title(t) => props.title = t.clone(),
8691                        P::Subtitle(t) => props.subtitle = t.clone(),
8692                        P::Detail(t) => props.detail = t.clone(),
8693                        P::Icon(i) => props.icon = i.clone(),
8694                        P::IconTint(c) => props.icon_tint = *c,
8695                        P::Checked(on) => props.checked = *on,
8696                    }
8697                    Some(props.clone())
8698                });
8699                if let Some(props) = props {
8700                    dress_list_item(h, &props, self.mtm());
8701                }
8702            }
8703            kinds::IMAGE => {
8704                if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
8705                    match p {
8706                        day_spec::props::ImagePatch::Tint(c) => {
8707                            // Template rendering + the view's content tint, exactly as at realize
8708                            // — the glyph repaints in place rather than being rebuilt
8709                            // (docs/vectors.md). A template glyph stays one when the tint goes.
8710                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8711                                let key = ptr_of(&iv);
8712                                let template = IMAGE_MODES
8713                                    .with(|t| {
8714                                        t.with(key, |m| {
8715                                            m.tinted = c.is_some();
8716                                            m.renders_template()
8717                                        })
8718                                    })
8719                                    .unwrap_or(c.is_some());
8720                                if let Some(img) = unsafe { iv.image() } {
8721                                    unsafe { img.setTemplate(template) };
8722                                }
8723                                unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
8724                            }
8725                        }
8726                        // A source swap repaints the same view (docs/images.md), so an `image()`
8727                        // bound to a signal shows new pixels without rebuilding its subtree —
8728                        // which is what makes a decode-then-show flow a patch and not a rebuild.
8729                        day_spec::props::ImagePatch::Source(source) => {
8730                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8731                                // A source that will not load leaves the view showing what it
8732                                // was — the patch's contract, and what GTK, Qt and Android do.
8733                                // The new image renders the way the view does: a tinted or
8734                                // template glyph stays one, so a recycled sidebar row shows the
8735                                // icon it was rebound to in the same color.
8736                                if let Some(img) = appkit_image_for(source) {
8737                                    let template = IMAGE_MODES
8738                                        .with(|t| t.get(ptr_of(&iv)))
8739                                        .is_some_and(|m| m.renders_template());
8740                                    unsafe {
8741                                        img.setTemplate(template);
8742                                        iv.setImage(Some(&img));
8743                                    }
8744                                }
8745                            }
8746                        }
8747                    }
8748                }
8749            }
8750            kinds::CONTAINER => {
8751                if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
8752                    patch.downcast_ref::<ContainerPatch>(),
8753                    h.clone().downcast::<DayFlipped>(),
8754                ) {
8755                    // A background patch only targets a background container (corner radius 0).
8756                    // The AnimSpec is not honored: the fill is drawRect content
8757                    // (rasterized by our own drawing code so dynamic system colors re-resolve
8758                    // per appearance), not a CALayer property, and Core Animation only
8759                    // interpolates layer properties, so there is nothing for the render server
8760                    // to tween. Day animates only what the toolkit's animator can execute
8761                    // (§8.4), so an animated background change applies at commit here.
8762                    v.set_surface(*c, 0.0, false);
8763                }
8764            }
8765            kinds::LABEL => {
8766                if let (Some(p), Ok(tf)) = (
8767                    patch.downcast_ref::<LabelPatch>(),
8768                    h.clone().downcast::<NSTextField>(),
8769                ) {
8770                    match p {
8771                        LabelPatch::Text(t) => {
8772                            unsafe { tf.setStringValue(&NSString::from_str(t)) };
8773                            if let Some(label) = h.downcast_ref::<DayLabel>() {
8774                                label.ivars().has_runs.set(false);
8775                                label.set_links(false);
8776                            }
8777                        }
8778                        LabelPatch::Color(c) => unsafe {
8779                            tf.setTextColor(c.map(nscolor).as_deref())
8780                        },
8781                        LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
8782                        LabelPatch::Runs(text, runs) => {
8783                            // The field's current font is the base the runs sit on, taken as the
8784                            // live object rather than rebuilt from a `FontSpec`, which would lose
8785                            // the semantic style behind the resolved size.
8786                            let base = unsafe { tf.font() };
8787                            let s = match base.as_deref() {
8788                                Some(f) => {
8789                                    attributed_label(text, f, None, Default::default(), runs)
8790                                }
8791                                None => attributed_label(
8792                                    text,
8793                                    &nsfont(day_spec::FontSpec::default()),
8794                                    None,
8795                                    Default::default(),
8796                                    runs,
8797                                ),
8798                            };
8799                            unsafe { tf.setAttributedStringValue(&s) };
8800                            // Preserve paragraph alignment and activate links introduced by a
8801                            // reactive markdown update without replacing the native label.
8802                            set_paragraph_alignment(&tf, unsafe { tf.alignment() });
8803                            if let Some(label) = h.downcast_ref::<DayLabel>() {
8804                                label.ivars().has_runs.set(!runs.is_empty());
8805                                label.set_links(runs.iter().any(|r| r.link.is_some()));
8806                            }
8807                        }
8808                    }
8809                }
8810            }
8811            kinds::BUTTON => {
8812                if let (Some(p), Ok(btn)) = (
8813                    patch.downcast_ref::<ButtonPatch>(),
8814                    h.clone().downcast::<NSButton>(),
8815                ) {
8816                    match p {
8817                        ButtonPatch::Content(c) => {
8818                            apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
8819                        }
8820                        ButtonPatch::Title(t) => {
8821                            let style = BUTTON_STYLES
8822                                .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
8823                                .unwrap_or_default();
8824                            set_button_title(&btn, t, style);
8825                        }
8826                        ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
8827                        ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
8828                        ButtonPatch::Style(s) => apply_button_style(&btn, *s),
8829                    }
8830                }
8831            }
8832            kinds::TOGGLE => {
8833                if let (Some(p), Ok(sw)) = (
8834                    patch.downcast_ref::<TogglePatch>(),
8835                    h.clone().downcast::<NSSwitch>(),
8836                ) {
8837                    match p {
8838                        TogglePatch::On(on) => {
8839                            let want = if *on { 1 } else { 0 };
8840                            if unsafe { sw.state() } != want {
8841                                unsafe { sw.setState(want) };
8842                            }
8843                        }
8844                        TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
8845                    }
8846                }
8847            }
8848            kinds::SLIDER => {
8849                if let (Some(p), Ok(sl)) = (
8850                    patch.downcast_ref::<SliderPatch>(),
8851                    h.clone().downcast::<NSSlider>(),
8852                ) {
8853                    match p {
8854                        SliderPatch::Value(v) => {
8855                            if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
8856                                unsafe { sl.setDoubleValue(*v) };
8857                            }
8858                        }
8859                        SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
8860                    }
8861                }
8862            }
8863            kinds::PROGRESS => {
8864                if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
8865                {
8866                    crate::controls::spinner::update(self, h, p);
8867                    return;
8868                }
8869
8870                if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
8871                    patch.downcast_ref::<ProgressPatch>(),
8872                    h.clone().downcast::<NSProgressIndicator>(),
8873                ) {
8874                    unsafe {
8875                        match v {
8876                            Some(val) => {
8877                                if pi.isIndeterminate() {
8878                                    pi.stopAnimation(None);
8879                                    pi.setIndeterminate(false);
8880                                    pi.setStyle(NSProgressIndicatorStyle::Bar);
8881                                    pi.setMinValue(0.0);
8882                                    pi.setMaxValue(1.0);
8883                                }
8884                                if (pi.doubleValue() - val).abs() > 0.0001 {
8885                                    pi.setDoubleValue(*val);
8886                                }
8887                            }
8888                            None => {
8889                                pi.setIndeterminate(true);
8890                                pi.setStyle(NSProgressIndicatorStyle::Spinning);
8891                                pi.startAnimation(None);
8892                            }
8893                        }
8894                    }
8895                }
8896            }
8897            kinds::NAV_MENU => {
8898                if let Some(NavMenuPatch::Items {
8899                    items,
8900                    icons,
8901                    badges,
8902                    badge_icons,
8903                    badge_tints,
8904                    sections,
8905                    tints,
8906                    menus,
8907                    movable,
8908                    sorted,
8909                    selected,
8910                    rows_changed,
8911                    ..
8912                }) = patch.downcast_ref::<NavMenuPatch>()
8913                {
8914                    NAV_MENUS.with(|m| {
8915                        let m = m.borrow();
8916                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
8917                            return;
8918                        };
8919                        *data.ivars().movable.borrow_mut() = movable.clone();
8920                        *data.ivars().sorted.borrow_mut() = sorted.clone();
8921                        data.set_items(
8922                            items,
8923                            icons,
8924                            badges,
8925                            badge_icons,
8926                            badge_tints,
8927                            sections,
8928                            tints,
8929                            menus,
8930                        );
8931                        data.ivars().suppress.set(true);
8932                        // The same rows with new words or counts: reload just those rows, which
8933                        // keeps the selection and every other row's view.
8934                        if let Some(rows) = rows_changed {
8935                            let set = objc2_foundation::NSMutableIndexSet::new();
8936                            for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
8937                                unsafe { set.addIndex(row) };
8938                            }
8939                            unsafe {
8940                                outline.reloadDataForRowIndexes_columnIndexes(
8941                                    &set,
8942                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
8943                                )
8944                            };
8945                            data.ivars().suppress.set(false);
8946                            return;
8947                        }
8948                        unsafe {
8949                            outline.reloadData();
8950                            match selected.and_then(|i| data.row_of_item(i)) {
8951                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
8952                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8953                                    false,
8954                                ),
8955                                None => outline.deselectAll(None),
8956                            }
8957                        }
8958                        data.ivars().suppress.set(false);
8959                    });
8960                    // The rows are a tabs host's labels where the menu sits in one.
8961                    adopt_menu_for_tabs(self.mtm(), h);
8962                } else if let Some(NavMenuPatch::IconProgress(progress)) =
8963                    patch.downcast_ref::<NavMenuPatch>()
8964                {
8965                    NAV_MENUS.with(|menus| {
8966                        let menus = menus.borrow();
8967                        let Some((outline, data)) = menus.get(&ptr_of(h)) else {
8968                            return;
8969                        };
8970                        let previous = data.ivars().icon_progress.replace(progress.clone());
8971                        for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
8972                            let Some(index) = item else {
8973                                continue;
8974                            };
8975                            let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
8976                            if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
8977                                continue;
8978                            }
8979                            if let Some(view) = unsafe {
8980                                outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
8981                            } && let Some(cell) =
8982                                view.downcast_ref::<objc2_app_kit::NSTableCellView>()
8983                                && let Some(icon) = unsafe { cell.imageView() }
8984                            {
8985                                nav_progress::update(&icon, value);
8986                            }
8987                        }
8988                    });
8989                } else if let Some(NavMenuPatch::Selected(sel)) =
8990                    patch.downcast_ref::<NavMenuPatch>()
8991                {
8992                    NAV_MENUS.with(|m| {
8993                        let m = m.borrow();
8994                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
8995                            return;
8996                        };
8997                        data.ivars().suppress.set(true);
8998                        unsafe {
8999                            match sel.and_then(|i| data.row_of_item(i)) {
9000                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
9001                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9002                                    false,
9003                                ),
9004                                None => outline.deselectAll(None),
9005                            }
9006                        }
9007                        data.ivars().suppress.set(false);
9008                    });
9009                }
9010            }
9011            kinds::INSPECTOR => {
9012                if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
9013                    INSPECTOR_STATE.with(|m| {
9014                        if let Some(state) = m.borrow().get(&ptr_of(h)) {
9015                            // Directly, not through the animator proxy: a screenshot must not
9016                            // catch a mid-animation pane (the sidebar-toggle rule).
9017                            state.panel_item.setCollapsed(!*v);
9018                        }
9019                    });
9020                }
9021            }
9022            kinds::SPLIT => {
9023                if let Some(p) = patch.downcast_ref::<SplitPatch>() {
9024                    SPLIT_STATE.with(|m| {
9025                        let m = m.borrow();
9026                        let Some(state) = m.get(&ptr_of(h)) else {
9027                            return;
9028                        };
9029                        let iv = state.delegate.ivars();
9030                        match p {
9031                            SplitPatch::Fraction(f) => {
9032                                iv.share.set(f.clamp(0.0, 1.0));
9033                                if iv.positioned.get() {
9034                                    split_place(&state.split, iv);
9035                                }
9036                            }
9037                            SplitPatch::Axis(axis) => unsafe {
9038                                state
9039                                    .split
9040                                    .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
9041                                state.split.adjustSubviews();
9042                                if iv.positioned.get() {
9043                                    split_place(&state.split, iv);
9044                                }
9045                            },
9046                        }
9047                    });
9048                }
9049            }
9050            kinds::NAV => {
9051                if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
9052                    nav_present(self.mtm(), h, *next);
9053                    return;
9054                }
9055                if let Some(p) = patch.downcast_ref::<NavPatch>() {
9056                    NAV_STATE.with(|m| {
9057                        let mut m = m.borrow_mut();
9058                        let Some(state) = m.get_mut(&ptr_of(h)) else {
9059                            return;
9060                        };
9061                        match p {
9062                            NavPatch::Pushed { title, .. } => {
9063                                // Only the new top detail page stays visible.
9064                                let last = state.pages.len().saturating_sub(1);
9065                                state.selected = last;
9066                                for (i, page) in state.pages.iter().enumerate() {
9067                                    page.setHidden(i != last);
9068                                }
9069                                if let Some(hdr) = state.header.as_mut() {
9070                                    hdr.titles.push(title.clone());
9071                                    sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9072                                }
9073                            }
9074                            NavPatch::Popped => {
9075                                // Hide the outgoing top; reveal its predecessor (Day
9076                                // removes the popped page right after this patch).
9077                                let n = state.pages.len();
9078                                if let Some(top) = state.pages.last() {
9079                                    top.setHidden(true);
9080                                }
9081                                if n >= 2 {
9082                                    state.pages[n - 2].setHidden(false);
9083                                }
9084                                state.selected = n.saturating_sub(2);
9085                                if let Some(hdr) = state.header.as_mut() {
9086                                    if hdr.titles.len() > 1 {
9087                                        hdr.titles.pop();
9088                                    }
9089                                    // The popped page is still in `pages` here (Day removes
9090                                    // it right after this patch), so frame for depth-after-pop.
9091                                    let after: Vec<Retained<NSView>> = state
9092                                        .pages
9093                                        .iter()
9094                                        .take(n.saturating_sub(1))
9095                                        .cloned()
9096                                        .collect();
9097                                    sync_nav_header(hdr, &state.detail_wrap, &after);
9098                                }
9099                            }
9100                            NavPatch::Title(t) => {
9101                                if let Some(hdr) = state.header.as_mut() {
9102                                    if let Some(last) = hdr.titles.last_mut() {
9103                                        *last = t.clone();
9104                                    }
9105                                    unsafe {
9106                                        hdr.title.setStringValue(&NSString::from_str(t));
9107                                    }
9108                                }
9109                            }
9110                            // The custom back header always routes back through Day
9111                            // (NavBack{already_popped:false}), so there is no native auto-pop to
9112                            // suppress; the guard runs in the pieces layer (docs/navigation.md).
9113                            NavPatch::GuardTop(_) => {}
9114                            NavPatch::Reorder(order) => {
9115                                let old = state.pages.clone();
9116                                state.pages =
9117                                    order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9118                                if let Some(tabs) = &state.tabs {
9119                                    TAB_PICK_SUPPRESS.with(|s| s.set(true));
9120                                    unsafe {
9121                                        let items = tabs.view.tabViewItems();
9122                                        for item in items.iter() {
9123                                            tabs.view.removeTabViewItem(&item);
9124                                        }
9125                                        for i in order {
9126                                            if let Some(item) = items.iter().nth(*i) {
9127                                                tabs.view.addTabViewItem(&item);
9128                                            }
9129                                        }
9130                                    }
9131                                    TAB_PICK_SUPPRESS.with(|s| s.set(false));
9132                                }
9133                            }
9134                            // Handled outside this borrow (it re-homes views and builds chrome).
9135                            NavPatch::Presentation(_) => {}
9136                            // Resident-page switch (docs/navigation.md): every page stays in the
9137                            // view hierarchy and only one is unhidden, so switching tabs keeps
9138                            // each page's scroll position and first responder exactly as left.
9139                            NavPatch::Select(i) => {
9140                                state.selected = *i;
9141                                match state.tabs.as_ref() {
9142                                    // The tab view shows exactly its selected item's page.
9143                                    Some(tabs) => {
9144                                        let n = unsafe { tabs.view.numberOfTabViewItems() };
9145                                        if (*i as isize) < n {
9146                                            TAB_PICK_SUPPRESS.with(|s| s.set(true));
9147                                            unsafe {
9148                                                tabs.view.selectTabViewItemAtIndex(*i as isize)
9149                                            };
9150                                            TAB_PICK_SUPPRESS.with(|s| s.set(false));
9151                                        }
9152                                    }
9153                                    None => {
9154                                        for (n, page) in state.pages.iter().enumerate() {
9155                                            page.setHidden(n != *i);
9156                                        }
9157                                    }
9158                                }
9159                            }
9160                            // Per-destination pane visibility (docs/navigation.md). Directly,
9161                            // not through the animator proxy: a screenshot must not catch a
9162                            // mid-animation pane (the sidebar-toggle rule), and settled now,
9163                            // like a re-present, so the detail's frame is right the instant
9164                            // the patch returns rather than one layout pass later.
9165                            NavPatch::ListVisible(v) => {
9166                                state.list_visible = *v;
9167                                if let Some(item) = state.list_item.as_ref() {
9168                                    item.setCollapsed(!*v);
9169                                    let split = unsafe { state._split_vc.splitView() };
9170                                    unsafe { split.layoutSubtreeIfNeeded() };
9171                                    // First time this pane is actually on screen: give it the
9172                                    // width the app asked for. The frame pass that would
9173                                    // otherwise do it has already run, back when there was no
9174                                    // pane to size.
9175                                    if let Some(w) = take_list_placement(state) {
9176                                        unsafe {
9177                                            split.setPosition_ofDividerAtIndex(
9178                                                day_spec::NAV_SIDEBAR_WIDTH + w,
9179                                                1,
9180                                            );
9181                                        }
9182                                    }
9183                                    // Re-frame the pane's page to the wrap it fills. A page
9184                                    // inserted while the pane was collapsed got a zero-width
9185                                    // frame, and `ViewWidthSizable` scales zero to zero however
9186                                    // wide the wrap becomes, so the list stayed invisible while
9187                                    // its rows were still there to click. An app opening on a
9188                                    // full-page section hits this on the first reveal.
9189                                    if *v
9190                                        && let Some(wrap) = state.list_wrap.as_ref()
9191                                        && let Some(page) = state.list_page.as_ref()
9192                                    {
9193                                        unsafe {
9194                                            wrap.layoutSubtreeIfNeeded();
9195                                            page.setFrame(wrap.bounds());
9196                                        }
9197                                    }
9198                                }
9199                            }
9200                            // Never arrives here: the pane persists through every presentation
9201                            // (`Cap::NavContentList` = Native), so the pieces layer never asks
9202                            // for the merged-stack shape.
9203                            NavPatch::ListInStack(_) => {}
9204                        }
9205                    });
9206                }
9207            }
9208            // Emulated cover (docs/cover.md): present = re-home onto the window's content view
9209            // at full bounds, topmost, autoresized with the window (the DayNavPage handle
9210            // reports FrameChanged on every resize). Dismiss = hide + report `CoverHidden`
9211            // immediately (no transition on this tier). Interactive dismissal doesn't exist on
9212            // this backend, so DismissDisabled has nothing to disable.
9213            kinds::COVER => {
9214                if let (Some(p), Ok(page)) = (
9215                    patch.downcast_ref::<CoverPatch>(),
9216                    h.clone().downcast::<DayNavPage>(),
9217                ) {
9218                    let node = page.ivars().node;
9219                    match p {
9220                        CoverPatch::Present { background, .. } => {
9221                            if page.ivars().sheet.get() {
9222                                if let Some(parent) =
9223                                    primary_content().and_then(|v| unsafe { v.window() })
9224                                {
9225                                    let bounds = parent.frame().size;
9226                                    let max = if page.ivars().large.get() {
9227                                        day_spec::props::LARGE_SHEET_MAX
9228                                    } else {
9229                                        day_spec::props::SHEET_MAX
9230                                    };
9231                                    let height = if page.ivars().half.get() {
9232                                        (bounds.height * 0.5).clamp(160.0, max.height)
9233                                    } else {
9234                                        (bounds.height - 80.0).clamp(300.0, max.height)
9235                                    };
9236                                    let size = NSSize::new(
9237                                        (bounds.width - 40.0).clamp(320.0, max.width),
9238                                        height,
9239                                    );
9240                                    let window = unsafe {
9241                                        NSWindow::initWithContentRect_styleMask_backing_defer(
9242                                            NSWindow::alloc(MainThreadMarker::new().unwrap()),
9243                                            NSRect::new(NSPoint::new(0.0, 0.0), size),
9244                                            NSWindowStyleMask::Titled,
9245                                            NSBackingStoreType::Buffered,
9246                                            false,
9247                                        )
9248                                    };
9249                                    unsafe {
9250                                        window.setReleasedWhenClosed(false);
9251                                        page.removeFromSuperview();
9252                                        page.setHidden(false);
9253                                        page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
9254                                        window.setContentView(Some(&page));
9255                                    }
9256                                    let key = ptr_of(h);
9257                                    SHEET_NODES.with(|t| {
9258                                        t.insert(Retained::as_ptr(&window) as usize, node)
9259                                    });
9260                                    install_sheet_escape_monitor();
9261                                    COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
9262                                    dispatch2::DispatchQueue::main().exec_async(move || {
9263                                        ffi_guard::contain((), || {
9264                                            let window =
9265                                                COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
9266                                            if let (Some(window), Some(parent)) = (
9267                                                window,
9268                                                primary_content()
9269                                                    .and_then(|v| unsafe { v.window() }),
9270                                            ) {
9271                                                unsafe {
9272                                                    parent.beginSheet_completionHandler(
9273                                                        &window, None,
9274                                                    );
9275                                                }
9276                                            }
9277                                        });
9278                                    });
9279                                    emit(
9280                                        node,
9281                                        Event::FrameChanged(Size::new(size.width, size.height)),
9282                                    );
9283                                }
9284                                return;
9285                            }
9286                            // A cover must occlude the window (the native tiers' modal surfaces
9287                            // are opaque): default to the window background when the app sets
9288                            // no explicit color.
9289                            unsafe {
9290                                page.setWantsLayer(true);
9291                                if let Some(layer) = page.layer() {
9292                                    let color = match background {
9293                                        Some(bg) => nscolor(*bg),
9294                                        None => NSColor::windowBackgroundColor(),
9295                                    };
9296                                    layer.setBackgroundColor(Some(&color.CGColor()));
9297                                }
9298                            }
9299                            // The primary window's content, specifically: firstObject()
9300                            // is arbitrary once secondary windows exist (docs/windows.md).
9301                            if let Some(content) = primary_content() {
9302                                if let Some(window) = unsafe { content.window() } {
9303                                    toolbar::cover_presented(ptr_of(h), &window);
9304                                }
9305                                // Edge to edge like the root's own background, laid out below
9306                                // the title bar like the root's content: the page starts at the
9307                                // top of the window (above the pinned content origin) and
9308                                // keeps the same strip above its own layout origin.
9309                                let top = title_bar_inset(&content);
9310                                let full = content.frame().size;
9311                                page.ivars().top_inset.set(top);
9312                                unsafe {
9313                                    page.removeFromSuperview();
9314                                    content.addSubview(&page);
9315                                    page.setFrame(NSRect::new(
9316                                        NSPoint::new(0.0, -top),
9317                                        NSSize::new(full.width, full.height),
9318                                    ));
9319                                    page.setBoundsOrigin(NSPoint::new(0.0, -top));
9320                                    page.setAutoresizingMask(
9321                                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9322                                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9323                                    );
9324                                    page.setHidden(false);
9325                                }
9326                                emit(
9327                                    node,
9328                                    Event::FrameChanged(Size::new(
9329                                        full.width,
9330                                        (full.height - top).max(0.0),
9331                                    )),
9332                                );
9333                            }
9334                        }
9335                        CoverPatch::DismissDisabled(_) => {}
9336                        CoverPatch::Dismiss => {
9337                            COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
9338                            toolbar::cover_dismissed(ptr_of(h));
9339                            unsafe {
9340                                page.setHidden(true);
9341                                page.removeFromSuperview();
9342                            }
9343                            emit(node, Event::CoverHidden);
9344                        }
9345                    }
9346                }
9347            }
9348            kinds::PICKER => picker::update_any(self, h, patch),
9349            kinds::TEXT_AREA => textarea::update_any(self, h, patch),
9350            kinds::TEXT_FIELD => {
9351                if let (Some(p), Ok(tf)) = (
9352                    patch.downcast_ref::<TextFieldPatch>(),
9353                    h.clone().downcast::<NSTextField>(),
9354                ) {
9355                    match p {
9356                        TextFieldPatch::Text { text, from_native } => {
9357                            // Origin-tagged echo suppression (§4.4).
9358                            if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
9359                                unsafe { tf.setStringValue(&NSString::from_str(text)) };
9360                            }
9361                        }
9362                        TextFieldPatch::Placeholder(t) => unsafe {
9363                            tf.setPlaceholderString(Some(&NSString::from_str(t)))
9364                        },
9365                        TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
9366                    }
9367                }
9368            }
9369            kinds::LIST => match patch.downcast_ref::<ListPatch>() {
9370                Some(ListPatch::Splice(deltas)) => {
9371                    // The set changed by exactly these deltas: animate each row in, out, or
9372                    // across, the thing a reload cannot express. Indexes are sequential, so
9373                    // each delta gets its own begin/endUpdates batch (NSTableView's combined
9374                    // batch semantics re-interpret indexes; one-at-a-time stays literal).
9375                    // Row realization stays deferred, as with Reload.
9376                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9377                        use objc2_app_kit::NSTableViewAnimationOptions;
9378                        for d in deltas {
9379                            unsafe {
9380                                table.beginUpdates();
9381                                match d {
9382                                    day_spec::props::RowDelta::Insert(i) => table
9383                                        .insertRowsAtIndexes_withAnimation(
9384                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9385                                            NSTableViewAnimationOptions::SlideDown,
9386                                        ),
9387                                    day_spec::props::RowDelta::Remove(i) => table
9388                                        .removeRowsAtIndexes_withAnimation(
9389                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9390                                            NSTableViewAnimationOptions::SlideUp,
9391                                        ),
9392                                    day_spec::props::RowDelta::Move(from, to) => {
9393                                        table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
9394                                    }
9395                                }
9396                                table.endUpdates();
9397                            }
9398                        }
9399                        // The displayed order matches the source again: refresh the cache a
9400                        // committed drag keeps in step and `permutation_moves` compares, or the
9401                        // next Reload finds a stale length and reloads flat instead of animating.
9402                        if let Some(source) = data.ivars().source.borrow().as_ref() {
9403                            let n = (source.len)();
9404                            *data.ivars().tokens.borrow_mut() =
9405                                (0..n).map(|i| (source.token_at)(i)).collect();
9406                        }
9407                    }
9408                    post_realize_visible_rows(ptr_of(h));
9409                }
9410                Some(ListPatch::Reload) => {
9411                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9412                        // NSTableView reloadData clears selection for this view-based source.
9413                        // Preserve identities, not indexes, across refreshes/reorders; removed
9414                        // items disappear from the selection without selecting their successor.
9415                        let selected = unsafe { table.selectedRowIndexes() };
9416                        let tokens: Vec<u64> = data
9417                            .ivars()
9418                            .tokens
9419                            .borrow()
9420                            .iter()
9421                            .enumerate()
9422                            .filter(|(row, _)| selected.containsIndex(*row))
9423                            .map(|(_, token)| *token)
9424                            .collect();
9425                        data.ivars().suppress.set(true);
9426                        // A reload whose rows are the same set in a new order (a shuffle,
9427                        // a programmatic sort) animates as native row moves instead of a
9428                        // blink: a `moveRowAtIndex` batch, the same animation a drag commit
9429                        // gets. Anything else (insert/remove/content change) reloads flat.
9430                        // reloadData queries numberOfRows synchronously (snapshot only, no
9431                        // tree) and defers viewForRow, so both paths are safe in with_tree.
9432                        if let Some(moves) = data.permutation_moves(&table) {
9433                            unsafe {
9434                                table.beginUpdates();
9435                                for (from, to) in moves {
9436                                    table.moveRowAtIndex_toIndex(from as isize, to as isize);
9437                                }
9438                                table.endUpdates();
9439                            }
9440                        } else {
9441                            unsafe { table.reloadData() };
9442                        }
9443                        let restored = objc2_foundation::NSMutableIndexSet::new();
9444                        for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
9445                            if tokens.contains(token) {
9446                                restored.addIndex(row);
9447                            }
9448                        }
9449                        unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
9450                        data.ivars().suppress.set(false);
9451                    }
9452                    // Realize the visible rows on the next main-loop turn, outside this borrow.
9453                    // An occluded window (locked screen, covered, headless CI) gets no normal
9454                    // draw pass; NSTableView would first realize these rows inside a snapshot's
9455                    // `cacheDisplayInRect`, where `bind_row` must skip the held borrow and the
9456                    // table would cache permanently blank cells.
9457                    post_realize_visible_rows(ptr_of(h));
9458                }
9459                Some(ListPatch::ScrollToRow(row)) => {
9460                    // Same deferral discipline as ScrollToEnd: the scroll tiles target rows
9461                    // synchronously, which must happen outside this `with_tree` borrow.
9462                    let (key, row) = (ptr_of(h), *row);
9463                    <AppKit as Platform>::post(Box::new(move || {
9464                        if let Some((table, _)) = list_entry(key) {
9465                            let rows = unsafe { table.numberOfRows() };
9466                            if rows > 0 {
9467                                unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
9468                            }
9469                        }
9470                    }));
9471                    post_realize_visible_rows(ptr_of(h));
9472                }
9473                Some(ListPatch::ScrollToEnd) => {
9474                    // Deferred to the next main-loop turn: an actual scroll forces NSTableView
9475                    // to tile (realize) the target rows synchronously, and this patch arrives
9476                    // inside a `with_tree` borrow where `bind_row` must skip; the table would
9477                    // cache blank cells for every newly exposed row (see Reload above).
9478                    let key = ptr_of(h);
9479                    <AppKit as Platform>::post(Box::new(move || {
9480                        if let Some((table, _)) = list_entry(key) {
9481                            let rows = unsafe { table.numberOfRows() };
9482                            if rows > 0 {
9483                                unsafe { table.scrollRowToVisible(rows - 1) };
9484                            }
9485                        }
9486                    }));
9487                    // ...and realize whatever the scroll exposed, still outside the borrow.
9488                    post_realize_visible_rows(ptr_of(h));
9489                }
9490                Some(ListPatch::Selected(rows)) => {
9491                    // Programmatic selection sync (empty = clear), suppressed so the
9492                    // delegate does not echo it back as a selection event.
9493                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9494                        data.ivars().suppress.set(true);
9495                        unsafe {
9496                            if rows.is_empty() {
9497                                table.deselectAll(None);
9498                            } else {
9499                                let set = objc2_foundation::NSMutableIndexSet::new();
9500                                let count = table.numberOfRows().max(0) as usize;
9501                                for r in rows.iter().copied().filter(|r| *r < count) {
9502                                    set.addIndex(r);
9503                                }
9504                                table.selectRowIndexes_byExtendingSelection(&set, false);
9505                            }
9506                        }
9507                        data.ivars().suppress.set(false);
9508                    }
9509                }
9510                Some(ListPatch::RowSizeInvalidated { cell, height }) => {
9511                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9512                        data.row_resized(&table, *cell, *height);
9513                    }
9514                }
9515                // `None` = a patch for another kind's enum. A desktop table has no editing mode
9516                // (Cap::ListEditing is Unsupported).
9517                Some(ListPatch::Editing(_)) | None => {}
9518            },
9519            kinds::TREE => match patch.downcast_ref::<TreePatch>() {
9520                Some(TreePatch::Reload) => {
9521                    // Interned items keep their identity across reloadData, so NSOutlineView
9522                    // itself preserves expansion; the piece re-asserts it (and the selection)
9523                    // by token right after, belt and braces. reloadData queries the child
9524                    // counts synchronously (snapshot only, no tree) and defers viewForItem.
9525                    if let Some((outline, _)) = tree_entry(ptr_of(h)) {
9526                        unsafe { outline.reloadData() };
9527                    }
9528                    post_realize_visible_tree_rows(ptr_of(h));
9529                }
9530                Some(TreePatch::Expand(token, on)) => {
9531                    // Deferred: expandItem/collapseItem realize (or remove) the disclosed
9532                    // rows synchronously, and this patch arrives inside a `with_tree` borrow
9533                    // where `bind_row` must skip; the outline would cache permanently blank,
9534                    // id-less rows (the ScrollToEnd rule, one arm over).
9535                    let (key, token, on) = (ptr_of(h), *token, *on);
9536                    <AppKit as Platform>::post(Box::new(move || {
9537                        if let Some((outline, data)) = tree_entry(key) {
9538                            let item = data.intern(token);
9539                            // Suppressed: a programmatic disclosure must not echo back as
9540                            // `Event::TreeExpanded`. Redundant applications are AppKit no-ops.
9541                            data.ivars().suppress.set(true);
9542                            unsafe {
9543                                if on {
9544                                    outline.expandItem(Some(&item));
9545                                } else {
9546                                    outline.collapseItem(Some(&item));
9547                                }
9548                            }
9549                            data.ivars().suppress.set(false);
9550                        }
9551                        day_core::pump_events();
9552                    }));
9553                    post_realize_visible_tree_rows(ptr_of(h));
9554                }
9555                Some(TreePatch::Selected(tokens)) => {
9556                    if let Some((outline, data)) = tree_entry(ptr_of(h)) {
9557                        data.ivars().suppress.set(true);
9558                        unsafe {
9559                            if tokens.is_empty() {
9560                                outline.deselectAll(None);
9561                            } else {
9562                                let set = objc2_foundation::NSMutableIndexSet::new();
9563                                for t in tokens {
9564                                    // A token under a collapsed ancestor has no row, so it is
9565                                    // skipped; the piece re-applies after expansion changes.
9566                                    let row = outline.rowForItem(Some(&data.intern(*t)));
9567                                    if row >= 0 {
9568                                        set.addIndex(row as usize);
9569                                    }
9570                                }
9571                                outline.selectRowIndexes_byExtendingSelection(&set, false);
9572                            }
9573                        }
9574                        data.ivars().suppress.set(false);
9575                    }
9576                }
9577                Some(TreePatch::Reveal(token)) => {
9578                    // Deferred: the scroll tiles target rows synchronously, which must
9579                    // happen outside this `with_tree` borrow (the ScrollToRow rule).
9580                    let (key, token) = (ptr_of(h), *token);
9581                    <AppKit as Platform>::post(Box::new(move || {
9582                        if let Some((outline, data)) = tree_entry(key) {
9583                            let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
9584                            if row >= 0 {
9585                                unsafe { outline.scrollRowToVisible(row) };
9586                            }
9587                        }
9588                    }));
9589                    post_realize_visible_tree_rows(ptr_of(h));
9590                }
9591                None => {}
9592            },
9593            _ => {
9594                if let Some(update) = self.registry.get(kind).map(|r| r.update) {
9595                    update(self, h, patch);
9596                }
9597            }
9598        }
9599    }
9600
9601    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
9602    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
9603        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
9604        // the hook needs it mutably.
9605        let f = self.registry.get(kind).and_then(|r| r.release);
9606        if let Some(f) = f {
9607            f(self, h);
9608        }
9609    }
9610    fn release(&mut self, h: Handle) {
9611        LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
9612        // A released window content = that window is gone (docs/windows.md teardown):
9613        // drop the SecondaryWin (closing a straggler NSWindow) and its delegate with it.
9614        // (A re-fired windowWillClose emits to a torn-down node: dropped, harmless.)
9615        self.secondary.retain(|w| {
9616            if ptr_of(&w.content) == ptr_of(&h) {
9617                w.window.close();
9618                // The window's keyed state goes with it: its toolbar (toolbar.rs BARS,
9619                // keyed by the window pointer) used to survive a secondary close, and its
9620                // items, targets, retained NSToolbar and delegate all leaked.
9621                day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
9622                false
9623            } else {
9624                true
9625            }
9626        });
9627        TARGETS.with(|m| {
9628            m.borrow_mut().remove(&ptr_of(&h));
9629        });
9630        LIST_STATE.with(|m| {
9631            m.borrow_mut().remove(&ptr_of(&h));
9632        });
9633        TREE_STATE.with(|m| {
9634            m.borrow_mut().remove(&ptr_of(&h));
9635        });
9636        GESTURES.with(|m| {
9637            m.borrow_mut().remove(&ptr_of(&h));
9638        });
9639        NAV_STATE.with(|m| {
9640            if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
9641                // Unhook the split view controller from the responder chain before the drop
9642                // deallocs it. AppKit rewires these pointers behind day's back (mounting the
9643                // split resets its next to the superview; the controller's own view keeps
9644                // aiming at the controller), and a controller whose next responder is its own
9645                // view dies in dealloc's chain splice with the "next responder should never
9646                // be yourself" NSException, foreign to Rust, so it aborts the process
9647                // instead of unwinding (the Stack-page teardown crash, 2026-08).
9648                unsafe {
9649                    nav._split_vc.setNextResponder(None);
9650                    let split = nav._split_vc.splitView();
9651                    if split.nextResponder().is_some_and(|r| {
9652                        core::ptr::eq::<objc2::runtime::AnyObject>(
9653                            r.as_ref(),
9654                            nav._split_vc.as_ref(),
9655                        )
9656                    }) {
9657                        split.setNextResponder(None);
9658                    }
9659                }
9660            }
9661        });
9662        NAV_PAGES.with(|set| {
9663            set.borrow_mut().remove(&ptr_of(&h));
9664        });
9665        SPLIT_STATE.with(|m| {
9666            if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
9667                state.split.setDelegate(None);
9668            }
9669        });
9670        INSPECTOR_STATE.with(|m| {
9671            if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
9672                // The same dealloc-splice guard as the nav host above: never let the
9673                // controller (or its split) dealloc aiming at itself.
9674                unsafe {
9675                    insp._split_vc.setNextResponder(None);
9676                    let split = insp._split_vc.splitView();
9677                    if split.nextResponder().is_some_and(|r| {
9678                        core::ptr::eq::<objc2::runtime::AnyObject>(
9679                            r.as_ref(),
9680                            insp._split_vc.as_ref(),
9681                        )
9682                    }) {
9683                        split.setNextResponder(None);
9684                    }
9685                }
9686            }
9687        });
9688        NAV_MENUS.with(|m| {
9689            if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
9690                // The outline registers under its pointer (`menuForEvent:` resolves by
9691                // outline, not by this scroll handle): sweep that auxiliary key too, so
9692                // NAV_OUTLINE_MENUS, and any future outline-keyed table, drops it. A
9693                // surviving entry served the dead menu's rows once the address was recycled.
9694                day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
9695            }
9696        });
9697        // One call reclaims this handle's entry from every SideTable on this thread (canvas
9698        // OPS, PAGE_PANE, the picker/textarea state, and whatever lands later), running each
9699        // table's teardown hook (day-spec sidetable). The explicit removals above are the
9700        // older per-map checklist; new per-view maps should be SideTables so this sweep covers
9701        // them without another line here.
9702        day_spec::sidetable::sweep(ptr_of(&h));
9703        unsafe { h.removeFromSuperview() };
9704    }
9705
9706    fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
9707        // A nav menu that has just gained ancestors: if one of them is a tabs host, its rows
9708        // Are that host's tab labels (`adopt_menu_for_tabs`). The menu is built after its rows
9709        // page joined the host, so this is the first moment the host can see its rows.
9710        if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
9711            unsafe { content_of(parent).addSubview(child) };
9712            adopt_menu_for_tabs(self.mtm(), child);
9713            return;
9714        }
9715        // Nav host: pages land by their pane, not their position (docs/size-classes.md). Pages
9716        // fill their pane via autoresizing; the pane, not Day, owns their frames.
9717        let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
9718        let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
9719        let handled = NAV_STATE.with(|m| {
9720            let mut m = m.borrow_mut();
9721            let Some(state) = m.get_mut(&ptr_of(parent)) else {
9722                return false;
9723            };
9724            // The content-list page fills its pane at every presentation
9725            // (docs/navigation.md), never a member of the detail stack.
9726            if page_pane == Some(day_spec::props::Pane::List)
9727                && let Some(wrap) = state.list_wrap.as_ref()
9728            {
9729                state.list_page = Some(child.clone());
9730                unsafe {
9731                    child.setFrame(wrap.bounds());
9732                    child.setAutoresizingMask(
9733                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9734                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9735                    );
9736                    wrap.addSubview(child);
9737                }
9738                return true;
9739            }
9740            if is_sidebar_page {
9741                state.sidebar_page = Some(child.clone());
9742            }
9743            // Split (nav host Sidebar): the sidebar pane's page goes in the sidebar; the rest are
9744            // detail pages. Stack: every page, including the sidebar's, which is the stack's
9745            // root, lives in the detail pane so push/pop visibility covers them all.
9746            // The rows page goes to the sidebar pane in every presentation but `Stack`, where
9747            // it is the stack root and joins the detail pages instead.
9748            let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
9749            // A tabs host's detail page becomes an item of its tab view, which frames it (the
9750            // page's `setFrameSize:` reports the size to Day). Its label comes with the
9751            // menu's rows: already here when a page joins a live host, otherwise when the
9752            // menu is inserted (`adopt_menu_for_tabs`).
9753            if !to_pane && let Some(tabs) = state.tabs.as_ref() {
9754                state.pages.push(child.clone());
9755                let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
9756                unsafe {
9757                    child.setAutoresizingMask(
9758                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9759                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9760                    );
9761                    item.setView(Some(child));
9762                    tabs.view.addTabViewItem(&item);
9763                }
9764                if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
9765                    sync_tab_labels(tabs, &titles, state.selected);
9766                }
9767                return true;
9768            }
9769            let (wrap, frame) = if to_pane {
9770                (&state.sidebar_wrap, state.sidebar_wrap.bounds())
9771            } else {
9772                state.pages.push(child.clone());
9773                let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
9774                (
9775                    &state.detail_wrap,
9776                    nav_page_frame(&state.detail_wrap, visible),
9777                )
9778            };
9779            unsafe {
9780                child.setFrame(frame);
9781                child.setAutoresizingMask(
9782                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9783                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9784                );
9785                wrap.addSubview(child);
9786            }
9787            true
9788        });
9789        if handled {
9790            return;
9791        }
9792        // Split host (docs/split.md): each pane fills its wrap, an arranged subview the
9793        // splitter sizes; the pane's own `setFrameSize:` reports the size to Day.
9794        let split_pane = SPLIT_STATE.with(|m| {
9795            let m = m.borrow();
9796            let Some(state) = m.get(&ptr_of(parent)) else {
9797                return false;
9798            };
9799            let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
9800            let wrap = if second {
9801                &state.second_wrap
9802            } else {
9803                &state.first_wrap
9804            };
9805            unsafe {
9806                child.setFrame(wrap.bounds());
9807                child.setAutoresizingMask(
9808                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9809                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9810                );
9811                wrap.addSubview(child);
9812            }
9813            true
9814        });
9815        if split_pane {
9816            return;
9817        }
9818        // Inspector host: each pane fills its wrap via autoresizing, the nav-page contract;
9819        // the split, not Day, owns the pane frames (docs/inspector.md).
9820        let inspected = INSPECTOR_STATE.with(|m| {
9821            let m = m.borrow();
9822            let Some(state) = m.get(&ptr_of(parent)) else {
9823                return false;
9824            };
9825            let panel = INSPECTOR_PANES
9826                .with(|t| t.get(ptr_of(child)))
9827                .unwrap_or(false);
9828            let wrap = if panel {
9829                &state.panel_wrap
9830            } else {
9831                &state.content_wrap
9832            };
9833            unsafe {
9834                child.setFrame(wrap.bounds());
9835                child.setAutoresizingMask(
9836                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9837                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9838                );
9839                wrap.addSubview(child);
9840            }
9841            true
9842        });
9843        if !inspected {
9844            // Absolute positioning: z-order is build order; index is irrelevant for
9845            // non-overlapping frames (stack_z will need ordered insertion later).
9846            unsafe { content_of(parent).addSubview(child) };
9847        }
9848    }
9849
9850    fn remove(&mut self, parent: &Handle, child: &Handle) {
9851        PAGE_PANE.with(|t| t.remove(ptr_of(child)));
9852        let mtm = self.mtm();
9853        NAV_STATE.with(|m| {
9854            if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
9855                // A tabs host: the page leaves with its tab item.
9856                if let Some(tabs) = state.tabs.as_ref() {
9857                    unsafe {
9858                        let n = tabs.view.numberOfTabViewItems();
9859                        for i in 0..n {
9860                            let item = tabs.view.tabViewItemAtIndex(i);
9861                            if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
9862                                tabs.view.removeTabViewItem(&item);
9863                                break;
9864                            }
9865                        }
9866                    }
9867                }
9868                state.pages.retain(|p| ptr_of(p) != ptr_of(child));
9869                if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
9870                    state.sidebar_page = None;
9871                }
9872            }
9873        });
9874        unsafe { child.removeFromSuperview() };
9875    }
9876
9877    fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
9878        unsafe { content_of(parent).addSubview(child) };
9879    }
9880
9881    fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
9882        match kind {
9883            kinds::LABEL => {
9884                if let Some(tf) = h.downcast_ref::<NSTextField>() {
9885                    let w = p.width.unwrap_or(1.0e6);
9886                    // The field owns maximumNumberOfLines; measuring its cell bypasses it.
9887                    let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
9888                    let mut height = s.height.ceil();
9889                    // AppKit's truncating single-line mode still measures explicit newlines
9890                    // as multiple lines. Bound that case using AppKit's own font metrics.
9891                    if tf.maximumNumberOfLines() == 1 {
9892                        thread_local! {
9893                            static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
9894                        }
9895                        if let Some(font) = unsafe { tf.font() } {
9896                            height = height.min(
9897                                METRICS
9898                                    .with(|metrics| metrics.defaultLineHeightForFont(&font))
9899                                    .ceil(),
9900                            );
9901                        }
9902                    }
9903                    return Size::new(s.width.ceil().min(w), height);
9904                }
9905                Size::ZERO
9906            }
9907            kinds::BUTTON | kinds::TOGGLE => {
9908                let s = unsafe { h.fittingSize() };
9909                Size::new(s.width.ceil(), s.height.ceil())
9910            }
9911            kinds::SLIDER => {
9912                let s = unsafe { h.fittingSize() };
9913                Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
9914            }
9915            kinds::PICKER => picker::measure_any(self, h, p),
9916            kinds::TEXT_AREA => textarea::measure_any(self, h, p),
9917            kinds::TEXT_FIELD => {
9918                let s = unsafe { h.fittingSize() };
9919                Size::new(
9920                    p.width.unwrap_or(s.width.max(160.0)),
9921                    s.height.max(22.0).ceil(),
9922                )
9923            }
9924            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
9925            // The stack's own fitting size, at least a table row's 28pt; the words truncate to
9926            // the row's width.
9927            kinds::LIST_ITEM => {
9928                let s = h.fittingSize();
9929                Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
9930            }
9931            kinds::PROGRESS => {
9932                // Indeterminate spinner is a fixed square; determinate bar fills width.
9933                let indeterminate = h
9934                    .clone()
9935                    .downcast::<NSProgressIndicator>()
9936                    .map(|pi| unsafe { pi.isIndeterminate() })
9937                    .unwrap_or(false);
9938                if indeterminate {
9939                    let large = h
9940                        .downcast_ref::<NSProgressIndicator>()
9941                        .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
9942                    let side = if large { 32.0 } else { 20.0 };
9943                    Size::new(side, side)
9944                } else {
9945                    Size::new(p.width.unwrap_or(180.0), 20.0)
9946                }
9947            }
9948            kinds::NAV_MENU => {
9949                let rows = NAV_MENUS.with(|m| {
9950                    m.borrow()
9951                        .get(&ptr_of(h))
9952                        .map(|(_, d)| d.ivars().items.borrow().len())
9953                        .unwrap_or(0)
9954                });
9955                Size::new(
9956                    p.width.unwrap_or(220.0),
9957                    p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
9958                )
9959            }
9960            // The recycling list fills the space it is offered (its native scroll owns overflow).
9961            kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
9962            _ => {
9963                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
9964                    measure(self, h, p)
9965                } else {
9966                    let s = unsafe { h.fittingSize() };
9967                    Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
9968                }
9969            }
9970        }
9971    }
9972
9973    fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
9974        unsafe {
9975            h.setWantsLayer(true);
9976        }
9977        let v = h.clone();
9978        with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
9979    }
9980
9981    fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
9982        // Expressed in the view's own geometry (see `TRANSFORMS`), so hit-testing follows the
9983        // drawing, as UIKit's does. Without a laid-out frame yet, `set_frame` applies it.
9984        TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
9985        let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
9986        let v = h.clone();
9987        with_appkit_anim(anim, move || {
9988            if let Some(base) = base {
9989                apply_geometry(&v, base, t);
9990            }
9991        });
9992    }
9993
9994    fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
9995        if let Some(label) = h.downcast_ref::<DayLabel>() {
9996            label.ivars().selectable.set(selectable);
9997            label.set_links(label.ivars().has_links.get());
9998        } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
9999            unsafe { tf.setSelectable(selectable) };
10000        }
10001        None
10002    }
10003
10004    fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
10005        let node = text_field_node(h)?;
10006        let old = h.downcast_ref::<NSTextField>()?;
10007        // Hidden characters are a class on AppKit. A field already of the right class is
10008        // dressed in place; otherwise its replacement is, and the node moves to it.
10009        let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
10010            .then(|| self.swap_text_field(h, old, node, traits.secure));
10011        let tf = swapped.as_deref().unwrap_or(old);
10012        unsafe {
10013            // Read-only keeps the bezel and the ordinary text color; the text stays
10014            // selectable, so it can still be copied.
10015            tf.setEditable(!traits.read_only);
10016            tf.setSelectable(true);
10017        }
10018        // The purpose is AutoFill's hint on the desktop: which saved credential or contact
10019        // detail the system offers. `Number` and `Decimal` have no content type. A constant
10020        // newer than the running system leaves the field untyped.
10021        let content_type = match traits.purpose {
10022            InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
10023            InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
10024            InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
10025            InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
10026            InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
10027            InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
10028            InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
10029            InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
10030            InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
10031        };
10032        unsafe {
10033            tf.setContentType(content_type);
10034            // Only free text wants the system finishing words; a name, an address or a code
10035            // is typed exactly.
10036            tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
10037        }
10038        // No on-screen keyboard, so no action key to label; and no native length limit:
10039        // day-pieces holds `max_length`.
10040        swapped.map(view_of)
10041    }
10042
10043    fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
10044        let key = Retained::as_ptr(h) as usize;
10045        if cursor == Cursor::Default {
10046            // Release: drop the tracking area, and the hide if this owner holds one.
10047            if let Some((owner, area)) = self.cursors.remove(&key) {
10048                unsafe { h.removeTrackingArea(&area) };
10049                if owner.ivars().hiding.replace(false) {
10050                    NSCursor::unhide();
10051                }
10052            }
10053            return;
10054        }
10055        let hidden = cursor == Cursor::None;
10056        let shape = if hidden { None } else { ns_cursor(&cursor) };
10057        let mtm = self.mtm;
10058        let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
10059            let owner = DayCursorOwner::new(mtm);
10060            // InVisibleRect: the area follows the view's bounds, so no rect to keep in step
10061            // with layout. ActiveInKeyWindow: the shape belongs to the window taking input.
10062            let opts = NSTrackingAreaOptions::CursorUpdate
10063                | NSTrackingAreaOptions::MouseEnteredAndExited
10064                | NSTrackingAreaOptions::ActiveInKeyWindow
10065                | NSTrackingAreaOptions::InVisibleRect;
10066            let any: &objc2::runtime::AnyObject = &owner;
10067            let area = unsafe {
10068                NSTrackingArea::initWithRect_options_owner_userInfo(
10069                    NSTrackingArea::alloc(),
10070                    NSRect::ZERO,
10071                    opts,
10072                    Some(any),
10073                    None,
10074                )
10075            };
10076            unsafe { h.addTrackingArea(&area) };
10077            (owner, area)
10078        });
10079        let changed = {
10080            let iv = owner.ivars();
10081            let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10082                (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10083                (None, None) => true,
10084                _ => false,
10085            };
10086            *iv.cursor.borrow_mut() = shape;
10087            let was_hidden = iv.hidden.replace(hidden);
10088            !same || was_hidden != hidden
10089        };
10090        // A reactive change while the pointer is already inside: AppKit only asks on entry,
10091        // so ask it to re-evaluate now.
10092        if changed && let Some(w) = h.window() {
10093            unsafe { w.invalidateCursorRectsForView(h) };
10094        }
10095    }
10096
10097    /// Where the control actually draws its first line of text (docs/baseline.md).
10098    ///
10099    /// AppKit publishes `firstBaselineOffsetFromTop`, but it is measured from the top of the
10100    /// view's alignment rect and it is rounded to whole points, and that rounding is visible.
10101    /// An `NSDatePicker` in a 26pt frame insets its alignment rect 4pt and answers 15, i.e. 19
10102    /// in frame terms, while it paints at 19.9; a label beside it then sits a point high, which
10103    /// is exactly the drift baseline alignment exists to remove.
10104    ///
10105    /// So derive it from the metrics AppKit rounded: a single line of the control's own font,
10106    /// centered in its alignment rect, with the baseline an ascender below the line's top. That
10107    /// reproduces AppKit's own numbers for a plain label and a bezeled field (12.91 → its 13,
10108    /// 19.91 → its 20) while keeping the fractional part that makes a picker land on the line.
10109    /// Controls with no font of their own keep AppKit's answer.
10110    fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
10111        if !day_spec::kind_has_baseline(kind) {
10112            return None;
10113        }
10114        // The view has to be at the height the row settled on before it answers: a control
10115        // that centers its text vertically moves its baseline with its box.
10116        let current = unsafe { h.frame() };
10117        if (current.size.height - size.height).abs() > 0.5 {
10118            unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
10119        }
10120        let insets = unsafe { h.alignmentRectInsets() };
10121        let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
10122        let font = h
10123            .downcast_ref::<NSControl>()
10124            .and_then(|c| unsafe { c.font() });
10125        let offset = match font {
10126            // A multi-line editor's first line sits at the top of its text container, not
10127            // centered in it, so the centering model would put its baseline half a box too low.
10128            Some(_) if kind == kinds::TEXT_AREA => reported,
10129            Some(f) => {
10130                let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
10131                let line = ascender - descender;
10132                let align_h = (size.height - insets.top - insets.bottom).max(0.0);
10133                insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
10134            }
10135            None => reported,
10136        };
10137        // AppKit's documented "no baseline" answer is the view's own height.
10138        (offset > 0.0 && offset < size.height).then_some(offset)
10139    }
10140
10141    fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
10142        // Nav pages: the splitter pane / nav container owns the frame (autoresized).
10143        if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
10144            return;
10145        }
10146        // Every Day parent is flipped (DayFlipped containers, flipped scroll document views),
10147        // so top-left frames apply directly.
10148        let r = NSRect::new(
10149            NSPoint::new(frame.origin.x, frame.origin.y),
10150            NSSize::new(frame.size.width, frame.size.height),
10151        );
10152        // Nav host: the sidebar holds its width when the window resizes and the detail pane
10153        // absorbs the change. That is now the sidebar NSSplitViewItem's behavior, so the
10154        // only thing left to do here is give the split its frame and place the divider once;
10155        // re-placing it on every resize would fight the item and undo a user's drag.
10156        if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
10157            // A host at the top of a window's pinned content reaches up under the title bar,
10158            // where its controller expects to be (see `pane_under_title_bar`); its panes keep
10159            // their content below the strip, so nothing Day laid out moves.
10160            let strip = unsafe { split.superview() }
10161                .and_then(|sup| {
10162                    let content = unsafe { sup.window() }?.contentView()?;
10163                    // Layout wrappers (for example zstack with a reader cover) may sit
10164                    // between the window root and its navigation host. A direct-parent
10165                    // check misses them and puts AppKit's frosted pocket over page text.
10166                    let mut ancestor = Some(sup.clone());
10167                    while let Some(view) = ancestor {
10168                        if std::ptr::eq(&*view, &*content) {
10169                            break;
10170                        }
10171                        if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
10172                            return None; // nested navigation belongs to the outer pane
10173                        }
10174                        ancestor = unsafe { view.superview() };
10175                    }
10176                    let point = unsafe {
10177                        sup.convertPoint_toView(
10178                            NSPoint::new(frame.origin.x, frame.origin.y),
10179                            Some(&content),
10180                        )
10181                    };
10182                    (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
10183                })
10184                .unwrap_or(0.0);
10185            let r = NSRect::new(
10186                NSPoint::new(r.origin.x, r.origin.y - strip),
10187                NSSize::new(r.size.width, r.size.height + strip),
10188            );
10189            let wraps = NAV_STATE.with(|m| {
10190                m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
10191                    (s.title_strip != strip).then(|| {
10192                        s.title_strip = strip;
10193                        let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
10194                        w.extend(s.list_wrap.clone());
10195                        w
10196                    })
10197                })
10198            });
10199            let first = NAV_STATE.with(|m| {
10200                m.borrow_mut()
10201                    .get_mut(&ptr_of(h))
10202                    .map(|s| {
10203                        if !s.presentation.is_split() {
10204                            return (false, None);
10205                        }
10206                        let sidebar = !std::mem::replace(&mut s.positioned, true);
10207                        // The list's divider waits for the pane to be showing. Placing it while
10208                        // the pane is collapsed re-opens it (which is how an app whose first
10209                        // destination has no list opened with one beside it) and spends the one
10210                        // placement the pane gets, leaving it at the solver's width later on.
10211                        (sidebar, take_list_placement(s))
10212                    })
10213                    .unwrap_or((false, None))
10214            });
10215            unsafe {
10216                split.setFrame(r);
10217                split.layoutSubtreeIfNeeded();
10218            }
10219            // After the panes have their new size, so each wrap is placed in the final pane;
10220            // autoresizing keeps the strip from then on.
10221            for wrap in wraps.iter().flatten() {
10222                place_below_strip(wrap, strip);
10223            }
10224            unsafe {
10225                if first.0 {
10226                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
10227                }
10228                // A triple split has a second divider, and nothing else places it: left alone,
10229                // the controller's initial constraint pass lands it wherever the solver liked, so
10230                // the content list opens at an arbitrary width and the detail pane gets the
10231                // leftovers until the first manual drag re-settles them.
10232                if let Some(w) = first.1 {
10233                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
10234                }
10235            }
10236        } else {
10237            BASE_FRAMES.with(|m| {
10238                m.insert(
10239                    ptr_of(h),
10240                    [
10241                        frame.origin.x,
10242                        frame.origin.y,
10243                        frame.size.width,
10244                        frame.size.height,
10245                    ],
10246                )
10247            });
10248            // A transform (`set_transform`) is applied to the frame Day laid out.
10249            match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
10250                Some(t) => apply_geometry(
10251                    h,
10252                    [
10253                        frame.origin.x,
10254                        frame.origin.y,
10255                        frame.size.width,
10256                        frame.size.height,
10257                    ],
10258                    t,
10259                ),
10260                None => unsafe { h.setFrame(r) },
10261            }
10262        }
10263    }
10264
10265    fn set_scroll_content(&mut self, h: &Handle, content: Size) {
10266        if let Some(sv) = h.downcast_ref::<NSScrollView>()
10267            && let Some(doc) = unsafe { sv.documentView() }
10268        {
10269            unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
10270        }
10271    }
10272
10273    /// A macOS table row: the dense rows of a Finder or Mail list, 28pt for an icon and a line of body text.
10274    fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
10275        day_spec::RowMetrics {
10276            insets: day_spec::Insets {
10277                top: 4.0,
10278                leading: 8.0,
10279                bottom: 4.0,
10280                trailing: 8.0,
10281            },
10282            min_height: 28.0,
10283        }
10284    }
10285
10286    fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
10287        if let Some(sv) = h.downcast_ref::<NSScrollView>()
10288            && let Some(doc) = unsafe { sv.documentView() }
10289        {
10290            unsafe {
10291                doc.scrollRectToVisible(NSRect::new(
10292                    NSPoint::new(target.origin.x, target.origin.y),
10293                    NSSize::new(target.size.width, target.size.height),
10294                ))
10295            };
10296        }
10297    }
10298
10299    fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
10300        let Some(window) = h.window() else { return };
10301        // A list's public handle is its scroll view; keyboard focus belongs to the table.
10302        let list = list_entry(ptr_of(h));
10303        let responder: &NSResponder = match &list {
10304            Some((table, _)) => table,
10305            None => h,
10306        };
10307        let responder_ptr = responder as *const NSResponder as usize;
10308        if focused {
10309            window.makeFirstResponder(Some(responder));
10310            return;
10311        }
10312        // Resign only while this view still owns focus, so a stale release can't blur a
10313        // sibling.
10314        let owns = window
10315            .firstResponder()
10316            .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
10317            || owns_first_responder(&window, h);
10318        if owns {
10319            window.makeFirstResponder(None);
10320        }
10321    }
10322
10323    fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
10324        // The overrides live on `DayFlipped` (the container view); registering any other
10325        // view is harmless but inert, the graceful silence the duty documents.
10326        if focusable {
10327            FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
10328        } else {
10329            FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
10330        }
10331    }
10332
10333    fn set_event_sink(&mut self, sink: EventSink) {
10334        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
10335    }
10336
10337    fn set_edit_state(&mut self, state: &day_spec::EditState) {
10338        EDIT_STATE.with(|s| s.set(*state));
10339    }
10340
10341    fn modifiers(&mut self) -> day_spec::Modifiers {
10342        let f = NSEvent::modifierFlags_class();
10343        day_spec::Modifiers {
10344            shift: f.contains(NSEventModifierFlags::Shift),
10345            primary: f.contains(NSEventModifierFlags::Command),
10346            alt: f.contains(NSEventModifierFlags::Option),
10347        }
10348    }
10349
10350    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
10351        let front = undo_front(self.mtm);
10352        *front.ivars().state.borrow_mut() = state.clone();
10353    }
10354
10355    fn attach_list(&mut self, host: &Handle, source: ListSource) {
10356        let key = ptr_of(host);
10357        if let Some((table, data)) = list_entry(key) {
10358            data.ivars().source.replace(Some(source));
10359            // Initial fill: numberOfRows reads the snapshot only; viewForRow is deferred.
10360            unsafe { table.reloadData() };
10361        }
10362        // Force the table to realize its visible row views on the next main-loop turn, outside
10363        // any `with_tree` borrow, so `viewForRow`/`bind_row` build the cells then. Otherwise a
10364        // headless CI window never lays the table out until a snapshot's `cacheDisplayInRect`
10365        // forces it *inside* the snapshot borrow, where `bind_row` must skip (blank rows).
10366        post_realize_visible_rows(key);
10367    }
10368
10369    fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
10370        let key = ptr_of(host);
10371        if let Some((outline, data)) = tree_entry(key) {
10372            data.ivars().source.replace(Some(source));
10373            // Initial fill: child counts read the snapshot only; viewForItem is deferred.
10374            unsafe { outline.reloadData() };
10375        }
10376        // Realize visible rows on the next main-loop turn, outside any borrow (the
10377        // attach_list comment has the occluded-window story).
10378        <AppKit as Platform>::post(Box::new(move || {
10379            if let Some((outline, _)) = tree_entry(key) {
10380                unsafe { outline.layoutSubtreeIfNeeded() };
10381            }
10382        }));
10383    }
10384
10385    fn adopt(&mut self, raw: RawHandle) -> Handle {
10386        // A recycling NSTableView cell view; Day builds/rebinds its row content in place.
10387        // Invariant, not app input: day-core only passes back the cell pointer this backend
10388        // itself vended through `bind_row`, so a null here is a framework bug worth stopping on.
10389        let ptr = raw as *mut NSView;
10390        unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
10391    }
10392
10393    fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
10394        self.edit_toolbar(h, ops)
10395    }
10396
10397    fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
10398        self.patch_toolbar(h, patch);
10399    }
10400
10401    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
10402        let mtm = self.mtm;
10403        if self.menu_escape_monitor.is_none() {
10404            let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
10405                ffi_guard::contain(event.as_ptr(), || {
10406                    let event_ref = unsafe { event.as_ref() };
10407                    let app = NSApplication::sharedApplication(mtm);
10408                    // Native dialogs retain their cancellation behavior. Only an enabled
10409                    // menu key equivalent can consume Escape, never the general key stream.
10410                    if app.modalWindow().is_none()
10411                        && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
10412                        && unsafe { event_ref.charactersIgnoringModifiers() }
10413                            .is_some_and(|s| s.to_string() == "\u{1b}")
10414                        && app
10415                            .mainMenu()
10416                            .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
10417                    {
10418                        std::ptr::null_mut()
10419                    } else {
10420                        event.as_ptr()
10421                    }
10422                })
10423            });
10424            self.menu_escape_monitor = unsafe {
10425                NSEvent::addLocalMonitorForEventsMatchingMask_handler(
10426                    objc2_app_kit::NSEventMask::KeyDown,
10427                    &block,
10428                )
10429            }
10430            .map(MenuEscapeMonitor);
10431        }
10432        let app = NSApplication::sharedApplication(mtm);
10433        let menubar = NSMenu::new(mtm);
10434        // macOS owns the application menu; relocate app-level roles while preserving
10435        // their callbacks, shortcuts, and enabled state.
10436        let mut items = items.to_vec();
10437        let about = extract_app_role(&mut items, day_spec::MenuRole::About);
10438        let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
10439        let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
10440        let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
10441        let services =
10442            install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
10443        // Fill the standard slots the app did not claim, in the platform's bar order
10444        // (day-core owns that policy so every backend arranges its bar the same way).
10445        // Fill the standard slots the app left open, in macOS's bar order. The Window menu is
10446        // installed natively below, so the style deliberately supplies none.
10447        let items =
10448            day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
10449        let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
10450        // Each top-level entry becomes a menu-bar menu.
10451        for item in &items {
10452            match item {
10453                day_spec::MenuItem::Submenu { label, items, role } => {
10454                    let sub = build_ns_menu(mtm, label, items);
10455                    let it = NSMenuItem::new(mtm);
10456                    // Help is held back: the Window menu is installed natively after this loop
10457                    // (AppKit owns it so it can append the live window list), and Help sits
10458                    // last on every Mac menu bar.
10459                    if *role == Some(day_spec::MenuBarRole::Help)
10460                        || *label == day_localization::t(day_localization::key::day_help)
10461                    {
10462                        help_menu = Some((label.clone(), sub));
10463                        continue;
10464                    }
10465                    it.setTitle(&NSString::from_str(label));
10466                    it.setSubmenu(Some(&sub));
10467                    menubar.addItem(&it);
10468                }
10469                other => {
10470                    // A bare top-level action → wrap in a one-item menu so it has a submenu.
10471                    let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
10472                    let it = NSMenuItem::new(mtm);
10473                    it.setSubmenu(Some(&sub));
10474                    menubar.addItem(&it);
10475                }
10476            }
10477        }
10478        // The Window menu (docs/windows.md): auto-installed unless the app's model owns
10479        // `MenuRole::Minimize` (then the app is composing its own window management).
10480        if !model_has_role(&items, day_spec::MenuRole::Minimize) {
10481            install_windows_menu(mtm, &app, &menubar);
10482        }
10483        if let Some((label, help)) = help_menu {
10484            let it = NSMenuItem::new(mtm);
10485            it.setTitle(&NSString::from_str(&label));
10486            it.setSubmenu(Some(&help));
10487            menubar.addItem(&it);
10488            // Registering it makes AppKit add the Help search field and index the help book —
10489            // behavior no hand-built menu reproduces.
10490            unsafe { app.setHelpMenu(Some(&help)) };
10491        }
10492        app.setMainMenu(Some(&menubar));
10493        unsafe { app.setServicesMenu(Some(&services)) };
10494    }
10495
10496    fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
10497        let Some(view) = h.downcast_ref::<NSView>() else {
10498            return;
10499        };
10500        if items.is_empty() {
10501            unsafe { view.setMenu(None) };
10502            return;
10503        }
10504        let menu = build_ns_menu(self.mtm, "", items);
10505        // Attach to the view AND its current subviews: a right-click that hit-tests a child
10506        // control (the label inside a padded target) must find the menu on the view it hit —
10507        // AppKit does not walk ancestors for `.menu`, and controls swallow the event.
10508        // DayFlipped's `rightMouseDown:` pops the menu explicitly; native controls (labels)
10509        // show their `.menu` through their own default path.
10510        unsafe { view.setMenu(Some(&menu)) };
10511        fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
10512            for sub in v.subviews() {
10513                unsafe { sub.setMenu(Some(menu)) };
10514                apply_to_subviews(&sub, menu);
10515            }
10516        }
10517        apply_to_subviews(view, &menu);
10518    }
10519
10520    fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
10521        transfer::source(h, source);
10522    }
10523    fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
10524        transfer::target(h, target);
10525    }
10526    fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
10527        // Consulted by the classes that override `menuForEvent:` (the canvas; docs/menus.md
10528        // "Dynamic context menus" lists the covered surfaces per backend).
10529        CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
10530    }
10531
10532    fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
10533        let key = ptr_of(h);
10534        // Pan is not a recognizer on macOS: the two-finger idiom is the trackpad SCROLL, so
10535        // the canvas view's own `scrollWheel:` override reports it for registered nodes.
10536        // Containers use a horizontal-only monitor so nested vertical scrolling still works.
10537        if kind == day_spec::GestureKind::Pan {
10538            PAN_NODES.with(|t| t.insert(key, node));
10539            install_container_pan_monitor();
10540            return;
10541        }
10542        // Nor is hover: it is a tracking area plus `mouseEntered:`/`mouseMoved:`/`mouseExited:`,
10543        // which only `DayCanvas` overrides — a hover enabled on another view emits nothing, the
10544        // same limitation Pan has.
10545        if kind == day_spec::GestureKind::Hover {
10546            // Idempotent, and it has to be checked here rather than falling through to the
10547            // recognizer guard below: day-core re-enables a gesture on rebuild, and a second
10548            // tracking area on the same view means a second copy of every hover event.
10549            let first = HOVER_NODES.with(|t| t.get(key)).is_none();
10550            HOVER_NODES.with(|t| t.insert(key, node));
10551            if first {
10552                install_tracking_area(h);
10553            }
10554            return;
10555        }
10556        // Idempotent: attach each kind at most once per view.
10557        let already = GESTURES.with(|m| {
10558            m.borrow()
10559                .get(&key)
10560                .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
10561        });
10562        if already {
10563            return;
10564        }
10565        let mtm = self.mtm;
10566        let target = DayGesture::new(mtm, node, kind);
10567        let recognizer: Retained<NSGestureRecognizer> = unsafe {
10568            match kind {
10569                day_spec::GestureKind::Drag => {
10570                    Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
10571                        NSPanGestureRecognizer::alloc(mtm),
10572                        Some(&target),
10573                        Some(sel!(fire:)),
10574                    ))
10575                }
10576                day_spec::GestureKind::Pinch => Retained::into_super(
10577                    objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
10578                        objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
10579                        Some(&target),
10580                        Some(sel!(fire:)),
10581                    ),
10582                ),
10583                _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
10584                    NSClickGestureRecognizer::alloc(mtm),
10585                    Some(&target),
10586                    Some(sel!(fire:)),
10587                )),
10588            }
10589        };
10590        unsafe { h.addGestureRecognizer(&recognizer) };
10591        GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
10592    }
10593
10594    fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
10595        unsafe {
10596            if let Some(id) = &a11y.identifier {
10597                h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
10598            }
10599            if let Some(label) = &a11y.label {
10600                h.setAccessibilityLabel(Some(&NSString::from_str(label)));
10601                APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
10602            } else {
10603                APP_LABELED.with(|t| t.remove(ptr_of(h)));
10604            }
10605            if let Some(hint) = &a11y.hint {
10606                h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
10607            }
10608            if let Some(value) = &a11y.value {
10609                let ns = NSString::from_str(value);
10610                h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
10611            }
10612            // Only apply an EXPLICIT role (canvas/custom pieces, e.g. a Meter): native controls
10613            // already report the right role, so Day records but doesn't override theirs (§13).
10614            if let Some(role) = ns_role(a11y.role) {
10615                h.setAccessibilityRole(Some(role));
10616            }
10617            if a11y.role == day_spec::Role::Tab {
10618                h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
10619            }
10620            if let Some(on) = a11y.selected {
10621                h.setAccessibilitySelected(on);
10622            }
10623            // Decorative / hidden: drop from the AX tree entirely. An ignored view alone is
10624            // not enough — AppKit promotes an ignored element's children into its parent's
10625            // list — so the subtree is cut off too, which also covers subviews added later
10626            // (list rows, re-created children). Hidden never flips back, so the override is
10627            // never lifted.
10628            if a11y.hidden {
10629                h.setAccessibilityElement(false);
10630                h.setAccessibilityChildren(Some(&NSArray::new()));
10631            }
10632        }
10633    }
10634
10635    /// The announcement request goes out from the primary window (any live element will
10636    /// do; the app object stands in before the window exists). Without VoiceOver nothing
10637    /// observes the notification, so posting is free.
10638    fn announce(&mut self, text: &str, urgent: bool) {
10639        use objc2_app_kit::{
10640            NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
10641            NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
10642            NSAccessibilityPriorityLevel,
10643        };
10644        let app = NSApplication::sharedApplication(self.mtm());
10645        let window = primary_content().and_then(|content| content.window());
10646        let element: &objc2::runtime::AnyObject = match &window {
10647            Some(window) => window,
10648            None => &app,
10649        };
10650        // High priority interrupts the current sentence; medium waits its turn.
10651        let priority = if urgent {
10652            NSAccessibilityPriorityLevel::High
10653        } else {
10654            NSAccessibilityPriorityLevel::Medium
10655        };
10656        let announcement = NSString::from_str(text);
10657        let priority = NSNumber::new_isize(priority.0);
10658        let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
10659        // SAFETY: the keys are AppKit's constants and both values are the types the
10660        // announcement notification documents (an NSString and an NSNumber).
10661        unsafe {
10662            let user_info = NSDictionary::from_slices::<NSString>(
10663                &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
10664                &values,
10665            );
10666            NSAccessibilityPostNotificationWithUserInfo(
10667                element,
10668                NSAccessibilityAnnouncementRequestedNotification,
10669                Some(&user_info),
10670            );
10671        }
10672    }
10673
10674    fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
10675        unsafe {
10676            let role = h
10677                .accessibilityRole()
10678                .map(|r| day_role_from_ns(&r.to_string()))
10679                .unwrap_or(day_spec::Role::None);
10680            // A picker answers its displayed selection and its enabled state itself: the
10681            // inline style is a stack of radios, not one control.
10682            let picker = picker::read_native(h);
10683            day_spec::NativeSnapshot {
10684                found: true,
10685                role,
10686                label: h.accessibilityLabel().map(|s| s.to_string()),
10687                value: h
10688                    .accessibilityValue()
10689                    .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
10690                identifier: h
10691                    .accessibilityIdentifier()
10692                    .map(|s| s.to_string())
10693                    .filter(|s| !s.is_empty()),
10694                text: match &picker {
10695                    Some((text, _)) => text.clone(),
10696                    None => native_text(h),
10697                },
10698                number: native_number(h),
10699                checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
10700                    match sw.state() {
10701                        s if s == NSControlStateValueOn => Some(true),
10702                        s if s == NSControlStateValueOff => Some(false),
10703                        // Mixed is neither on nor off.
10704                        _ => None,
10705                    }
10706                } else if let Some(btn) = h.downcast_ref::<NSButton>() {
10707                    // A Day button's selected state (`ButtonProps::selected`): its own
10708                    // `state`, which a momentary button holds off at rest.
10709                    BUTTON_SELECTED
10710                        .with(|m| m.borrow().contains_key(&ptr_of(h)))
10711                        .then(|| btn.state() == NSControlStateValueOn)
10712                } else {
10713                    None
10714                },
10715                // A label is a non-editable NSTextField whose `isEnabled` says nothing about
10716                // input; every other control answers for itself.
10717                enabled: match (&picker, h.downcast_ref::<NSControl>()) {
10718                    (Some((_, on)), _) => *on,
10719                    (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
10720                    (None, Some(c)) => Some(c.isEnabled()),
10721                    (None, None) => None,
10722                },
10723                // Off-window counts as not shown: nothing of it reaches the screen.
10724                visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
10725                frame: native_frame(h),
10726            }
10727        }
10728    }
10729
10730    fn request_frame(
10731        &mut self,
10732        host: &Handle,
10733        cb: day_spec::FrameCallback,
10734    ) -> day_spec::CancelFrame {
10735        frame::request(host, cb)
10736    }
10737
10738    fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
10739        OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
10740        unsafe { h.setNeedsDisplay(true) };
10741    }
10742    fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
10743        NAV_STATE.with(|m| {
10744            let m = m.borrow();
10745            let Some(st) = m.get(&ptr_of(host)) else {
10746                return false;
10747            };
10748            // A pane to toggle exists in `Split` and `Rail`; a stack has none and a tab bar
10749            // keeps its rows in the chrome, where hiding them would strand the user.
10750            if !matches!(
10751                st.presentation,
10752                NavPresentation::Split | NavPresentation::Rail
10753            ) {
10754                return false;
10755            }
10756            let item = &st.sidebar_item;
10757            // Set directly, not through the `animator` proxy. The proxy defers the change to
10758            // an animation the dayscript screenshot step does not wait on, so a scripted
10759            // toggle captured a sidebar that had not moved yet. AppKit's own
10760            // NSToolbarToggleSidebarItem still animates — it runs `toggleSidebar:` on the
10761            // controller and never comes through here.
10762            let collapsed = unsafe { item.isCollapsed() };
10763            unsafe { item.setCollapsed(!collapsed) };
10764            true
10765        })
10766    }
10767
10768    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
10769        let content = self.content.as_ref().ok_or("no window content")?;
10770        snapshot_view(content)
10771    }
10772
10773    /// Decode bytes into an `NSImage` (docs/images.md).
10774    ///
10775    /// `NSBitmapImageRep` is asked first and kept: it is what actually reads the container, it
10776    /// answers in PIXELS (`NSImage.size` is in points and reports a 144-DPI photo at
10777    /// two-thirds its real width), and it is the only thing here that can re-encode later.
10778    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
10779        use objc2::AllocAnyThread as _;
10780        let data = NSData::with_bytes(bytes);
10781        let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
10782        else {
10783            emit(
10784                WINDOW_NODE,
10785                Event::ImageDecoded {
10786                    req,
10787                    result: Err(day_spec::ImageError::Decode),
10788                },
10789            );
10790            return;
10791        };
10792        let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
10793        let info = day_spec::BitmapInfo {
10794            pixels: Size::new(w, h),
10795            // Decoded bytes carry no density — a PNG is simply its pixels. Only a staged @2x
10796            // asset has a scale, and that arrives through the named path instead.
10797            scale: 1.0,
10798            format: day_spec::ImageFormat::sniff(bytes),
10799            has_alpha: unsafe { rep.hasAlpha() },
10800        };
10801        // Built AT the rep's pixel size so it draws 1:1 by default: an NSImage otherwise adopts
10802        // the rep's own `size`, which ImageIO derives from the file's DPI — that is what shrinks
10803        // a 144-DPI photo for no reason the app asked for.
10804        let image = unsafe {
10805            objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
10806        };
10807        unsafe { image.addRepresentation(&rep) };
10808        BITMAPS.with(|m| {
10809            m.borrow_mut().insert(
10810                id.0,
10811                AppKitBitmap {
10812                    image,
10813                    rep: Some(rep),
10814                    info,
10815                },
10816            )
10817        });
10818        emit(
10819            WINDOW_NODE,
10820            Event::ImageDecoded {
10821                req,
10822                result: Ok(info),
10823            },
10824        );
10825    }
10826
10827    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
10828        BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
10829    }
10830
10831    /// The container's own metadata (docs/images.md).
10832    ///
10833    /// DPI is DERIVED rather than read from a tag: AppKit has already resolved the file's
10834    /// resolution into the rep's point size, so pixels-per-point × 72 is the number the platform
10835    /// itself believes — and it is right for containers that record resolution in ways EXIF
10836    /// does not.
10837    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
10838        let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
10839        let mut out = day_spec::ImageProperties::default();
10840        let size = unsafe { rep.size() };
10841        if size.width > 0.0 {
10842            let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
10843            // 72 is "no resolution recorded" wearing a number; reporting it would read as a fact
10844            // the file never stated.
10845            if (dpi - 72.0).abs() > 0.5 {
10846                out.dpi = Some(dpi);
10847            }
10848        }
10849        // EXIF arrives as a dictionary of the format's own keys. It is walked through
10850        // `msg_send!` rather than a downcast because a generic `NSDictionary` is not a
10851        // `DowncastTarget`.
10852        if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
10853            let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
10854            for key in keys.iter() {
10855                let value: Option<Retained<objc2::runtime::AnyObject>> =
10856                    unsafe { msg_send![&*exif, objectForKey: &*key] };
10857                let Some(value) = value else { continue };
10858                let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
10859                let (k, v) = (key.to_string(), text.to_string());
10860                match k.as_str() {
10861                    "Orientation" => out.orientation = v.parse().ok(),
10862                    "DateTimeOriginal" => out.created = Some(v.clone()),
10863                    _ => {}
10864                }
10865                // Keys stay in EXIF's own vocabulary, passed through rather than translated —
10866                // the doc for `extra` promises exactly that.
10867                out.extra.push((k, v));
10868            }
10869        }
10870        Some(out)
10871    }
10872
10873    /// What `NSBitmapImageRep` WRITES. It reads more than this — WebP and HEIF among them — and
10874    /// the asymmetry is the platform's own, which is exactly why this duty exists instead of
10875    /// letting `Cap::ImageEncode` imply every format round-trips.
10876    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
10877        use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
10878        vec![Png, Jpeg, Tiff, Bmp, Gif]
10879    }
10880
10881    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
10882        let result = encode_bitmap(id, spec);
10883        emit(WINDOW_NODE, Event::ImageEncoded { req, result });
10884    }
10885
10886    fn release_image(&mut self, id: day_spec::BitmapId) {
10887        release_bitmap(id);
10888    }
10889
10890    /// Replay `ops` offscreen through the canvas's own painter (docs/canvas.md "Exporting") and
10891    /// keep the result in the decode table, so `image`, `encode_image` and `DrawOp::Image` take
10892    /// it like any decoded bitmap.
10893    fn render_bitmap(
10894        &mut self,
10895        req: u64,
10896        id: day_spec::BitmapId,
10897        ops: &[DrawOp],
10898        size: Size,
10899        scale: f64,
10900    ) {
10901        let result = render_bitmap_image(ops, size, scale).map(|bitmap| {
10902            let info = bitmap.info;
10903            BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
10904            info
10905        });
10906        emit(WINDOW_NODE, Event::BitmapRendered { req, result });
10907    }
10908
10909    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
10910        let result = render_pdf_bytes(pages, info);
10911        emit(WINDOW_NODE, Event::PdfRendered { req, result });
10912    }
10913
10914    /// `NSFontManager.availableFontFamilies` + `availableMembersOfFontFamily:`, whose members
10915    /// are `[postscriptName, styleName, weight 0 … 15, traits]` (docs/fonts.md). The `.`-prefixed
10916    /// families are the system's private UI faces and are skipped, as Font Book skips them.
10917    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
10918        use day_spec::FontWeight as W;
10919        let mtm =
10920            objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
10921        let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
10922        let mut out = Vec::new();
10923        for family in unsafe { manager.availableFontFamilies() }.iter() {
10924            let name = family.to_string();
10925            if name.starts_with('.') {
10926                continue;
10927            }
10928            let mut faces = Vec::new();
10929            if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
10930                for member in members.iter() {
10931                    if member.count() < 4 {
10932                        continue;
10933                    }
10934                    let style = member
10935                        .objectAtIndex(1)
10936                        .downcast_ref::<NSString>()
10937                        .map(|s| s.to_string())
10938                        .unwrap_or_default();
10939                    let weight = member
10940                        .objectAtIndex(2)
10941                        .downcast_ref::<objc2_foundation::NSNumber>()
10942                        .map(|n| n.integerValue())
10943                        .unwrap_or(5);
10944                    let traits = member
10945                        .objectAtIndex(3)
10946                        .downcast_ref::<objc2_foundation::NSNumber>()
10947                        .map(|n| n.integerValue())
10948                        .unwrap_or(0);
10949                    let weight = match weight {
10950                        ..=2 => W::UltraLight,
10951                        3 => W::Thin,
10952                        4 => W::Light,
10953                        5 => W::Regular,
10954                        6 => W::Medium,
10955                        7 | 8 => W::Semibold,
10956                        9 => W::Bold,
10957                        10 | 11 => W::Heavy,
10958                        _ => W::Black,
10959                    };
10960                    let italic = traits & 0x1 != 0; // NSItalicFontMask
10961                    faces.push(day_spec::FontFace {
10962                        name: if style.is_empty() {
10963                            day_spec::FontFace::synthesized_name(weight, italic)
10964                        } else {
10965                            style
10966                        },
10967                        weight,
10968                        italic,
10969                    });
10970                }
10971            }
10972            out.push(day_spec::FontFamilyInfo {
10973                family: name,
10974                faces,
10975            });
10976        }
10977        out
10978    }
10979
10980    /// `sizeWithAttributes:` with the attributes `replay` draws with; the ascent is the
10981    /// font's own, so `at.y + ascent` is where the glyphs' baseline lands.
10982    fn measure_text(
10983        &mut self,
10984        text: &str,
10985        size: f64,
10986        font: &day_spec::CanvasFont,
10987    ) -> Option<day_spec::TextMetrics> {
10988        let nsfont = canvas_nsfont(size, font);
10989        let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
10990        let ns = NSString::from_str(text);
10991        let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
10992        // The INK box: `NSStringDrawingUsesDeviceMetrics` is what turns `boundingRectWithSize:`
10993        // from the layout box into the glyphs' own bounds, and it comes back baseline-relative
10994        // with y up — hence the flip. An unbounded size so nothing wraps: this measures one line.
10995        let unbounded = NSSize::new(f64::MAX, f64::MAX);
10996        let ink: NSRect = unsafe {
10997            msg_send![
10998                &ns,
10999                boundingRectWithSize: unbounded,
11000                options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
11001                attributes: &*attrs,
11002            ]
11003        };
11004        Some(day_spec::TextMetrics::from_baseline(
11005            sz.width,
11006            nsfont.ascender(),
11007            sz.height - nsfont.ascender(),
11008            nsfont.capHeight(),
11009            day_spec::Rect::new(
11010                ink.origin.x,
11011                -(ink.origin.y + ink.size.height),
11012                ink.size.width,
11013                ink.size.height,
11014            ),
11015        ))
11016    }
11017
11018    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
11019        let content = self.content.as_ref().ok_or("no window content")?;
11020        snapshot_view_chrome(content)
11021    }
11022
11023    fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
11024        snapshot_view(host)
11025    }
11026
11027    fn open_window(
11028        &mut self,
11029        id: NodeId,
11030        options: &WindowOptions,
11031        kind: day_spec::WindowKind,
11032    ) -> day_spec::WindowOpenReply<Handle> {
11033        let prefs = kind.is_panel();
11034        let (window, delegate, content) = self.make_window(options, prefs, Some(id));
11035        if prefs {
11036            // A settings panel is one-of-a-kind and centered, and it stays OUT of the Window
11037            // menu — the macOS convention every stock app follows (docs/windows.md).
11038            window.center();
11039            unsafe { window.setExcludedFromWindowsMenu(true) };
11040        } else {
11041            // Stagger, don't stack. Without this every window opens at the same centered frame
11042            // and the one underneath is invisible — which is exactly what two Day windows did.
11043            //
11044            // `cascadeTopLeftFromPoint:` puts the window AT the point it is given and answers
11045            // the point for the one after, so the series has to be primed from the primary
11046            // rather than seeded with its corner — seeding lands the first new window exactly
11047            // on top of the primary, which is the bug this replaces.
11048            let from = match self.cascade {
11049                Some(p) => p,
11050                None => self
11051                    .window
11052                    .as_ref()
11053                    .map(|w| {
11054                        let f = w.frame();
11055                        let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
11056                        // Asking the primary to cascade from where it already is leaves it
11057                        // there and answers the next slot — the offset the first new window wants.
11058                        unsafe { w.cascadeTopLeftFromPoint(top_left) }
11059                    })
11060                    .unwrap_or(NSPoint::new(0.0, 0.0)),
11061            };
11062            self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
11063        }
11064        window_chrome::place(&window, options.placement);
11065        // `center` (a settings panel's, or a `Centered` placement's) uses the main screen, the
11066        // one with the keyboard focus, which on a Mac with several displays need not be the
11067        // app's: such a window goes to the primary's screen instead. A scripted run on the
11068        // capture display relies on this to keep the window in its captures.
11069        if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
11070            center_on_screen_of(&window, self.window.as_deref());
11071        }
11072        // Secondary windows need the same initial client-coordinate pinning as the
11073        // primary. Native document pages may move here before any resize notification.
11074        let _ = pin_below_title_bar(&window);
11075        if !options.start_hidden {
11076            window.makeKeyAndOrderFront(None);
11077        }
11078        // Same macOS 26 quirk as the primary (`run`): a window ordered front before its
11079        // first turn drops pre-run layer displays — nudge every layer once.
11080        mark_tree_needs_display(&content);
11081        self.secondary.push(SecondaryWin {
11082            window,
11083            delegate,
11084            content: content.clone(),
11085        });
11086        day_spec::WindowOpenReply::Open(content)
11087    }
11088
11089    fn native_window_tabs(&self) -> bool {
11090        true
11091    }
11092    fn group_windows(&mut self, hosts: &[Handle]) {
11093        let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
11094        let Some(first) = windows.first() else {
11095            return;
11096        };
11097        unsafe {
11098            NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
11099        }
11100        // Explicit insertion respects the model even when system automatic tabbing is off.
11101        for window in windows.iter().skip(1) {
11102            unsafe {
11103                first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
11104            }
11105        }
11106        if let Some(group) = first.tabGroup() {
11107            if !group.isTabBarVisible() {
11108                unsafe {
11109                    first.toggleTabBar(None);
11110                }
11111            }
11112            for (i, window) in windows.iter().enumerate() {
11113                group.insertWindow_atIndex(window, i as isize);
11114            }
11115        }
11116        // Adding/showing a native tab strip changes contentLayoutRect without necessarily
11117        // resizing the window. Re-pin every member and tell the layout tree its usable size.
11118        for window in &windows {
11119            if let Some(size) = pin_below_title_bar(window) {
11120                let node = window
11121                    .delegate()
11122                    .and_then(|d| d.downcast::<DayWinDelegate>().ok())
11123                    .and_then(|d| d.ivars().node)
11124                    .unwrap_or(WINDOW_NODE);
11125                emit(node, Event::WindowResized(size));
11126            }
11127        }
11128    }
11129    fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
11130        let Some(window) = self.ns_window_for(host) else {
11131            return Vec::new();
11132        };
11133        let windows = window.tabGroup().map(|g| g.windows());
11134        let Some(windows) = windows else {
11135            return Vec::new();
11136        };
11137        windows
11138            .iter()
11139            .filter_map(|window| {
11140                self.secondary
11141                    .iter()
11142                    .find(|w| std::ptr::eq(&*w.window, &*window))
11143                    .and_then(|w| w.delegate.ivars().node)
11144            })
11145            .collect()
11146    }
11147
11148    fn close_window(&mut self, host: &Handle) {
11149        // `close()` runs the full native path — windowWillClose → `WindowClosed` →
11150        // day-core teardown — so programmatic and title-bar closes are one code path.
11151        if let Some(w) = self
11152            .secondary
11153            .iter()
11154            .find(|w| ptr_of(&w.content) == ptr_of(host))
11155        {
11156            w.window.close();
11157        }
11158    }
11159
11160    fn focus_window(&mut self, host: &Handle) {
11161        if let Some(w) = self
11162            .secondary
11163            .iter()
11164            .find(|w| ptr_of(&w.content) == ptr_of(host))
11165        {
11166            w.window.makeKeyAndOrderFront(None);
11167        }
11168    }
11169
11170    fn fit_window(&mut self, host: &Handle, size: Size) {
11171        let Some(w) = self
11172            .secondary
11173            .iter()
11174            .find(|w| ptr_of(&w.content) == ptr_of(host))
11175        else {
11176            return;
11177        };
11178        unsafe {
11179            // `setContentSize:` rather than `setFrame:`: Day measured the CONTENT, and AppKit
11180            // adds the title bar itself. Sizing the frame instead would eat the bar's height out
11181            // of the panel and clip the last row by exactly that much.
11182            w.window
11183                .setContentSize(NSSize::new(size.width, size.height));
11184            // A settings panel that fits its content has no reason to be resizable, and macOS
11185            // panels are not — dropping the mask also stops the user dragging it back to a size
11186            // the content does not fill.
11187            let mask = w.window.styleMask();
11188            w.window
11189                .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
11190            w.window.center();
11191        }
11192        center_on_screen_of(&w.window, self.window.as_deref());
11193    }
11194
11195    fn set_window_title(&mut self, host: &Handle, title: &str) {
11196        if let Some(w) = self
11197            .secondary
11198            .iter()
11199            .find(|w| ptr_of(&w.content) == ptr_of(host))
11200        {
11201            w.window.setTitle(&NSString::from_str(title));
11202            return;
11203        }
11204        // The PRIMARY window is retitlable too. It is an ordinary window (docs/windows.md), so
11205        // `window_title` in the first window's shell and `set_title` on `initial_window()` both
11206        // arrive here — and searching only the secondary list silently dropped them.
11207        if self
11208            .content
11209            .as_ref()
11210            .is_some_and(|c| ptr_of(c) == ptr_of(host))
11211            && let Some(w) = self.window.as_ref()
11212        {
11213            w.setTitle(&NSString::from_str(title));
11214        }
11215    }
11216
11217    fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
11218        use day_spec::WindowChange as C;
11219        let Some(window) = self.ns_window_for(host) else {
11220            return;
11221        };
11222        match change {
11223            C::State(state) => set_ns_window_state(&window, *state),
11224            // Screen capture, recording and sharing see an empty window; the user still does.
11225            C::ContentProtected(on) => window.setSharingType(if *on {
11226                objc2_app_kit::NSWindowSharingType::None
11227            } else {
11228                objc2_app_kit::NSWindowSharingType::ReadOnly
11229            }),
11230            other => window_chrome::apply_property(&window, other),
11231        }
11232    }
11233
11234    fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
11235        self.ns_window_for(host)
11236            .map(|w| window_chrome::frame_of(&w))
11237    }
11238
11239    fn monitors(&self) -> Vec<day_spec::Monitor> {
11240        window_chrome::monitors(self.mtm)
11241    }
11242
11243    /// The Dock menu lists them: day-core folds the run-time shortcuts into the model it sends
11244    /// through `set_dock_menu`, so there is nothing more to install here.
11245    fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
11246
11247    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
11248        dock::set_app_items(self.mtm, items);
11249    }
11250
11251    fn set_drag_region(&mut self, h: &Handle, drag: bool) {
11252        window_chrome::set_drag_region(h, drag);
11253    }
11254
11255    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
11256        status_item::set_items(self.mtm, items);
11257    }
11258
11259    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
11260        status_item::set_progress(self.mtm, progress);
11261    }
11262
11263    fn set_dock_visible(&mut self, visible: bool) {
11264        status_item::set_dock_visible(self.mtm, visible);
11265    }
11266
11267    fn set_keep_running(&mut self, keep: bool) {
11268        status_item::set_keep_running(keep);
11269    }
11270
11271    fn quit_app(&mut self) {
11272        let app = NSApplication::sharedApplication(self.mtm);
11273        unsafe { app.terminate(None) };
11274    }
11275
11276    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
11277        use present::PresentSpec;
11278        let mtm = self.mtm;
11279        // Sheets attach to the KEY window at present time (docs/windows.md) — a dialog
11280        // raised from a secondary/preferences window belongs on it; primary is the
11281        // fallback when no DAY window is key (a system panel may hold key status).
11282        let app = NSApplication::sharedApplication(mtm);
11283        let key = app.keyWindow().filter(|k| {
11284            let mut owner = k.clone();
11285            while let Some(parent) = owner.sheetParent() {
11286                owner = parent;
11287            }
11288            self.window
11289                .as_deref()
11290                .is_some_and(|w| std::ptr::eq(w, &*owner))
11291                || self
11292                    .secondary
11293                    .iter()
11294                    .any(|s| std::ptr::eq(&*s.window, &*owner))
11295        });
11296        let Some(mut window) = key.or_else(|| self.window.clone()) else {
11297            emit(
11298                WINDOW_NODE,
11299                Event::PresentResult {
11300                    req,
11301                    result: present::PresentResult::Dismissed,
11302                },
11303            );
11304            return;
11305        };
11306        // A dialog opened from a modal cover belongs on the active sheet, not behind it.
11307        while let Some(sheet) = window.attachedSheet() {
11308            window = sheet;
11309        }
11310        // File pickers use a different native object (NSOpen/NSSavePanel), not an NSAlert.
11311        match spec {
11312            PresentSpec::OpenFile {
11313                filters, multiple, ..
11314            } => {
11315                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11316                unsafe {
11317                    panel.setCanChooseFiles(true);
11318                    panel.setCanChooseDirectories(false);
11319                    panel.setAllowsMultipleSelection(*multiple);
11320                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11321                }
11322                apply_allowed_file_types(&panel, filters);
11323                let p = panel.clone();
11324                // Completion blocks run inside a C ABI frame, so their bodies are contained
11325                // like every other trampoline (§8.5) — this one and the four below.
11326                let handler: block2::RcBlock<dyn Fn(isize)> =
11327                    block2::RcBlock::new(move |resp: isize| {
11328                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11329                    });
11330                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11331                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11332                return;
11333            }
11334            // The folder chooser is the same NSOpenPanel with files and directories swapped.
11335            PresentSpec::OpenFolder { .. } => {
11336                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11337                unsafe {
11338                    panel.setCanChooseFiles(false);
11339                    panel.setCanChooseDirectories(true);
11340                    panel.setCanCreateDirectories(true);
11341                    panel.setAllowsMultipleSelection(false);
11342                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11343                }
11344                let p = panel.clone();
11345                let handler: block2::RcBlock<dyn Fn(isize)> =
11346                    block2::RcBlock::new(move |resp: isize| {
11347                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11348                    });
11349                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11350                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11351                return;
11352            }
11353            PresentSpec::SaveFile { suggested_name, .. } => {
11354                let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
11355                unsafe {
11356                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11357                    panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
11358                }
11359                apply_allowed_file_types(&panel, spec.filters());
11360                let p = panel.clone();
11361                let handler: block2::RcBlock<dyn Fn(isize)> =
11362                    block2::RcBlock::new(move |resp: isize| {
11363                        // The pieces layer copies the staged bytes to the chosen local path.
11364                        ffi_guard::contain((), || emit_panel_result(req, resp, &p));
11365                    });
11366                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11367                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
11368                return;
11369            }
11370            _ => {}
11371        }
11372        let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
11373        unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
11374        if let Some(msg) = spec.message() {
11375            unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
11376        }
11377        // The completion handler must outlive this call, so it's a heap (Rc) block.
11378        let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
11379            PresentSpec::Dialog { buttons, .. } => {
11380                if buttons
11381                    .iter()
11382                    .any(|b| b.role == present::ButtonRole::Destructive)
11383                {
11384                    unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
11385                }
11386                for b in buttons {
11387                    unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
11388                }
11389                block2::RcBlock::new(move |resp: isize| {
11390                    ffi_guard::contain((), || {
11391                        // NSAlertFirstButtonReturn = 1000; add order == spec order.
11392                        let idx = resp - 1000;
11393                        emit(
11394                            WINDOW_NODE,
11395                            Event::PresentResult {
11396                                req,
11397                                result: present::PresentResult::Button(idx as i64),
11398                            },
11399                        );
11400                        PRESENT_ALERTS.with(|m| {
11401                            m.borrow_mut().remove(&req);
11402                        });
11403                    })
11404                })
11405            }
11406            PresentSpec::Prompt {
11407                placeholder,
11408                initial,
11409                ok,
11410                cancel,
11411                ..
11412            } => {
11413                let tf = unsafe { NSTextField::new(mtm) };
11414                unsafe {
11415                    tf.setFrame(NSRect::new(
11416                        NSPoint::new(0.0, 0.0),
11417                        NSSize::new(260.0, 24.0),
11418                    ));
11419                    tf.setEditable(true);
11420                    tf.setBezeled(true);
11421                    tf.setStringValue(&NSString::from_str(initial));
11422                    tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
11423                    alert.setAccessoryView(Some(&tf));
11424                    alert.addButtonWithTitle(&NSString::from_str(ok)); // resp 1000
11425                    alert.addButtonWithTitle(&NSString::from_str(cancel)); // resp 1001
11426                }
11427                block2::RcBlock::new(move |resp: isize| {
11428                    ffi_guard::contain((), || {
11429                        let result = if resp == 1000 {
11430                            present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
11431                        } else {
11432                            present::PresentResult::Dismissed
11433                        };
11434                        emit(WINDOW_NODE, Event::PresentResult { req, result });
11435                        PRESENT_ALERTS.with(|m| {
11436                            m.borrow_mut().remove(&req);
11437                        });
11438                    })
11439                })
11440            }
11441            // File pickers returned early above.
11442            PresentSpec::OpenFile { .. }
11443            | PresentSpec::OpenFolder { .. }
11444            | PresentSpec::SaveFile { .. } => unreachable!(),
11445        };
11446        unsafe {
11447            alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
11448        }
11449        PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
11450    }
11451
11452    fn dismiss(&mut self, req: u64) {
11453        // Close the sheet; its completion handler fires but its (native) result is dropped
11454        // because day-core already removed the pending request when it resolved.
11455        let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
11456        if let Some(alert) = alert {
11457            let sheet = alert.window();
11458            if let Some(parent) = sheet.sheetParent() {
11459                unsafe { parent.endSheet(&sheet) };
11460            }
11461        }
11462        // File-picker sheets are their own NSWindow.
11463        let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
11464        if let Some(panel) = panel
11465            && let Some(parent) = panel.sheetParent()
11466        {
11467            unsafe { parent.endSheet(&panel) };
11468        }
11469    }
11470
11471    fn application_handlers(
11472        &mut self,
11473        query: &day_spec::applications::HandlerQuery,
11474    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
11475    {
11476        applications::handlers(query)
11477    }
11478
11479    fn open_url_with_application(
11480        &mut self,
11481        url: &str,
11482        application: &str,
11483        completion: day_spec::applications::OpenApplicationCompletion,
11484    ) {
11485        applications::open(url, application, completion);
11486    }
11487
11488    fn share_support(&self) -> day_spec::Support {
11489        day_spec::Support::Native
11490    }
11491    fn share_url(&mut self, url: &str, _title: &str) -> bool {
11492        use objc2::{msg_send, runtime::AnyObject};
11493        use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
11494        let Some(mtm) = objc2::MainThreadMarker::new() else {
11495            return false;
11496        };
11497        let Some(url) = NSURL::URLWithString(&NSString::from_str(url)) else {
11498            return false;
11499        };
11500        let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
11501        let Some(view) = app.keyWindow().and_then(|w| w.contentView()) else {
11502            return false;
11503        };
11504        unsafe {
11505            let items = NSArray::from_retained_slice(&[url]);
11506            let picker: objc2::rc::Allocated<AnyObject> =
11507                msg_send![objc2::class!(NSSharingServicePicker), alloc];
11508            let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
11509            let bounds = view.bounds();
11510            let y = if view.isFlipped() {
11511                30.0
11512            } else {
11513                bounds.size.height - 30.0
11514            };
11515            let rect = NSRect::new(
11516                NSPoint::new(bounds.size.width - 30.0, y),
11517                NSSize::new(1.0, 1.0),
11518            );
11519            let _: () = msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: 3usize];
11520            self.sharing = Some(picker);
11521        }
11522        true
11523    }
11524    fn open_url(&mut self, url: &str) {
11525        // NSWorkspace opens the URL in the user's default handler (Safari for http(s), Mail for
11526        // mailto:, …). An unparseable string yields no NSURL and is silently ignored.
11527        let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
11528        if let Some(nsurl) = nsurl {
11529            unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
11530        }
11531    }
11532}
11533
11534/// Apply a file dialog's extension filters (`allowedFileTypes` — deprecated but still the simplest
11535/// extension-based API; `UTType` would pull in another framework crate for no benefit here).
11536#[allow(deprecated)]
11537fn apply_allowed_file_types(
11538    panel: &objc2_app_kit::NSSavePanel,
11539    filters: &[day_spec::present::FileFilter],
11540) {
11541    let exts: Vec<Retained<NSString>> = filters
11542        .iter()
11543        .flat_map(|f| f.extensions.iter())
11544        .map(|e| NSString::from_str(e))
11545        .collect();
11546    if !exts.is_empty() {
11547        let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
11548        let arr = objc2_foundation::NSArray::from_slice(&refs);
11549        unsafe { panel.setAllowedFileTypes(Some(&arr)) };
11550    }
11551}
11552
11553/// Turn an open panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1):
11554/// every chosen URL, so a multiple-selection pick reports all of its files (and a folder
11555/// chooser its one directory).
11556fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
11557    let mut paths = Vec::new();
11558    if resp == 1 {
11559        for url in unsafe { panel.URLs() }.iter() {
11560            if let Some(p) = unsafe { url.path() } {
11561                paths.push(p.to_string());
11562            }
11563        }
11564    }
11565    let result = if paths.is_empty() {
11566        present::PresentResult::Dismissed
11567    } else {
11568        present::PresentResult::Files(paths)
11569    };
11570    emit(WINDOW_NODE, Event::PresentResult { req, result });
11571    PRESENT_PANELS.with(|m| {
11572        m.borrow_mut().remove(&req);
11573    });
11574}
11575
11576/// Turn a save panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1).
11577fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
11578    let result = if resp == 1 {
11579        unsafe { panel.URL() }
11580            .and_then(|url| unsafe { url.path() })
11581            .map(|p| present::PresentResult::Files(vec![p.to_string()]))
11582            .unwrap_or(present::PresentResult::Dismissed)
11583    } else {
11584        present::PresentResult::Dismissed
11585    };
11586    emit(WINDOW_NODE, Event::PresentResult { req, result });
11587    PRESENT_PANELS.with(|m| {
11588        m.borrow_mut().remove(&req);
11589    });
11590}
11591
11592impl Platform for AppKit {
11593    const TARGET: &'static str = "macos-appkit";
11594    const TOOLKIT: &'static str = "appkit";
11595
11596    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
11597        let mtm = self.mtm;
11598        // The App menu / About use the app's display name. `app_name` overrides the (possibly
11599        // decorated) window title; setting the process name also makes the standard About panel and
11600        // the bold App-menu title show it (an unbundled binary otherwise shows the exe name).
11601        self.app_name = options
11602            .app_name
11603            .clone()
11604            .unwrap_or_else(|| options.title.clone());
11605        // The bold App-menu title, the About panel and Quit all show the app's NAME. Always set
11606        // it, not just when `app_name` was given explicitly — an app that only set `title` was
11607        // showing its kebab-case cargo target ("day-sheets") where its name belongs.
11608        //
11609        // Two sources, because AppKit consults them in order: the main bundle's CFBundleName
11610        // wins when there is one, and `day launch` runs the binary UNBUNDLED during development,
11611        // where the name falls back to the executable's file name. Writing the info dictionary
11612        // covers the bundled case; the process name covers the unbundled one.
11613        unsafe {
11614            objc2_foundation::NSProcessInfo::processInfo()
11615                .setProcessName(&NSString::from_str(&self.app_name));
11616            let bundle = objc2_foundation::NSBundle::mainBundle();
11617            let info: Option<Retained<objc2_foundation::NSDictionary>> =
11618                msg_send![&bundle, infoDictionary];
11619            if let Some(info) = info {
11620                let key = NSString::from_str("CFBundleName");
11621                let value = NSString::from_str(&self.app_name);
11622                // `infoDictionary` is documented immutable, but the instance backing an
11623                // unbundled process is a mutable dictionary; guard the send so a genuinely
11624                // immutable one is left alone instead of raising.
11625                if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
11626                    let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
11627                }
11628            }
11629        }
11630        // RTL locales (docs/localization): AppleTextDirection flips AppKit's app-wide
11631        // userInterfaceLayoutDirection (label alignment, slider fill, control mirroring) —
11632        // read at NSApplication init, so register before sharedApplication. Registration
11633        // domain only: volatile, never persisted to the app's defaults.
11634        if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
11635            unsafe {
11636                use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
11637                let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
11638                    .into_super()
11639                    .into_super()
11640                    .into_super();
11641                let dict = NSDictionary::from_retained_objects(
11642                    &[
11643                        &*NSString::from_str("AppleTextDirection"),
11644                        &*NSString::from_str("NSForceRightToLeftWritingDirection"),
11645                    ],
11646                    &[yes.clone(), yes],
11647                );
11648                NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
11649            }
11650        }
11651        let app = NSApplication::sharedApplication(mtm);
11652        // A menu-bar app keeps out of the Dock from the first frame (docs/status-item.md): its
11653        // bundle carries LSUIElement, and an unbundled `day launch` run hears DAY_MACOS_DOCK=0.
11654        let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
11655            || unsafe {
11656                let bundle = objc2_foundation::NSBundle::mainBundle();
11657                let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
11658                    &bundle,
11659                    objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
11660                ];
11661                value.is_some_and(|v| {
11662                    let on: bool = msg_send![&v, boolValue];
11663                    on
11664                })
11665            };
11666        app.setActivationPolicy(if menu_bar_app {
11667            NSApplicationActivationPolicy::Accessory
11668        } else {
11669            NSApplicationActivationPolicy::Regular
11670        });
11671        let document_delegate = documents::delegate(mtm);
11672        app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
11673        // DAY_THEME=light|dark forces the appearance app-wide (themed CI screenshot runs and
11674        // local theme checks); unset ⇒ follow the system.
11675        if let Ok(theme) = std::env::var("DAY_THEME") {
11676            let name = match theme.as_str() {
11677                "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11678                "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11679                _ => None,
11680            };
11681            if let Some(name) = name {
11682                let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
11683                unsafe { app.setAppearance(appearance.as_deref()) };
11684            }
11685        }
11686        // Bundled custom fonts (§18.4) must be registered before the first label realizes.
11687        register_bundled_fonts();
11688
11689        // Default menu bar (standard app menu + Edit) so ⌘Q / Cut-Copy-Paste work before the app
11690        // installs its own via `app_menu(...)`. Rebuilt after `ready` for the items that depend
11691        // on the app's registrations — see there.
11692        let app_name = self.app_name.clone();
11693        install_main_menu(mtm, &app, &app_name);
11694        // App activation / termination → day lifecycle events (docs/lifecycle.md).
11695        install_lifecycle_observers();
11696        install_appearance_observer();
11697        install_reduce_motion_observer();
11698
11699        let (window, delegate, content) = self.make_window(&options, false, None);
11700        // Optional window-appearance override (opt-in via env). An app with a fixed light/dark
11701        // palette sets `DAY_APPEARANCE=light|dark` so native controls (list, fields, editor) match
11702        // its own colors instead of following the system appearance. Unset = follow the system.
11703        let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
11704            Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11705            Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11706            _ => None,
11707        };
11708        if let Some(name) = appearance_name
11709            && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
11710        {
11711            window.setAppearance(Some(&appearance));
11712        }
11713        // The primary delegate lives for the process (this frame never returns); secondary
11714        // delegates are retained in `self.secondary`.
11715        std::mem::forget(delegate);
11716
11717        self.window = Some(window.clone());
11718        self.content = Some(content.clone());
11719        PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
11720
11721        // The root lays out below the title bar, not under it (§7.7).
11722        let layout = pin_below_title_bar(&window)
11723            .unwrap_or(Size::new(options.size.width, options.size.height));
11724        ready(self, content, layout);
11725
11726        // `ready` ran the app's root() — registrations are in. Without a new-window
11727        // builder only one Normal window can ever exist: turn automatic tabbing off so no
11728        // tab bar, "+" button, or dead tab menu items appear (docs/windows.md).
11729        if day_core::windows::new_window_action_id() == 0
11730            && options.tabbing == day_spec::WindowTabbing::Automatic
11731        {
11732            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
11733        }
11734        // The DEFAULT menu bar was built before `root()` ran, so its registration-dependent
11735        // items — Settings…/⌘, and File ▸ New Window — could not exist yet. Rebuild it now that
11736        // they can. An app with its own `app_menu` model already replaced the whole bar and
11737        // gets its items through the injection path instead.
11738        if !day_core::has_app_menu() {
11739            install_main_menu(mtm, &app, &app_name);
11740        }
11741
11742        // Reopen where the user left it (docs/windows.md). AppKit persists the frame under an
11743        // autosave name and hands it back on request; `setFrameUsingName` answers false the
11744        // first time, which is when centering is the right answer.
11745        //
11746        // NOT while a dayscript is driving or `DAY_WINDOW` has forced a size: a restored frame
11747        // would make every captured screenshot's dimensions depend on where the developer last
11748        // dragged the window, and the capture suites compare those across machines.
11749        let deterministic =
11750            std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
11751        let autosave = NSString::from_str("day.main");
11752        if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
11753            window.center();
11754            // An explicit placement wins over centering, but not over the frame the user left.
11755            window_chrome::place(&window, options.placement);
11756        }
11757        // A scripted run whose capture needs a display scale this host's displays lack opens on
11758        // the one `day launch` made for it (`DAY_WINDOW_SCREEN`, a CGDirectDisplayID): a
11759        // capture is the window server's pixels, so it has the scale of the display under it.
11760        if let Some(screen) = capture_screen(mtm) {
11761            let (visible, frame) = (screen.visibleFrame(), window.frame());
11762            window.setFrameOrigin(NSPoint::new(
11763                visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
11764                visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
11765            ));
11766        }
11767        if !deterministic {
11768            unsafe { window.setFrameAutosaveName(&autosave) };
11769        }
11770        if !options.start_hidden {
11771            window.makeKeyAndOrderFront(None);
11772            app.activate();
11773        }
11774        // The root was mounted before the window was shown (ready() runs first), and on
11775        // macOS 26 layer displays requested pre-run are dropped for a window ordered front
11776        // before the app finishes launching — the window stays blank until the next real
11777        // event. Re-mark the whole tree so the first run-loop turn commits a full frame.
11778        if let Some(content) = window.contentView() {
11779            mark_tree_needs_display(&content);
11780        }
11781        if std::env::var_os("DAY_DUMP").is_some() {
11782            std::thread::spawn(|| {
11783                std::thread::sleep(std::time::Duration::from_millis(2000));
11784                Self::post(Box::new(|| {
11785                    // The primary's content specifically (docs/windows.md).
11786                    if let Some(content) = primary_content() {
11787                        let desc: Retained<NSString> =
11788                            unsafe { msg_send![&*content, _subtreeDescription] };
11789                        log::warn!("{desc}");
11790                    }
11791                }));
11792            });
11793        }
11794        app.run();
11795    }
11796
11797    fn post(f: Box<dyn FnOnce() + Send>) {
11798        // Posted-closure trampoline (§8.5): the closure runs inside dispatch's C frame, so a
11799        // panic is contained here rather than unwinding into libdispatch.
11800        dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
11801    }
11802
11803    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
11804        // The timer door behind `day::sleep` (docs/async.md): `dispatch_after` on the main
11805        // queue, so a sleep is a dispatch timer rather than a parked helper thread. Contained
11806        // like `post`. A delay too large for dispatch's clock runs at the far horizon instead.
11807        let when =
11808            dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
11809                .unwrap_or(dispatch2::DispatchTime::FOREVER);
11810        if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
11811            ffi_guard::contain((), f);
11812        }) {
11813            log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
11814        }
11815    }
11816
11817    fn locale_hints(&self) -> Vec<String> {
11818        // The user's ordered language preference from Settings ("fr-FR", "en-US", …), which is
11819        // the ambient locale Day negotiates its catalogs against (§12.2, docs/localization.md).
11820        objc2_foundation::NSLocale::preferredLanguages()
11821            .iter()
11822            .map(|s| s.to_string())
11823            .collect()
11824    }
11825}
11826
11827// `CGWindowListCreateImage` is obsoleted as of the macOS 15 SDK (ScreenCaptureKit is the
11828// sanctioned replacement) but still resolves and answers on macOS 26. It is declared here rather
11829// than taken from a binding because the availability attribute would refuse the call outright,
11830// and every use below treats a NULL return as "ask the offscreen path instead".
11831unsafe extern "C" {
11832    fn CGWindowListCreateImage(
11833        bounds: objc2_core_foundation::CGRect,
11834        list_option: u32,
11835        window_id: u32,
11836        image_option: u32,
11837    ) -> *mut objc2_core_graphics::CGImage;
11838}
11839
11840/// kCGWindowListOptionIncludingWindow — composite only this window, so whatever is stacked over
11841/// it (another app, a CI runner's stray window) cannot appear in the capture.
11842const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
11843/// kCGWindowImageBoundsIgnoreFraming — the window's own frame, without its drop shadow, which
11844/// makes the returned image exactly `window.frame()` at the backing scale.
11845const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
11846
11847/// Encode a captured rep as PNG, in sRGB.
11848///
11849/// A capture arrives in the color space of the display it was composited for, and a PNG of it
11850/// embeds that display's ICC profile: the same color then has different sample values on every
11851/// machine, and on every other Day target, which all capture sRGB. Converting first makes a
11852/// macOS capture's samples comparable with theirs and independent of the capturing display.
11853fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
11854    let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
11855        &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
11856        objc2_app_kit::NSColorRenderingIntent::Default,
11857    );
11858    let rep = srgb.as_deref().unwrap_or(rep);
11859    let data = unsafe {
11860        rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
11861    }
11862    .ok_or("png encode failed")?;
11863    Ok(data.to_vec())
11864}
11865
11866/// Capture `content` by asking the WINDOW SERVER for the composited window and cropping to it.
11867///
11868/// This exists because an offscreen render cannot draw macOS's own materials. As of macOS 26 a
11869/// sidebar `NSSplitViewItem` is a Liquid Glass surface the window server composites from what is
11870/// behind it; `cacheDisplayInRect` has no backdrop to sample, so it renders the sidebar as an
11871/// opaque white slab with none of its rows in it — every macos-appkit gallery shot had a blank
11872/// sidebar. The window server has the real pixels, including the rows.
11873///
11874/// It answers only while the window is actually on screen. A hidden, minimized or
11875/// never-composited window has no image to hand back (verified: hiding the app makes this return
11876/// NULL while the offscreen path still produces a frame), so this returns `Err` and the caller
11877/// falls back rather than failing the capture.
11878fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
11879    let window = content.window().ok_or("view is not in a window")?;
11880    // An attached sheet is the active modal surface and has its own composited window.
11881    // Capturing only the parent's window would show dimmed content without the modal UI.
11882    if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
11883        return snapshot_via_window_server(&sheet, chrome);
11884    }
11885    let number = window.windowNumber();
11886    if number <= 0 {
11887        return Err(format!("window {number} is not on screen"));
11888    }
11889    // The server hands back the frame it last COMPOSITED, which is the previous one whenever the
11890    // app has changed the view tree since. A capture taken right after a state change then shows
11891    // the state before it — a `when` whose outgoing arm is already gone from the tree and from the
11892    // view hierarchy still appears in the image, so a walkthrough asserting on pixels reads a
11893    // stale frame as "the change did not happen". Push the pending work out first: lay out, draw,
11894    // then commit the layer tree to the render server.
11895    unsafe { content.layoutSubtreeIfNeeded() };
11896    window.displayIfNeeded();
11897    CATransaction::flush();
11898    // CGRectNull asks for the window's own bounds rather than a screen region.
11899    let null_rect = objc2_core_foundation::CGRect::new(
11900        objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
11901        objc2_core_foundation::CGSize::new(0.0, 0.0),
11902    );
11903    let shot = unsafe {
11904        CGWindowListCreateImage(
11905            null_rect,
11906            CG_WINDOW_LIST_INCLUDING_WINDOW,
11907            number as u32,
11908            CG_WINDOW_IMAGE_IGNORE_FRAMING,
11909        )
11910    };
11911    if shot.is_null() {
11912        return Err("the window server has no image for this window".into());
11913    }
11914    // SAFETY: non-NULL CGImageRef owned by this call (Create rule); CFRetained takes that
11915    // ownership over, so it is released exactly once.
11916    let shot = unsafe {
11917        objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
11918    };
11919
11920    // A chrome capture is the window image as the server composited it — titlebar, toolbar and
11921    // rounded corners included — so it is done here, before the crop.
11922    if chrome {
11923        let rep = unsafe {
11924            objc2_app_kit::NSBitmapImageRep::initWithCGImage(
11925                objc2_app_kit::NSBitmapImageRep::alloc(),
11926                &shot,
11927            )
11928        };
11929        return png_of_rep(&rep);
11930    }
11931
11932    // Crop the window frame down to the content view. Keeping the framing identical to the
11933    // offscreen path is the point: the titlebar has never been part of a Day capture, and every
11934    // published gallery shot would otherwise change size.
11935    let frame = window.frame();
11936    if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
11937        return Err("zero-size window".into());
11938    }
11939    let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
11940    // Cocoa rects are bottom-left origin; a CGImage's are top-left, so the content's distance
11941    // from the window top is what the crop needs.
11942    let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
11943    let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
11944    let crop = objc2_core_foundation::CGRect::new(
11945        objc2_core_foundation::CGPoint::new(
11946            (in_window.origin.x * scale).round(),
11947            (from_top * scale).round(),
11948        ),
11949        objc2_core_foundation::CGSize::new(
11950            (in_window.size.width * scale).round(),
11951            (in_window.size.height * scale).round(),
11952        ),
11953    );
11954    let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
11955        .ok_or("crop to the content view failed")?;
11956    let rep = unsafe {
11957        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
11958            objc2_app_kit::NSBitmapImageRep::alloc(),
11959            &cropped,
11960        )
11961    };
11962    png_of_rep(&rep)
11963}
11964
11965/// Capture a window content view as PNG (the dayscript screenshot seam, §14).
11966///
11967/// The window server first, because it is the only one of the two that can show macOS's own
11968/// composited materials; the offscreen render when it declines, because it is the only one of the
11969/// two that works with no window on screen. See each for why.
11970/// Put a [`Transform`] on a view through its own geometry rather than its layer: the frame is
11971/// the laid-out `base` scaled about its center and moved by the translation, the bounds keep the
11972/// laid-out size (so the content draws at the scale), and the rotation is the frame's center
11973/// rotation (positive is clockwise on screen: Day's parents are flipped, y down).
11974fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
11975    let [x, y, w, h] = base;
11976    let (sw, sh) = (w * t.sx, h * t.sy);
11977    let frame = NSRect::new(
11978        NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
11979        NSSize::new(sw, sh),
11980    );
11981    unsafe {
11982        // The rotation goes first and comes back last: a rotated view's frame is its bounding
11983        // box, so setting the frame of a rotated view would scale it.
11984        v.setFrameCenterRotation(0.0);
11985        v.setFrame(frame);
11986        v.setBoundsSize(NSSize::new(w, h));
11987        if t.rotate_deg != 0.0 {
11988            v.setFrameCenterRotation(t.rotate_deg);
11989        }
11990    }
11991}
11992
11993fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
11994    let modal = content
11995        .window()
11996        .and_then(|w| w.attachedSheet())
11997        .and_then(|s| s.contentView());
11998    let content = modal.as_deref().unwrap_or(content);
11999    match snapshot_via_window_server(content, false) {
12000        Ok(bytes) => Ok(bytes),
12001        Err(_) => snapshot_view_cache(content),
12002    }
12003}
12004
12005/// Capture a window *with* its chrome — the titlebar and toolbar the content capture crops away
12006/// (`day::window_image().chrome()`, docs/window-image.md).
12007///
12008/// Only the window server can produce this: the offscreen path renders the content view's own
12009/// hierarchy, which the titlebar is not part of. When it declines (an offscreen or hidden window)
12010/// the content capture stands in — a smaller image beats no image, and it is what the caller
12011/// would have got from the plain duty.
12012fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
12013    let modal = content
12014        .window()
12015        .and_then(|w| w.attachedSheet())
12016        .and_then(|s| s.contentView());
12017    let content = modal.as_deref().unwrap_or(content);
12018    match snapshot_via_window_server(content, true) {
12019        Ok(bytes) => Ok(bytes),
12020        Err(_) => snapshot_view_cache(content),
12021    }
12022}
12023
12024/// The offscreen fallback: `cacheDisplayInRect` over a window-background pre-fill resolved for
12025/// the view's light/dark appearance. Renders the view hierarchy Day drew, and nothing the window
12026/// server composites (see `snapshot_via_window_server`).
12027fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
12028    let bounds = content.bounds();
12029    let rep =
12030        unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
12031    // Day containers are transparent (the window server paints the backdrop), so pre-fill
12032    // the rep with the window background — resolved for the window's light/dark appearance —
12033    // before compositing the view hierarchy over it (§14).
12034    let ctx =
12035        NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
12036    NSGraphicsContext::saveGraphicsState_class();
12037    NSGraphicsContext::setCurrentContext(Some(&ctx));
12038    content
12039        .effectiveAppearance()
12040        .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
12041            NSColor::windowBackgroundColor().setFill();
12042            objc2_app_kit::NSRectFill(bounds);
12043        }));
12044    NSGraphicsContext::restoreGraphicsState_class();
12045    unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
12046    png_of_rep(&rep)
12047}
12048
12049/// The screen a scripted run asked to open on: `DAY_WINDOW_SCREEN`, the CGDirectDisplayID of the
12050/// capture display `day launch --script` provides when no attached display has the capture's
12051/// scale. `None` when unset or when no screen has that id, which leaves the window where it was.
12052/// Center `window` on `primary`'s screen when `center` put it on another, as high as `center`
12053/// places a window (a third of the free height above it, two below).
12054fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
12055    let Some(screen) = primary.and_then(|w| w.screen()) else {
12056        return;
12057    };
12058    if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
12059        return;
12060    }
12061    let (visible, frame) = (screen.visibleFrame(), window.frame());
12062    window.setFrameOrigin(NSPoint::new(
12063        visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12064        visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
12065    ));
12066}
12067
12068fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
12069    let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
12070        .ok()?
12071        .trim()
12072        .parse()
12073        .ok()?;
12074    let key = NSString::from_str("NSScreenNumber");
12075    objc2_app_kit::NSScreen::screens(mtm)
12076        .into_iter()
12077        .find(|screen| {
12078            let number: Option<Retained<objc2_foundation::NSNumber>> =
12079                unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
12080            number.is_some_and(|n| n.unsignedIntValue() == wanted)
12081        })
12082}
12083
12084/// Recursively mark a view tree as needing display (startup first-frame fix, see `run`).
12085fn mark_tree_needs_display(view: &NSView) {
12086    view.setNeedsDisplay(true);
12087    for sub in view.subviews() {
12088        mark_tree_needs_display(&sub);
12089    }
12090}
12091
12092/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
12093/// macOS has no true background/foreground or memory-warning lifecycle. `const` so
12094/// `day::require_lifecycle!` can reject unsupported phases at compile time. Must agree with the
12095/// `Toolkit::supports_lifecycle` default (which also returns `is_universal`).
12096pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
12097    phase.is_universal()
12098}
12099
12100/// Follow the SYSTEM appearance while the app runs: macOS posts the distributed
12101/// "AppleInterfaceThemeChangedNotification" on a theme switch, and AppKit updates
12102/// `effectiveAppearance` just after — so re-read on the next main-queue turn and refresh
12103/// day-core's reactive dark-mode signal (palette closures recolor live instead of going
12104/// stale until the next rebuild). The token is leaked to observe for the app's lifetime.
12105fn install_appearance_observer() {
12106    use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
12107    let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
12108    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12109        dispatch2::DispatchQueue::main()
12110            .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
12111    });
12112    let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
12113    let token = unsafe {
12114        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
12115    };
12116    std::mem::forget(token);
12117}
12118
12119/// Follow the SYSTEM reduce-motion switch while the app runs: NSWorkspace posts
12120/// `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification` on its own notification
12121/// center when any Accessibility › Display option flips, and
12122/// `accessibilityDisplayShouldReduceMotion` already answers the new value by then. The
12123/// notification arrives on the main thread; the main-queue hop keeps the re-read off the
12124/// poster's stack, as the appearance observer does. The token is leaked to observe for the
12125/// app's lifetime.
12126fn install_reduce_motion_observer() {
12127    use objc2_foundation::NSNotification;
12128    let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
12129    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12130        dispatch2::DispatchQueue::main()
12131            .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
12132    });
12133    let token = unsafe {
12134        center.addObserverForName_object_queue_usingBlock(
12135            Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
12136            None,
12137            None,
12138            &block,
12139        )
12140    };
12141    std::mem::forget(token);
12142}
12143
12144/// Bridge the NSApplication activation/termination notifications to day lifecycle events
12145/// (docs/lifecycle.md). The observer tokens are leaked to live for the whole app.
12146fn install_lifecycle_observers() {
12147    use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
12148    let center = unsafe { NSNotificationCenter::defaultCenter() };
12149    let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
12150        let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12151            ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
12152        });
12153        let token = unsafe {
12154            center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
12155        };
12156        std::mem::forget(token); // observe for the app's lifetime
12157    };
12158    unsafe {
12159        observe(
12160            NSApplicationDidBecomeActiveNotification,
12161            day_spec::Lifecycle::DidBecomeActive,
12162        );
12163        observe(
12164            NSApplicationWillResignActiveNotification,
12165            day_spec::Lifecycle::WillResignActive,
12166        );
12167        observe(
12168            NSApplicationWillTerminateNotification,
12169            day_spec::Lifecycle::WillTerminate,
12170        );
12171        // `terminate:` exits the process from inside the run loop, so the loop never returns to
12172        // `launch_with`: the last Day code to run is this notification's second observer, which
12173        // NSNotificationCenter calls after the first (docs/lifecycle.md).
12174        observe(
12175            NSApplicationWillTerminateNotification,
12176            day_spec::Lifecycle::DidExit,
12177        );
12178    }
12179}
12180
12181day_localization_ui::locales!();
12182
12183/// Shared by the initial menu and every reactive replacement. AppKit owns Services
12184/// and the hide actions; these commands must not depend on a window or app callback.
12185fn install_application_menu(
12186    mtm: MainThreadMarker,
12187    menubar: &NSMenu,
12188    title: &str,
12189    about: Option<day_spec::MenuItem>,
12190    updates: Option<day_spec::MenuItem>,
12191    prefs: Option<day_spec::MenuItem>,
12192    quit: Option<day_spec::MenuItem>,
12193) -> Retained<NSMenu> {
12194    let app = NSApplication::sharedApplication(mtm);
12195    use day_spec::{MenuItem as M, MenuRole as R};
12196    let standard = |role, label| M::Action {
12197        id: None,
12198        action: 0,
12199        label,
12200        shortcut: None,
12201        enabled: true,
12202        checked: None,
12203        role: Some(role),
12204        icon: None,
12205    };
12206    let mut about =
12207        about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
12208    let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
12209    for (item, title) in [
12210        (&mut about, res::str::about_app(title).format()),
12211        (&mut quit, res::str::quit_app(title).format()),
12212    ] {
12213        if let M::Action { label, .. } = item {
12214            *label = title;
12215        }
12216    }
12217    // A registered Day About (docs/settings.md) replaces the stock Info.plist panel: the
12218    // item fires the dispatch action instead of `orderFrontStandardAboutPanel:`.
12219    if let M::Action { action, .. } = &mut about
12220        && *action == 0
12221    {
12222        *action = day_core::windows::about_action_id();
12223    }
12224    // Check for Updates… sits directly under About (the Sparkle convention), whether the app
12225    // placed the role itself or the updater only registered its action.
12226    let updates_id = day_core::windows::check_for_updates_action_id();
12227    let updates = updates.or_else(|| {
12228        (updates_id != 0).then(|| {
12229            standard(
12230                R::CheckForUpdates,
12231                day_localization::t(day_localization::key::day_check_for_updates),
12232            )
12233        })
12234    });
12235    let mut head = vec![about];
12236    if let Some(mut updates) = updates {
12237        if let M::Action { action, .. } = &mut updates
12238            && *action == 0
12239        {
12240            *action = updates_id;
12241        }
12242        head.push(updates);
12243    }
12244    head.push(M::Separator);
12245    let menu = build_ns_menu(mtm, title, &head);
12246    if let Some(mut prefs) = prefs {
12247        if let M::Action { label, .. } = &mut prefs {
12248            *label = res::str::settings().format();
12249        }
12250        let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
12251        for item in section.itemArray() {
12252            section.removeItem(&item);
12253            menu.addItem(&item);
12254        }
12255    }
12256    // AppKit keeps the registered Services menu across main-menu replacements.
12257    // Move that same menu to the new bar rather than abandoning its system-populated items.
12258    let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
12259    if let Some(parent) = unsafe { services.supermenu() } {
12260        let index = parent.indexOfItemWithSubmenu(Some(&services));
12261        if index >= 0 {
12262            parent.itemAtIndex(index).unwrap().setSubmenu(None);
12263        }
12264    }
12265    let services_item = NSMenuItem::new(mtm);
12266    services_item.setTitle(&NSString::from_str(&res::str::services().format()));
12267    services_item.setSubmenu(Some(&services));
12268    menu.addItem(&services_item);
12269    menu.addItem(&NSMenuItem::separatorItem(mtm));
12270    for (label, selector, shortcut) in [
12271        (
12272            res::str::hide_app(title).format(),
12273            sel!(hide:),
12274            Some(day_spec::Shortcut::primary("h")),
12275        ),
12276        (
12277            res::str::hide_others().format(),
12278            sel!(hideOtherApplications:),
12279            Some(day_spec::Shortcut::primary("h").alt()),
12280        ),
12281        (
12282            res::str::show_all().format(),
12283            sel!(unhideAllApplications:),
12284            None,
12285        ),
12286    ] {
12287        let item = unsafe {
12288            NSMenuItem::initWithTitle_action_keyEquivalent(
12289                NSMenuItem::alloc(mtm),
12290                &NSString::from_str(&label),
12291                Some(selector),
12292                &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
12293            )
12294        };
12295        if let Some(shortcut) = shortcut {
12296            item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
12297        }
12298        // Explicitly target the application so window responders cannot override Hide.
12299        unsafe { item.setTarget(Some(&app)) };
12300        menu.addItem(&item);
12301    }
12302    menu.addItem(&NSMenuItem::separatorItem(mtm));
12303    let section = build_ns_menu(mtm, title, &[quit]);
12304    let quit = section.itemAtIndex(0).unwrap();
12305    section.removeItem(&quit);
12306    menu.addItem(&quit);
12307    let item = NSMenuItem::new(mtm);
12308    item.setSubmenu(Some(&menu));
12309    menubar.addItem(&item);
12310    services
12311}
12312
12313/// The default main menu (§21.2 M2): standard application menu; Edit menu wired to the responder
12314/// chain so Cmd+C/V/X/A work in NSTextFields; Window menu basics.
12315fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
12316    let menubar = NSMenu::new(mtm);
12317
12318    let prefs_id = day_core::windows::preferences_action_id();
12319    let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
12320        id: None,
12321        action: prefs_id,
12322        label: res::str::settings().format(),
12323        shortcut: None,
12324        enabled: true,
12325        checked: None,
12326        role: Some(day_spec::MenuRole::Preferences),
12327        icon: None,
12328    });
12329    let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
12330
12331    // File ▸ New Window / Close, when the app registered a new-window builder — the same
12332    // zero-menu-code rule as Settings…/⌘, above (docs/windows.md). Without this an app that
12333    // never calls `app_menu` gets the tab-bar "+" and the Window menu's tab commands but no
12334    // File ▸ New Window, because the default menu bar has no File menu to put it in.
12335    let new_window_id = day_core::windows::new_window_action_id();
12336    if new_window_id != 0 {
12337        let file_item = NSMenuItem::new(mtm);
12338        let file_menu = unsafe {
12339            NSMenu::initWithTitle(
12340                NSMenu::alloc(mtm),
12341                &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
12342            )
12343        };
12344        let new_window = unsafe {
12345            NSMenuItem::initWithTitle_action_keyEquivalent(
12346                NSMenuItem::alloc(mtm),
12347                &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
12348                Some(sel!(fire:)),
12349                &NSString::from_str("n"),
12350            )
12351        };
12352        let target = menu_target(mtm);
12353        let tobj: &objc2::runtime::AnyObject = target.as_ref();
12354        unsafe { new_window.setTarget(Some(tobj)) };
12355        new_window.setTag(new_window_id as isize);
12356        file_menu.addItem(&new_window);
12357        file_menu.addItem(&NSMenuItem::separatorItem(mtm));
12358        // Nil-targeted, so it closes whatever window is key — the standard responder route.
12359        let close = unsafe {
12360            NSMenuItem::initWithTitle_action_keyEquivalent(
12361                NSMenuItem::alloc(mtm),
12362                &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
12363                Some(sel!(performClose:)),
12364                &NSString::from_str("w"),
12365            )
12366        };
12367        file_menu.addItem(&close);
12368        file_item.setSubmenu(Some(&file_menu));
12369        menubar.addItem(&file_item);
12370    }
12371
12372    let edit_item = NSMenuItem::new(mtm);
12373    let edit_menu = unsafe {
12374        NSMenu::initWithTitle(
12375            NSMenu::alloc(mtm),
12376            &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
12377        )
12378    };
12379    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12380        let item = unsafe {
12381            NSMenuItem::initWithTitle_action_keyEquivalent(
12382                NSMenuItem::alloc(mtm),
12383                &NSString::from_str(&day_localization::t(key)),
12384                Some(action),
12385                &NSString::from_str(accel),
12386            )
12387        };
12388        edit_menu.addItem(&item);
12389    };
12390    add("day_undo", sel!(undo:), "z");
12391    add("day_redo", sel!(redo:), "Z");
12392    edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
12393    add("day_cut", sel!(cut:), "x");
12394    add("day_copy", sel!(copy:), "c");
12395    add("day_paste", sel!(paste:), "v");
12396    add("day_select_all", sel!(selectAll:), "a");
12397    edit_item.setSubmenu(Some(&edit_menu));
12398    menubar.addItem(&edit_item);
12399
12400    install_windows_menu(mtm, app, &menubar);
12401
12402    app.setMainMenu(Some(&menubar));
12403    unsafe { app.setServicesMenu(Some(&services)) };
12404}
12405
12406/// The standard Window menu (docs/windows.md): Minimize ⌘M / Zoom / Bring All to Front,
12407/// registered as `NSApp.windowsMenu` — AppKit then appends the open-window list and, with
12408/// tabbing live, the tab commands (Show Next/Previous Tab, Merge All Windows) itself. All
12409/// nav hosts are nil-targeted (responder chain), so they act on the key window.
12410fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
12411    let menu = unsafe {
12412        NSMenu::initWithTitle(
12413            NSMenu::alloc(mtm),
12414            &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
12415        )
12416    };
12417    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12418        let item = unsafe {
12419            NSMenuItem::initWithTitle_action_keyEquivalent(
12420                NSMenuItem::alloc(mtm),
12421                &NSString::from_str(&day_localization::t(key)),
12422                Some(action),
12423                &NSString::from_str(accel),
12424            )
12425        };
12426        menu.addItem(&item);
12427    };
12428    add("day_minimize", sel!(performMiniaturize:), "m");
12429    add("day_zoom", sel!(performZoom:), "");
12430    menu.addItem(&NSMenuItem::separatorItem(mtm));
12431    add("day_bring_all_front", sel!(arrangeInFront:), "");
12432    let item = NSMenuItem::new(mtm);
12433    item.setTitle(&NSString::from_str(&day_localization::t(
12434        day_localization::key::day_window,
12435    )));
12436    item.setSubmenu(Some(&menu));
12437    menubar.addItem(&item);
12438    unsafe { app.setWindowsMenu(Some(&menu)) };
12439}
12440
12441/// Hoist application roles even from nested menus. First declaration wins; remove
12442/// duplicates and empty containers, then normalize separators left by the move.
12443fn extract_app_role(
12444    items: &mut Vec<day_spec::MenuItem>,
12445    role: day_spec::MenuRole,
12446) -> Option<day_spec::MenuItem> {
12447    use day_spec::MenuItem as M;
12448    let mut found = None;
12449    let mut remaining = Vec::new();
12450    for mut item in items.drain(..) {
12451        match &mut item {
12452            M::Action { role: Some(r), .. } if *r == role => {
12453                found.get_or_insert(item);
12454                continue;
12455            }
12456            M::Submenu { items, .. } => {
12457                let nested = extract_app_role(items, role);
12458                if found.is_none() {
12459                    found = nested;
12460                }
12461                if items.is_empty() {
12462                    continue;
12463                }
12464            }
12465            M::Separator
12466                if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
12467            {
12468                continue;
12469            }
12470            _ => {}
12471        }
12472        remaining.push(item);
12473    }
12474    while matches!(remaining.last(), Some(M::Separator)) {
12475        remaining.pop();
12476    }
12477    *items = remaining;
12478    found
12479}
12480
12481/// Whether any action in the model (recursively) carries `role`.
12482fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
12483    items.iter().any(|it| match it {
12484        day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
12485        day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
12486        day_spec::MenuItem::Separator => false,
12487    })
12488}
12489
12490// ---------------------------------------------------------------------------
12491// Menus (§ menus): render day's MenuItem model with NSMenu. Custom items route to a shared
12492// DayMenuTarget (id in the item's tag → Event::MenuAction); role items use the native selector.
12493// ---------------------------------------------------------------------------
12494
12495define_class!(
12496    #[unsafe(super(NSObject))]
12497    #[thread_kind = MainThreadOnly]
12498    #[name = "DayMenuTarget"]
12499    #[ivars = ()]
12500    struct DayMenuTarget;
12501
12502    unsafe impl NSObjectProtocol for DayMenuTarget {}
12503
12504    impl DayMenuTarget {
12505        #[unsafe(method(fire:))]
12506        fn fire(&self, sender: &NSMenuItem) {
12507            ffi_guard::contain((), || {
12508                let id = sender.tag() as u64;
12509                if id != 0 {
12510                    emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
12511                }
12512            })
12513        }
12514    }
12515);
12516
12517/// The primary window's content view (set once in `run`).
12518/// Pin the window's content coordinate space under its title bar and toolbar (§7.7). The
12519/// content view is full-size (`FullSizeContentView`, for the unified toolbar), so it runs
12520/// beneath the bar; moving its bounds origin up by that strip makes Day's root, laid out from
12521/// (0, 0), start below the bar — the way UIKit pins the root inside `safeAreaInsets` — while
12522/// the view's own background still paints edge to edge. Returns the size Day lays out at, the
12523/// window's `contentLayoutRect`. Called wherever that rect can change: window creation, every
12524/// resize, and a toolbar coming or going.
12525pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
12526    let content = window.contentView()?;
12527    let full = content.frame().size;
12528    let layout = unsafe { window.contentLayoutRect() }.size;
12529    let top = (full.height - layout.height).max(0.0);
12530    // An overlay title bar (docs/window-chrome.md) is the one place the content belongs under
12531    // the bar: it keeps the full height, and the bar's height goes to the app as a safe-area
12532    // inset so it can pad its own content.
12533    if window_chrome::is_overlay(window) {
12534        unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
12535        window_chrome::report_title_bar_inset(window, top);
12536        return Some(Size::new(full.width, full.height));
12537    }
12538    unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
12539    Some(Size::new(full.width, (full.height - top).max(0.0)))
12540}
12541
12542/// The text a widget displays, for `read_native`: a label's or text field's string, a
12543/// button's title, a text area's contents. `None` for a secure field (it masks its text), an
12544/// icon-only button (its title is a tooltip), and every other view.
12545fn native_text(h: &NSView) -> Option<String> {
12546    if h.downcast_ref::<NSSecureTextField>().is_some() {
12547        return None;
12548    }
12549    if let Some(tf) = h.downcast_ref::<NSTextField>() {
12550        // `stringValue` answers the field editor's live text while the field edits.
12551        return Some(tf.stringValue().to_string());
12552    }
12553    if let Some(btn) = h.downcast_ref::<NSButton>() {
12554        if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
12555            return None;
12556        }
12557        return Some(btn.title().to_string());
12558    }
12559    // A text area is an NSTextView inside the scroll view its handle names (textarea.rs).
12560    let sv = h.downcast_ref::<NSScrollView>()?;
12561    let doc = sv.documentView()?;
12562    let tv = doc.downcast_ref::<NSTextView>()?;
12563    Some(tv.string().to_string())
12564}
12565
12566/// A slider's value or a determinate progress bar's fraction, for `read_native`. Both native
12567/// ranges are the ones Day gave: the slider is built with Day's min and max, the bar runs 0–1.
12568fn native_number(h: &NSView) -> Option<f64> {
12569    if let Some(sl) = h.downcast_ref::<NSSlider>() {
12570        return Some(sl.doubleValue());
12571    }
12572    let pi = h.downcast_ref::<NSProgressIndicator>()?;
12573    (!pi.isIndeterminate()).then(|| pi.doubleValue())
12574}
12575
12576/// The view's frame in its window's content coordinates, origin top left, for `read_native`.
12577/// The content view is flipped and pinned below the title bar (`pin_below_title_bar`), so
12578/// converting into it gives Day's layout space; an unflipped content view is flipped here.
12579fn native_frame(h: &NSView) -> Option<Rect> {
12580    let content = h.window()?.contentView()?;
12581    let r = h.convertRect_toView(h.bounds(), Some(&content));
12582    let y = if content.isFlipped() {
12583        r.origin.y
12584    } else {
12585        let b = content.bounds();
12586        b.origin.y + b.size.height - (r.origin.y + r.size.height)
12587    };
12588    Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
12589}
12590
12591/// The strip a pinned content view keeps above its layout origin (see `pin_below_title_bar`).
12592fn title_bar_inset(content: &NSView) -> f64 {
12593    (-content.bounds().origin.y).max(0.0)
12594}
12595
12596fn primary_content() -> Option<Retained<NSView>> {
12597    PRIMARY_CONTENT.with(|c| c.borrow().clone())
12598}
12599
12600fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
12601    MENU_TARGET.with(|t| {
12602        t.borrow_mut()
12603            .get_or_insert_with(|| {
12604                let this = DayMenuTarget::alloc(mtm).set_ivars(());
12605                let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
12606                obj
12607            })
12608            .clone()
12609    })
12610}
12611
12612fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
12613    use objc2_app_kit::NSEventModifierFlags as F;
12614    let mut m = F::empty();
12615    if s.primary {
12616        m |= F::Command;
12617    }
12618    if s.shift {
12619        m |= F::Shift;
12620    }
12621    if s.alt {
12622        m |= F::Option;
12623    }
12624    if s.control {
12625        m |= F::Control;
12626    }
12627    m
12628}
12629
12630/// A shortcut's key-equivalent string. Single chars pass through (lowercased); a few named keys map
12631/// to their control characters. Modifiers ride separately via `setKeyEquivalentModifierMask`.
12632fn ns_key_equivalent(key: &str) -> String {
12633    match key {
12634        "Return" | "Enter" => "\r".into(),
12635        "Tab" => "\t".into(),
12636        "Delete" | "Backspace" => "\u{8}".into(),
12637        "Escape" => "\u{1b}".into(),
12638        "Space" => " ".into(),
12639        k if k.chars().count() == 1 => k.to_lowercase(),
12640        _ => String::new(), // named keys we don't map get no key-equivalent (still shown in menu)
12641    }
12642}
12643
12644/// A standard role → (default label, nav host, default shortcut). Nav host `None` = no native action
12645/// (the app should attach its own via a custom item); the role then only supplies label placement.
12646fn role_spec(
12647    role: day_spec::MenuRole,
12648) -> (
12649    &'static str,
12650    Option<objc2::runtime::Sel>,
12651    Option<day_spec::Shortcut>,
12652) {
12653    use day_spec::MenuRole as R;
12654    use day_spec::Shortcut as S;
12655    match role {
12656        R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
12657        R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
12658        R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
12659        R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
12660        R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
12661        R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
12662        R::Delete => ("Delete", Some(sel!(delete:)), None),
12663        R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
12664        R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
12665        R::Preferences => ("Settings…", None, Some(S::primary(","))),
12666        R::Minimize => (
12667            "Minimize",
12668            Some(sel!(performMiniaturize:)),
12669            Some(S::primary("m")),
12670        ),
12671        R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
12672        R::Fullscreen => (
12673            "Enter Full Screen",
12674            Some(sel!(toggleFullScreen:)),
12675            Some(S::primary("f").control()),
12676        ),
12677        // No native selector (docs/windows.md): the item dispatches the registered
12678        // new-window action through the ordinary custom-item path (`fire:`).
12679        R::NewWindow => ("New Window", None, Some(S::primary("n"))),
12680        // Likewise: no selector, the registered updater action fires through `fire:`.
12681        R::CheckForUpdates => ("Check for Updates…", None, None),
12682    }
12683}
12684
12685pub(crate) fn build_ns_menu(
12686    mtm: MainThreadMarker,
12687    title: &str,
12688    items: &[day_spec::MenuItem],
12689) -> Retained<NSMenu> {
12690    use day_spec::MenuItem as MI;
12691    let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
12692    let target = menu_target(mtm);
12693    for item in items {
12694        match item {
12695            MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
12696            MI::Submenu { label, items, .. } => {
12697                let sub = build_ns_menu(mtm, label, items);
12698                let it = NSMenuItem::new(mtm);
12699                it.setTitle(&NSString::from_str(label));
12700                it.setSubmenu(Some(&sub));
12701                menu.addItem(&it);
12702            }
12703            MI::Action {
12704                action,
12705                label,
12706                shortcut,
12707                enabled,
12708                checked,
12709                role,
12710                icon,
12711                ..
12712            } => {
12713                // Resolve label/nav host/shortcut, folding in the role's native defaults.
12714                let (mut lbl, sel, mut sc) = match role {
12715                    Some(r) => {
12716                        let (dl, ds, dsc) = role_spec(*r);
12717                        (dl.to_string(), ds, dsc)
12718                    }
12719                    None => (String::new(), None, None),
12720                };
12721                if !label.is_empty() {
12722                    lbl = label.clone();
12723                }
12724                if shortcut.is_some() {
12725                    sc = shortcut.clone();
12726                }
12727                // Custom action (nonzero id) overrides any role nav host and targets our
12728                // trampoline — except the responder-routed set (undo pair, clipboard trio),
12729                // whose nonzero ids are only the other platforms' fallback dispatchers: here
12730                // the nil-target nav hosts must stay, so the responder chain resolves the
12731                // acting object (a focused text field before the app's bridge).
12732                let responder_role = matches!(
12733                    role,
12734                    Some(
12735                        day_spec::MenuRole::Undo
12736                            | day_spec::MenuRole::Redo
12737                            | day_spec::MenuRole::Cut
12738                            | day_spec::MenuRole::Copy
12739                            | day_spec::MenuRole::Paste
12740                            | day_spec::MenuRole::SelectAll
12741                    )
12742                );
12743                let custom = *action != 0 && !responder_role;
12744                let key = sc
12745                    .as_ref()
12746                    .map(|s| ns_key_equivalent(&s.key))
12747                    .unwrap_or_default();
12748                let it = unsafe {
12749                    NSMenuItem::initWithTitle_action_keyEquivalent(
12750                        NSMenuItem::alloc(mtm),
12751                        &NSString::from_str(&lbl),
12752                        if custom { Some(sel!(fire:)) } else { sel },
12753                        &NSString::from_str(&key),
12754                    )
12755                };
12756                if let Some(s) = &sc {
12757                    it.setKeyEquivalentModifierMask(ns_modifiers(s));
12758                    // AppKit's own per-layout/per-language adjustments (macOS 12+): remap a
12759                    // key equivalent the current keyboard layout cannot type, and MIRROR
12760                    // directional pairs (⌘[ / ⌘]) under RTL languages — the system half of
12761                    // shortcut localization; the catalog half is the `.key` attribute
12762                    // (docs/localization.md).
12763                    it.setAllowsAutomaticKeyEquivalentLocalization(true);
12764                    it.setAllowsAutomaticKeyEquivalentMirroring(true);
12765                }
12766                if custom {
12767                    let tobj: &objc2::runtime::AnyObject = target.as_ref();
12768                    unsafe { it.setTarget(Some(tobj)) };
12769                    it.setTag(*action as isize);
12770                }
12771                it.setEnabled(*enabled);
12772                // A checkable item takes NSMenuItem's own state, so macOS draws the ✓ it draws
12773                // everywhere else and reserves the mark's column when it is off (docs/menus.md).
12774                if let Some(on) = checked {
12775                    it.setState(if *on {
12776                        NSControlStateValueOn
12777                    } else {
12778                        NSControlStateValueOff
12779                    });
12780                }
12781                // The item's glyph, drawn the way NSMenuItem draws its own (docs/menus.md):
12782                // template-tinted, sized to the menu's text.
12783                if let Some(icon) = icon
12784                    && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
12785                {
12786                    img.setSize(NSSize::new(16.0, 16.0));
12787                    it.setImage(Some(&img));
12788                }
12789                menu.addItem(&it);
12790            }
12791        }
12792    }
12793    menu
12794}
12795
12796// AppKit's TLS may be destroyed before the reactive arena drops its last Bitmap.
12797// The registry already released the native images in that case.
12798fn release_bitmap(id: day_spec::BitmapId) {
12799    let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
12800}
12801
12802#[cfg(test)]
12803mod bitmap_teardown_tests {
12804    use super::*;
12805
12806    #[test]
12807    fn releasing_after_bitmap_registry_teardown_does_not_abort() {
12808        // Isolate destructor panics: Rust aborts the process when a TLS destructor unwinds.
12809        const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
12810        if std::env::var_os(CHILD).is_some() {
12811            struct LateRelease;
12812            impl Drop for LateRelease {
12813                fn drop(&mut self) {
12814                    assert!(BITMAPS.try_with(|_| ()).is_err());
12815                    // Same duty called by Bitmap::drop; no NSApplication is needed.
12816                    release_bitmap(day_spec::BitmapId(1));
12817                }
12818            }
12819            std::thread_local! {
12820                static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
12821            }
12822            std::thread::spawn(|| {
12823                LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
12824                BITMAPS.with(|_| ()); // initialized last, destroyed first
12825            })
12826            .join()
12827            .unwrap();
12828            return;
12829        }
12830        let output = std::process::Command::new(std::env::current_exe().unwrap())
12831            .args([
12832                "--exact",
12833                "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
12834                "--nocapture",
12835            ])
12836            .env(CHILD, "1")
12837            .output()
12838            .unwrap();
12839        assert!(
12840            output.status.success(),
12841            "{}",
12842            String::from_utf8_lossy(&output.stderr)
12843        );
12844    }
12845}