Skip to main content

day_toolkit_appkit/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-appkit: the macos-appkit backend (DESIGN.md §9). objc2, pure Rust, no shim.
5//!
6//! `Handle = Retained<NSView>`. Containers are flipped `NSView`s (top-left origin, so Day's
7//! frames apply directly and survive diffing). One custom target class (`DayTarget`) forwards
8//! target/action + text-delegate callbacks into the Day event sink, node-id keyed (§8.3).
9
10#![allow(unused_unsafe)]
11#![cfg(target_os = "macos")]
12
13mod controls;
14
15mod applications;
16mod nav_progress;
17
18use std::any::Any;
19use std::cell::{Cell, RefCell};
20use std::collections::HashMap;
21use std::rc::Rc;
22
23use linkme::distributed_slice;
24use objc2::Message as _;
25use objc2::rc::Retained;
26use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel};
27use objc2::{
28    AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
29};
30use objc2_app_kit::NSAccessibility as _;
31use objc2_app_kit::NSAppearanceCustomization as _;
32use objc2_app_kit::NSDraggingInfo as _;
33use objc2_app_kit::NSSplitViewDelegate;
34use objc2_app_kit::NSTextContent as _;
35use objc2_app_kit::NSTextInputClient;
36use objc2_app_kit::NSUserInterfaceItemIdentification as _;
37use objc2_app_kit::{
38    NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
39    NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
40};
41use objc2_app_kit::{
42    NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
43    NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
44    NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
45    NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
46    NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
47    NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
48    NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
49    NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
50    NSWindowDelegate, NSWindowStyleMask,
51};
52use objc2_app_kit::{
53    NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
54    NSApplicationWillTerminateNotification,
55};
56use objc2_app_kit::{
57    NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
58};
59use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
60use objc2_core_foundation::CGAffineTransform;
61use objc2_foundation::{
62    NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
63    NSNumber, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString,
64};
65use objc2_quartz_core::{
66    CAMediaTimingFunction, CATransaction, kCAMediaTimingFunctionEaseIn,
67    kCAMediaTimingFunctionEaseInEaseOut, kCAMediaTimingFunctionEaseOut,
68    kCAMediaTimingFunctionLinear,
69};
70
71use day_spec::ffi_guard;
72use day_spec::present;
73use day_spec::props::*;
74use day_spec::sidetable::SideTable;
75use day_spec::{
76    A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
77    InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
78    Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
79    WindowOptions, kinds, props_of,
80};
81
82pub type Handle = Retained<NSView>;
83
84/// Icon resolution for a piece renderer's own `NSToolbar` items (see `toolbar::image_for`).
85pub use toolbar::image_for as toolbar_image;
86
87// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
88mod dock;
89mod documents;
90mod frame;
91mod picker;
92mod status_item;
93mod textarea;
94mod toolbar;
95mod transfer;
96mod window_chrome;
97use objc2_app_kit::NSDraggingSource;
98
99pub mod ext;
100pub use ext::*;
101
102// ---------------------------------------------------------------------------
103// Event plumbing: node-id keyed sink, thread-local (single UI thread)
104// ---------------------------------------------------------------------------
105
106/// The day-core event sink (node-id keyed).
107type Sink = Rc<dyn Fn(NodeId, Event)>;
108
109day_core::tls_group! {
110    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
111    /// Keeps each control's `DayTarget` alive (target/action holds it weakly).
112    static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
113    /// The style each button currently carries, keyed by its view pointer.
114    ///
115    /// Needed because a tinted title is an attributed string (see `set_button_title`), and
116    /// `ButtonPatch::Title` would otherwise replace it with a plain one and lose the color.
117    static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
118        RefCell::new(HashMap::new());
119    /// Original template images, retained across tint changes and swept on view release.
120    static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
121    /// Each button's selected state (`ButtonProps::selected`), keyed by its view pointer: what
122    /// the `action:` handler restores after a click toggles a push-on/push-off button, and the
123    /// buttons whose `state` `read_native` reports as `checked`.
124    static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
125
126    /// Canvas ptr → its display list. A [`SideTable`], so the release sweep reclaims it
127    /// (replay inserted but nothing ever removed).
128    static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
129    /// Views the app gave an accessibility label (`set_a11y`): a button's title change must then
130    /// leave the label alone (`apply_button_content`). Swept on release like the other tables.
131    static APP_LABELED: SideTable<()> = SideTable::new();
132    /// How each image view renders its glyph (docs/vectors.md "Tint", "Template"): whether it
133    /// was realized as a template, and whether a tint is on it now. Template rendering is a
134    /// property of the NSImage, so a source swap has to re-apply it, and a tint patch of `None`
135    /// keeps a template in the neutral tint rather than returning to the authored art. Swept
136    /// on release.
137    static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
138    /// Each transformed view's `Transform` (`set_transform`). AppKit owns a layer-backed view's
139    /// layer geometry and re-syncs it from the view, so a transform written into the layer
140    /// never showed. It is expressed in the view's own geometry instead (`apply_geometry`).
141    static TRANSFORMS: SideTable<Transform> = SideTable::new();
142    /// Each view's frame as Day laid it out, before any translation, so a translation change can
143    /// move the view without waiting for the next layout.
144    static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
145    static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
146    /// A presented cover sheet's window → its cover node, for Escape (docs/cover.md).
147    static SHEET_NODES: SideTable<NodeId> = SideTable::new();
148    static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
149    /// View ptr → node for `GestureKind::Pan` (docs/shapes.md): macOS pans arrive as trackpad
150    /// scroll events, so `DayCanvas::scrollWheel:` reports them here instead of a recognizer.
151    static PAN_NODES: SideTable<NodeId> = SideTable::new();
152    static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
153    /// View ptr → node for `GestureKind::Hover` (docs/canvas.md "Interaction"). Hover is not a
154    /// recognizer on macOS either: it is an `NSTrackingArea` plus the three mouse methods, so
155    /// like [`PAN_NODES`] this holds the canvases that asked and `DayCanvas` reports for them.
156    static HOVER_NODES: SideTable<NodeId> = SideTable::new();
157    /// Canvas view ptr → its node, so the view's own `keyDown:` knows who to report to. Every
158    /// canvas is registered at realize (unlike [`PAN_NODES`], which only holds the ones that
159    /// asked for a pan) because focus, not a gesture, is what decides who hears a key.
160    static KEY_NODES: SideTable<NodeId> = SideTable::new();
161    /// Focusable container view ptr → its node (docs/focus.md): `Decorate::focusable` opts a
162    /// `DayFlipped` into the canvas contract (accepts first responder, takes focus on a
163    /// press, reports both directions, hears the arrows). Empty for every container that
164    /// never asked, whose behavior is exactly as before.
165    static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
166    /// Canvas view ptr → the text an input method is still composing in it (docs/menus.md
167    /// "The full route"): a dead key's accent, a Japanese reading. Nothing reaches the app
168    /// until the input method commits; the entry is gone the moment it does or cancels.
169    static MARKED: SideTable<String> = SideTable::new();
170    /// The key press the text input system is interpreting right now: its unmodified name and
171    /// the modifier mask, so the text it commits is named by the key that typed it.
172    static INTERPRETING: RefCell<Option<(String, u8)>> = const { RefCell::new(None) };
173
174    /// Keeps each view's gesture targets alive + records which gestures are attached (idempotent).
175    static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
176        RefCell::new(HashMap::new());
177
178    static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
179    /// Handles whose frames are native-owned (nav pages): set_frame skips them.
180    static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
181        RefCell::new(std::collections::HashSet::new());
182    /// Each nav page's pane, recorded at realize because `insert` sees only handles
183    /// (docs/size-classes.md). Identity rather than position: a re-present re-homes the pages
184    /// without changing their order, so "index 0 is the sidebar" stops being true the moment a
185    /// host can morph. A [`SideTable`]: `remove` clears it on the normal path, and the release
186    /// sweep catches a page released without one (a stale entry could mis-pane a recycled ptr).
187    static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
188
189    static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
190    /// INSPECTOR_PANE ptr → is-panel, recorded at realize because `insert` sees only handles.
191    /// A [`SideTable`]: the release sweep drops it with the view.
192    static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
193
194    /// Split host (the wrap around an `NSSplitView`, docs/split.md) ptr → its state.
195    static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
196    /// SPLIT_PANE ptr → is-second, recorded at realize because `insert` sees only handles.
197    static SPLIT_PANES: SideTable<bool> = SideTable::new();
198
199    /// Outline ptr → its data source, for [`DayNavOutlineView::menu_for_event`]'s row lookup.
200    /// A [`SideTable`], reclaimed by the outline-keyed auxiliary sweep in `release`: the entry
201    /// used to outlive its host, so a recycled outline address served the dead menu's rows.
202    static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
203
204    static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
205    /// Tree host scroll-view ptr → (outline, data source) (docs/tree.md).
206    static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
207
208    /// `BitmapId` → the decoded image (docs/images.md). Keyed by the id day-core minted, not by
209    /// a view pointer: a bitmap outlives any one view and may be drawn by several at once.
210    /// Entries leave only through `release_image`, which day-core calls when the app drops its
211    /// last `Bitmap` handle.
212    static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
213    /// View ptr → its summon-time context-menu provider (docs/menus.md). Swept on release
214    /// via `day_spec::sidetable`.
215    static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
216
217    /// NAV_MENU scroll-view ptr → (outline, data source) for patches and measure.
218    static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
219
220    /// The app's edit-bridge state (`set_edit_state`), which validateMenuItem consults.
221    static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
222        const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
223    static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
224        const { std::cell::RefCell::new(None) };
225
226    /// Live modal sheets keyed by request id (for programmatic dismissal).
227    static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
228        RefCell::new(HashMap::new());
229    /// Live file-picker sheets (NSOpenPanel is stored via its NSSavePanel supertype).
230    static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
231        RefCell::new(HashMap::new());
232
233    // NSMenuItem does not retain its target, so one shared target is kept alive for the app's
234    // lifetime.
235    static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
236        const { std::cell::RefCell::new(None) };
237    /// The primary window's content view, for call sites without backend access that must
238    /// address the main window specifically (cover re-homing, DAY_DUMP). With secondary
239    /// windows open, `app.windows().firstObject()` is arbitrary (docs/windows.md).
240    static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
241        const { std::cell::RefCell::new(None) };
242
243}
244
245/// Emit an event into day-core's queue (public: external Day Piece renderers use this too).
246pub fn emit(id: NodeId, ev: Event) {
247    let sink = SINK.with(|s| s.borrow().clone());
248    if let Some(sink) = sink {
249        sink(id, ev);
250    }
251}
252
253fn ptr_of(v: &NSView) -> usize {
254    (v as *const NSView).cast::<()>() as usize
255}
256
257/// An image view's rendering (`IMAGE_MODES`).
258#[derive(Clone, Copy)]
259struct ImageMode {
260    template: bool,
261    tinted: bool,
262}
263
264impl ImageMode {
265    /// Template rendering: the glyph's alpha as a mask, filled with the tint or the neutral
266    /// template color.
267    fn renders_template(self) -> bool {
268        self.template || self.tinted
269    }
270}
271
272/// A decoded bitmap (docs/images.md), held until day-core drops its last handle.
273///
274/// The `NSBitmapImageRep` is kept beside the image rather than fetched on demand for two
275/// reasons: it is the only thing here that can re-encode to other formats, and it is the only
276/// accurate source of pixel dimensions, since `NSImage.size` is in points and reports a @2x
277/// asset at half its real width.
278struct AppKitBitmap {
279    image: Retained<objc2_app_kit::NSImage>,
280    rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
281    info: day_spec::BitmapInfo,
282}
283
284/// Draw a decoded image into a fresh bitmap `scale`× its pixel size, for [`day_spec::EncodeSpec`]'s
285/// `fit`.
286///
287/// 8 bits across 4 samples with alpha is the one layout every writer here accepts, and the only
288/// one that carries transparency through a PNG round-trip intact.
289fn scaled_rep(
290    image: &objc2_app_kit::NSImage,
291    pixels: Size,
292    scale: f64,
293) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
294    use objc2::AllocAnyThread as _;
295    let w = (pixels.width * scale).round().max(1.0);
296    let h = (pixels.height * scale).round().max(1.0);
297    let rep = unsafe {
298        objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
299            objc2_app_kit::NSBitmapImageRep::alloc(),
300            std::ptr::null_mut(),
301            w as isize,
302            h as isize,
303            8,
304            4,
305            true,
306            false,
307            objc2_app_kit::NSDeviceRGBColorSpace,
308            0,
309            0,
310        )
311    }?;
312    let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
313    NSGraphicsContext::saveGraphicsState_class();
314    objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
315    unsafe {
316        image.drawInRect_fromRect_operation_fraction(
317            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
318            NSRect::ZERO,
319            objc2_app_kit::NSCompositingOperation::SourceOver,
320            1.0,
321        );
322    }
323    NSGraphicsContext::restoreGraphicsState_class();
324    Some(rep)
325}
326
327/// Re-encode a decoded bitmap (docs/images.md).
328///
329/// A free function rather than the duty's body so each refusal reads as an early return instead
330/// of another copy of the same emit.
331fn encode_bitmap(
332    id: day_spec::BitmapId,
333    spec: &day_spec::EncodeSpec,
334) -> Result<Vec<u8>, day_spec::ImageError> {
335    use day_spec::ImageFormat as F;
336    use objc2_app_kit::NSBitmapImageFileType as T;
337    let file_type = match spec.format {
338        F::Png => T::PNG,
339        F::Jpeg => T::JPEG,
340        F::Tiff => T::TIFF,
341        F::Bmp => T::BMP,
342        F::Gif => T::GIF,
343        // Readable here but not writable: `NSBitmapImageRep` ships no WebP or HEIF writer. That
344        // asymmetry is why `encode_formats` exists instead of letting `Cap::ImageEncode` imply
345        // that everything decodable is also encodable.
346        _ => return Err(day_spec::ImageError::Encode),
347    };
348    let held = BITMAPS.with(|m| {
349        m.borrow()
350            .get(&id.0)
351            .map(|b| (b.rep.clone(), b.image.clone(), b.info))
352    });
353    let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
354    let rep = rep.ok_or(day_spec::ImageError::Encode)?;
355
356    // `fit` scales the longest side down first. A box larger than the original is ignored:
357    // upscaling on an export path inflates the bytes without adding any detail.
358    let rep = match spec.fit {
359        Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
360            let scale = (fit.width / info.pixels.width)
361                .min(fit.height / info.pixels.height)
362                .min(1.0);
363            if scale < 1.0 {
364                scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
365            } else {
366                rep
367            }
368        }
369        _ => rep,
370    };
371
372    let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
373        // AppKit's own compression-factor property; a lossless writer ignores it.
374        Some(q) => {
375            let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
376            let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
377            let value: &objc2::runtime::AnyObject = &number;
378            NSDictionary::from_slices::<NSString>(&[key], &[value])
379        }
380        None => NSDictionary::new(),
381    };
382    let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
383        .ok_or(day_spec::ImageError::Encode)?;
384    Ok(data.to_vec())
385}
386
387/// Replay a display list into the current graphics context. The one painter both the on-screen
388/// `DayCanvas` (its `drawRect:`) and the canvas exports run, so the two cannot drift apart
389/// (docs/canvas.md "Exporting").
390fn paint_ops(ops: &[DrawOp]) {
391    for op in ops {
392        draw_op(op);
393    }
394}
395
396/// Paint `ops` into `cg` with a top-left origin and y down, as the flipped `DayCanvas` sees
397/// them. `height` is the context's own height in its base units (pixels for a bitmap, points for
398/// a PDF page) and `scale` its units per canvas point.
399///
400/// The CTM flip turns the geometry the right way up; wrapping the context as a FLIPPED
401/// `NSGraphicsContext` is what tells AppKit's text and image drawing to keep glyphs and pictures
402/// upright inside that flip, exactly as they are in a flipped view's `drawRect:`.
403fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
404    use objc2_core_graphics::CGContext;
405    CGContext::save_g_state(Some(cg));
406    CGContext::translate_ctm(Some(cg), 0.0, height);
407    CGContext::scale_ctm(Some(cg), scale, -scale);
408    let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
409    NSGraphicsContext::saveGraphicsState_class();
410    NSGraphicsContext::setCurrentContext(Some(&ns));
411    paint_ops(ops);
412    NSGraphicsContext::restoreGraphicsState_class();
413    CGContext::restore_g_state(Some(cg));
414}
415
416/// Render a canvas display list offscreen (docs/canvas.md "Exporting"): `export_pixels` of
417/// transparent sRGB, premultiplied RGBA, painted at `scale` pixels per point.
418///
419/// A `CGBitmapContext` rather than `NSGraphicsContext(bitmapImageRep:)`: it carries a real sRGB
420/// color space, so the `NSBitmapImageRep` built from its image is tagged sRGB like every canvas
421/// color, shows on the display through the same color matching the live canvas gets, and writes
422/// that profile into a PNG.
423fn render_bitmap_image(
424    ops: &[DrawOp],
425    size: Size,
426    scale: f64,
427) -> Result<AppKitBitmap, day_spec::ExportError> {
428    use objc2::AllocAnyThread as _;
429    use objc2_core_graphics::{
430        CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
431    };
432    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
433    let (pw, ph) = day_spec::export_pixels(size, scale);
434    // SAFETY: `kCGColorSpaceSRGB` is an immutable CoreGraphics constant, valid for the process.
435    let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
436        .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
437    // SAFETY: a null data pointer asks CoreGraphics to allocate (and own) the buffer, and a zero
438    // row stride lets it choose one; 8 bits × RGBA premultiplied is a supported layout.
439    let cg = unsafe {
440        CGBitmapContextCreate(
441            std::ptr::null_mut(),
442            pw as usize,
443            ph as usize,
444            8,
445            0,
446            Some(&space),
447            CGImageAlphaInfo::PremultipliedLast.0,
448        )
449    }
450    .ok_or_else(|| {
451        day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
452    })?;
453    // A new bitmap context starts zeroed, which is the transparent background.
454    paint_flipped(&cg, ph as f64, scale, ops);
455    let cg_image = CGBitmapContextCreateImage(Some(&cg))
456        .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))?;
457    let rep = unsafe {
458        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
459            objc2_app_kit::NSBitmapImageRep::alloc(),
460            &cg_image,
461        )
462    };
463    // Sized in POINTS, pixels over scale, so the image draws at the drawing's size and stays
464    // sharp at `scale`× — the same shape as a staged @2x asset.
465    let points = NSSize::new(pw as f64 / scale, ph as f64 / scale);
466    unsafe { rep.setSize(points) };
467    let image =
468        unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
469    unsafe { image.addRepresentation(&rep) };
470    Ok(AppKitBitmap {
471        image,
472        rep: Some(rep),
473        info: day_spec::BitmapInfo {
474            pixels: Size::new(pw as f64, ph as f64),
475            scale,
476            format: None,
477            has_alpha: true,
478        },
479    })
480}
481
482/// Write `pages` as one PDF document (docs/canvas.md "Exporting"): a `CGPDFContext` on a
483/// `CGDataConsumer` over memory, one page per drawing with its own media box, the title and
484/// author in the document info. Shapes and text stay vector: the same painter draws into the PDF
485/// context, and AppKit's string drawing there emits real glyphs from embedded font subsets.
486fn render_pdf_bytes(
487    pages: &[day_spec::PdfPage],
488    info: &day_spec::PdfInfo,
489) -> Result<Vec<u8>, day_spec::ExportError> {
490    use objc2_core_foundation::{
491        CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
492    };
493    use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
494    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
495    let media =
496        |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
497    let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
498    let data = CFMutableData::new(None, 0)
499        .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
500    let consumer = CGDataConsumer::with_cf_data(Some(&data))
501        .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
502
503    let mut keys: Vec<&CFString> = Vec::new();
504    let mut values: Vec<CFRetained<CFString>> = Vec::new();
505    // SAFETY: the auxiliary-info keys are immutable CoreGraphics constants.
506    let (title_key, author_key) = unsafe {
507        (
508            objc2_core_graphics::kCGPDFContextTitle,
509            objc2_core_graphics::kCGPDFContextAuthor,
510        )
511    };
512    for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
513        if let Some(value) = value {
514            keys.push(key);
515            values.push(CFString::from_str(value));
516        }
517    }
518    let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
519    let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
520
521    let first_box = media(first.size);
522    // SAFETY: `first_box` outlives the call, and the dictionary maps the documented
523    // auxiliary-info string keys to strings, which is the type those keys take.
524    let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
525        .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
526    for page in pages {
527        let page_box = media(page.size);
528        // SAFETY: `page_box` outlives the call; in a PDF context it becomes the page's MediaBox.
529        unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
530        paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
531        CGContext::end_page(Some(&pdf));
532    }
533    // Closing flushes the trailer into the consumer; the bytes are complete only after it.
534    CGPDFContextClose(Some(&pdf));
535    drop(pdf);
536    drop(consumer);
537    Ok(data.to_vec())
538}
539
540thread_local! {
541    /// Each realized list item's current props, by its view: a patch updates one part and the
542    /// item is re-dressed from the whole (docs/list.md "List items").
543    static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
544        std::cell::RefCell::new(std::collections::HashMap::new());
545}
546
547/// A list row's standard content (docs/list.md "List items"), as an image-and-text table cell
548/// draws it: a 16pt template image, the title in the system font with a smaller secondary
549/// subtitle under it, a secondary trailing value, and the accent checkmark, in a horizontal
550/// stack at least 28pt tall. Parts that are absent are hidden, and the stack closes up around
551/// them.
552///
553/// The row's width is spoken for explicitly, as an image-and-text cell's is: the stack fills
554/// its frame edge to edge, the words take every spare point and give way first, and the
555/// trailing parts keep their own size. Left to the stack's default gravity areas, the spare
556/// width had two equally weak claims, the words' column and the gap before the trailing parts,
557/// so Auto Layout settled it from whatever the row's last layout had been: a checkmark landed
558/// beside the title in one row and at the trailing edge in the next, and stayed put.
559fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
560    use objc2_app_kit::{
561        NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
562    };
563    let label = |text: &str, size: f64, secondary: bool| {
564        let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
565        unsafe {
566            tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
567            if secondary {
568                tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
569            }
570            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
571        }
572        tf
573    };
574    let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
575    let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
576    const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
577        objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
578    // Hugging: the words stretch (1), the trailing parts hold their size (750), and the stack
579    // keeps its edges on its first and last parts (750), so exactly one part takes the slack.
580    const STRETCH: f32 = 1.0;
581    const HOLD: f32 = 750.0;
582    let stack = NSStackView::new(mtm);
583    stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
584    stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
585    stack.setAlignment(NSLayoutAttribute::CenterY);
586    stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
587    stack.setSpacing(6.0);
588    // A table row's breathing room above and below; the list gives the sides.
589    stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
590        top: 4.0,
591        left: 0.0,
592        bottom: 4.0,
593        right: 0.0,
594    });
595    let icon = unsafe { NSImageView::new(mtm) };
596    unsafe {
597        icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
598        icon.widthAnchor()
599            .constraintEqualToConstant(16.0)
600            .setActive(true);
601        icon.heightAnchor()
602            .constraintEqualToConstant(16.0)
603            .setActive(true);
604    }
605    stack.addArrangedSubview(&icon);
606    // The title and subtitle span the words' column (Width alignment), so the column's width is
607    // theirs and nothing is left over inside it.
608    let texts = NSStackView::new(mtm);
609    texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
610    texts.setAlignment(NSLayoutAttribute::Width);
611    texts.setSpacing(1.0);
612    // Its height is its lines', centered in the row, not the row's height with the lines
613    // floating somewhere inside it.
614    texts.setHuggingPriority_forOrientation(
615        HOLD,
616        objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
617    );
618    let title = label("", size, false);
619    let subtitle = label("", small, true);
620    // The words take the width and give way first, truncating, before the trailing parts.
621    for line in [&title, &subtitle] {
622        line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
623        line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
624    }
625    texts.addArrangedSubview(&title);
626    texts.addArrangedSubview(&subtitle);
627    stack.addArrangedSubview(&texts);
628    let detail = label("", size, true);
629    detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
630    detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
631    stack.addArrangedSubview(&detail);
632    let check = unsafe { NSImageView::new(mtm) };
633    unsafe {
634        check.setImage(
635            objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
636                &NSString::from_str("checkmark"),
637                None,
638            )
639            .as_deref(),
640        );
641        check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
642    }
643    check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
644    check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
645    stack.addArrangedSubview(&check);
646    let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
647    LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
648    dress_list_item(&view, p, mtm);
649    view
650}
651
652/// Show `p` on a list item's stack (see [`make_list_item`]), as one accessibility element.
653fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
654    use objc2_app_kit::{NSImageView, NSStackView};
655    let Some(stack) = view.downcast_ref::<NSStackView>() else {
656        return;
657    };
658    let parts = stack.arrangedSubviews();
659    if parts.len() < 4 {
660        return;
661    }
662    let icon = parts.objectAtIndex(0);
663    if let Some(iv) = icon.downcast_ref::<NSImageView>() {
664        let image = p
665            .icon
666            .as_ref()
667            .and_then(|i| toolbar::image_for(i, &p.title, mtm));
668        unsafe {
669            iv.setImage(image.as_deref());
670            iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
671        }
672    }
673    icon.setHidden(p.icon.is_none());
674    if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
675        let lines = texts.arrangedSubviews();
676        if lines.len() == 2 {
677            if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
678                tf.setStringValue(&NSString::from_str(&p.title));
679            }
680            let sub = lines.objectAtIndex(1);
681            if let Some(tf) = sub.downcast_ref::<NSTextField>() {
682                tf.setStringValue(&NSString::from_str(&p.subtitle));
683            }
684            sub.setHidden(p.subtitle.is_empty());
685        }
686    }
687    let detail = parts.objectAtIndex(2);
688    if let Some(tf) = detail.downcast_ref::<NSTextField>() {
689        tf.setStringValue(&NSString::from_str(&p.detail));
690    }
691    detail.setHidden(p.detail.is_empty());
692    parts.objectAtIndex(3).setHidden(!p.checked);
693    let words = [&p.title, &p.subtitle, &p.detail]
694        .into_iter()
695        .filter(|w| !w.is_empty())
696        .map(String::as_str)
697        .collect::<Vec<_>>()
698        .join(", ");
699    unsafe {
700        view.setAccessibilityElement(true);
701        view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
702        view.setAccessibilitySelected(p.checked);
703    }
704}
705
706/// The `NSImage` behind an [`day_spec::ImageSource`] (docs/images.md).
707///
708/// Shared by realize and the `Source` patch: a swapped source must load exactly what a fresh
709/// realize would have, or a piece would show different pixels depending on whether it was
710/// built or updated.
711fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
712    use objc2::AllocAnyThread as _;
713    match source {
714        // A vector glyph's SVG first (docs/vectors.md): NSImage renders SVG at display size
715        // (macOS 11+), so vectors stay vector with no build-time raster resampling. Then the
716        // shared image-file resolver (images/ then assets/ then bundle), which is macOS's native
717        // path: a bundle file loaded straight into NSImage (§18.3).
718        day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
719            .or_else(|| day_spec::resource::resolve_image_file(name))
720            .and_then(|path| unsafe {
721                objc2_app_kit::NSImage::initWithContentsOfFile(
722                    objc2_app_kit::NSImage::alloc(),
723                    &NSString::from_str(&path.to_string_lossy()),
724                )
725            }),
726        // Bytes the app already holds (a download, a picked file, a paste) with no staged
727        // resource behind them.
728        day_spec::ImageSource::Bytes(bytes) => unsafe {
729            objc2_app_kit::NSImage::initWithData(
730                objc2_app_kit::NSImage::alloc(),
731                &NSData::with_bytes(bytes),
732            )
733        },
734        // Already decoded: share the one NSImage rather than parsing the same bytes twice.
735        day_spec::ImageSource::Decoded(id) => {
736            BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
737        }
738    }
739}
740
741/// Day `Role` → the `NSAccessibilityRole` constant to apply (§13). `None` for `Role::None`:
742/// Day leaves native controls' roles untouched and only applies explicit canvas/custom roles.
743fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
744    use day_spec::Role;
745    use objc2_app_kit::{
746        NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
747        NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
748        NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
749        NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
750    };
751    unsafe {
752        Some(match role {
753            Role::Button => NSAccessibilityButtonRole,
754            Role::Toggle => NSAccessibilityCheckBoxRole,
755            // A tab is a radio button with the tab-button subrole (`set_a11y` adds it), which
756            // is how NSTabView's own tabs read to VoiceOver; the strip is a tab group.
757            Role::Tab => NSAccessibilityRadioButtonRole,
758            Role::TabList => NSAccessibilityTabGroupRole,
759            Role::Slider => NSAccessibilitySliderRole,
760            Role::TextInput => NSAccessibilityTextFieldRole,
761            // `AXHeading` lands the label in VoiceOver's headings rotor. The level has no
762            // AppKit attribute of its own: the only convention (the level as `AXValue`) would
763            // displace the text an NSTextField reports as its value, so the level stays
764            // unspoken.
765            Role::Heading(_) => NSAccessibilityHeadingRole,
766            Role::Image => NSAccessibilityImageRole,
767            Role::Meter => NSAccessibilityLevelIndicatorRole,
768            Role::Group => NSAccessibilityGroupRole,
769            // NSOutlineView already reports these itself; the mapping is for the audit's
770            // expectation and for any composed stand-in (docs/tree.md).
771            Role::Tree => NSAccessibilityOutlineRole,
772            Role::TreeItem => NSAccessibilityRowRole,
773            Role::None => return None,
774        })
775    }
776}
777
778/// Native `AXRole` string → Day `Role` (best-effort, for `read_native`/`a11y_audit`).
779fn day_role_from_ns(ax: &str) -> day_spec::Role {
780    use day_spec::Role;
781    match ax {
782        "AXButton" => Role::Button,
783        "AXCheckBox" => Role::Toggle,
784        "AXSlider" => Role::Slider,
785        "AXTextField" => Role::TextInput,
786        // Plain text is ambiguous with a heading, and neither carries a level; the audit
787        // ignores the level either way.
788        "AXStaticText" | "AXHeading" => Role::Heading(0),
789        "AXOutline" => Role::Tree,
790        "AXImage" => Role::Image,
791        "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
792        "AXGroup" => Role::Group,
793        "AXRadioButton" => Role::Tab,
794        "AXTabGroup" => Role::TabList,
795        _ => Role::None,
796    }
797}
798
799// ---------------------------------------------------------------------------
800// DayTarget: target/action + text delegate trampoline
801// ---------------------------------------------------------------------------
802
803struct TargetIvars {
804    node: NodeId,
805}
806
807define_class!(
808    #[unsafe(super(NSObject))]
809    #[thread_kind = MainThreadOnly]
810    #[name = "DayTarget"]
811    #[ivars = TargetIvars]
812    struct DayTarget;
813
814    unsafe impl NSObjectProtocol for DayTarget {}
815    unsafe impl NSTextFieldDelegate for DayTarget {}
816
817    /// A tabs host's `NSTabView` (docs/navigation.md). A pick emits against the NAV_MENU's
818    /// node, exactly as the sidebar's outline view does, so as far as everything above this
819    /// backend is concerned, picking a tab and clicking a sidebar row are the same event, and
820    /// neither the pieces layer nor dayscript needs to know which chrome the window wears.
821    unsafe impl NSTabViewDelegate for DayTarget {
822        #[unsafe(method(tabView:didSelectTabViewItem:))]
823        fn tab_view_did_select(
824            &self,
825            tab_view: &objc2_app_kit::NSTabView,
826            item: Option<&objc2_app_kit::NSTabViewItem>,
827        ) {
828            ffi_guard::contain((), || {
829                if TAB_PICK_SUPPRESS.with(|s| s.get()) {
830                    return;
831                }
832                if let Some(item) = item {
833                    let idx = unsafe { tab_view.indexOfTabViewItem(item) };
834                    if idx >= 0 {
835                        emit(self.ivars().node, Event::SelectionChanged(idx as i64));
836                    }
837                }
838            })
839        }
840    }
841
842    impl DayTarget {
843        // Every trampoline that dispatches into the sink (and through it, app handlers) runs
844        // its body through `ffi_guard::contain` (§8.5): a Rust panic unwinding out of an ObjC
845        // frame is an abort, so it is caught, reported, and the reactive runtime recovered.
846        // The same guard wraps every other target/delegate entry in this backend.
847        #[unsafe(method(action:))]
848        fn action(&self, sender: &NSControl) {
849            ffi_guard::contain((), || {
850                let node = self.ivars().node;
851                if sender.downcast_ref::<NSSwitch>().is_some() {
852                    emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
853                } else if sender.downcast_ref::<NSSlider>().is_some() {
854                    let value = unsafe { sender.doubleValue() };
855                    // The live value first: bindings follow this, so the UI tracks the thumb.
856                    emit(node, Event::ValueChanged(value));
857                    // Then, once, the value the user settled on. The slider is `continuous`, so
858                    // this action fires on every tick of a drag; AppKit's way to tell where in the
859                    // gesture you are is the event that provoked it. A mouse-up ends a drag; a key
860                    // press (arrow keys) moves the value by one discrete step and is already settled;
861                    // anything else (mouse-down, mouse-dragged) is mid-gesture and commits nothing.
862                    if slider_value_settled() {
863                        emit(node, Event::ValueCommitted(value));
864                    }
865                } else {
866                    emit(node, Event::Pressed);
867                    // A push-on/push-off button toggled its state on the click; Day owns the
868                    // selected state (`set_button_selected`), so put back what it last asked.
869                    let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
870                    if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
871                        unsafe {
872                            btn.setState(if on {
873                                NSControlStateValueOn
874                            } else {
875                                NSControlStateValueOff
876                            })
877                        };
878                    }
879                }
880            })
881        }
882
883        /// The stack-nav back header's button (docs/navigation.md): a day-initiated pop. The
884        /// nav host's handler writes it into the path signal, which reconciles the pop.
885        #[unsafe(method(navBack:))]
886        fn nav_back(&self, _sender: &NSControl) {
887            ffi_guard::contain((), || {
888                emit(
889                    self.ivars().node,
890                    Event::NavBack {
891                        already_popped: false,
892                    },
893                );
894            })
895        }
896    }
897
898    unsafe impl NSControlTextEditingDelegate for DayTarget {
899        #[unsafe(method(controlTextDidChange:))]
900        fn control_text_did_change(&self, notification: &NSNotification) {
901            ffi_guard::contain((), || {
902                let node = self.ivars().node;
903                if let Some(obj) = unsafe { notification.object() }
904                    && let Ok(tf) = obj.downcast::<NSTextField>() {
905                        emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
906                    }
907            })
908        }
909
910        /// End of an editing session (docs/focus.md). Return submits: AppKit keeps the field
911        /// first responder and re-selects, so it is not a focus loss; every other movement
912        /// (tab, click-away, cancel) reports `FocusChanged(false)`.
913        #[unsafe(method(controlTextDidEndEditing:))]
914        fn control_text_did_end_editing(&self, notification: &NSNotification) {
915            ffi_guard::contain((), || {
916                let node = self.ivars().node;
917                let movement = unsafe { notification.userInfo() }
918                    .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
919                    .and_then(|n| n.downcast::<NSNumber>().ok())
920                    .map(|n| NSTextMovement(n.integerValue()))
921                    .unwrap_or(NSTextMovement::Other);
922                if movement == NSTextMovement::Return {
923                    emit(node, Event::Submitted);
924                } else {
925                    emit(node, Event::FocusChanged(false));
926                }
927            })
928        }
929    }
930);
931
932impl DayTarget {
933    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
934        let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
935        unsafe { msg_send![super(this), init] }
936    }
937}
938
939// ---------------------------------------------------------------------------
940// DayCursorOwner: the `.cursor()` decorator's tracking-area owner (docs/cursor.md)
941// ---------------------------------------------------------------------------
942
943struct CursorIvars {
944    /// The shape to set on `cursorUpdate:`; `None` leaves the platform's own choice.
945    cursor: RefCell<Option<Retained<NSCursor>>>,
946    /// `Cursor::None`: hide the pointer while it is inside, unhide on exit.
947    hidden: Cell<bool>,
948    /// Whether this owner is the one that hid the pointer (balanced by `unhide`).
949    hiding: Cell<bool>,
950}
951
952// AppKit only re-evaluates the pointer's shape on `cursorUpdate:`, which it sends to a
953// tracking area's owner when the pointer enters the area (and on request through
954// `invalidateCursorRectsForView:`). One owner per view keeps the view class untouched: a label,
955// a button, or a plain container all get the same treatment without subclassing. Nested areas
956// resolve by entry order: the innermost is entered last, so its shape is the one that stays.
957define_class!(
958    #[unsafe(super(NSObject))]
959    #[thread_kind = MainThreadOnly]
960    #[name = "DayCursorOwner"]
961    #[ivars = CursorIvars]
962    struct DayCursorOwner;
963
964    unsafe impl NSObjectProtocol for DayCursorOwner {}
965
966    impl DayCursorOwner {
967        #[unsafe(method(cursorUpdate:))]
968        fn cursor_update(&self, _event: &NSEvent) {
969            let iv = self.ivars();
970            if iv.hidden.get() {
971                if !iv.hiding.replace(true) {
972                    NSCursor::hide();
973                }
974                return;
975            }
976            if let Some(c) = iv.cursor.borrow().as_ref() {
977                c.set();
978            }
979        }
980
981        #[unsafe(method(mouseExited:))]
982        fn mouse_exited(&self, _event: &NSEvent) {
983            if self.ivars().hiding.replace(false) {
984                NSCursor::unhide();
985            }
986        }
987    }
988);
989
990impl DayCursorOwner {
991    fn new(mtm: MainThreadMarker) -> Retained<Self> {
992        let this = Self::alloc(mtm).set_ivars(CursorIvars {
993            cursor: RefCell::new(None),
994            hidden: Cell::new(false),
995            hiding: Cell::new(false),
996        });
997        unsafe { msg_send![super(this), init] }
998    }
999}
1000
1001/// The `NSCursor` for a [`Cursor`], or `None` where the platform's own choice should stand
1002/// (`Cursor::None`, which the owner hides instead, and a native name AppKit does not have).
1003/// AppKit has no wait, progress, help, or move shape, so those take the arrow; the zoom, frame
1004/// (diagonal) resize, and column/row resize cursors arrived in macOS 15 and are probed by
1005/// nav host, with the nearest older shape below it.
1006// `resizeLeftRightCursor` and `resizeUpDownCursor` are deprecated in favor of the macOS 15
1007// column/row resize cursors, which are probed above them; below 15 they are the shape.
1008#[allow(deprecated)]
1009fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1010    let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1011    Some(match c {
1012        Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1013        Cursor::Pointer => NSCursor::pointingHandCursor(),
1014        Cursor::Text => NSCursor::IBeamCursor(),
1015        Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1016        Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1017        Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1018        Cursor::Grabbing => NSCursor::closedHandCursor(),
1019        Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1020        Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1021        Cursor::Copy => NSCursor::dragCopyCursor(),
1022        Cursor::Alias => NSCursor::dragLinkCursor(),
1023        Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1024        Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1025        Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1026        Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1027        Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1028        Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1029            NSCursor::frameResizeCursorFromPosition_inDirections(
1030                NSCursorFrameResizePosition::TopRight,
1031                NSCursorFrameResizeDirections::All,
1032            )
1033        }
1034        Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1035            NSCursor::frameResizeCursorFromPosition_inDirections(
1036                NSCursorFrameResizePosition::TopLeft,
1037                NSCursorFrameResizeDirections::All,
1038            )
1039        }
1040        Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1041        Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1042        Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1043        Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1044        Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1045        Cursor::None => return None,
1046        Cursor::Native(name) => match &**name {
1047            "disappearingItem" => NSCursor::disappearingItemCursor(),
1048            "dragCopy" => NSCursor::dragCopyCursor(),
1049            "dragLink" => NSCursor::dragLinkCursor(),
1050            "contextualMenu" => NSCursor::contextualMenuCursor(),
1051            "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1052            _ => return None,
1053        },
1054    })
1055}
1056
1057/// Whether the NSEvent currently being dispatched ends a slider's interaction (see the
1058/// `ValueCommitted` emission in `DayTarget::action:`). AppKit gives a continuous slider no
1059/// "drag ended" callback, so the event that provoked the action is what says where in the gesture
1060/// we are: a mouse-up ends a drag, an arrow key moves one discrete step and is already settled,
1061/// and mouse-down/mouse-dragged are mid-gesture. No current event at all (a programmatic
1062/// `setDoubleValue:` that fires the action) is not a user commit either.
1063fn slider_value_settled() -> bool {
1064    let Some(mtm) = MainThreadMarker::new() else {
1065        return false;
1066    };
1067    let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1068        return false;
1069    };
1070    matches!(
1071        unsafe { event.r#type() },
1072        NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1073    )
1074}
1075
1076// ---------------------------------------------------------------------------
1077// DayTextField: NSTextField that reports focus gain (docs/focus.md)
1078// ---------------------------------------------------------------------------
1079
1080struct FieldIvars {
1081    node: NodeId,
1082}
1083
1084define_class!(
1085    #[unsafe(super(NSTextField))]
1086    #[thread_kind = MainThreadOnly]
1087    #[name = "DayTextField"]
1088    #[ivars = FieldIvars]
1089    struct DayTextField;
1090
1091    impl DayTextField {
1092        /// Focus gain. Key events go to the shared field editor, but the field itself receives
1093        /// `becomeFirstResponder` first, the reliable gain hook (`controlTextDidBeginEditing:`
1094        /// waits for the first keystroke). Loss comes from `controlTextDidEndEditing:` on the
1095        /// delegate.
1096        #[unsafe(method(becomeFirstResponder))]
1097        fn become_first_responder(&self) -> bool {
1098            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1099            if ok {
1100                field_gained_focus(self.ivars().node);
1101            }
1102            ok
1103        }
1104    }
1105);
1106
1107impl DayTextField {
1108    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1109        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1110        unsafe { msg_send![super(this), init] }
1111    }
1112}
1113
1114// The secure twin (docs/textfield.md). AppKit hides characters with a class, not a property:
1115// `NSSecureTextField` brings its own cell and field editor, which keep the text out of the
1116// pasteboard, the spelling checker and the accessibility value. A `text_field` that turns
1117// `secure` is rebuilt as this class (`set_input_traits`), with the same focus hook.
1118define_class!(
1119    #[unsafe(super(NSSecureTextField))]
1120    #[thread_kind = MainThreadOnly]
1121    #[name = "DaySecureTextField"]
1122    #[ivars = FieldIvars]
1123    struct DaySecureTextField;
1124
1125    impl DaySecureTextField {
1126        /// Focus gain, as on `DayTextField`.
1127        #[unsafe(method(becomeFirstResponder))]
1128        fn become_first_responder(&self) -> bool {
1129            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1130            if ok {
1131                field_gained_focus(self.ivars().node);
1132            }
1133            ok
1134        }
1135    }
1136);
1137
1138impl DaySecureTextField {
1139    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1140        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1141        unsafe { msg_send![super(this), init] }
1142    }
1143}
1144
1145thread_local! {
1146    /// A plain/secure class swap in flight (`set_input_traits`): focus moves from the old
1147    /// field to its replacement, which the app must not see as a focus change.
1148    static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1149}
1150
1151/// Report a text field's focus gain, unless it is a class swap handing focus to the
1152/// replacement of a field that already had it.
1153fn field_gained_focus(node: NodeId) {
1154    if FIELD_SWAP.with(|s| s.get()) {
1155        return;
1156    }
1157    // Guard only the sink dispatch: the responder change already happened, so a contained
1158    // panic must not flip the answer AppKit acts on.
1159    ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1160}
1161
1162/// The node a `text_field`'s view reports against, or `None` when the view is not one
1163/// (a label is an `NSTextField` too).
1164fn text_field_node(v: &NSView) -> Option<NodeId> {
1165    v.downcast_ref::<DayTextField>()
1166        .map(|f| f.ivars().node)
1167        .or_else(|| {
1168            v.downcast_ref::<DaySecureTextField>()
1169                .map(|f| f.ivars().node)
1170        })
1171}
1172
1173/// Build a `text_field`'s view, plain or secure, with its delegate wired and registered.
1174/// `realize` and the class swap in `set_input_traits` both come through here, so both classes
1175/// report text, submit and focus the same way against the same node.
1176fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1177    let target = DayTarget::new(mtm, node);
1178    // Up to `NSTextField` (the declared superclass of both), so the AsRef<NSView> bound on
1179    // `view_of` resolves and every `NSTextField` downcast sees either class.
1180    let tf: Retained<NSTextField> = if secure {
1181        Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1182    } else {
1183        Retained::into_super(DayTextField::new(mtm, node))
1184    };
1185    unsafe {
1186        tf.setEditable(true);
1187        tf.setBezeled(true);
1188        tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1189    }
1190    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1191    tf
1192}
1193
1194/// Whether `h` (a text field, or the field editor's client) holds its window's focus. A
1195/// focused `NSTextField`'s first responder is the shared field editor, so unwrap it back to
1196/// the field via its delegate.
1197fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1198    window.firstResponder().is_some_and(|fr| {
1199        if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
1200            return true;
1201        }
1202        fr.downcast::<NSText>().is_ok_and(|text| {
1203            unsafe { text.delegate() }
1204                .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
1205        })
1206    })
1207}
1208
1209/// An `NSTextContentType` constant by symbol name, or `None` on a system that predates it.
1210/// Looked up at run time because most of the vocabulary arrived in macOS 14: a direct
1211/// reference binds at launch, and one missing symbol would keep the whole app from starting
1212/// on an older system.
1213fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1214    unsafe extern "C" {
1215        fn dlsym(
1216            handle: *mut std::ffi::c_void,
1217            symbol: *const std::ffi::c_char,
1218        ) -> *mut std::ffi::c_void;
1219    }
1220    // <dlfcn.h>: search every image loaded in the process.
1221    const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1222    // SAFETY: `symbol` is NUL-terminated. Each name passed here is an AppKit
1223    // `NSString * const`, so a non-null result is the address of a pointer to an immortal
1224    // constant string.
1225    unsafe {
1226        let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1227        if slot.is_null() {
1228            None
1229        } else {
1230            (*slot).as_ref()
1231        }
1232    }
1233}
1234
1235/// Move a view-keyed entry to the view that replaces it.
1236fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1237    if let Some(v) = table.take(old) {
1238        table.insert(new, v);
1239    }
1240}
1241
1242/// A label is the shared field editor's delegate. AppKit does not forward
1243/// `textView:clickedOnLink:atIndex:` to an NSTextField's separate control delegate, so the
1244/// label itself must handle it to prevent the field editor from opening the target externally.
1245/// See Apple's "Working With the Field Editor" and docs/text-runs.md.
1246struct LabelIvars {
1247    node: NodeId,
1248    has_links: Cell<bool>,
1249    has_runs: Cell<bool>,
1250    selectable: Cell<bool>,
1251}
1252
1253define_class!(
1254    #[unsafe(super(NSTextField))]
1255    #[thread_kind = MainThreadOnly]
1256    #[name = "DayLabel"]
1257    #[ivars = LabelIvars]
1258    struct DayLabel;
1259
1260    impl DayLabel {
1261        #[unsafe(method_id(menuForEvent:))]
1262        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1263            ffi_guard::contain(None, || {
1264                if !self.isSelectable()
1265                    && let Some(menu) = inherited_context_menu(self, event)
1266                {
1267                    return menu;
1268                }
1269                unsafe { msg_send![super(self), menuForEvent: event] }
1270            })
1271        }
1272
1273        #[unsafe(method(drawRect:))]
1274        fn draw_rect(&self, dirty: NSRect) {
1275            // AppKit cannot propagate a table cell's background style through arbitrary
1276            // Day containers. Resolve selection at paint time so keyboard focus, window
1277            // activation, and cell reuse all use the actual native row state.
1278            let mut ancestor = unsafe { self.superview() };
1279            let mut selection_color = None;
1280            if !self.ivars().has_runs.get() {
1281                while let Some(view) = ancestor {
1282                    if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1283                        if unsafe { row.isSelected() } {
1284                            selection_color = Some(unsafe {
1285                                if row.isEmphasized() {
1286                                    objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1287                                } else {
1288                                    objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1289                                }
1290                            });
1291                        }
1292                        break;
1293                    }
1294                    ancestor = unsafe { view.superview() };
1295                }
1296            }
1297            let cell = unsafe { self.cell() }
1298                .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1299            if let (Some(color), Some(cell)) = (selection_color, cell) {
1300                let original = unsafe { cell.textColor() };
1301                // Mutate the cell only for this paint; changing the field would invalidate
1302                // the view again. Keep the app's normal color for deselection and reuse.
1303                unsafe {
1304                    cell.setTextColor(Some(&color));
1305                    let _: () = msg_send![super(self), drawRect: dirty];
1306                    cell.setTextColor(original.as_deref());
1307                }
1308            } else {
1309                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1310            }
1311        }
1312    }
1313
1314    unsafe impl NSObjectProtocol for DayLabel {}
1315    unsafe impl NSTextDelegate for DayLabel {}
1316
1317    unsafe impl NSTextViewDelegate for DayLabel {
1318        #[unsafe(method(textView:clickedOnLink:atIndex:))]
1319        fn clicked_on_link(
1320            &self,
1321            _tv: &NSTextView,
1322            link: &objc2::runtime::AnyObject,
1323            _index: usize,
1324        ) -> bool {
1325            ffi_guard::contain(true, || {
1326                // NSString targets stay verbatim (including #route); accept NSURL too.
1327                let url: Retained<NSString> = unsafe { msg_send![link, description] };
1328                emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1329                true // Handled: AppKit must never also open the target itself.
1330            })
1331        }
1332    }
1333);
1334
1335impl DayLabel {
1336    fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1337        let this = Self::alloc(mtm).set_ivars(LabelIvars {
1338            node,
1339            has_links: Cell::new(false),
1340            has_runs: Cell::new(false),
1341            selectable: Cell::new(false),
1342        });
1343        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1344        unsafe {
1345            this.setStringValue(&NSString::from_str(text));
1346            this.setEditable(false);
1347            this.setSelectable(false);
1348            this.setBordered(false);
1349            this.setBezeled(false);
1350            this.setDrawsBackground(false);
1351        }
1352        this
1353    }
1354
1355    fn set_links(&self, has_links: bool) {
1356        self.ivars().has_links.set(has_links);
1357        unsafe {
1358            self.setSelectable(has_links || self.ivars().selectable.get());
1359            self.setAllowsEditingTextAttributes(has_links);
1360        }
1361    }
1362}
1363
1364struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1365impl Drop for PanMonitor {
1366    fn drop(&mut self) {
1367        unsafe { NSEvent::removeMonitor(&self.0) };
1368    }
1369}
1370
1371// Escape closes a cover's window sheet, as it cancels any sheet on macOS (docs/cover.md
1372// "Modal sheet"): the cover hears it as its back request. A local monitor, because the key
1373// window's first responder may be a web view or a field that keeps Escape to itself. A sheet
1374// with its own sheet or alert over it, and app-modal panels, keep their Escape.
1375fn install_sheet_escape_monitor() {
1376    SHEET_ESCAPE_MONITOR.with(|slot| {
1377        if slot.borrow().is_some() {
1378            return;
1379        }
1380        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1381            let event = unsafe { raw.as_ref() };
1382            ffi_guard::contain(raw.as_ptr(), || {
1383                let Some(mtm) = MainThreadMarker::new() else {
1384                    return raw.as_ptr();
1385                };
1386                let escape = unsafe { event.charactersIgnoringModifiers() }
1387                    .is_some_and(|s| s.to_string() == "\u{1b}");
1388                let Some(window) = event.window(mtm).filter(|_| escape) else {
1389                    return raw.as_ptr();
1390                };
1391                let app = NSApplication::sharedApplication(mtm);
1392                if app.modalWindow().is_some() || window.attachedSheet().is_some() {
1393                    return raw.as_ptr();
1394                }
1395                match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
1396                    Some(node) => {
1397                        emit(
1398                            node,
1399                            Event::NavBack {
1400                                already_popped: false,
1401                            },
1402                        );
1403                        std::ptr::null_mut()
1404                    }
1405                    None => raw.as_ptr(),
1406                }
1407            })
1408        });
1409        let monitor = unsafe {
1410            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1411                objc2_app_kit::NSEventMask::KeyDown,
1412                &block,
1413            )
1414        };
1415        *slot.borrow_mut() = monitor.map(PanMonitor);
1416    });
1417}
1418
1419// A container pan observes horizontal wheel events over its descendants, including native
1420// scroll views. Leave vertical scrolling and canvas 2D pans to their existing handlers.
1421fn install_container_pan_monitor() {
1422    PAN_MONITOR.with(|slot| {
1423        if slot.borrow().is_some() {
1424            return;
1425        }
1426        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1427            let event = unsafe { raw.as_ref() };
1428            ffi_guard::contain(raw.as_ptr(), || {
1429                let dx = unsafe { event.scrollingDeltaX() };
1430                let dy = unsafe { event.scrollingDeltaY() };
1431                if dx.abs() <= dy.abs() {
1432                    return raw.as_ptr();
1433                }
1434                let Some(mtm) = MainThreadMarker::new() else {
1435                    return raw.as_ptr();
1436                };
1437                let Some(window) = event.window(mtm) else {
1438                    return raw.as_ptr();
1439                };
1440                let Some(content) = window.contentView() else {
1441                    return raw.as_ptr();
1442                };
1443                let point =
1444                    content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1445                let mut view = content.hitTest(point);
1446                while let Some(v) = view {
1447                    if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1448                        if v.downcast_ref::<DayCanvas>().is_some() {
1449                            return raw.as_ptr();
1450                        }
1451                        let raw_phase = unsafe { event.phase() };
1452                        let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1453                            day_spec::DragPhase::Began
1454                        } else if raw_phase.intersects(
1455                            objc2_app_kit::NSEventPhase::Ended
1456                                | objc2_app_kit::NSEventPhase::Cancelled,
1457                        ) {
1458                            day_spec::DragPhase::Ended
1459                        } else {
1460                            day_spec::DragPhase::Changed
1461                        };
1462                        let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1463                        emit(
1464                            node,
1465                            Event::Pan {
1466                                phase,
1467                                delta: Point::new(dx, dy),
1468                                location: Point::new(p.x, p.y),
1469                            },
1470                        );
1471                        return std::ptr::null_mut();
1472                    }
1473                    view = unsafe { v.superview() };
1474                }
1475                raw.as_ptr()
1476            })
1477        });
1478        *slot.borrow_mut() = unsafe {
1479            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1480                objc2_app_kit::NSEventMask::ScrollWheel,
1481                &block,
1482            )
1483        }
1484        .map(PanMonitor);
1485    });
1486}
1487
1488// ---------------------------------------------------------------------------
1489// DayFlipped: top-left-origin container view
1490// ---------------------------------------------------------------------------
1491
1492/// A `background(..)` fill: `(r, g, b, a, corner_radius)`, painted in `drawRect` with NSColor.
1493type Surface = (f64, f64, f64, f64, f64);
1494
1495#[derive(Default)]
1496struct FlippedIvars {
1497    surface: Cell<Option<Surface>>,
1498    /// SurfaceRole::SectionCard: `(radius,)`, drawn with a dynamic system fill resolved at
1499    /// draw time, so the card tracks light/dark appearance changes automatically.
1500    section_card: Cell<Option<f64>>,
1501    /// Paint the whole view with the dynamic window background before anything else: the
1502    /// inspector panel wrap (docs/inspector.md). The inspector NSSplitViewItem backs its pane
1503    /// with a vibrancy material, and the section cards' thin quaternary fill composites over
1504    /// it into near-black in dark mode (and the material itself captures black offscreen; see
1505    /// the sidebar-screenshot rule, docs/navigation.md). An opaque appearance-resolved
1506    /// backdrop gives the cards the same ground System Settings draws them on.
1507    pane_backdrop: Cell<bool>,
1508}
1509
1510define_class!(
1511    #[unsafe(super(NSView))]
1512    #[thread_kind = MainThreadOnly]
1513    #[name = "DayFlipped"]
1514    #[ivars = FlippedIvars]
1515    struct DayFlipped;
1516
1517    impl DayFlipped {
1518        #[unsafe(method_id(menuForEvent:))]
1519        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1520            ffi_guard::contain(None, || {
1521                inherited_context_menu(self, event)
1522                    .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1523            })
1524        }
1525
1526        #[unsafe(method(isFlipped))]
1527        fn is_flipped(&self) -> bool {
1528            true
1529        }
1530
1531        // Focus, and with it the keyboard (docs/focus.md): the canvas contract, opted into by
1532        // `Decorate::focusable`. A container never in FOCUSABLE_NODES behaves exactly as
1533        // before (refuses first responder, forwards every key).
1534        #[unsafe(method(acceptsFirstResponder))]
1535        fn accepts_first_responder(&self) -> bool {
1536            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1537            FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1538        }
1539
1540        // Clicking a focusable container focuses it, the way clicking a table does. The
1541        // gesture recognizers still see the press: this runs before `super`, which is what
1542        // forwards it to them.
1543        #[unsafe(method(mouseDown:))]
1544        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1545            if transfer::pressed(self, event) { return; }
1546            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1547            if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1548                && let Some(window) = self.window()
1549            {
1550                window.makeFirstResponder(Some(self));
1551            }
1552            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1553        }
1554
1555        #[unsafe(method(becomeFirstResponder))]
1556        fn become_first_responder(&self) -> bool {
1557            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1558            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1559                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1560            }
1561            true
1562        }
1563
1564        #[unsafe(method(resignFirstResponder))]
1565        fn resign_first_responder(&self) -> bool {
1566            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1567            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1568                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1569            }
1570            true
1571        }
1572
1573        /// The arrows, delivered here while this container is the first responder. Anything
1574        /// else (and every arrow when the app registered no key handler for the node) goes
1575        /// to `super`, which walks the responder chain exactly as it would have without us.
1576        #[unsafe(method(keyDown:))]
1577        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1578            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1579            let handled = ffi_guard::contain(false, || {
1580                let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
1581                    return false;
1582                };
1583                let Some(key) = key_name(event) else {
1584                    return false;
1585                };
1586                if !day_spec::keys::handled(node) {
1587                    return false;
1588                }
1589                emit(
1590                    node,
1591                    Event::Key(day_spec::KeyEvent::named(
1592                        key,
1593                        key_modifiers(event.modifierFlags()),
1594                    )),
1595                );
1596                true
1597            });
1598            if !handled {
1599                let _: () = unsafe { msg_send![super(self), keyDown: event] };
1600            }
1601        }
1602
1603        /// Show the attached context menu (docs/menus.md) explicitly rather than relying on
1604        /// `NSResponder`'s default `.menu` display: popping it ourselves is deterministic
1605        /// regardless of how the click threads through Day's container hierarchy.
1606        #[unsafe(method(rightMouseDown:))]
1607        fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1608            if let Some(menu) = self.menuForEvent(event) {
1609                unsafe {
1610                    objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
1611                };
1612            } else {
1613                let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
1614            }
1615        }
1616
1617        #[unsafe(method(drawRect:))]
1618        fn draw_rect(&self, _dirty: NSRect) {
1619            let paint = || {
1620                if self.ivars().pane_backdrop.get() {
1621                    let bounds = self.bounds();
1622                    unsafe {
1623                        // Resolved at draw time, like the section fill below, so the backdrop
1624                        // follows light/dark appearance changes automatically.
1625                        NSColor::windowBackgroundColor().setFill();
1626                        objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
1627                    }
1628                }
1629                if let Some(radius) = self.ivars().section_card.get() {
1630                    let bounds = self.bounds();
1631                    unsafe {
1632                        // quaternarySystemFill (macOS 14+) is the grouped-card material System
1633                        // Settings uses; older systems fall back to the control background.
1634                        let cls = objc2::class!(NSColor);
1635                        let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
1636                        let color: objc2::rc::Retained<NSColor> = if has {
1637                            msg_send![cls, quaternarySystemFillColor]
1638                        } else {
1639                            msg_send![cls, controlBackgroundColor]
1640                        };
1641                        color.setFill();
1642                        let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1643                            bounds, radius, radius,
1644                        );
1645                        path.fill();
1646                    }
1647                }
1648                if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
1649                    let bounds = self.bounds();
1650                    unsafe {
1651                        NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
1652                        let path = if radius > 0.0 {
1653                            objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1654                                bounds, radius, radius,
1655                            )
1656                        } else {
1657                            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
1658                        };
1659                        path.fill();
1660                    }
1661                }
1662            };
1663            // Paint under the standard counterpart of this view's appearance. Inside an
1664            // NSVisualEffectView subtree (the inspector pane) the effective appearance is
1665            // a vibrant one (NSAppearanceNameVibrantDark/-Light), and the system fills'
1666            // vibrant variants are opaque blend colors that only composite correctly in an
1667            // `allowsVibrancy` view: drawn plainly, dark-mode quaternary fill comes out
1668            // near-black instead of lightening. Resolving under aqua/darkAqua gives exactly
1669            // the fills System Settings draws with, and re-resolves on every theme change
1670            // (this runs per draw, and appearance flips redraw).
1671            unsafe {
1672                let names = objc2_foundation::NSArray::from_slice(&[
1673                    objc2_app_kit::NSAppearanceNameAqua,
1674                    objc2_app_kit::NSAppearanceNameDarkAqua,
1675                ]);
1676                let standard = self
1677                    .effectiveAppearance()
1678                    .bestMatchFromAppearancesWithNames(&names)
1679                    .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
1680                match standard {
1681                    Some(appearance) => {
1682                        let block = block2::StackBlock::new(paint);
1683                        appearance.performAsCurrentDrawingAppearance(&block);
1684                    }
1685                    None => paint(),
1686                }
1687            }
1688        }
1689    }
1690    unsafe impl NSObjectProtocol for DayFlipped {}
1691    unsafe impl NSDraggingSource for DayFlipped {
1692        #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
1693        fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
1694    }
1695    impl DayFlipped {
1696        #[unsafe(method(mouseDragged:))]
1697        fn transfer_dragged(&self, event: &NSEvent) {
1698            if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
1699        }
1700        #[unsafe(method(draggingEntered:))]
1701        fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1702        #[unsafe(method(draggingUpdated:))]
1703        fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1704        #[unsafe(method(performDragOperation:))]
1705        fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
1706    }
1707
1708);
1709
1710impl DayFlipped {
1711    fn new(mtm: MainThreadMarker) -> Retained<Self> {
1712        let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
1713        unsafe { msg_send![super(this), init] }
1714    }
1715
1716    /// Apply a `background`/`corner_radius` surface. The fill (rounded by `corner_radius`) is
1717    /// drawn in `drawRect` with NSColor, not via the layer's `backgroundColor`, whose CGColorRef
1718    /// argument objc2's `msg_send` cannot type-check. A rounded child clip does use the CALayer
1719    /// (`cornerRadius` + `masksToBounds` are a CGFloat + `BOOL`, which are fine).
1720    /// SurfaceRole::SectionCard: the fill resolves dynamically in drawRect (theme-adaptive).
1721    fn set_section_card(&self, corner_radius: f64) {
1722        self.ivars().section_card.set(Some(corner_radius));
1723        unsafe {
1724            let _: () = msg_send![self, setNeedsDisplay: true];
1725        }
1726    }
1727
1728    /// Opaque window-background backdrop (the inspector panel wrap; see `FlippedIvars`).
1729    fn set_pane_backdrop(&self) {
1730        self.ivars().pane_backdrop.set(true);
1731        unsafe {
1732            let _: () = msg_send![self, setNeedsDisplay: true];
1733        }
1734    }
1735
1736    fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
1737        self.ivars()
1738            .surface
1739            .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
1740        unsafe {
1741            let _: () = msg_send![self, setNeedsDisplay: true];
1742            if clips || corner_radius > 0.0 {
1743                let _: () = msg_send![self, setWantsLayer: true];
1744                let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
1745                if !layer.is_null() {
1746                    let _: () = msg_send![layer, setCornerRadius: corner_radius];
1747                    let _: () = msg_send![layer, setMasksToBounds: true];
1748                }
1749            }
1750        }
1751    }
1752}
1753
1754// ---------------------------------------------------------------------------
1755// DayCanvas — a flipped view replaying the Day display list in drawRect (§11)
1756// ---------------------------------------------------------------------------
1757
1758struct CanvasIvars;
1759
1760define_class!(
1761    #[unsafe(super(NSView))]
1762    #[thread_kind = MainThreadOnly]
1763    #[name = "DayCanvas"]
1764    #[ivars = CanvasIvars]
1765    struct DayCanvas;
1766
1767    impl DayCanvas {
1768        #[unsafe(method(isFlipped))]
1769        fn is_flipped(&self) -> bool {
1770            true
1771        }
1772
1773        /// A summon-time context menu (docs/menus.md): built when the right-click lands,
1774        /// from the provider `set_context_menu_fn` registered — so a canvas can select what
1775        /// is under the pointer and offer commands for that selection.
1776        #[unsafe(method_id(menuForEvent:))]
1777        fn menu_for_event(
1778            &self,
1779            event: &objc2_app_kit::NSEvent,
1780        ) -> Option<Retained<NSMenu>> {
1781            let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
1782            let Some(f) = f else {
1783                return unsafe { msg_send![super(self), menuForEvent: event] };
1784            };
1785            // Guarded: the provider is app code (it usually re-selects, then builds).
1786            ffi_guard::contain(None, || {
1787                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1788                let items = f(day_spec::Point::new(p.x, p.y));
1789                if items.is_empty() {
1790                    return None;
1791                }
1792                Some(build_ns_menu(self.mtm(), "", &items))
1793            })
1794        }
1795
1796        // Focus, and with it the keyboard (docs/focus.md, docs/menus.md). A canvas is the one
1797        // built-in piece with no native control under it, so nothing else would ever make it
1798        // the first responder — and without that, arrow keys aimed at what it draws could only
1799        // be caught by watching the whole app.
1800        #[unsafe(method(acceptsFirstResponder))]
1801        fn accepts_first_responder(&self) -> bool {
1802            true
1803        }
1804
1805        // Clicking a canvas focuses it, the way clicking a table or a text field does. The
1806        // gesture recognizers (tap/drag) still see the press — this runs before `super`, which
1807        // is what forwards it to them.
1808        #[unsafe(method(mouseDown:))]
1809        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1810            if let Some(window) = self.window() {
1811                window.makeFirstResponder(Some(self));
1812            }
1813            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1814        }
1815
1816        // Report focus both ways, so `.focused(signal)` binds two-way and dayscript's
1817        // `assert_focused` can see it.
1818        #[unsafe(method(becomeFirstResponder))]
1819        fn become_first_responder(&self) -> bool {
1820            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1821            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1822                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1823            }
1824            true
1825        }
1826
1827        #[unsafe(method(resignFirstResponder))]
1828        fn resign_first_responder(&self) -> bool {
1829            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1830            // A composition in progress goes with the focus: the input method is told, so it
1831            // does not commit into whatever is focused next.
1832            if MARKED.with(|t| t.remove(ptr)).is_some()
1833                && let Some(context) = self.inputContext()
1834            {
1835                context.discardMarkedText();
1836            }
1837            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1838                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1839            }
1840            true
1841        }
1842
1843        /// The keys, delivered to this canvas because it is the first responder. On the short
1844        /// route the arrows and digits; on the full route (docs/menus.md "The full route")
1845        /// every key, through the text input system for the ones that type. Anything
1846        /// unclaimed — and every key when the app registered no handler for this node — goes
1847        /// to `super`, which walks the responder chain exactly as it would have without us.
1848        #[unsafe(method(keyDown:))]
1849        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1850            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1851            let handled = ffi_guard::contain(false, || {
1852                let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
1853                    return false;
1854                };
1855                // A canvas nobody asked keys from does not get to keep them: an enclosing
1856                // scroll view still scrolls, and an unclaimed key still beeps the way the
1857                // platform means it to.
1858                if !day_spec::keys::handled(node) {
1859                    return false;
1860                }
1861                if day_spec::keys::text(node) {
1862                    return full_route_key_down(self, node, event);
1863                }
1864                let Some(key) = key_name(event) else {
1865                    return false;
1866                };
1867                emit(
1868                    node,
1869                    Event::Key(day_spec::KeyEvent::named(
1870                        key,
1871                        key_modifiers(event.modifierFlags()),
1872                    )),
1873                );
1874                true
1875            });
1876            if !handled {
1877                let _: () = unsafe { msg_send![super(self), keyDown: event] };
1878            }
1879        }
1880
1881        /// The text input context, only for a canvas on the full route: an input context is
1882        /// what makes the input method (and the keyboard layout's dead keys) address this
1883        /// view, and a drawing canvas that hears the arrows alone must not look like a text
1884        /// field to it.
1885        #[unsafe(method_id(inputContext))]
1886        fn input_context(&self) -> Option<Retained<objc2_app_kit::NSTextInputContext>> {
1887            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1888            let takes_keyboard = KEY_NODES
1889                .with(|t| t.get(ptr))
1890                .is_some_and(|node| ffi_guard::contain(false, || day_spec::keys::text(node)));
1891            if takes_keyboard {
1892                unsafe { msg_send![super(self), inputContext] }
1893            } else {
1894                None
1895            }
1896        }
1897
1898        #[unsafe(method(drawRect:))]
1899        fn draw_rect(&self, _dirty: NSRect) {
1900            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1901            let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
1902            paint_ops(&ops);
1903        }
1904
1905        /// Hover entry/motion/exit (docs/canvas.md "Interaction"). The tracking area is installed
1906        /// by `enable_gesture`; `updateTrackingAreas` below keeps it the size of the view.
1907        #[unsafe(method(mouseEntered:))]
1908        fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
1909            self.report_hover(event, day_spec::DragPhase::Began);
1910        }
1911
1912        #[unsafe(method(mouseMoved:))]
1913        fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
1914            self.report_hover(event, day_spec::DragPhase::Changed);
1915        }
1916
1917        #[unsafe(method(mouseExited:))]
1918        fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
1919            self.report_hover(event, day_spec::DragPhase::Ended);
1920        }
1921
1922        #[unsafe(method(scrollWheel:))]
1923        fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
1924            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1925            let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
1926                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
1927                return;
1928            };
1929            ffi_guard::contain((), || {
1930                // Trackpads bracket a pan with phases; a discrete wheel tick has none and
1931                // arrives as a lone Changed — exactly the Event::Pan contract.
1932                let raw = unsafe { event.phase() };
1933                let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
1934                    day_spec::DragPhase::Began
1935                } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
1936                    || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
1937                {
1938                    day_spec::DragPhase::Ended
1939                } else {
1940                    day_spec::DragPhase::Changed
1941                };
1942                let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
1943                    event.scrollingDeltaY()
1944                });
1945                let win = unsafe { event.locationInWindow() };
1946                let loc = self.convertPoint_fromView(win, None);
1947                emit(
1948                    node,
1949                    Event::Pan {
1950                        phase,
1951                        delta,
1952                        location: Point::new(loc.x, loc.y),
1953                    },
1954                );
1955            })
1956        }
1957    }
1958
1959    unsafe impl NSObjectProtocol for DayCanvas {}
1960
1961    /// The text input system's client (docs/menus.md "The full route"): the view a dead key
1962    /// or an input method composes into. A canvas has no document, so the marked text is
1963    /// held here and never shown; what the input method commits is the key event's text.
1964    unsafe impl NSTextInputClient for DayCanvas {
1965        #[unsafe(method(insertText:replacementRange:))]
1966        unsafe fn insert_text(&self, string: &AnyObject, _replacement: NSRange) {
1967            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1968            MARKED.with(|t| t.remove(ptr));
1969            let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
1970                return;
1971            };
1972            let text = text_of_input_string(string);
1973            if text.is_empty() {
1974                return;
1975            }
1976            ffi_guard::contain((), || {
1977                let interpreting = INTERPRETING.with(|i| i.borrow().clone());
1978                let event = match interpreting {
1979                    // One character typed by the key being interpreted: named by that key.
1980                    Some((key, mods)) if text.chars().count() == 1 => {
1981                        day_spec::KeyEvent::typed_by(key, text, mods)
1982                    }
1983                    Some((_, mods)) => day_spec::KeyEvent::typed_text(text, mods),
1984                    // Committed outside any key press (the Character Viewer, dictation).
1985                    None => day_spec::KeyEvent::typed_text(text, 0),
1986                };
1987                emit(node, Event::Key(event));
1988            });
1989        }
1990
1991        /// A key the text input system turned into an editing command (`insertNewline:`,
1992        /// `moveLeft:`, …). `keyDown:` already named every key the route carries before it
1993        /// asked the input system, so nothing is left to do here; anything else (a `noop:`
1994        /// for a function key the vocabulary lacks) types nothing, by design.
1995        #[unsafe(method(doCommandBySelector:))]
1996        unsafe fn do_command_by_selector(&self, _selector: Sel) {}
1997
1998        #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
1999        unsafe fn set_marked_text(&self, string: &AnyObject, _selected: NSRange, _replacement: NSRange) {
2000            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2001            let text = text_of_input_string(string);
2002            if text.is_empty() {
2003                MARKED.with(|t| t.remove(ptr));
2004            } else {
2005                MARKED.with(|t| t.insert(ptr, text));
2006            }
2007        }
2008
2009        #[unsafe(method(unmarkText))]
2010        fn unmark_text(&self) {
2011            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2012            MARKED.with(|t| t.remove(ptr));
2013        }
2014
2015        #[unsafe(method(selectedRange))]
2016        fn selected_range(&self) -> NSRange {
2017            NSRange::new(objc2_foundation::NSNotFound as usize, 0)
2018        }
2019
2020        #[unsafe(method(markedRange))]
2021        fn marked_range(&self) -> NSRange {
2022            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2023            match MARKED.with(|t| t.get(ptr)) {
2024                Some(marked) => NSRange::new(0, marked.encode_utf16().count()),
2025                None => NSRange::new(objc2_foundation::NSNotFound as usize, 0),
2026            }
2027        }
2028
2029        #[unsafe(method(hasMarkedText))]
2030        fn has_marked_text(&self) -> bool {
2031            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2032            MARKED.with(|t| t.contains(ptr))
2033        }
2034
2035        #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
2036        unsafe fn attributed_substring(
2037            &self,
2038            _range: NSRange,
2039            _actual: objc2_foundation::NSRangePointer,
2040        ) -> Option<Retained<objc2_foundation::NSAttributedString>> {
2041            None
2042        }
2043
2044        #[unsafe(method_id(validAttributesForMarkedText))]
2045        fn valid_attributes(&self) -> Retained<NSArray<objc2_foundation::NSAttributedStringKey>> {
2046            NSArray::new()
2047        }
2048
2049        /// Where the input method puts its candidate window: under the canvas, since the
2050        /// canvas does not say where its caret is.
2051        #[unsafe(method(firstRectForCharacterRange:actualRange:))]
2052        unsafe fn first_rect(&self, _range: NSRange, _actual: objc2_foundation::NSRangePointer) -> NSRect {
2053            let bounds = self.bounds();
2054            let in_window = self.convertRect_toView(bounds, None);
2055            match self.window() {
2056                Some(window) => window.convertRectToScreen(in_window),
2057                None => in_window,
2058            }
2059        }
2060
2061        #[unsafe(method(characterIndexForPoint:))]
2062        fn character_index_for_point(&self, _point: NSPoint) -> objc2_foundation::NSUInteger {
2063            objc2_foundation::NSNotFound as objc2_foundation::NSUInteger
2064        }
2065    }
2066);
2067
2068impl DayCanvas {
2069    fn new(mtm: MainThreadMarker) -> Retained<Self> {
2070        let this = Self::alloc(mtm).set_ivars(CanvasIvars);
2071        unsafe { msg_send![super(this), init] }
2072    }
2073
2074    /// One hover phase, reported to whichever node asked for it (docs/canvas.md "Interaction").
2075    ///
2076    /// `mouseEntered:`/`mouseExited:` are scoped by the tracking area, but **`mouseMoved:` is
2077    /// not**: it walks the responder chain, so a focused canvas hears about motion anywhere in
2078    /// its window — including outside itself. Hence the bounds test, without which a canvas
2079    /// reports a hover for a pointer that is nowhere near it (measured: a pointer parked outside
2080    /// the window entirely still produced hover positions).
2081    fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
2082        let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2083        let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
2084            return;
2085        };
2086        ffi_guard::contain((), || {
2087            let win = unsafe { event.locationInWindow() };
2088            let loc = self.convertPoint_fromView(win, None);
2089            let b = self.bounds();
2090            let inside = loc.x >= b.origin.x
2091                && loc.x <= b.origin.x + b.size.width
2092                && loc.y >= b.origin.y
2093                && loc.y <= b.origin.y + b.size.height;
2094            // An exit is reported wherever it happens — that is the point of it — but a move
2095            // outside the view is not this view's hover.
2096            if !inside && phase != day_spec::DragPhase::Ended {
2097                return;
2098            }
2099            emit(
2100                node,
2101                Event::Hover {
2102                    phase,
2103                    location: Point::new(loc.x, loc.y),
2104                },
2105            );
2106        });
2107    }
2108}
2109
2110/// The tracking area a hovering canvas needs. `InVisibleRect` makes it follow the view's bounds,
2111/// so there is no rect to keep in step with layout; `ActiveInKeyWindow` matches the cursor areas
2112/// already installed here — a background window does not report hovers.
2113fn install_tracking_area(h: &NSView) {
2114    let opts = NSTrackingAreaOptions::MouseEnteredAndExited
2115        | NSTrackingAreaOptions::MouseMoved
2116        | NSTrackingAreaOptions::ActiveInKeyWindow
2117        | NSTrackingAreaOptions::InVisibleRect;
2118    let any: &objc2::runtime::AnyObject = h;
2119    let area = unsafe {
2120        NSTrackingArea::initWithRect_options_owner_userInfo(
2121            NSTrackingArea::alloc(),
2122            NSRect::ZERO,
2123            opts,
2124            Some(any),
2125            None,
2126        )
2127    };
2128    unsafe { h.addTrackingArea(&area) };
2129}
2130
2131// ---------------------------------------------------------------------------
2132// DayGesture — tap/drag recognizer target, node-id keyed (docs/shapes.md)
2133// ---------------------------------------------------------------------------
2134
2135struct GestureIvars {
2136    node: NodeId,
2137    kind: day_spec::GestureKind,
2138}
2139
2140define_class!(
2141    #[unsafe(super(NSObject))]
2142    #[thread_kind = MainThreadOnly]
2143    #[name = "DayGesture"]
2144    #[ivars = GestureIvars]
2145    struct DayGesture;
2146
2147    unsafe impl NSObjectProtocol for DayGesture {}
2148
2149    impl DayGesture {
2150        #[unsafe(method(fire:))]
2151        fn fire(&self, g: &NSGestureRecognizer) {
2152            ffi_guard::contain((), || {
2153                let node = self.ivars().node;
2154                let view = g.view();
2155                let loc = g.locationInView(view.as_deref());
2156                let at = Point::new(loc.x, loc.y);
2157                let phase = match g.state() {
2158                    NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
2159                    NSGestureRecognizerState::Ended
2160                    | NSGestureRecognizerState::Cancelled
2161                    | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
2162                    _ => day_spec::DragPhase::Changed,
2163                };
2164                let obj: &objc2::runtime::AnyObject = g.as_ref();
2165                match self.ivars().kind {
2166                    day_spec::GestureKind::Drag => {
2167                        let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
2168                            let t = unsafe { pan.translationInView(view.as_deref()) };
2169                            Point::new(t.x, t.y)
2170                        } else {
2171                            Point::ZERO
2172                        };
2173                        emit(node, Event::Drag { phase, location: at, translation });
2174                    }
2175                    day_spec::GestureKind::Pinch => {
2176                        // Cumulative since Began: `magnification` is the total delta (0 =
2177                        // unchanged), and Day's contract wants a factor.
2178                        let scale = if let Some(m) =
2179                            obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
2180                        {
2181                            1.0 + unsafe { m.magnification() }
2182                        } else {
2183                            1.0
2184                        };
2185                        emit(node, Event::Pinch { phase, scale, location: at });
2186                    }
2187                    _ => emit(node, Event::Tap(at)),
2188                }
2189            })
2190        }
2191    }
2192);
2193
2194impl DayGesture {
2195    fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2196        let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2197        unsafe { msg_send![super(this), init] }
2198    }
2199}
2200
2201// ---------------------------------------------------------------------------
2202// Navigation (docs/navigation.md): NSSplitView host, sidebar + detail panes.
2203// Page FRAMES are pane-owned (autoresized); Day lays content inside the size each
2204// page reports from setFrameSize:. Day's set_frame on pages is skipped.
2205// ---------------------------------------------------------------------------
2206
2207/// The stack presentation's back header (desktop has no system back affordance — this bar
2208/// gives a pushed page its way out, like AdwNavigationView's header on GTK). Hidden at root.
2209struct NavHeader {
2210    bar: Retained<NSView>,
2211    title: Retained<NSTextField>,
2212    /// Title per stack level (index 0 = root); the field shows the last.
2213    titles: Vec<String>,
2214    _target: Retained<DayTarget>,
2215}
2216
2217/// Height of the stack-nav back header while a pushed page is showing.
2218const NAV_HEADER_H: f64 = 34.0;
2219
2220// Drag limits for both draggable panes come from day-spec (`NAV_SIDEBAR_MIN_W` and friends): a
2221// sidebar NSSplitViewItem enforces them itself, which is why the divider no longer needs
2222// restoring by hand after every window resize.
2223use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2224
2225/// The content-list width to place divider 1 at, once, the first time the pane is showing —
2226/// `None` when the pane is collapsed or has already been placed. Latches on the way out, so the
2227/// two callers (the first frame pass, and the patch that reveals the pane) cannot both spend it.
2228fn take_list_placement(state: &mut NavState) -> Option<f64> {
2229    if !state.list_visible || state.list_positioned {
2230        return None;
2231    }
2232    state.list_positioned = true;
2233    state.list_width
2234}
2235
2236/// A tabs host's `NSTabView` margins inside its pane: the sides and the foot, and the top —
2237/// deeper, since the tabs themselves stand about a segment's height above the bezel.
2238const NAV_TABVIEW_INSET: f64 = 12.0;
2239const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2240
2241/// The `NavPresentation::Tabs` container: a real `NSTabView` — the Mac's own tab control, top
2242/// tabs on a bezel — whose items own the detail pages. The page frames stay native-owned
2243/// exactly as in a split: the tab view frames the selected item's view, and the page's
2244/// `setFrameSize:` reports it. The labels come from the NAV_MENU's rows, which arrive after
2245/// the pages' host (day-core mounts top-down: the rows page joins the host before its menu is
2246/// built), so `adopt_menu_for_tabs` runs when the menu is inserted and whenever its rows are
2247/// rebuilt.
2248///
2249/// Until 2026-09-12 this was an `NSSegmentedControl` docked at the foot, built from the rows
2250/// page's menu at the moment that page was inserted — before the menu existed — so no bar was
2251/// ever built and a tabs host showed its first page alone.
2252struct TabHost {
2253    view: Retained<objc2_app_kit::NSTabView>,
2254    /// The delegate reporting a native tab pick against the NAV_MENU's node; set once the menu
2255    /// is known.
2256    target: Option<Retained<DayTarget>>,
2257}
2258
2259thread_local! {
2260    /// A Day-driven tab selection in flight (`NavPatch::Select`, a label sync): the tab view's
2261    /// delegate must not echo it back as `SelectionChanged`.
2262    static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2263}
2264
2265/// Give the tab view its labels from the rows, and its selection. Rows and items are
2266/// index-aligned (destination `i` is item `i`); a count mismatch mid-rebuild labels what both
2267/// have.
2268fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2269    unsafe {
2270        let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2271        for (i, title) in titles.iter().enumerate().take(n) {
2272            tabs.view
2273                .tabViewItemAtIndex(i as isize)
2274                .setLabel(&NSString::from_str(title));
2275        }
2276        if n > 0 {
2277            TAB_PICK_SUPPRESS.with(|s| s.set(true));
2278            tabs.view
2279                .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2280            TAB_PICK_SUPPRESS.with(|s| s.set(false));
2281        }
2282    }
2283}
2284
2285/// A NAV_MENU reached a tabs host (its rows page sits in the host's collapsed sidebar pane):
2286/// the menu's rows become the tab labels and its node the delegate's target. Walks up from the
2287/// menu, so the innermost host — the one whose rows these are — is the one that takes them.
2288fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2289    let Some((titles, node)) = NAV_MENUS.with(|m| {
2290        m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2291            let ivars = d.ivars();
2292            (
2293                ivars
2294                    .items
2295                    .borrow()
2296                    .iter()
2297                    .map(|s| s.to_string())
2298                    .collect::<Vec<String>>(),
2299                ivars.node,
2300            )
2301        })
2302    }) else {
2303        return;
2304    };
2305    let mut up = unsafe { menu.superview() };
2306    while let Some(v) = up {
2307        let reached = NAV_STATE.with(|m| {
2308            let mut m = m.borrow_mut();
2309            let Some(s) = m.get_mut(&ptr_of(&v)) else {
2310                return false;
2311            };
2312            let selected = s.selected;
2313            if let Some(tabs) = s.tabs.as_mut() {
2314                if tabs.target.is_none() {
2315                    let target = DayTarget::new(mtm, node);
2316                    unsafe {
2317                        tabs.view
2318                            .setDelegate(Some(ProtocolObject::from_ref(&*target)))
2319                    };
2320                    tabs.target = Some(target);
2321                }
2322                sync_tab_labels(tabs, &titles, selected);
2323            }
2324            true
2325        });
2326        if reached {
2327            return;
2328        }
2329        up = unsafe { v.superview() };
2330    }
2331}
2332
2333struct NavState {
2334    sidebar_wrap: Retained<NSView>,
2335    detail_wrap: Retained<NSView>,
2336    /// The container behind the host view. A view holds NO strong reference to its controller,
2337    /// and the split view controller is what owns the items, their holding priorities, the
2338    /// sidebar's material and the split's delegate duties — so it has to be retained here or
2339    /// the sidebar loses its treatment the moment this realize returns.
2340    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2341    /// The sidebar item, for the `SidebarToggle` duty (docs/toolbars.md). AppKit's own
2342    /// `NSToolbarToggleSidebarItem` reaches the controller through the responder chain; this is
2343    /// the path dayscript and any non-toolbar caller take.
2344    sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2345    /// The content-list pane (docs/navigation.md), `Some` only on a host whose
2346    /// `NavProps::list_width` was set: the wrap its `Pane::List` page fills, and the
2347    /// `contentList` split item `NavPatch::ListVisible` collapses. The pane PERSISTS through
2348    /// every presentation (`Cap::NavContentList` = Native) — a narrow window collapses the
2349    /// sidebar and keeps the list, exactly as a narrow Mail.app does.
2350    list_wrap: Option<Retained<NSView>>,
2351    list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2352    /// The app's requested content-list width (`NavProps::list_width`) — applied once, at the
2353    /// first frame pass, by placing divider 1 (see `set_frame`).
2354    list_width: Option<f64>,
2355    /// Whether the content-list pane is showing (`NavProps::list_visible`, then
2356    /// `NavPatch::ListVisible`). Placing divider 1 for a pane that is collapsed is what re-opens
2357    /// it, so both placement paths ask first.
2358    list_visible: bool,
2359    /// Whether divider 1 has been placed at the app's requested width yet. Separate from
2360    /// `positioned` because the pane may not exist on screen when the first frame pass runs: an
2361    /// app opening on a full-width destination has nothing to size then, and spending the
2362    /// one-time placement there is what left the list at the solver's own width when it did
2363    /// appear.
2364    list_positioned: bool,
2365    /// Detail pages in stack order (the sidebar page is not in here in split mode; in stack
2366    /// mode `split == false`, the root page is here too, so push/pop visibility covers it).
2367    pages: Vec<Retained<NSView>>,
2368    /// The host's sidebar page, once it has one — what a re-present moves between the sidebar
2369    /// pane and the head of `pages` (docs/size-classes.md).
2370    sidebar_page: Option<Retained<NSView>>,
2371    /// The content-list pane's page, re-framed when the pane is first revealed: it was inserted
2372    /// into a collapsed wrap, where autoresizing can only keep it at zero.
2373    list_page: Option<Retained<NSView>>,
2374    positioned: bool,
2375    /// Which of the four presentations is drawn right now (docs/size-classes.md). All of them are
2376    /// the same `NSSplitViewController`: a stack is that split with its sidebar collapsed, a rail
2377    /// is it with a narrow one, and a tab bar is a collapsed sidebar plus the bottom bar below.
2378    presentation: NavPresentation,
2379    /// The detail page on screen, as an index into `pages`. Maintained by every patch that
2380    /// changes it — push, pop and select alike — so a re-present can carry it across.
2381    selected: usize,
2382    /// The tab view (`NavPresentation::Tabs` only), holding the detail pages as its items and
2383    /// labeled from the same rows the sidebar's outline view shows; a pick emits
2384    /// `SelectionChanged` against the same NAV_MENU node.
2385    tabs: Option<TabHost>,
2386    /// Back header (stack presentation only).
2387    header: Option<NavHeader>,
2388    /// The host's own title, kept so a re-present into a stack can seed a fresh back header
2389    /// with the same root title the initial build would have used.
2390    root_title: String,
2391    /// The host's node, for the same reason — a back header's button targets it.
2392    node: NodeId,
2393    /// How far the host reaches up under the window's title bar (see `pane_under_title_bar`):
2394    /// the strip each pane's wrap is kept below. Zero for a host that does not start at the top
2395    /// of a pinned window.
2396    title_strip: f64,
2397}
2398
2399/// A split item's view: a transparent pane that runs the item's full height, with `wrap` (the
2400/// view Day's pages and the rest of this backend frame themselves against) inside it.
2401///
2402/// `NSSplitViewController` expects its split view to reach the top of a full-size-content window
2403/// and lays its title-bar treatment over the top of every item: a title-bar background, and on
2404/// macOS 26 and later the frosted scroll pocket. Day pins its content below the title bar
2405/// (`pin_below_title_bar`), so a split framed where Day lays it out put that treatment over the
2406/// first strip of every page instead, blurring a detail page's heading. The host is framed up
2407/// under the bar instead (`set_frame`), and each wrap is held below the strip inside its pane, so
2408/// the treatment lands on the bar, the sidebar's material runs to the top of the window as
2409/// `allowsFullHeightLayout` intends, and every page still starts where Day laid it out.
2410fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2411    let pane = view_of(DayFlipped::new(mtm));
2412    unsafe {
2413        wrap.setFrame(pane.bounds());
2414        wrap.setAutoresizingMask(
2415            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2416                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2417        );
2418        pane.addSubview(wrap);
2419    }
2420    pane
2421}
2422
2423/// Hold `wrap` `strip` points below the top of the pane that holds it.
2424fn place_below_strip(wrap: &NSView, strip: f64) {
2425    let Some(pane) = (unsafe { wrap.superview() }) else {
2426        return;
2427    };
2428    let b = pane.bounds();
2429    unsafe {
2430        wrap.setFrame(NSRect::new(
2431            NSPoint::new(0.0, strip),
2432            NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2433        ))
2434    };
2435}
2436
2437/// The stack presentation's back header: a chevron + centered title docked above the pages,
2438/// hidden at the root. Desktop has no system back affordance, so a pushed page carries its own
2439/// way out (docs/navigation.md).
2440///
2441/// Built here rather than inline because a host that RE-PRESENTS into a stack needs one at that
2442/// moment (docs/size-classes.md), and a header that differed from the one a stack-at-launch host
2443/// gets would be a second shape to keep in step.
2444fn build_nav_header(
2445    mtm: MainThreadMarker,
2446    id: NodeId,
2447    detail_wrap: &NSView,
2448    root_title: &str,
2449) -> NavHeader {
2450    let bar = view_of(DayFlipped::new(mtm));
2451    let target = DayTarget::new(mtm, id);
2452    let back = unsafe {
2453        // Invariant: NSImageNameGoBackTemplate is one of AppKit's own named images, present
2454        // on every macOS release this backend builds for.
2455        let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2456            .expect("NSGoBackTemplate");
2457        let tobj: &objc2::runtime::AnyObject = target.as_ref();
2458        objc2_app_kit::NSButton::buttonWithImage_target_action(
2459            &img,
2460            Some(tobj),
2461            Some(sel!(navBack:)),
2462            mtm,
2463        )
2464    };
2465    let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2466    unsafe {
2467        back.setFrame(NSRect::new(
2468            NSPoint::new(6.0, 4.0),
2469            NSSize::new(30.0, NAV_HEADER_H - 8.0),
2470        ));
2471        title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2472        title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2473        title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2474        title.setFrame(NSRect::new(
2475            NSPoint::new(44.0, 9.0),
2476            NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2477        ));
2478        title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2479        bar.setFrame(NSRect::new(
2480            NSPoint::new(0.0, 0.0),
2481            NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2482        ));
2483        bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2484        bar.addSubview(&back);
2485        bar.addSubview(&title);
2486        bar.setHidden(true);
2487        detail_wrap.addSubview(&bar);
2488    }
2489    NavHeader {
2490        bar,
2491        title,
2492        titles: vec![root_title.to_string()],
2493        _target: target,
2494    }
2495}
2496
2497/// The frame a stack page occupies inside the detail wrap: full bounds at the root, inset below
2498/// the back header while a pushed page is showing. (A tabs host's pages are framed by its
2499/// `NSTabView`, never through here.)
2500fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
2501    let b = wrap.bounds();
2502    let top = if header_visible { NAV_HEADER_H } else { 0.0 };
2503    NSRect::new(
2504        NSPoint::new(0.0, top),
2505        NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
2506    )
2507}
2508
2509/// The row titles and the NAV_MENU node of the menu inside `page`, if it has one.
2510///
2511/// The tab bar needs the same rows the sidebar shows, and they arrive at the NAV_MENU rather
2512/// than at the host. Rather than plumb a second copy through the props, this walks down to the
2513/// menu that is already there — the sidebar page is Day-built and shallow, so the search is a
2514/// handful of views — and reads the titles it has stored for its own outline view.
2515fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
2516    fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
2517        if out.is_some() {
2518            return;
2519        }
2520        let found = NAV_MENUS.with(|m| {
2521            m.borrow()
2522                .get(&(v as *const NSView as usize))
2523                .map(|(_, d)| {
2524                    let ivars = d.ivars();
2525                    (
2526                        ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
2527                        ivars.node,
2528                    )
2529                })
2530        });
2531        if found.is_some() {
2532            *out = found;
2533            return;
2534        }
2535        for sub in unsafe { v.subviews() }.iter() {
2536            walk(&sub, out);
2537        }
2538    }
2539    let mut out = None;
2540    walk(page, &mut out);
2541    out
2542}
2543
2544/// Apply a presentation to the sidebar split item. All four are the same item at a different
2545/// thickness or collapsed outright, which is why a morph never rebuilds the split.
2546fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
2547    let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
2548    unsafe {
2549        item.setCanCollapse(shown);
2550        item.setCollapsed(!shown);
2551        match pres {
2552            NavPresentation::Split => {
2553                item.setAllowsFullHeightLayout(true);
2554                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2555                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2556            }
2557            // macOS has no rail: nothing in AppKit is a vertical strip of icon-only
2558            // destinations, and a source list pinned to icon width just truncates every row to an
2559            // ellipsis. `NavPresentation::Rail` is explicitly ROUNDABLE for exactly this case, so
2560            // it lands on the neighbor a Mac does have — an ordinary sidebar. Windows rounds the
2561            // other way (`PaneDisplayMode = LeftCompact` is a real rail there).
2562            NavPresentation::Rail => {
2563                item.setAllowsFullHeightLayout(true);
2564                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2565                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2566            }
2567            // Zero the thickness bounds before collapsing takes effect, or the pane keeps a
2568            // minimum width and the detail never reaches the window edge.
2569            NavPresentation::Stack | NavPresentation::Tabs => {
2570                item.setMinimumThickness(0.0);
2571                item.setMaximumThickness(0.0);
2572            }
2573        }
2574    }
2575}
2576
2577/// Show/hide the stack-nav back header for the given page stack and re-frame the pages under
2578/// it. The header shows exactly while a pushed page (depth ≥ 1 above the root) is on top; each
2579/// page's `DayNavPage::setFrameSize` reports the new size so Day re-lays its content.
2580/// The split view of the navigation host in `window` that has a content-list pane, for the
2581/// tracking separator pinned to its second divider (docs/toolbars.md).
2582pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
2583    NAV_STATE.with(|m| {
2584        m.borrow()
2585            .values()
2586            .find(|st| {
2587                st.list_item.is_some()
2588                    && st
2589                        .sidebar_wrap
2590                        .window()
2591                        .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
2592            })
2593            .map(|st| unsafe { st._split_vc.splitView() })
2594    })
2595}
2596
2597fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
2598    let visible = pages.len() >= 2;
2599    hdr.bar.setHidden(!visible);
2600    unsafe {
2601        hdr.title.setStringValue(&NSString::from_str(
2602            hdr.titles.last().map(String::as_str).unwrap_or(""),
2603        ));
2604    }
2605    let frame = nav_page_frame(wrap, visible);
2606    for page in pages {
2607        unsafe { page.setFrame(frame) };
2608    }
2609}
2610
2611/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
2612/// chrome changes but the pages do not.
2613///
2614/// Both presentations already share one `NSSplitViewController` — a stack is the same split with
2615/// its sidebar item collapsed to zero thickness — so the morph is three moves, and none of them
2616/// touches a page's CONTENT:
2617///
2618/// 1. the sidebar item collapses or expands (AppKit animates it and re-runs the titlebar
2619///    separator on its own),
2620/// 2. the sidebar PAGE moves between the sidebar wrap and the head of the detail stack,
2621/// 3. the back header appears or hides, since only a stack has one.
2622///
2623/// `addSubview` re-parents a view rather than rebuilding it, so every page keeps its subtree,
2624/// its scroll position, and its first responder across the move.
2625fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
2626    let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
2627        NAV_STATE.with(|m| {
2628            let st = m.borrow();
2629            let s = st.get(&ptr_of(host))?;
2630            Some((
2631                s.sidebar_page.clone(),
2632                s.detail_wrap.clone(),
2633                s.sidebar_wrap.clone(),
2634                s.sidebar_item.clone(),
2635                s.presentation,
2636                s.root_title.clone(),
2637                s.node,
2638                s.selected,
2639            ))
2640        })
2641    else {
2642        return;
2643    };
2644    if was == next {
2645        return;
2646    }
2647    apply_sidebar_item(&sidebar_item, next);
2648    // Settle the split now rather than at the next natural layout pass. `setCollapsed` marks the
2649    // split view as needing layout; without this the pane keeps its old width for one more frame,
2650    // which the dayscript screenshot seam captures (it renders the window offscreen the instant
2651    // the patch returns) and which a user crossing a breakpoint sees as a stutter.
2652    NAV_STATE.with(|m| {
2653        if let Some(s) = m.borrow().get(&ptr_of(host)) {
2654            unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
2655        }
2656    });
2657    // A stack needs a back header; nothing else may show one. Built on demand and kept
2658    // afterwards — rebuilding it on every morph would leak a target per crossing.
2659    let stacked = next == NavPresentation::Stack;
2660    let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
2661    if stacked && header.is_none() {
2662        header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
2663    }
2664    if let Some(hdr) = header.as_ref() {
2665        hdr.bar.setHidden(true);
2666    }
2667    // No tab view here: `Tabs` is a PINNED style on this backend (`Cap::NavTabsAdaptive` is
2668    // off), resolved the same at every width, so a host never morphs into or out of it — its
2669    // `NSTabView` is built at realize and lives for the host.
2670    // Which page is on screen, by IDENTITY: moving the sidebar page in or out of the detail list
2671    // shifts every index past it, so an index captured now would name the wrong page after.
2672    let mut pages = NAV_STATE.with(|m| {
2673        m.borrow()
2674            .get(&ptr_of(host))
2675            .map(|s| s.pages.clone())
2676            .unwrap_or_default()
2677    });
2678    let shown_page = pages.get(sel).cloned();
2679    // The sidebar page is a stack ROOT only while stacked; otherwise it lives in its own pane,
2680    // which is the sidebar in `Split`/`Rail` and a collapsed one behind a tab bar in `Tabs`.
2681    if let Some(page) = sidebar_page {
2682        pages.retain(|p| ptr_of(p) != ptr_of(&page));
2683        unsafe {
2684            if stacked {
2685                detail_wrap.addSubview(&page);
2686                pages.insert(0, page.clone());
2687            } else {
2688                page.setFrame(sidebar_wrap.bounds());
2689                sidebar_wrap.addSubview(&page);
2690            }
2691        }
2692        // A pane always shows its page; as a stack root it may have been hidden under a push.
2693        page.setHidden(false);
2694    }
2695    let shown = shown_page
2696        .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
2697        .unwrap_or_else(|| pages.len().saturating_sub(1));
2698    for (i, page) in pages.iter().enumerate() {
2699        page.setHidden(i != shown);
2700    }
2701    NAV_STATE.with(|m| {
2702        let mut m = m.borrow_mut();
2703        if let Some(s) = m.get_mut(&ptr_of(host)) {
2704            s.presentation = next;
2705            s.pages = pages;
2706            s.selected = shown;
2707            s.header = header;
2708            if let Some(hdr) = s.header.as_ref() {
2709                // Depth drives visibility, and the header is meaningless anywhere but a stack.
2710                if stacked {
2711                    sync_nav_header(hdr, &s.detail_wrap, &s.pages);
2712                } else {
2713                    hdr.bar.setHidden(true);
2714                }
2715            }
2716            if !stacked {
2717                // Leaving the stack: the pages were inset below the header, so give them the
2718                // pane back.
2719                let frame = nav_page_frame(&s.detail_wrap, false);
2720                for page in &s.pages {
2721                    unsafe { page.setFrame(frame) };
2722                }
2723            }
2724        }
2725    });
2726}
2727
2728// ---------------------------------------------------------------------------
2729// The sidebar pane holds its width through NSSplitViewController's own holding priorities
2730// (docs/navigation.md) — a sidebar NSSplitViewItem pins its thickness and lets the detail
2731// absorb a window resize, which is exactly the Finder/Mail behavior the hand-rolled
2732// `splitView:shouldAdjustSizeOfSubview:` delegate used to approximate. The controller IS the
2733// split's delegate, so Day must not install one of its own.
2734// ---------------------------------------------------------------------------
2735
2736struct CoverSheet(Retained<NSWindow>);
2737impl Drop for CoverSheet {
2738    fn drop(&mut self) {
2739        // try_with: the table may already be gone when the thread's locals tear down.
2740        let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
2741        // Sheet transitions may run a nested AppKit update cycle. Defer them until the
2742        // core's tree borrow has ended; this retained pointer travels only to the main queue.
2743        let raw = Retained::into_raw(self.0.clone()) as usize;
2744        dispatch2::DispatchQueue::main().exec_async(move || {
2745            ffi_guard::contain((), || unsafe {
2746                let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
2747                if let Some(parent) = window.sheetParent() {
2748                    parent.endSheet(&window);
2749                }
2750                window.orderOut(None);
2751                window.setContentView(None);
2752            });
2753        });
2754    }
2755}
2756struct NavPageIvars {
2757    node: NodeId,
2758    /// A presented cover's strip under the window's title bar: the page paints it (its frame
2759    /// starts above the layout area) but lays its content out below it, and reports the
2760    /// remaining height (see `pin_below_title_bar`).
2761    top_inset: Cell<f64>,
2762    sheet: Cell<bool>,
2763    /// A half sheet (docs/cover.md): the window sheet stands half the parent's height.
2764    half: Cell<bool>,
2765    /// A large sheet (docs/cover.md "Large sheet"): the window sheet grows to
2766    /// `LARGE_SHEET_MAX`.
2767    large: Cell<bool>,
2768}
2769
2770define_class!(
2771    #[unsafe(super(NSView))]
2772    #[thread_kind = MainThreadOnly]
2773    #[name = "DayNavPage"]
2774    #[ivars = NavPageIvars]
2775    struct DayNavPage;
2776
2777    impl DayNavPage {
2778        #[unsafe(method(isFlipped))]
2779        fn is_flipped(&self) -> bool {
2780            true
2781        }
2782
2783        #[unsafe(method(setFrameSize:))]
2784        fn set_frame_size(&self, size: NSSize) {
2785            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
2786            // Pane-driven resize (splitter drag, window resize): report the usable size
2787            // so NavLayout re-lays this page's content (enqueue-only, §8.3).
2788            ffi_guard::contain((), || {
2789                let inset = self.ivars().top_inset.get();
2790                emit(
2791                    self.ivars().node,
2792                    Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
2793                );
2794            })
2795        }
2796    }
2797);
2798
2799impl DayNavPage {
2800    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2801        let this = Self::alloc(mtm).set_ivars(NavPageIvars {
2802            node,
2803            top_inset: Cell::new(0.0),
2804            sheet: Cell::new(false),
2805            half: Cell::new(false),
2806            large: Cell::new(false),
2807        });
2808        unsafe { msg_send![super(this), init] }
2809    }
2810}
2811
2812// ---------------------------------------------------------------------------
2813// Inspector (docs/inspector.md): an NSSplitViewController whose trailing pane is a REAL
2814// inspector item (`inspectorWithViewController:`) — the system treatment for exactly this
2815// surface: its own backing material, the standard thickness handling, full-height layout
2816// under the titlebar. Day's bound signal is the only visibility driver (the item cannot be
2817// user-collapsed), so this backend never emits `Event::InspectorChanged`.
2818// ---------------------------------------------------------------------------
2819
2820struct InspectorState {
2821    content_wrap: Handle,
2822    panel_wrap: Handle,
2823    /// Retained so the controller (the split's delegate) lives as long as its split.
2824    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2825    panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
2826}
2827
2828// ---------------------------------------------------------------------------
2829// Split (docs/split.md): a plain `NSSplitView` inside a flipped wrap (the wrap is the handle,
2830// so `set_frame`'s nav-host treatment of split views never sees it), two arranged flipped
2831// subviews as the panes, and a delegate that places the divider by the bound share, keeps
2832// both panes above the minimum, and reports a drag back as the new share.
2833// ---------------------------------------------------------------------------
2834
2835struct SplitState {
2836    split: Retained<objc2_app_kit::NSSplitView>,
2837    first_wrap: Handle,
2838    second_wrap: Handle,
2839    delegate: Retained<DaySplitDelegate>,
2840}
2841
2842struct SplitDelegateIvars {
2843    node: NodeId,
2844    min_pane: f64,
2845    /// The share as last patched or reported: what a report is compared against, and where
2846    /// the divider goes when the split first has a size or turns.
2847    share: Cell<f64>,
2848    /// The divider has been placed once; before that the split has no size to place it in.
2849    positioned: Cell<bool>,
2850    /// Day is moving the divider itself: the resize that follows is not a report.
2851    suppress: Cell<bool>,
2852}
2853
2854define_class!(
2855    #[unsafe(super(NSObject))]
2856    #[thread_kind = MainThreadOnly]
2857    #[name = "DaySplitDelegate"]
2858    #[ivars = SplitDelegateIvars]
2859    struct DaySplitDelegate;
2860
2861    unsafe impl NSObjectProtocol for DaySplitDelegate {}
2862
2863    unsafe impl NSSplitViewDelegate for DaySplitDelegate {
2864        #[unsafe(method(splitViewDidResizeSubviews:))]
2865        fn did_resize(&self, notification: &NSNotification) {
2866            ffi_guard::contain((), || {
2867                let Some(obj) = notification.object() else {
2868                    return;
2869                };
2870                let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
2871                    return;
2872                };
2873                let iv = self.ivars();
2874                let usable = split_usable(&sv);
2875                if usable <= 0.0 {
2876                    return;
2877                }
2878                // The first resize with a size: place the divider by the share, once.
2879                if !iv.positioned.replace(true) {
2880                    split_place(&sv, iv);
2881                    return;
2882                }
2883                if iv.suppress.get() {
2884                    return;
2885                }
2886                let Some(first) = sv.subviews().iter().next() else {
2887                    return;
2888                };
2889                let f = first.frame();
2890                let a = if sv.isVertical() {
2891                    f.size.width
2892                } else {
2893                    f.size.height
2894                };
2895                let share = (a / usable).clamp(0.0, 1.0);
2896                if (share - iv.share.get()).abs() > 1e-4 {
2897                    iv.share.set(share);
2898                    emit(iv.node, Event::ValueChanged(share));
2899                }
2900            })
2901        }
2902
2903        #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
2904        fn constrain_min(
2905            &self,
2906            _sv: &objc2_app_kit::NSSplitView,
2907            proposed: f64,
2908            _index: isize,
2909        ) -> f64 {
2910            proposed.max(self.ivars().min_pane)
2911        }
2912
2913        #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
2914        fn constrain_max(
2915            &self,
2916            sv: &objc2_app_kit::NSSplitView,
2917            proposed: f64,
2918            _index: isize,
2919        ) -> f64 {
2920            proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
2921        }
2922    }
2923);
2924
2925impl DaySplitDelegate {
2926    fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
2927        let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
2928            node,
2929            min_pane,
2930            share: Cell::new(share.clamp(0.0, 1.0)),
2931            positioned: Cell::new(false),
2932            suppress: Cell::new(false),
2933        });
2934        unsafe { msg_send![super(this), init] }
2935    }
2936}
2937
2938/// The length the two panes share along the split's axis: the frame minus the divider.
2939fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
2940    let frame = sv.frame();
2941    let len = if sv.isVertical() {
2942        frame.size.width
2943    } else {
2944        frame.size.height
2945    };
2946    (len - sv.dividerThickness()).max(0.0)
2947}
2948
2949/// Move the divider so the first pane takes the share, silently (Day's own write, not a drag).
2950fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
2951    let usable = split_usable(sv);
2952    if usable <= 0.0 {
2953        return;
2954    }
2955    iv.suppress.set(true);
2956    unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
2957    iv.suppress.set(false);
2958}
2959
2960// ---------------------------------------------------------------------------
2961
2962// ---------------------------------------------------------------------------
2963// DayNavMenuData — flat NSOutlineView source list for nav_menu() (docs/navigation.md)
2964// ---------------------------------------------------------------------------
2965
2966struct NavMenuIvars {
2967    node: NodeId,
2968    items: RefCell<Vec<Retained<NSString>>>,
2969    /// Pre-resolved template icons per row (docs/navigation.md), `None` where a row has no icon.
2970    /// Template images tint with the source-list's selection/appearance, so they read in light,
2971    /// dark, and while selected — the macOS-idiomatic sidebar look (Finder/Mail).
2972    icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2973    /// How much of each icon's box its drawing spans (`nav_icon_fill`), index-aligned with
2974    /// `icons`: the cell sizes the icon so the drawing matches a system sidebar glyph.
2975    icon_fills: RefCell<Vec<f64>>,
2976    /// Per-row icon tint (docs/vectors.md): recolors the template glyph via contentTintColor;
2977    /// `None` keeps the source-list's neutral template tint.
2978    tints: RefCell<Vec<Option<day_spec::Color>>>,
2979    /// Trailing accessory per item row (an unread count), `None` where a row has none.
2980    badges: RefCell<Vec<Option<Retained<NSString>>>>,
2981    /// Trailing accessory GLYPH per row, in the same slot as `badges` and drawn after it —
2982    /// a starred page's star. Resolved to images once per rebuild, like `icons`.
2983    icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
2984    badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2985    /// Tint for `badge_icons`; `None` keeps the neutral template tint.
2986    badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
2987    /// Per-row context menu (docs/menus.md), empty = none. Built into an NSMenu and attached
2988    /// to the row's cell view, so a secondary click pops it like any native sidebar menu.
2989    menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
2990    /// Which items drag to reorder (`NavMenuProps::movable`); empty when none do.
2991    movable: RefCell<Vec<bool>>,
2992    /// Movable rows may cross section headers (`NavMenuProps::regroup`); set at creation.
2993    regroup: std::cell::Cell<bool>,
2994    /// Which movable items keep their section's sorted order (`NavMenuProps::sorted`).
2995    sorted: RefCell<Vec<bool>>,
2996    /// The outline's rows, in display order: `Some(i)` is item `i`, `None` is a section
2997    /// header. Day addresses rows by ITEM index, so every selection crossing the boundary
2998    /// goes through this map — a header must never shift what index 3 means.
2999    rows: RefCell<Vec<Option<usize>>>,
3000    /// One retained NSString per outline row: the row's text (a header's or an item's).
3001    row_objects: RefCell<Vec<Retained<NSString>>>,
3002    /// One NSNumber per outline row, holding the row's index: the outline's item IDENTITY.
3003    /// NSOutlineView matches items with `isEqual:`, so an NSString cannot be the identity —
3004    /// a section header titled "Controls" and an item titled "Controls" would collapse into one
3005    /// row, and the header would wear the item's icon. Row indexes are unique by construction.
3006    row_ids: RefCell<Vec<Retained<NSNumber>>>,
3007    /// Programmatic selection in flight: don't re-emit SelectionChanged.
3008    suppress: std::cell::Cell<bool>,
3009}
3010
3011struct NavCellIvars {
3012    /// The trailing accessories (an unread count, a status glyph), when the row has any: the
3013    /// label ends before them.
3014    accessory: RefCell<Option<Retained<NSView>>>,
3015    /// The unread count among them, sized to follow the row's text.
3016    count: RefCell<Option<Retained<NSTextField>>>,
3017    /// How much of the icon's box its drawing spans (`nav_icon_fill`).
3018    icon_fill: std::cell::Cell<f64>,
3019}
3020
3021define_class!(
3022    /// A sidebar row's cell. `NSTableCellView` lays out its icon and label itself, at the
3023    /// size the outline's row size style gives them: the system's Sidebar icon size setting,
3024    /// followed live (docs/navigation.md). This only makes room for the trailing accessories,
3025    /// which AppKit knows nothing about.
3026    #[unsafe(super(objc2_app_kit::NSTableCellView))]
3027    #[thread_kind = MainThreadOnly]
3028    #[name = "DayNavCell"]
3029    #[ivars = NavCellIvars]
3030    struct DayNavCell;
3031
3032    unsafe impl NSObjectProtocol for DayNavCell {}
3033
3034    impl DayNavCell {
3035        #[unsafe(method(layout))]
3036        fn layout(&self) {
3037            let _: () = unsafe { msg_send![super(self), layout] };
3038            ffi_guard::contain((), || self.fit_accessories());
3039        }
3040    }
3041);
3042
3043impl DayNavCell {
3044    fn new(mtm: MainThreadMarker) -> Retained<Self> {
3045        let this = Self::alloc(mtm).set_ivars(NavCellIvars {
3046            accessory: RefCell::new(None),
3047            count: RefCell::new(None),
3048            icon_fill: std::cell::Cell::new(1.0),
3049        });
3050        unsafe { msg_send![super(this), init] }
3051    }
3052
3053    /// After AppKit's layout: the count takes a size two points under the label's, and the
3054    /// label, which AppKit stretches to the cell's trailing edge, ends 6pt before the
3055    /// accessories so a long title truncates instead of running under its count. A showing
3056    /// progress ring re-fits the icon AppKit just sized.
3057    fn fit_accessories(&self) {
3058        let label = unsafe { self.textField() };
3059        if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
3060            let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
3061                (f.pointSize() - 2.0).max(9.0)
3062            });
3063            if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
3064                unsafe {
3065                    count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
3066                        size,
3067                        objc2_app_kit::NSFontWeightRegular,
3068                    )));
3069                }
3070                self.layoutSubtreeIfNeeded();
3071            }
3072        }
3073        if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
3074            let mut frame = label.frame();
3075            let end = accessory.frame().origin.x - 6.0;
3076            if frame.origin.x + frame.size.width > end {
3077                frame.size.width = (end - frame.origin.x).max(0.0);
3078                label.setFrame(frame);
3079            }
3080        }
3081        if let Some(icon) = unsafe { self.imageView() } {
3082            fit_nav_icon(&icon, self.ivars().icon_fill.get());
3083            nav_progress::fit(&icon);
3084        }
3085    }
3086}
3087
3088thread_local! {
3089    /// The side of a system sidebar glyph per symbol configuration (see `fit_nav_icon`).
3090    static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
3091}
3092
3093/// Draw a sidebar row's icon so its drawing is the size a system sidebar draws its SF Symbol,
3094/// centered in the slot AppKit lays out for it; `fill` is how much of the image's box the
3095/// drawing spans (`nav_icon_fill`). The slot is wider than the glyph AppKit puts there (22pt for a
3096/// 16pt glyph at Medium), and Day's icons are artwork that fills whatever frame it gets, so
3097/// left at the slot's size they read a third larger and heavier than Finder's or Mail's.
3098/// The side is measured, not tabled: a square symbol (`gearshape`) drawn with the symbol
3099/// configuration the row size style gave this image view, so it tracks the Sidebar icon size
3100/// setting and whatever a later macOS draws.
3101fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
3102    let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
3103        return;
3104    };
3105    let slot = icon.frame();
3106    // Configurations compare by value, and AppKit gives every cell of a row size style an
3107    // equal one, so the hash names the style.
3108    let key = config.hash() as u64;
3109    let side = NAV_GLYPH_SIDES
3110        .with(|m| m.borrow().get(&key).copied())
3111        .or_else(|| {
3112            let symbol =
3113                objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
3114                    &NSString::from_str("gearshape"),
3115                    None,
3116                )?;
3117            let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
3118            NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
3119            Some(side)
3120        });
3121    // The box that puts the drawing itself at the glyph's size: a Material Symbols icon keeps
3122    // the margin of its grid inside the box, so its box is that much larger.
3123    let Some(side) = side
3124        .filter(|s| *s > 0.0)
3125        .map(|s| (s / fill.clamp(0.25, 1.0)).round())
3126    else {
3127        return;
3128    };
3129    if slot.size.width <= side && slot.size.height <= side {
3130        return;
3131    }
3132    icon.setFrame(NSRect::new(
3133        NSPoint::new(
3134            (slot.origin.x + (slot.size.width - side) / 2.0).round(),
3135            (slot.origin.y + (slot.size.height - side) / 2.0).round(),
3136        ),
3137        NSSize::new(side, side),
3138    ));
3139}
3140
3141define_class!(
3142    #[unsafe(super(objc2_app_kit::NSTableRowView))]
3143    #[thread_kind = MainThreadOnly]
3144    #[name = "DayNavRowView"]
3145    struct DayNavRowView;
3146
3147    unsafe impl NSObjectProtocol for DayNavRowView {}
3148
3149    impl DayNavRowView {
3150        /// Always report the emphasized (key-window) state, so the selected sidebar row draws
3151        /// the accent pill with auto-whitened label/icon in both themes. Without this, a run
3152        /// whose window never becomes key (scripted screenshot captures) falls back to the
3153        /// unemphasized selection fill, which under a forced appearance rendered as a
3154        /// near-black pill that swallowed the row's label.
3155        #[unsafe(method(isEmphasized))]
3156        fn is_emphasized(&self) -> bool {
3157            true
3158        }
3159    }
3160);
3161
3162define_class!(
3163    #[unsafe(super(objc2_app_kit::NSOutlineView))]
3164    #[thread_kind = MainThreadOnly]
3165    #[name = "DayNavOutlineView"]
3166    struct DayNavOutlineView;
3167
3168    unsafe impl NSObjectProtocol for DayNavOutlineView {}
3169
3170    impl DayNavOutlineView {
3171        /// The clicked row's context menu (docs/menus.md): NSTableView-family views consume
3172        /// right-clicks themselves, so per-row menus are served here — resolve the row under
3173        /// the click, then build the same NSMenu the piece decorator would.
3174        #[unsafe(method_id(menuForEvent:))]
3175        fn menu_for_event(
3176            &self,
3177            event: &objc2_app_kit::NSEvent,
3178        ) -> Option<Retained<NSMenu>> {
3179            ffi_guard::contain(None, || {
3180                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3181                let row = unsafe { self.rowAtPoint(point) };
3182                let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
3183                // `define_class!` rewrites the return, so no early `return` — one expression.
3184                match data {
3185                    None => None,
3186                    Some(d) => {
3187                        let items = d
3188                            .item_of_row(row)
3189                            .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
3190                            .unwrap_or_default();
3191                        if items.is_empty() {
3192                            None
3193                        } else {
3194                            Some(build_ns_menu(d.mtm(), "", &items))
3195                        }
3196                    }
3197                }
3198            })
3199        }
3200    }
3201);
3202
3203define_class!(
3204    #[unsafe(super(NSObject))]
3205    #[thread_kind = MainThreadOnly]
3206    #[name = "DayNavMenuData"]
3207    #[ivars = NavMenuIvars]
3208    struct DayNavMenuData;
3209
3210    unsafe impl NSObjectProtocol for DayNavMenuData {}
3211
3212    unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3213        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3214        fn number_of_children(
3215            &self,
3216            _ov: &objc2_app_kit::NSOutlineView,
3217            item: Option<&objc2::runtime::AnyObject>,
3218        ) -> isize {
3219            if item.is_none() {
3220                self.ivars().row_objects.borrow().len() as isize
3221            } else {
3222                0
3223            }
3224        }
3225
3226        #[unsafe(method_id(outlineView:child:ofItem:))]
3227        fn child_of_item(
3228            &self,
3229            _ov: &objc2_app_kit::NSOutlineView,
3230            index: isize,
3231            _item: Option<&objc2::runtime::AnyObject>,
3232        ) -> Retained<objc2::runtime::AnyObject> {
3233            let ids = self.ivars().row_ids.borrow();
3234            // AppKit only asks for children it was told exist, but a stale query racing a
3235            // reload must degrade (an unmatched identity) rather than index out of bounds —
3236            // a panic here unwinds into an ObjC frame and aborts.
3237            let id = ids
3238                .get(index as usize)
3239                .cloned()
3240                .unwrap_or_else(|| NSNumber::new_isize(-1));
3241            unsafe { objc2::rc::Retained::cast_unchecked(id) }
3242        }
3243
3244        #[unsafe(method(outlineView:isItemExpandable:))]
3245        fn is_expandable(
3246            &self,
3247            _ov: &objc2_app_kit::NSOutlineView,
3248            _item: &objc2::runtime::AnyObject,
3249        ) -> bool {
3250            false
3251        }
3252
3253        // --- drag-to-reorder (docs/navigation.md "Reordering sidebar destinations"): the
3254        // outline's own drag pipeline, with the Gap placeholder Finder's sidebar shows. A row
3255        // moves within the run of movable rows around it, or, regrouping, into any section of
3256        // movable rows (`regroup_gap`); the app's data change brings the new order back as
3257        // `NavMenuPatch::Items`.
3258
3259        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3260        fn pasteboard_writer_for_item(
3261            &self,
3262            _ov: &objc2_app_kit::NSOutlineView,
3263            item: &objc2::runtime::AnyObject,
3264        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3265            let make = || {
3266                let row = Self::outline_row(item);
3267                let index = self.item_of_row(row)?;
3268                if !self.is_movable(index) {
3269                    return None;
3270                }
3271                let pbitem = objc2_app_kit::NSPasteboardItem::new();
3272                unsafe {
3273                    pbitem.setString_forType(
3274                        &NSString::from_str(&row.to_string()),
3275                        &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3276                    );
3277                }
3278                Some(ProtocolObject::from_retained(pbitem))
3279            };
3280            ffi_guard::contain(None, make)
3281        }
3282
3283        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3284        fn validate_drop(
3285            &self,
3286            ov: &objc2_app_kit::NSOutlineView,
3287            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3288            item: Option<&objc2::runtime::AnyObject>,
3289            child_index: isize,
3290        ) -> objc2_app_kit::NSDragOperation {
3291            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3292                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3293                    return objc2_app_kit::NSDragOperation::None;
3294                };
3295                // A drop past the run's end lands at that end: move the gap there.
3296                if drop.retarget {
3297                    unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3298                }
3299                objc2_app_kit::NSDragOperation::Move
3300            })
3301        }
3302
3303        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3304        fn accept_drop(
3305            &self,
3306            ov: &objc2_app_kit::NSOutlineView,
3307            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3308            item: Option<&objc2::runtime::AnyObject>,
3309            child_index: isize,
3310        ) -> bool {
3311            ffi_guard::contain(false, || {
3312                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3313                    return false;
3314                };
3315                // Deferred through the event queue: the app's callback never runs inside
3316                // AppKit's drop, and its data change reloads the rows in the new order.
3317                match drop.moves {
3318                    Some(NavMove::Reorder { from, to }) => {
3319                        emit(self.ivars().node, Event::ListReorder { from, to });
3320                    }
3321                    Some(NavMove::Regroup {
3322                        from,
3323                        section,
3324                        before,
3325                    }) => emit(
3326                        self.ivars().node,
3327                        Event::NavRegroup {
3328                            from,
3329                            section,
3330                            before,
3331                        },
3332                    ),
3333                    None => {}
3334                }
3335                true
3336            })
3337        }
3338    }
3339
3340    unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3341
3342    unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3343        /// Section headers are AppKit group rows: the source-list treatment (small, bold,
3344        /// secondary) comes free, and they are excluded from selection below.
3345        #[unsafe(method(outlineView:isGroupItem:))]
3346        fn is_group_item(
3347            &self,
3348            _ov: &objc2_app_kit::NSOutlineView,
3349            item: &objc2::runtime::AnyObject,
3350        ) -> bool {
3351            let row = Self::outline_row(item);
3352            row >= 0 && self.item_of_row(row).is_none()
3353        }
3354
3355        #[unsafe(method(outlineView:shouldSelectItem:))]
3356        fn should_select(
3357            &self,
3358            _ov: &objc2_app_kit::NSOutlineView,
3359            item: &objc2::runtime::AnyObject,
3360        ) -> bool {
3361            self.item_of_row(Self::outline_row(item)).is_some()
3362        }
3363
3364        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3365        fn view_for(
3366            &self,
3367            ov: &objc2_app_kit::NSOutlineView,
3368            _col: Option<&objc2_app_kit::NSTableColumn>,
3369            item: &objc2::runtime::AnyObject,
3370        ) -> Option<Retained<NSView>> {
3371            let mtm = self.mtm();
3372            let row = Self::outline_row(item);
3373            let text = self
3374                .ivars()
3375                .row_objects
3376                .borrow()
3377                .get(usize::try_from(row).unwrap_or(usize::MAX))
3378                .cloned();
3379            // No early returns: the method_id macro owns the return conversion.
3380            text.map(|text| {
3381                let text: &NSString = &text;
3382                let Some(index) = self.item_of_row(row) else {
3383                    // A section header: a plain label. AppKit gives group rows their own
3384                    // typography and places the text, so this only supplies it.
3385                    let cell = DayNavCell::new(mtm);
3386                    let label = unsafe { NSTextField::labelWithString(text, mtm) };
3387                    unsafe {
3388                        label.cell().inspect(|c| {
3389                            c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3390                        });
3391                        cell.addSubview(&label);
3392                        cell.setTextField(Some(&label));
3393                    }
3394                    return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3395                };
3396                let icon = self
3397                    .ivars()
3398                    .icons
3399                    .borrow()
3400                    .get(index)
3401                    .and_then(|o| o.clone());
3402                let badge = self
3403                    .ivars()
3404                    .badges
3405                    .borrow()
3406                    .get(index)
3407                    .and_then(|o| o.clone());
3408                let badge_icon = self
3409                    .ivars()
3410                    .badge_icons
3411                    .borrow()
3412                    .get(index)
3413                    .and_then(|o| o.clone());
3414                let badge_tint = self
3415                    .ivars()
3416                    .badge_tints
3417                    .borrow()
3418                    .get(index)
3419                    .copied()
3420                    .flatten();
3421                // The cell places the icon and the label itself, at the row size style's size
3422                // (the system's Sidebar icon size); `DayNavCell` keeps the label clear of the
3423                // trailing accessories.
3424                let cell = DayNavCell::new(mtm);
3425                let label = unsafe { NSTextField::labelWithString(text, mtm) };
3426                unsafe {
3427                    // Feed titles are arbitrarily long, so the label truncates with an
3428                    // ellipsis within the frame the cell gives it.
3429                    label.cell().inspect(|c| {
3430                        c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3431                    });
3432                    cell.addSubview(&label);
3433                    cell.setTextField(Some(&label));
3434                    // The badge sits at the trailing edge and keeps its intrinsic width; the
3435                    // label truncates into whatever is left, so a long feed name never pushes
3436                    // its own unread count off the pane.
3437                    // Both accessories share the trailing slot: the count (if any) and then
3438                    // the status glyph (if any), in a stack so a row can carry either or both
3439                    // without the constraints below caring which it got.
3440                    let accessory = objc2_app_kit::NSStackView::new(mtm);
3441                    accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3442                    accessory.setOrientation(
3443                        objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3444                    );
3445                    accessory.setSpacing(4.0);
3446                    let mut has_accessory = false;
3447                    let trailing: Retained<NSView> = match &badge {
3448                        Some(text) => {
3449                            let b = NSTextField::labelWithString(text, mtm);
3450                            b.setTranslatesAutoresizingMaskIntoConstraints(false);
3451                            b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3452                            b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3453                            b.setFont(Some(
3454                                &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3455                                    objc2_app_kit::NSFont::smallSystemFontSize(),
3456                                    objc2_app_kit::NSFontWeightRegular,
3457                                ),
3458                            ));
3459                            b.setContentCompressionResistancePriority_forOrientation(
3460                                objc2_app_kit::NSLayoutPriorityRequired,
3461                                objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3462                            );
3463                            *cell.ivars().count.borrow_mut() = Some(b.clone());
3464                            accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3465                                objc2::rc::Retained::into_super(b),
3466                            ));
3467                            has_accessory = true;
3468                            let v: Retained<NSView> =
3469                                objc2::rc::Retained::into_super(accessory.clone());
3470                            v
3471                        }
3472                        None => objc2::rc::Retained::into_super(accessory.clone()),
3473                    };
3474                    // The status glyph, tinted where the app gave it a meaning-bearing color
3475                    // (a star is yellow because that is what a star IS, not because the theme
3476                    // says so). Template images take contentTintColor exactly as the row's
3477                    // leading icon does.
3478                    if let Some(img) = &badge_icon {
3479                        let iv = objc2_app_kit::NSImageView::new(mtm);
3480                        iv.setImage(Some(img));
3481                        iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3482                        if let Some(c) = badge_tint {
3483                            iv.setContentTintColor(Some(&nscolor(c)));
3484                        }
3485                        iv.setContentCompressionResistancePriority_forOrientation(
3486                            objc2_app_kit::NSLayoutPriorityRequired,
3487                            objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3488                        );
3489                        accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
3490                        has_accessory = true;
3491                    }
3492                    cell.addSubview(&trailing);
3493                    if has_accessory {
3494                        *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
3495                    }
3496                    objc2_app_kit::NSLayoutConstraint::activateConstraints(
3497                        &objc2_foundation::NSArray::from_retained_slice(&[
3498                            trailing
3499                                .trailingAnchor()
3500                                .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
3501                            trailing
3502                                .centerYAnchor()
3503                                .constraintEqualToAnchor(&cell.centerYAnchor()),
3504                        ]),
3505                    );
3506                }
3507                if let Some(img) = icon {
3508                    let fill = self.ivars().icon_fills.borrow().get(index).copied();
3509                    cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
3510                    let tint = self.ivars().tints.borrow().get(index).copied().flatten();
3511                    let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
3512                    unsafe {
3513                        iv.setImage(Some(&img));
3514                        // Per-row tint (docs/vectors.md): the icons are template images, so
3515                        // contentTintColor recolors the alpha mask; None keeps the neutral look.
3516                        if let Some(t) = tint {
3517                            iv.setContentTintColor(Some(&nscolor(t)));
3518                        }
3519                        iv.setImageScaling(
3520                            objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
3521                        );
3522                        cell.addSubview(&iv);
3523                        cell.setImageView(Some(&iv));
3524                        let progress = self
3525                            .ivars()
3526                            .icon_progress
3527                            .borrow()
3528                            .iter()
3529                            .find(|(row, _)| *row == index)
3530                            .map(|(_, f)| *f);
3531                        nav_progress::update(&iv, progress);
3532                    }
3533                }
3534                objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
3535            })
3536        }
3537
3538        #[unsafe(method_id(outlineView:rowViewForItem:))]
3539        fn row_view_for(
3540            &self,
3541            _ov: &objc2_app_kit::NSOutlineView,
3542            _item: &objc2::runtime::AnyObject,
3543        ) -> Retained<objc2_app_kit::NSTableRowView> {
3544            let row: Retained<DayNavRowView> =
3545                unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
3546            objc2::rc::Retained::into_super(row)
3547        }
3548
3549        #[unsafe(method(outlineViewSelectionDidChange:))]
3550        fn selection_did_change(&self, notification: &NSNotification) {
3551            ffi_guard::contain((), || {
3552                if self.ivars().suppress.get() {
3553                    return;
3554                }
3555                let Some(obj) = (unsafe { notification.object() }) else {
3556                    return;
3557                };
3558                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
3559                    return;
3560                };
3561                let row = unsafe { ov.selectedRow() };
3562                if let Some(item) = self.item_of_row(row) {
3563                    emit(self.ivars().node, Event::SelectionChanged(item as i64));
3564                }
3565            })
3566        }
3567    }
3568);
3569
3570thread_local! {
3571    /// `nav_icon_fill` per icon name: a sidebar rebuilds its rows on every count change, and an
3572    /// icon's drawing does not change with them.
3573    static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
3574}
3575
3576/// `nav_icon_fill` for each resolved icon, by name; 1 where a row has none.
3577fn nav_icon_fills(
3578    names: &[Option<String>],
3579    images: &[Option<Retained<objc2_app_kit::NSImage>>],
3580) -> Vec<f64> {
3581    names
3582        .iter()
3583        .zip(images)
3584        .map(|(name, image)| match (name, image) {
3585            (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
3586                *m.borrow_mut()
3587                    .entry(name.clone())
3588                    .or_insert_with(|| nav_icon_fill(image))
3589            }),
3590            _ => 1.0,
3591        })
3592        .collect()
3593}
3594
3595/// How much of an icon's box its drawing spans along its longer side, in (0, 1]: a Material
3596/// Symbols glyph keeps the 80-unit margin of its 960-unit grid (about 0.83), an SF Symbol export
3597/// is boxed to its content (1), and artwork usually fills its square. Measured from the alpha of
3598/// one small render, since a plain SVG says nothing about where its drawing sits.
3599fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
3600    const PX: f64 = 64.0;
3601    let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
3602        return 1.0;
3603    };
3604    let (w, h) = (
3605        rep.pixelsWide().max(0) as usize,
3606        rep.pixelsHigh().max(0) as usize,
3607    );
3608    let stride = rep.bytesPerRow().max(0) as usize;
3609    let data = unsafe { rep.bitmapData() };
3610    if data.is_null() || stride < w * 4 {
3611        return 1.0;
3612    }
3613    // SAFETY: `scaled_rep` made a meshed 8-bit RGBA bitmap of `h` rows of `stride` bytes, which
3614    // `rep` owns and keeps alive for this borrow.
3615    let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
3616    let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
3617    for y in 0..h {
3618        for x in 0..w {
3619            if bytes[y * stride + x * 4 + 3] > 24 {
3620                (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
3621            }
3622        }
3623    }
3624    if x1 <= x0 || y1 <= y0 {
3625        return 1.0;
3626    }
3627    // The render stretched the image to a square; back in the image's own proportions, the
3628    // drawing's longer extent over the image's longer side is what proportional scaling keeps.
3629    let size = image.size();
3630    let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
3631    let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
3632    ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
3633}
3634
3635fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
3636    // A bundled icon name → a template NSImage (tinted by the source list); `None` per iconless row.
3637    icons
3638        .iter()
3639        .map(|ic| {
3640            let name = ic.as_deref()?;
3641            // Prefer the glyph SVG (docs/vectors.md): NSImage renders it at display size.
3642            let path = day_spec::resource::resolve_vector_svg(name)
3643                .or_else(|| day_spec::resource::resolve_image_file(name))?;
3644            use objc2::AllocAnyThread as _;
3645            let img = unsafe {
3646                objc2_app_kit::NSImage::initWithContentsOfFile(
3647                    objc2_app_kit::NSImage::alloc(),
3648                    &NSString::from_str(&path.to_string_lossy()),
3649                )
3650            }?;
3651            // Downloaded/user-file icons are artwork; bundled glyphs remain templates.
3652            unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
3653            Some(img)
3654        })
3655        .collect()
3656}
3657
3658impl DayNavMenuData {
3659    #[allow(clippy::too_many_arguments)]
3660    fn new(
3661        mtm: MainThreadMarker,
3662        node: NodeId,
3663        items: &[String],
3664        icons: &[Option<String>],
3665        badges: &[Option<String>],
3666        badge_icons: &[Option<String>],
3667        badge_tints: &[Option<day_spec::Color>],
3668        sections: &[Option<String>],
3669        tints: &[Option<day_spec::Color>],
3670        menus: &[Vec<day_spec::MenuItem>],
3671    ) -> Retained<Self> {
3672        let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
3673            node,
3674            items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
3675            icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
3676            icons: RefCell::new(resolve_nav_icons(icons)),
3677            tints: RefCell::new(tints.to_vec()),
3678            menus: RefCell::new(menus.to_vec()),
3679            movable: RefCell::new(Vec::new()),
3680            regroup: std::cell::Cell::new(false),
3681            sorted: RefCell::new(Vec::new()),
3682            badges: RefCell::new(ns_badges(badges)),
3683            icon_progress: RefCell::new(Vec::new()),
3684            badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
3685            badge_tints: RefCell::new(badge_tints.to_vec()),
3686            rows: RefCell::new(Vec::new()),
3687            row_objects: RefCell::new(Vec::new()),
3688            row_ids: RefCell::new(Vec::new()),
3689            suppress: std::cell::Cell::new(false),
3690        });
3691        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
3692        this.rebuild_rows(items, sections);
3693        this
3694    }
3695
3696    /// Data-driven rows changed (`NavMenuPatch::Items`): swap the stored decorations in place.
3697    // The parameters are the patch's payload: index-aligned per-row decoration arrays, each
3698    // landing in its own ivar. Bundling them would just move the same eight fields.
3699    #[allow(clippy::too_many_arguments)]
3700    fn set_items(
3701        &self,
3702        items: &[String],
3703        icons: &[Option<String>],
3704        badges: &[Option<String>],
3705        badge_icons: &[Option<String>],
3706        badge_tints: &[Option<day_spec::Color>],
3707        sections: &[Option<String>],
3708        tints: &[Option<day_spec::Color>],
3709        menus: &[Vec<day_spec::MenuItem>],
3710    ) {
3711        *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
3712        let resolved = resolve_nav_icons(icons);
3713        *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
3714        *self.ivars().icons.borrow_mut() = resolved;
3715        *self.ivars().tints.borrow_mut() = tints.to_vec();
3716        *self.ivars().menus.borrow_mut() = menus.to_vec();
3717        *self.ivars().badges.borrow_mut() = ns_badges(badges);
3718        self.ivars().icon_progress.borrow_mut().clear();
3719        *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
3720        *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
3721        self.rebuild_rows(items, sections);
3722    }
3723
3724    /// Flatten items + section headers into the outline's display rows. Each row gets its own
3725    /// retained NSString so the outline can tell two rows apart by identity even when their
3726    /// labels match (two feeds legitimately share a title).
3727    fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
3728        let mut rows = Vec::with_capacity(items.len());
3729        let mut objects = Vec::with_capacity(items.len());
3730        for (i, label) in items.iter().enumerate() {
3731            if let Some(Some(header)) = sections.get(i) {
3732                rows.push(None);
3733                objects.push(NSString::from_str(header));
3734            }
3735            rows.push(Some(i));
3736            objects.push(NSString::from_str(label));
3737        }
3738        let ids = (0..objects.len())
3739            .map(|i| NSNumber::new_isize(i as isize))
3740            .collect();
3741        *self.ivars().rows.borrow_mut() = rows;
3742        *self.ivars().row_objects.borrow_mut() = objects;
3743        *self.ivars().row_ids.borrow_mut() = ids;
3744    }
3745
3746    /// The outline row an item object names — the index its NSNumber identity carries — or
3747    /// `-1` for anything that is not one of ours (a stale query racing a reload).
3748    fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
3749        item.downcast_ref::<NSNumber>()
3750            .map(|n| n.integerValue())
3751            .unwrap_or(-1)
3752    }
3753
3754    /// Outline row → day item index.
3755    fn item_of_row(&self, row: isize) -> Option<usize> {
3756        if row < 0 {
3757            return None;
3758        }
3759        self.ivars()
3760            .rows
3761            .borrow()
3762            .get(row as usize)
3763            .copied()
3764            .flatten()
3765    }
3766
3767    /// Day item index → outline row.
3768    fn row_of_item(&self, item: usize) -> Option<usize> {
3769        self.ivars()
3770            .rows
3771            .borrow()
3772            .iter()
3773            .position(|r| *r == Some(item))
3774    }
3775
3776    fn is_movable(&self, item: usize) -> bool {
3777        self.ivars()
3778            .movable
3779            .borrow()
3780            .get(item)
3781            .copied()
3782            .unwrap_or(false)
3783    }
3784
3785    /// What a drop proposal means for a reorder, or `None` when it is no drop of ours: a drag
3786    /// from another view, of a row that cannot move, or (regrouping) to a gap no rule allows.
3787    /// Reordering, the gap clamps to the run of movable rows around the dragged one, which
3788    /// section headers and fixed rows end ([`reorder_gap`]); regrouping, see [`regroup_gap`].
3789    fn nav_drop(
3790        &self,
3791        ov: &objc2_app_kit::NSOutlineView,
3792        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3793        item: Option<&objc2::runtime::AnyObject>,
3794        child_index: isize,
3795    ) -> Option<NavDrop> {
3796        let src = unsafe { info.draggingSource() }?;
3797        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
3798            != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
3799        {
3800            return None;
3801        }
3802        let pb = unsafe { info.draggingPasteboard() };
3803        let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
3804            .to_string()
3805            .parse::<usize>()
3806            .ok()?;
3807        let rows = self.ivars().rows.borrow();
3808        // The flat outline proposes a gap among the root's children, or a row itself (a drop
3809        // ONTO it, index -1).
3810        let proposed = match item {
3811            Some(item) => Self::outline_row(item),
3812            None => child_index,
3813        };
3814        let proposed = usize::try_from(proposed).unwrap_or(rows.len());
3815        if self.ivars().regroup.get() {
3816            regroup_gap(
3817                &rows,
3818                &self.ivars().movable.borrow(),
3819                &self.ivars().sorted.borrow(),
3820                from_row,
3821                proposed,
3822                item.is_some(),
3823            )
3824        } else {
3825            reorder_gap(
3826                &rows,
3827                &self.ivars().movable.borrow(),
3828                from_row,
3829                proposed,
3830                item.is_some(),
3831            )
3832        }
3833    }
3834}
3835
3836/// A drop in a sidebar outline (`DayNavMenuData::nav_drop`).
3837#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3838struct NavDrop {
3839    /// The gap the row drops into, among the outline's rows.
3840    gap: usize,
3841    /// The proposal named some other place, and the gap moves here.
3842    retarget: bool,
3843    /// What the drop reports, or `None` for a drop back in place.
3844    moves: Option<NavMove>,
3845}
3846
3847/// What a sidebar drop reports, in item indices (the rows before the move).
3848#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3849enum NavMove {
3850    /// `Event::ListReorder`: `from` takes `to`'s place.
3851    Reorder { from: usize, to: usize },
3852    /// `Event::NavRegroup`: `from` joins the section whose first row is `section`, before
3853    /// `before` or at the section's end.
3854    Regroup {
3855        from: usize,
3856        section: usize,
3857        before: Option<usize>,
3858    },
3859}
3860
3861/// A reorder drop at `proposed`, a gap among the outline's `rows` (`None` a header, `Some(i)`
3862/// item `i`), for the row at `from_row`; `onto` when the proposal named a row itself, which
3863/// reads as the gap above it. The gap clamps to the run of movable rows around the dragged
3864/// one, which section headers and fixed rows end. `None` when that row cannot move.
3865fn reorder_gap(
3866    rows: &[Option<usize>],
3867    movable: &[bool],
3868    from_row: usize,
3869    proposed: usize,
3870    onto: bool,
3871) -> Option<NavDrop> {
3872    let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
3873    let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
3874    let in_run = |r: usize| rows[r].is_some_and(is_movable);
3875    let first = (0..from_row)
3876        .rev()
3877        .take_while(|r| in_run(*r))
3878        .last()
3879        .unwrap_or(from_row);
3880    let last = (from_row + 1..rows.len())
3881        .take_while(|r| in_run(*r))
3882        .last()
3883        .unwrap_or(from_row);
3884    let gap = proposed.clamp(first, last + 1);
3885    // The row's place once it has left its own: the row whose position it takes.
3886    let target_row = if gap > from_row { gap - 1 } else { gap };
3887    let moves = (target_row != from_row)
3888        .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
3889        .flatten();
3890    Some(NavDrop {
3891        gap,
3892        retarget: gap != proposed || onto,
3893        moves,
3894    })
3895}
3896
3897/// A regroup drop at `proposed`, a gap among the outline's `rows` (as [`reorder_gap`]'s), for
3898/// the row at `from_row` (docs/navigation.md "Moving rows between sections"). The gap's section
3899/// is the nearest header above it, or the rows above the first header; `before` is the item
3900/// right below the gap when that row is in the same section. A drop ONTO a header reads as
3901/// that section's first gap, onto an item as the gap above it. `None` when the row cannot
3902/// move, the gap is above the first header with no rows there, the section holds a fixed row,
3903/// or the gap is in the row's own section and the row is sorted. Gaps are never clamped.
3904fn regroup_gap(
3905    rows: &[Option<usize>],
3906    movable: &[bool],
3907    sorted: &[bool],
3908    from_row: usize,
3909    proposed: usize,
3910    onto: bool,
3911) -> Option<NavDrop> {
3912    let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
3913    let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
3914    let gap = match rows.get(proposed) {
3915        Some(None) if onto => proposed + 1,
3916        _ => proposed.min(rows.len()),
3917    };
3918    // The first outline row of the section a gap (or a row, as the gap above it) sits in.
3919    let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
3920        Some(header) => Some(header + 1),
3921        None => rows.first().copied().flatten().map(|_| 0),
3922    };
3923    let first = section_start(gap)?;
3924    let end = (first..rows.len())
3925        .find(|r| rows[*r].is_none())
3926        .unwrap_or(rows.len());
3927    let section = rows.get(first).copied().flatten()?;
3928    if !rows[first..end]
3929        .iter()
3930        .all(|r| r.is_some_and(|i| flag(movable, i)))
3931    {
3932        return None;
3933    }
3934    let own = section_start(from_row) == Some(first);
3935    if own && flag(sorted, from) {
3936        return None;
3937    }
3938    let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
3939        from,
3940        section,
3941        before: rows.get(gap).copied().flatten(),
3942    });
3943    Some(NavDrop {
3944        gap,
3945        retarget: gap != proposed || onto,
3946        moves,
3947    })
3948}
3949
3950#[cfg(test)]
3951mod nav_gap_tests {
3952    use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
3953
3954    /// 0 today, 1 [news], 2 a, 3 b, 4 e, 5 [tech], 6 c, 7 d, 8 [smart], 9 starred: items 0..=6.
3955    const ROWS: [Option<usize>; 10] = [
3956        Some(0),
3957        None,
3958        Some(1),
3959        Some(2),
3960        Some(3),
3961        None,
3962        Some(4),
3963        Some(5),
3964        None,
3965        Some(6),
3966    ];
3967    /// The feeds move; today and starred are fixed.
3968    const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
3969    const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
3970    const UNSORTED: [bool; 7] = [false; 7];
3971
3972    fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
3973        Some(NavMove::Regroup {
3974            from,
3975            section,
3976            before,
3977        })
3978    }
3979
3980    #[test]
3981    fn regroup_gaps_name_the_section_above_and_the_row_below() {
3982        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3983        // a, into tech's first gap: before c.
3984        assert_eq!(
3985            at(2, 6),
3986            Some(NavDrop {
3987                gap: 6,
3988                retarget: false,
3989                moves: regroup(1, 4, Some(4)),
3990            })
3991        );
3992        // c, into the gap above tech's header: the end of news.
3993        assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
3994        // a, between c and d, and at tech's end above smart's header.
3995        assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
3996        assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
3997    }
3998
3999    #[test]
4000    fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
4001        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4002        // Smart holds starred, and the rows above the first header hold today.
4003        for gap in [0, 1, 9, 10] {
4004            assert_eq!(at(2, gap), None, "gap {gap}");
4005        }
4006        // A sorted row's own section offers no gap, its own place included.
4007        for gap in [2, 3, 4, 5] {
4008            assert_eq!(at(2, gap), None, "gap {gap}");
4009        }
4010        // Fixed rows and headers never drag.
4011        assert_eq!(at(0, 6), None);
4012        assert_eq!(at(1, 6), None);
4013        assert_eq!(at(9, 6), None);
4014    }
4015
4016    #[test]
4017    fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
4018        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
4019        // a, between b and e.
4020        assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
4021        // a, at news's end above tech's header.
4022        assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
4023        // Back in place, either side of itself: a drop that reports nothing.
4024        for gap in [2, 3] {
4025            let drop = at(2, gap).expect("offered");
4026            assert_eq!(drop.moves, None, "gap {gap}");
4027        }
4028    }
4029
4030    #[test]
4031    fn regroup_drops_onto_a_row_move_to_a_gap() {
4032        // Onto tech's header: its first gap. Onto d: the gap above d.
4033        assert_eq!(
4034            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
4035            Some(NavDrop {
4036                gap: 6,
4037                retarget: true,
4038                moves: regroup(1, 4, Some(4)),
4039            })
4040        );
4041        assert_eq!(
4042            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
4043            Some(NavDrop {
4044                gap: 7,
4045                retarget: true,
4046                moves: regroup(1, 4, Some(5)),
4047            })
4048        );
4049    }
4050
4051    #[test]
4052    fn regroup_offers_nothing_above_a_leading_header() {
4053        // 0 [news], 1 a, 2 [tech], 3 b.
4054        let rows = [None, Some(0), None, Some(1)];
4055        let movable = [true, true];
4056        let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
4057        assert_eq!(at(0), None);
4058        assert_eq!(at(1).map(|d| d.moves), Some(None));
4059        assert_eq!(at(2).map(|d| d.moves), Some(None));
4060        assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
4061        assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
4062    }
4063
4064    #[test]
4065    fn reorder_gaps_clamp_to_the_run() {
4066        // a past the run's end lands at its end: e's place.
4067        assert_eq!(
4068            reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
4069            Some(NavDrop {
4070                gap: 5,
4071                retarget: true,
4072                moves: Some(NavMove::Reorder { from: 1, to: 3 }),
4073            })
4074        );
4075        // Back in place.
4076        assert_eq!(
4077            reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
4078            Some(None)
4079        );
4080        // b above the run's start lands at a's place; a fixed row offers nothing.
4081        assert_eq!(
4082            reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
4083            Some(NavMove::Reorder { from: 2, to: 1 })
4084        );
4085        assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
4086    }
4087}
4088
4089/// The private pasteboard type carrying a dragged sidebar row (local reorder only).
4090const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
4091
4092/// Badge strings, retained once per rebuild rather than per cell.
4093fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
4094    badges
4095        .iter()
4096        .map(|b| b.as_deref().map(NSString::from_str))
4097        .collect()
4098}
4099
4100// ---------------------------------------------------------------------------
4101/// Force the table's visible rows to exist on the next main-loop turn — outside any `with_tree`
4102/// borrow, so `bind_row` may build them. `layoutSubtreeIfNeeded` is not enough: an occluded
4103/// window's table skips row tiling entirely, so `viewAtColumn:row:makeIfNecessary:` is the only
4104/// reliable way to realize rows without a draw pass (§10; see the Reload patch for why).
4105fn post_realize_visible_rows(key: usize) {
4106    <AppKit as Platform>::post(Box::new(move || {
4107        if let Some((table, data)) = list_entry(key) {
4108            unsafe { table.layoutSubtreeIfNeeded() };
4109            let range = unsafe { table.rowsInRect(table.visibleRect()) };
4110            if let Some(source) = data.ivars().source.borrow().clone()
4111                && let Some(report) = &source.first_visible
4112            {
4113                report(range.location.min((source.len)().saturating_sub(1)));
4114            }
4115            for row in range.location..range.location + range.length {
4116                let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
4117                // A snapshot/layout can have requested this cell while day-core held its
4118                // tree borrow. The delegate then returned an empty container; AppKit caches
4119                // it and will not ask viewForRow again. Complete that skipped bind here.
4120                if let Some(cell) = cell
4121                    && cell.subviews().is_empty()
4122                {
4123                    let source = data.ivars().source.borrow().clone();
4124                    if let Some(source) = source {
4125                        (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
4126                    }
4127                }
4128            }
4129        }
4130        // The builds above queued their styling effects; drain them now — outside the pump, no
4131        // event may arrive for a while (idle app), and a snapshot would capture bare rows.
4132        day_core::pump_events();
4133    }));
4134}
4135
4136/// A native drop changes the snapshot synchronously and suppresses the app's echo Reload.
4137/// Once AppKit has unwound its drop/gap tracking, reconcile the table with that snapshot:
4138/// the incremental move alone can leave its row tiling and scroll extent out of sync.
4139/// Preserve the user's viewport and selection; never force a jump to the moved row.
4140fn post_settle_list_drop(key: usize) {
4141    <AppKit as Platform>::post(Box::new(move || {
4142        // Publish the deferred on_reorder before reading the final row set. App code may
4143        // remove rows or close the list, so resolve the native handles only after the drain.
4144        day_core::pump_events();
4145        let Some((table, data)) = list_entry(key) else {
4146            return;
4147        };
4148        let Some(scroll) = table.enclosingScrollView() else {
4149            return;
4150        };
4151        let clip = scroll.contentView();
4152        let origin = clip.bounds().origin;
4153        let selected = table.selectedRowIndexes();
4154        let suppressed = data.ivars().suppress.replace(true);
4155        table.reloadData();
4156        // Outside with_tree: tiling is allowed to bind/rebind Day's cell contents here.
4157        table.layoutSubtreeIfNeeded();
4158        let restored = objc2_foundation::NSMutableIndexSet::new();
4159        for row in 0..table.numberOfRows().max(0) as usize {
4160            if selected.containsIndex(row) {
4161                restored.addIndex(row);
4162            }
4163        }
4164        table.selectRowIndexes_byExtendingSelection(&restored, false);
4165        let mut bounds = clip.bounds();
4166        bounds.origin = origin;
4167        clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
4168        scroll.reflectScrolledClipView(&clip);
4169        data.ivars().suppress.set(suppressed);
4170        post_realize_visible_rows(key);
4171    }));
4172}
4173
4174// DayListData — NSTableView data-source + delegate for the recycling list (docs/list.md, §10)
4175//
4176// No custom NSTableRowView: the table runs the PLAIN style, whose standard row view lays cell
4177// views out at the full row bounds — no inset to pin away — and whose cell-frame slide is what
4178// animates a row-action swipe. (A `layout`-override pin lived here under FullWidth until
4179// 2026-08; it also froze row content mid-swipe, revealing actions behind a motionless row.)
4180// ---------------------------------------------------------------------------
4181
4182define_class!(
4183    #[unsafe(super(NSTableView))]
4184    #[thread_kind = MainThreadOnly]
4185    #[name = "DayListView"]
4186    struct DayListView;
4187    unsafe impl NSObjectProtocol for DayListView {}
4188    impl DayListView {
4189        /// NSTableView consumes right-clicks before the row's container sees them. Resolve
4190        /// its summon-time provider from the visible cell, never from the selected row.
4191        #[unsafe(method_id(menuForEvent:))]
4192        fn menu_for_event(
4193            &self,
4194            event: &objc2_app_kit::NSEvent,
4195        ) -> Option<Retained<NSMenu>> {
4196            ffi_guard::contain(None, || {
4197                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4198                let row = unsafe { self.rowAtPoint(point) };
4199                let provider = if row >= 0 {
4200                    unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
4201                        .and_then(|cell| list_row_menu_provider(&cell))
4202                } else {
4203                    None
4204                };
4205                match provider {
4206                    Some((view, provider)) => {
4207                        let point = view.convertPoint_fromView(
4208                            unsafe { event.locationInWindow() }, None,
4209                        );
4210                        let items = provider(day_spec::Point::new(point.x, point.y));
4211                        if items.is_empty() {
4212                            None
4213                        } else {
4214                            Some(build_ns_menu(self.mtm(), "", &items))
4215                        }
4216                    }
4217                    None => unsafe { msg_send![super(self), menuForEvent: event] },
4218                }
4219            })
4220        }
4221
4222        #[unsafe(method(becomeFirstResponder))]
4223        fn become_first_responder(&self) -> bool {
4224            let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4225            if accepted {
4226                self.report_focus(true);
4227            }
4228            accepted
4229        }
4230
4231        #[unsafe(method(resignFirstResponder))]
4232        fn resign_first_responder(&self) -> bool {
4233            let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4234            if accepted {
4235                self.report_focus(false);
4236            }
4237            accepted
4238        }
4239
4240        #[unsafe(method(keyDown:))]
4241        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4242            ffi_guard::contain((), || {
4243                let key = unsafe { event.keyCode() };
4244                if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4245                    let row = unsafe { self.selectedRow() };
4246                    if row >= 0 && let Some(target) = unsafe { self.target() } {
4247                        let _: () = unsafe { msg_send![&*target, activateRow: self] };
4248                        return;
4249                    }
4250                }
4251                let _: () = unsafe { msg_send![super(self), keyDown: event] };
4252            });
4253        }
4254    }
4255);
4256
4257/// The cell can wrap its decorated row in layout containers. Search only this visible
4258/// cell, not other rows; cloning the provider releases the registry borrow before app code.
4259fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4260    if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
4261        return Some((view.retain(), provider));
4262    }
4263    view.subviews()
4264        .iter()
4265        .find_map(|view| list_row_menu_provider(&view))
4266}
4267
4268/// Plain labels receive the mouse event before their row does. Resolve the nearest dynamic
4269/// owner without copying providers onto descendants (which would go stale on recycling).
4270/// `Some(None)` means an owner deliberately returned no menu; do not fall through to a parent.
4271fn inherited_context_menu(
4272    view: &NSView,
4273    event: &objc2_app_kit::NSEvent,
4274) -> Option<Option<Retained<NSMenu>>> {
4275    let mut current = Some(view.retain());
4276    while let Some(view) = current {
4277        if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4278            let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4279            let items = provider(day_spec::Point::new(point.x, point.y));
4280            return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4281        }
4282        current = unsafe { view.superview() };
4283    }
4284    None
4285}
4286
4287impl DayListView {
4288    fn report_focus(&self, focused: bool) {
4289        ffi_guard::contain((), || {
4290            if let Some(target) = unsafe { self.target() }
4291                && let Some(data) = target.downcast_ref::<DayListData>()
4292            {
4293                emit(data.ivars().node, Event::FocusChanged(focused));
4294            }
4295        });
4296    }
4297}
4298
4299struct ListIvars {
4300    node: NodeId,
4301    /// Injected by `attach_list` once day-core wires the driver.
4302    source: RefCell<Option<ListSource>>,
4303    selectable: std::cell::Cell<bool>,
4304    /// Multi-select mode (docs/list.md): every change reports the FULL selected set.
4305    multi: std::cell::Cell<bool>,
4306    /// Programmatic selection in flight: don't re-emit SelectionChanged.
4307    suppress: std::cell::Cell<bool>,
4308    /// The row-token order this table currently displays — the baseline `permutation_moves`
4309    /// diffs a Reload against (docs/list.md: a same-set reorder animates as row moves).
4310    tokens: RefCell<Vec<u64>>,
4311    /// `RowHeight::Automatic` (docs/list.md "Row heights"): each row is as tall as Day laid
4312    /// it, through `tableView:heightOfRow:`. A uniform list never answers that selector, so
4313    /// NSTableView keeps its fixed-pitch fast path.
4314    automatic: bool,
4315    /// The list has section headers (docs/list.md "Sections"): AppKit group rows, which float
4316    /// at the top as their section scrolls under them. A header sizes to its content in any
4317    /// list, so a sectioned list answers `tableView:heightOfRow:` even when it is uniform.
4318    sections: bool,
4319    /// The height a header nobody has bound yet is given, like `estimate` for rows.
4320    header_estimate: std::cell::Cell<f64>,
4321    /// Each self-sizing row's height by row token, as Day last laid it. By token, not row: a
4322    /// splice or a drag moves rows without rebinding them.
4323    heights: RefCell<std::collections::HashMap<u64, f64>>,
4324    /// The row token each bound cell shows, so `RowSizeInvalidated` (which names the cell)
4325    /// finds the height it corrects.
4326    cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4327    /// The height a row nobody has bound yet is given: the last one Day measured, so a list
4328    /// of like rows scrolls without its rows jumping as they arrive.
4329    estimate: std::cell::Cell<f64>,
4330    /// A height pass is posted and not yet run (`post_row_heights` coalesces).
4331    heights_pending: std::cell::Cell<bool>,
4332}
4333
4334define_class!(
4335    #[unsafe(super(NSObject))]
4336    #[thread_kind = MainThreadOnly]
4337    #[name = "DayListData"]
4338    #[ivars = ListIvars]
4339    struct DayListData;
4340
4341    unsafe impl NSObjectProtocol for DayListData {}
4342    unsafe impl NSControlTextEditingDelegate for DayListData {}
4343
4344    impl DayListData {
4345        /// Only a self-sizing list answers `tableView:heightOfRow:`: NSTableView asks that
4346        /// of every row on each reload, and a uniform list's fixed `rowHeight` is the fast
4347        /// path. NSTableView reads this once, at `setDelegate:`, after `automatic` is set.
4348        #[unsafe(method(respondsToSelector:))]
4349        fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4350            if selector == objc2::sel!(tableView:heightOfRow:)
4351                && !self.ivars().automatic
4352                && !self.ivars().sections
4353            {
4354                false
4355            } else {
4356                unsafe { msg_send![super(self), respondsToSelector: selector] }
4357            }
4358        }
4359
4360        #[unsafe(method(listViewportChanged:))]
4361        fn list_viewport_changed(&self, notification: &NSNotification) {
4362            ffi_guard::contain((), || {
4363                let source = self.ivars().source.borrow().clone();
4364                if let Some(source) = source && let Some(report) = &source.first_visible
4365                    && let Some(object) = notification.object()
4366                    && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4367                    && let Some(document) = clip.documentView()
4368                    && let Some(table) = document.downcast_ref::<NSTableView>() {
4369                    let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4370                    report(visible.location.min((source.len)().saturating_sub(1)));
4371                }
4372            });
4373        }
4374
4375        #[unsafe(method(activateRow:))]
4376        fn activate_row(&self, table: &NSTableView) {
4377            ffi_guard::contain((), || {
4378                let row = unsafe { table.selectedRow() };
4379                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4380            });
4381        }
4382        #[unsafe(method(doubleClickRow:))]
4383        fn double_click_row(&self, table: &NSTableView) {
4384            ffi_guard::contain((), || {
4385                let row = unsafe { table.clickedRow() };
4386                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4387            });
4388        }
4389    }
4390
4391    unsafe impl NSTableViewDataSource for DayListData {
4392        #[unsafe(method(numberOfRowsInTableView:))]
4393        fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4394            // Reads the piece's snapshot only (no tree access) — safe even when called
4395            // synchronously from reloadData inside a with_tree borrow. Guarded because
4396            // `len` is a day-core closure.
4397            ffi_guard::contain(0, || {
4398                self.ivars()
4399                    .source
4400                    .borrow()
4401                    .as_ref()
4402                    .map(|s| (s.len)() as isize)
4403                    .unwrap_or(0)
4404            })
4405        }
4406
4407        // --- drag-to-reorder (docs/list.md): NSTableView's native drag pipeline. The dragged
4408        // row rides the pasteboard as a private-typed string; `validateDrop` consults the app's
4409        // guard live (the `.gap` feedback style opens the placeholder gap only where the guard
4410        // allows), and `acceptDrop` commits through the sync seam, then animates the native move.
4411
4412        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4413        fn pasteboard_writer_for_row(
4414            &self,
4415            _tv: &NSTableView,
4416            row: isize,
4417        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4418            // (Closure body: define_class converts only the TAIL expression, so early `return`s
4419            // must not escape the method itself.)
4420            let make = || {
4421                // Only reorderable lists write drag items — no seam, no drag.
4422                let reorderable = self
4423                    .ivars()
4424                    .source
4425                    .borrow()
4426                    .as_ref()
4427                    .is_some_and(|s| s.reorder.is_some());
4428                // A group row (a section header) never lifts (docs/list.md "Sections").
4429                if !reorderable || row < 0 || self.is_header(row) {
4430                    return None;
4431                }
4432                let item = objc2_app_kit::NSPasteboardItem::new();
4433                unsafe {
4434                    item.setString_forType(
4435                        &NSString::from_str(&row.to_string()),
4436                        &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4437                    );
4438                }
4439                Some(ProtocolObject::from_retained(item))
4440            };
4441            ffi_guard::contain(None, make)
4442        }
4443
4444        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4445        fn validate_drop(
4446            &self,
4447            tv: &NSTableView,
4448            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4449            row: isize,
4450            _op: objc2_app_kit::NSTableViewDropOperation,
4451        ) -> objc2_app_kit::NSDragOperation {
4452            // Guarded: `can_move` consults the app's reorder guard closure.
4453            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4454                let Some((from, len)) = self.drag_context(tv, info) else {
4455                    return objc2_app_kit::NSDragOperation::None;
4456                };
4457                // Normalize to an above insertion point (the gap style's semantics), convert to
4458                // the post-removal target index, and ask the guard.
4459                let ins = row.clamp(0, len as isize) as usize;
4460                let to = insertion_to_target(from, ins, len);
4461                let accepted = self.can_move(from, to);
4462                if accepted < 0 {
4463                    return objc2_app_kit::NSDragOperation::None;
4464                }
4465                let accepted = (accepted as usize).min(len.saturating_sub(1));
4466                if accepted != to {
4467                    // The guard retargeted: move the gap to where the drop would actually land.
4468                    unsafe {
4469                        tv.setDropRow_dropOperation(
4470                            target_to_insertion(from, accepted) as isize,
4471                            objc2_app_kit::NSTableViewDropOperation::Above,
4472                        );
4473                    }
4474                }
4475                objc2_app_kit::NSDragOperation::Move
4476            })
4477        }
4478
4479        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4480        fn accept_drop(
4481            &self,
4482            tv: &NSTableView,
4483            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4484            row: isize,
4485            _op: objc2_app_kit::NSTableViewDropOperation,
4486        ) -> bool {
4487            // (Closure body: early `return`s must not escape the define_class method itself.)
4488            let drop = || {
4489                let Some((from, len)) = self.drag_context(tv, info) else {
4490                    return false;
4491                };
4492                let ins = row.clamp(0, len as isize) as usize;
4493                let to = insertion_to_target(from, ins, len);
4494                let accepted = self.can_move(from, to);
4495                if accepted < 0 {
4496                    return false;
4497                }
4498                let accepted = (accepted as usize).min(len.saturating_sub(1));
4499                if accepted == from {
4500                    return true; // dropped back home — nothing to commit
4501                }
4502                // Commit through the sync seam (rotates Day's snapshot, defers the app
4503                // callback), THEN animate the native move — the data source already answers in
4504                // the new order.
4505                let mv = self
4506                    .ivars()
4507                    .source
4508                    .borrow()
4509                    .as_ref()
4510                    .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
4511                let Some(mv) = mv else { return false };
4512                mv(from, accepted);
4513                // Keep the displayed-order cache in step (the commit's echo skips the Reload
4514                // that would otherwise refresh it — see `permutation_moves`).
4515                {
4516                    let mut toks = self.ivars().tokens.borrow_mut();
4517                    if from < toks.len() && accepted < toks.len() {
4518                        let t = toks.remove(from);
4519                        toks.insert(accepted, t);
4520                    }
4521                }
4522                unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
4523                if let Some(scroll) = tv.enclosingScrollView() {
4524                    post_settle_list_drop(ptr_of(&scroll));
4525                }
4526                true
4527            };
4528            // Guarded: the commit runs the seam's move closure into day-core and the app.
4529            ffi_guard::contain(false, drop)
4530        }
4531    }
4532
4533    unsafe impl NSTableViewDelegate for DayListData {
4534        /// A self-sizing row's height (docs/list.md "Row heights"): the height Day laid it at
4535        /// once it has been bound, the running estimate until then. Asked before the row's view
4536        /// exists, often from inside `reloadData` under a day-core borrow, so it reads only this
4537        /// table's own record and the source's token snapshot.
4538        #[unsafe(method(tableView:heightOfRow:))]
4539        fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
4540            ffi_guard::contain(44.0, || {
4541                let ivars = self.ivars();
4542                let header = self.is_header(row);
4543                // A uniform sectioned list: rows keep the fixed pitch, headers size themselves.
4544                if !header && !ivars.automatic {
4545                    return unsafe { tv.rowHeight() };
4546                }
4547                let token = ivars
4548                    .source
4549                    .borrow()
4550                    .as_ref()
4551                    .filter(|s| row >= 0 && (row as usize) < (s.len)())
4552                    .map(|s| (s.token_at)(row as usize));
4553                token
4554                    .and_then(|t| ivars.heights.borrow().get(&t).copied())
4555                    .unwrap_or_else(|| {
4556                        if header {
4557                            ivars.header_estimate.get()
4558                        } else {
4559                            ivars.estimate.get()
4560                        }
4561                    })
4562            })
4563        }
4564
4565        /// Section headers are AppKit group rows (docs/list.md "Sections"): drawn in the
4566        /// group style, spanning the row, and floated over their section by
4567        /// `floatsGroupRows`.
4568        #[unsafe(method(tableView:isGroupRow:))]
4569        fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
4570            ffi_guard::contain(false, || self.is_header(row))
4571        }
4572
4573        /// A header is not an item: clicks and arrow keys pass over it.
4574        #[unsafe(method(tableView:shouldSelectRow:))]
4575        fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
4576            ffi_guard::contain(true, || !self.is_header(row))
4577        }
4578
4579        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
4580        fn view_for_row(
4581            &self,
4582            tv: &NSTableView,
4583            _col: Option<&NSTableColumn>,
4584            row: isize,
4585        ) -> Option<Retained<NSView>> {
4586            // Guarded: `bind_row` builds the app's row content.
4587            ffi_guard::contain(None, || {
4588                let mtm = self.mtm();
4589                // Headers pool apart from rows, so a recycled cell keeps its kind and rebinds.
4590                let header = self.is_header(row);
4591                let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
4592                // Recycle a cell view if one is free; else make a fresh flipped container.
4593                let cell: Retained<NSView> =
4594                    unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
4595                        let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
4596                        unsafe { v.setIdentifier(Some(&ident)) };
4597                        v
4598                    });
4599                // Day builds row content the first time it sees this cell, and rebinds
4600                // (slot-write) when the cell is recycled. NSTableView calls this outside
4601                // reloadData's stack, so the re-entry into with_tree is safe.
4602                let source = self.ivars().source.borrow().clone();
4603                if let Some(source) = source {
4604                    let raw = Retained::as_ptr(&cell) as RawHandle;
4605                    (source.bind_row)(row as usize, raw);
4606                    if self.ivars().automatic || header {
4607                        self.note_row_height(tv, &source, row, raw, header);
4608                    }
4609                }
4610                Some(cell)
4611            })
4612        }
4613
4614        #[unsafe(method(tableView:didRemoveRowView:forRow:))]
4615        fn did_remove_row_view(
4616            &self,
4617            _tv: &NSTableView,
4618            row_view: &objc2_app_kit::NSTableRowView,
4619            _row: isize,
4620        ) {
4621            // The row went back to the reuse pool (a reload dropping it past a shrunk source, a
4622            // scroll): clear its day element ids so it stops answering lookups, as the tree's
4623            // `outlineView:didRemoveRowView:forRow:` does. Deferred, since this fires inside
4624            // reload stacks that hold the day-core borrow, and re-checked: a cell the same
4625            // turn's reload already reused has a window again, and its fresh ids must survive.
4626            ffi_guard::contain((), || {
4627                let Some(cell) = row_view.subviews().iter().find(|sub| {
4628                    sub.identifier()
4629                        .map(|i| {
4630                            let i = i.to_string();
4631                            i == DAY_ROW_CELL || i == DAY_HEADER_CELL
4632                        })
4633                        .unwrap_or(false)
4634                }) else {
4635                    return;
4636                };
4637                // Raw +1 pointers across the post (the closure must be Send, which Retained is
4638                // not; everything stays on the main thread). AppKit may free a removed row view.
4639                let cell = Retained::into_raw(cell) as usize;
4640                let Some(this) = (unsafe {
4641                    Retained::retain(self as *const DayListData as *mut DayListData)
4642                }) else {
4643                    return;
4644                };
4645                let this = Retained::into_raw(this) as usize;
4646                <AppKit as Platform>::post(Box::new(move || {
4647                    // Reclaim both +1s first, so every early return balances them.
4648                    let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4649                    let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
4650                    let (Some(this), Some(cell)) = (this, cell) else {
4651                        return;
4652                    };
4653                    if cell.window().is_some() {
4654                        return; // reused already: its ids are the live row's
4655                    }
4656                    let recycle = this
4657                        .ivars()
4658                        .source
4659                        .borrow()
4660                        .as_ref()
4661                        .map(|s| s.recycle.clone());
4662                    if let Some(recycle) = recycle {
4663                        recycle(Retained::as_ptr(&cell) as RawHandle);
4664                    }
4665                }));
4666            })
4667        }
4668
4669        #[unsafe(method(tableViewSelectionDidChange:))]
4670        fn selection_did_change(&self, notification: &NSNotification) {
4671            ffi_guard::contain((), || {
4672                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
4673                    return;
4674                }
4675                let Some(obj) = (unsafe { notification.object() }) else {
4676                    return;
4677                };
4678                let Ok(tv) = obj.downcast::<NSTableView>() else {
4679                    return;
4680                };
4681                if self.ivars().multi.get() {
4682                    // Multi-select: report the FULL set (ascending; empty = cleared).
4683                    let idx = unsafe { tv.selectedRowIndexes() };
4684                    let mut rows = Vec::with_capacity(idx.count());
4685                    let mut i = idx.firstIndex();
4686                    while i != objc2_foundation::NSNotFound as usize {
4687                        rows.push(i as i64);
4688                        i = unsafe { idx.indexGreaterThanIndex(i) };
4689                    }
4690                    emit(self.ivars().node, Event::SelectionSet(rows));
4691                } else {
4692                    let row = unsafe { tv.selectedRow() };
4693                    if row >= 0 {
4694                        emit(self.ivars().node, Event::SelectionChanged(row as i64));
4695                    } else {
4696                        // CLEARED. `selectedRow()` answers -1, which is not a row, so there is
4697                        // nothing for `SelectionChanged` to carry and nothing for `on_select` to
4698                        // be called with — but the app still has to hear about it, or a detail
4699                        // pane goes on showing the row the user just deselected. The empty set is
4700                        // how that is said (`on_selection`, docs/list.md); reporting nothing was
4701                        // a silent contract break, since single-selection backends are documented
4702                        // as firing it with a one-element OR EMPTY set.
4703                        emit(self.ivars().node, Event::SelectionSet(Vec::new()));
4704                    }
4705                }
4706            })
4707        }
4708
4709        // --- swipe actions (docs/list.md): NSTableView's row-action pipeline. AppKit calls
4710        // this as the two-finger swipe starts, so the offer reflects the row's state at
4711        // GESTURE time; a full swipe across activates the first action (AppKit's own
4712        // full-slide behavior). The handler commits through the seam, which defers the app's
4713        // callback to the event drain.
4714        #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
4715        fn row_actions_for_row(
4716            &self,
4717            tv: &NSTableView,
4718            row: isize,
4719            edge: objc2_app_kit::NSTableRowActionEdge,
4720        ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
4721            // Guarded: `actions_at` runs the app's provider closure.
4722            ffi_guard::contain(NSArray::new(), || {
4723                let sw = self
4724                    .ivars()
4725                    .source
4726                    .borrow()
4727                    .as_ref()
4728                    .and_then(|s| s.swipe.clone());
4729                let Some(sw) = sw else {
4730                    return NSArray::new();
4731                };
4732                if row < 0 {
4733                    return NSArray::new();
4734                }
4735                // AppKit's Leading/Trailing already speak reading direction, same as ours.
4736                let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
4737                    day_spec::SwipeEdge::Leading
4738                } else {
4739                    day_spec::SwipeEdge::Trailing
4740                };
4741                let offer = (sw.actions_at)(row as usize, day_edge);
4742                let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
4743                    .iter()
4744                    .enumerate()
4745                    .map(|(i, a)| {
4746                        let style = if a.destructive {
4747                            objc2_app_kit::NSTableViewRowActionStyle::Destructive
4748                        } else {
4749                            objc2_app_kit::NSTableViewRowActionStyle::Regular
4750                        };
4751                        let perform = sw.perform.clone();
4752                        // Retained only for the swipe session: AppKit releases the actions
4753                        // (and this block) when the revealed buttons close.
4754                        let table = tv.retain();
4755                        let handler = block2::RcBlock::new(
4756                            move |_action: std::ptr::NonNull<
4757                                objc2_app_kit::NSTableViewRowAction,
4758                            >,
4759                                  row: isize| {
4760                                ffi_guard::contain((), || {
4761                                    perform(row as usize, day_edge, i);
4762                                    // A button press leaves the buttons revealed; close
4763                                    // them (a full slide already closed itself).
4764                                    unsafe { table.setRowActionsVisible(false) };
4765                                })
4766                            },
4767                        );
4768                        let action =
4769                            objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
4770                                style,
4771                                &NSString::from_str(&a.label),
4772                                &handler,
4773                            );
4774                        if let Some(t) = a.tint {
4775                            unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
4776                        }
4777                        // Glyph above the label — the Mail row-action look. The SF symbol
4778                        // resolves per OS release; an unknown name yields no image and the
4779                        // button keeps its label alone.
4780                        if let Some(sym) = a.symbol {
4781                            let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
4782                                &NSString::from_str(day_spec::sf_symbol_name(sym)),
4783                                None,
4784                            );
4785                            if let Some(img) = img {
4786                                unsafe { action.setImage(Some(&img)) };
4787                            }
4788                        }
4789                        action
4790                    })
4791                    .collect();
4792                NSArray::from_retained_slice(&actions)
4793            })
4794        }
4795    }
4796);
4797
4798impl DayListData {
4799    fn new(
4800        mtm: MainThreadMarker,
4801        node: NodeId,
4802        selectable: bool,
4803        multi: bool,
4804        automatic: bool,
4805        sections: bool,
4806    ) -> Retained<Self> {
4807        let this = Self::alloc(mtm).set_ivars(ListIvars {
4808            node,
4809            source: RefCell::new(None),
4810            selectable: std::cell::Cell::new(selectable),
4811            multi: std::cell::Cell::new(multi),
4812            suppress: std::cell::Cell::new(false),
4813            tokens: RefCell::new(Vec::new()),
4814            automatic,
4815            sections,
4816            header_estimate: std::cell::Cell::new(28.0),
4817            heights: RefCell::new(std::collections::HashMap::new()),
4818            cell_tokens: RefCell::new(std::collections::HashMap::new()),
4819            estimate: std::cell::Cell::new(44.0),
4820            heights_pending: std::cell::Cell::new(false),
4821        });
4822        unsafe { msg_send![super(this), init] }
4823    }
4824
4825    /// A self-sizing row was just bound to `cell`: record the height Day laid it at, and if
4826    /// the table drew the row at another height (the estimate, or the row's old content),
4827    /// correct it on the next turn. Not here: this runs inside NSTableView's own tiling.
4828    fn note_row_height(
4829        &self,
4830        table: &NSTableView,
4831        source: &ListSource,
4832        row: isize,
4833        cell: RawHandle,
4834        header: bool,
4835    ) {
4836        let height = (source.cell_height)(cell);
4837        if height <= 0.0 || row < 0 {
4838            return;
4839        }
4840        let token = (source.token_at)(row as usize);
4841        self.ivars()
4842            .cell_tokens
4843            .borrow_mut()
4844            .insert(cell as usize, token);
4845        self.ivars().heights.borrow_mut().insert(token, height);
4846        if header {
4847            self.ivars().header_estimate.set(height);
4848        } else {
4849            self.ivars().estimate.set(height);
4850        }
4851        let drawn = unsafe { table.rectOfRow(row) }.size.height;
4852        if (drawn - height).abs() > 0.5 {
4853            self.post_row_heights(table);
4854        }
4855    }
4856
4857    /// Whether display row `row` is a section header (docs/list.md "Sections").
4858    fn is_header(&self, row: isize) -> bool {
4859        row >= 0
4860            && self
4861                .ivars()
4862                .source
4863                .borrow()
4864                .as_ref()
4865                .and_then(|s| s.is_header.clone())
4866                .is_some_and(|is_header| is_header(row as usize))
4867    }
4868
4869    /// `ListPatch::RowSizeInvalidated`: the row in `cell` was re-laid at `height`. Arrives under
4870    /// the day-core borrow, so it only records the height; the table is told after the pass.
4871    fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
4872        let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
4873        if let Some(token) = token {
4874            self.ivars().heights.borrow_mut().insert(token, height);
4875            self.post_row_heights(table);
4876        }
4877    }
4878
4879    /// Tell the table, on the next main-loop turn, about every row near the viewport whose drawn
4880    /// height differs from the one Day laid it at. Coalesced: a pass that re-lays many rows
4881    /// posts one correction.
4882    fn post_row_heights(&self, table: &NSTableView) {
4883        if self.ivars().heights_pending.replace(true) {
4884            return;
4885        }
4886        // Raw +1 pointers across the post (the closure must be Send, which Retained is not;
4887        // everything stays on the main thread).
4888        let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
4889            return;
4890        };
4891        let this = Retained::into_raw(this) as usize;
4892        let table = Retained::into_raw(table.retain()) as usize;
4893        <AppKit as Platform>::post(Box::new(move || {
4894            // Reclaim both +1s first, so every early return balances them.
4895            let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4896            let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
4897            let (Some(this), Some(table)) = (this, table) else {
4898                return;
4899            };
4900            this.ivars().heights_pending.set(false);
4901            ffi_guard::contain((), || this.apply_row_heights(&table));
4902        }));
4903    }
4904
4905    fn apply_row_heights(&self, table: &NSTableView) {
4906        let Some(source) = self.ivars().source.borrow().clone() else {
4907            return;
4908        };
4909        let count = unsafe { table.numberOfRows() }.max(0) as usize;
4910        let shown = unsafe { table.rowsInRect(table.visibleRect()) };
4911        // The viewport and the rows AppKit prepares around it.
4912        let first = shown.location.saturating_sub(8);
4913        let last = (shown.location + shown.length + 8)
4914            .min(count)
4915            .min((source.len)());
4916        let changed = objc2_foundation::NSMutableIndexSet::new();
4917        {
4918            let heights = self.ivars().heights.borrow();
4919            for row in first..last {
4920                if let Some(&height) = heights.get(&(source.token_at)(row)) {
4921                    let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
4922                    if (drawn - height).abs() > 0.5 {
4923                        unsafe { changed.addIndex(row) };
4924                    }
4925                }
4926            }
4927        }
4928        if changed.count() == 0 {
4929            return;
4930        }
4931        // Unanimated: the row takes its content's height, it does not grow into it.
4932        NSAnimationContext::beginGrouping();
4933        NSAnimationContext::currentContext().setDuration(0.0);
4934        unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
4935        NSAnimationContext::endGrouping();
4936    }
4937
4938    /// If this Reload is the same row set in a new order, the incremental `moveRowAtIndex`
4939    /// steps (each `(from, to)` interpreted against the already-moved rows, NSTableView's
4940    /// semantics) that transform the displayed order into the new one — and `None` for
4941    /// anything else (insert/remove/content change/no change), which reloads flat. Always
4942    /// refreshes the displayed-order cache.
4943    ///
4944    /// Every row that changes position must have a REALIZED row view (`table`): moving a
4945    /// viewless row (its old position sat outside the viewport, so it was never bound)
4946    /// animates nothing and leaves the row unbound at its new position — its content, and any
4947    /// element ids inside it, would simply not exist. Such a reorder returns `None` and
4948    /// reloads flat, which realizes and binds the row at its new position.
4949    fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
4950        let source = self.ivars().source.borrow();
4951        let source = source.as_ref()?;
4952        let n = (source.len)();
4953        let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
4954        let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
4955        if old.len() != n || n == 0 || old == new {
4956            return None;
4957        }
4958        let (mut so, mut sn) = (old.clone(), new.clone());
4959        so.sort_unstable();
4960        sn.sort_unstable();
4961        if so != sn {
4962            return None;
4963        }
4964        for i in 0..n {
4965            if old[i] != new[i]
4966                && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
4967            {
4968                return None;
4969            }
4970        }
4971        let mut work = old;
4972        let mut moves = Vec::new();
4973        for i in 0..n {
4974            if work[i] == new[i] {
4975                continue;
4976            }
4977            let j = (i + 1..n).find(|&j| work[j] == new[i])?;
4978            let t = work.remove(j);
4979            work.insert(i, t);
4980            moves.push((j, i));
4981        }
4982        Some(moves)
4983    }
4984
4985    /// The dragged row + current row count for an in-flight LOCAL reorder drag — `None` when the
4986    /// drag came from anywhere but this table (day never accepts foreign drops into a list) or
4987    /// the pasteboard doesn't carry the day row type.
4988    fn drag_context(
4989        &self,
4990        tv: &NSTableView,
4991        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4992    ) -> Option<(usize, usize)> {
4993        let src = unsafe { info.draggingSource() }?;
4994        if Retained::as_ptr(&src) as *const std::ffi::c_void
4995            != tv as *const NSTableView as *const std::ffi::c_void
4996        {
4997            return None;
4998        }
4999        let pb = unsafe { info.draggingPasteboard() };
5000        let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
5001            .to_string()
5002            .parse::<usize>()
5003            .ok()?;
5004        let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
5005        (from < len).then_some((from, len))
5006    }
5007
5008    /// The guard's verdict for `from -> to` (accepted index, or -1), through the sync seam.
5009    fn can_move(&self, from: usize, to: usize) -> i64 {
5010        self.ivars()
5011            .source
5012            .borrow()
5013            .as_ref()
5014            .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
5015            .unwrap_or(-1)
5016    }
5017}
5018
5019/// The reuse identifiers of a list's row cells and its section-header cells.
5020const DAY_ROW_CELL: &str = "day.cell";
5021const DAY_HEADER_CELL: &str = "day.header";
5022
5023/// The private pasteboard type carrying a dragged day list row's index (local reorder only).
5024const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
5025
5026/// An NSTableView drop lands at an INSERTION point (`row` with `.Above` semantics, 0..=len);
5027/// day's seam speaks post-removal target indices. Dropping `from` at insertion `ins`:
5028fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
5029    let to = if ins > from { ins - 1 } else { ins };
5030    to.min(len.saturating_sub(1))
5031}
5032
5033/// The inverse, for retargeting the drop gap: where the gap sits for a post-removal target.
5034fn target_to_insertion(from: usize, to: usize) -> usize {
5035    if to > from { to + 1 } else { to }
5036}
5037
5038/// A realized LIST's scroll view ptr → (table, data source) for attach_list / update / measure.
5039type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
5040
5041/// Clone a list's (table, data) out of `LIST_STATE` under a SHORT borrow. Every caller then
5042/// talks to AppKit with the map free: table calls that look innocuous (`endUpdates`, a scroll's
5043/// tiling, `viewAtColumn:row:makeIfNecessary:`, even `layoutSubtreeIfNeeded`) can synchronously
5044/// re-enter `viewForRow` → `bind_row` → a flush that tears nodes down — and `release` must be
5045/// able to take its own borrow at that depth. Holding the map across any of them was the
5046/// "RefCell already borrowed" contained panic every list walkthrough used to log, 24 a run.
5047fn list_entry(key: usize) -> Option<ListEntry> {
5048    LIST_STATE.with(|m| m.borrow().get(&key).cloned())
5049}
5050
5051// ---------------------------------------------------------------------------
5052// DayTreeData — NSOutlineView data-source + delegate for the hierarchical tree (docs/tree.md)
5053// ---------------------------------------------------------------------------
5054
5055struct TreeIvars {
5056    node: NodeId,
5057    /// Injected by `attach_tree` once day-core wires the driver.
5058    source: RefCell<Option<TreeSource>>,
5059    selectable: std::cell::Cell<bool>,
5060    /// Programmatic selection/disclosure in flight: don't re-emit the event (echo rule).
5061    suppress: std::cell::Cell<bool>,
5062    /// token → its interned NSNumber. NSOutlineView tracks items (selection, expansion,
5063    /// rowForItem) by object identity/equality, so every query for a token must answer with
5064    /// the same object — which is also what preserves expansion across reloadData.
5065    items: RefCell<HashMap<u64, Retained<NSNumber>>>,
5066}
5067
5068define_class!(
5069    #[unsafe(super(NSObject))]
5070    #[thread_kind = MainThreadOnly]
5071    #[name = "DayTreeData"]
5072    #[ivars = TreeIvars]
5073    struct DayTreeData;
5074
5075    unsafe impl NSObjectProtocol for DayTreeData {}
5076
5077    unsafe impl NSOutlineViewDataSource for DayTreeData {
5078        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
5079        fn number_of_children(
5080            &self,
5081            _ov: &objc2_app_kit::NSOutlineView,
5082            item: Option<&objc2::runtime::AnyObject>,
5083        ) -> isize {
5084            // Reads the piece's snapshot only (no tree access) — safe even when called
5085            // synchronously from reloadData inside a with_tree borrow. Guarded because
5086            // the closures are day-core's.
5087            ffi_guard::contain(0, || {
5088                let parent = item.and_then(Self::token_of_item);
5089                if item.is_some() && parent.is_none() {
5090                    return 0; // not one of ours (stale query racing a reload)
5091                }
5092                self.ivars()
5093                    .source
5094                    .borrow()
5095                    .as_ref()
5096                    .map(|s| (s.children_len)(parent) as isize)
5097                    .unwrap_or(0)
5098            })
5099        }
5100
5101        #[unsafe(method_id(outlineView:child:ofItem:))]
5102        fn child_of_item(
5103            &self,
5104            _ov: &objc2_app_kit::NSOutlineView,
5105            index: isize,
5106            item: Option<&objc2::runtime::AnyObject>,
5107        ) -> Retained<objc2::runtime::AnyObject> {
5108            // AppKit only asks for children it was told exist, but a stale query racing a
5109            // reload must degrade (token 0, an unmatched identity) rather than panic — an
5110            // unwind here crosses an ObjC frame and aborts.
5111            let token = ffi_guard::contain(0, || {
5112                let parent = item.and_then(Self::token_of_item);
5113                self.ivars()
5114                    .source
5115                    .borrow()
5116                    .as_ref()
5117                    .map(|s| (s.child_token)(parent, index.max(0) as usize))
5118                    .unwrap_or(0)
5119            });
5120            let ns = self.intern(token);
5121            unsafe { objc2::rc::Retained::cast_unchecked(ns) }
5122        }
5123
5124        #[unsafe(method(outlineView:isItemExpandable:))]
5125        fn is_expandable(
5126            &self,
5127            _ov: &objc2_app_kit::NSOutlineView,
5128            item: &objc2::runtime::AnyObject,
5129        ) -> bool {
5130            ffi_guard::contain(false, || {
5131                let Some(token) = Self::token_of_item(item) else {
5132                    return false;
5133                };
5134                self.ivars()
5135                    .source
5136                    .borrow()
5137                    .as_ref()
5138                    .map(|s| (s.expandable)(token))
5139                    .unwrap_or(false)
5140            })
5141        }
5142
5143        // --- drag-to-move (docs/tree.md): the dragged node rides the pasteboard as a
5144        // private-typed token string; `validateDrop` consults the guard live (forbidden
5145        // cursor where it denies, including ONTO-a-row drops via childIndex -1), and
5146        // `acceptDrop` commits through the sync seam — the app's own data write reloads.
5147
5148        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
5149        fn pasteboard_writer_for_item(
5150            &self,
5151            _ov: &objc2_app_kit::NSOutlineView,
5152            item: &objc2::runtime::AnyObject,
5153        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
5154            let make = || {
5155                let movable = self
5156                    .ivars()
5157                    .source
5158                    .borrow()
5159                    .as_ref()
5160                    .is_some_and(|s| s.moves.is_some());
5161                let token = Self::token_of_item(item)?;
5162                if !movable {
5163                    return None;
5164                }
5165                let pbitem = objc2_app_kit::NSPasteboardItem::new();
5166                unsafe {
5167                    pbitem.setString_forType(
5168                        &NSString::from_str(&token.to_string()),
5169                        &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
5170                    );
5171                }
5172                Some(ProtocolObject::from_retained(pbitem))
5173            };
5174            ffi_guard::contain(None, make)
5175        }
5176
5177        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
5178        fn validate_drop(
5179            &self,
5180            ov: &objc2_app_kit::NSOutlineView,
5181            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5182            item: Option<&objc2::runtime::AnyObject>,
5183            child_index: isize,
5184        ) -> objc2_app_kit::NSDragOperation {
5185            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
5186                match self.drop_proposal(ov, info, item, child_index) {
5187                    Some((token, parent, index)) if self.can_move(token, parent, index) => {
5188                        objc2_app_kit::NSDragOperation::Move
5189                    }
5190                    _ => objc2_app_kit::NSDragOperation::None,
5191                }
5192            })
5193        }
5194
5195        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
5196        fn accept_drop(
5197            &self,
5198            ov: &objc2_app_kit::NSOutlineView,
5199            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5200            item: Option<&objc2::runtime::AnyObject>,
5201            child_index: isize,
5202        ) -> bool {
5203            let drop = || {
5204                let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
5205                else {
5206                    return false;
5207                };
5208                if !self.can_move(token, parent, index) {
5209                    return false;
5210                }
5211                // Commit through the sync seam: defers the app's `on_move`; the app's own
5212                // data write drives the Reload (no native row animation on this path).
5213                let mv = self
5214                    .ivars()
5215                    .source
5216                    .borrow()
5217                    .as_ref()
5218                    .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5219                let Some(mv) = mv else { return false };
5220                mv(token, parent, index);
5221                true
5222            };
5223            ffi_guard::contain(false, drop)
5224        }
5225    }
5226
5227    unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5228
5229    unsafe impl NSOutlineViewDelegate for DayTreeData {
5230        #[unsafe(method(outlineView:isGroupItem:))]
5231        fn is_group_item(
5232            &self,
5233            _ov: &objc2_app_kit::NSOutlineView,
5234            item: &objc2::runtime::AnyObject,
5235        ) -> bool {
5236            Self::token_of_item(item).is_some_and(|t| {
5237                self.ivars()
5238                    .source
5239                    .borrow()
5240                    .as_ref()
5241                    .is_some_and(|s| (s.section_header)(t))
5242            })
5243        }
5244        #[unsafe(method(outlineView:shouldSelectItem:))]
5245        fn should_select_item(
5246            &self,
5247            _ov: &objc2_app_kit::NSOutlineView,
5248            item: &objc2::runtime::AnyObject,
5249        ) -> bool {
5250            Self::token_of_item(item).is_some_and(|t| {
5251                self.ivars()
5252                    .source
5253                    .borrow()
5254                    .as_ref()
5255                    .is_some_and(|s| !(s.section_header)(t))
5256            })
5257        }
5258
5259        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5260        fn view_for_item(
5261            &self,
5262            ov: &objc2_app_kit::NSOutlineView,
5263            _col: Option<&NSTableColumn>,
5264            item: &objc2::runtime::AnyObject,
5265        ) -> Option<Retained<NSView>> {
5266            // Guarded: `bind_row` builds the app's row content.
5267            ffi_guard::contain(None, || {
5268                let mtm = self.mtm();
5269                let token = Self::token_of_item(item)?;
5270                let ident = NSString::from_str("day.tree.cell");
5271                // Recycle a cell view if one is free; else make a fresh flipped container
5272                // (DayTreeCell re-lays its Day row at its own width — indentation makes
5273                // every tree cell's width per-row).
5274                let cell: Retained<NSView> =
5275                    unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5276                        let v: Retained<NSView> =
5277                            Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5278                        unsafe { v.setIdentifier(Some(&ident)) };
5279                        v
5280                    });
5281                if let Some(source) = self.ivars().source.borrow().as_ref() {
5282                    let raw = Retained::as_ptr(&cell) as RawHandle;
5283                    if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5284                        unsafe {
5285                            cell.setTextField(None);
5286                        }
5287                    }
5288                    (source.bind_row)(token, raw);
5289                    // Associate the actual Day label with NSTableCellView so AppKit can
5290                    // apply group typography and source-list background styles normally.
5291                    if (source.section_header)(token) {
5292                        fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5293                            for child in unsafe { view.subviews() }.iter() {
5294                                if let Ok(label) = child.clone().downcast::<NSTextField>() {
5295                                    return Some(label);
5296                                }
5297                                if let Some(label) = label_in(&child) {
5298                                    return Some(label);
5299                                }
5300                            }
5301                            None
5302                        }
5303                        if let Some(label) = label_in(&cell) {
5304                            let cell = cell.downcast_ref::<DayTreeCell>()?;
5305                            unsafe {
5306                                cell.setTextField(Some(&label));
5307                            }
5308                        }
5309                    }
5310                }
5311                Some(cell)
5312            })
5313        }
5314
5315        #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5316        fn type_select_string(
5317            &self,
5318            _ov: &objc2_app_kit::NSOutlineView,
5319            _col: Option<&NSTableColumn>,
5320            item: &objc2::runtime::AnyObject,
5321        ) -> Option<Retained<NSString>> {
5322            ffi_guard::contain(None, || {
5323                let token = Self::token_of_item(item)?;
5324                let text = self
5325                    .ivars()
5326                    .source
5327                    .borrow()
5328                    .as_ref()
5329                    .map(|s| (s.type_select_text)(token))
5330                    .unwrap_or_default();
5331                // Empty = this row doesn't participate in type-select.
5332                (!text.is_empty()).then(|| NSString::from_str(&text))
5333            })
5334        }
5335
5336        #[unsafe(method_id(outlineView:rowViewForItem:))]
5337        fn row_view_for_item(
5338            &self,
5339            ov: &objc2_app_kit::NSOutlineView,
5340            _item: &objc2::runtime::AnyObject,
5341        ) -> Retained<objc2_app_kit::NSTableRowView> {
5342            if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5343                // AppKit owns source-list group backgrounds, floating headers and selection.
5344                unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5345            } else {
5346                // The rounded-selection row (see DayTreeRowView).
5347                let rv: Retained<DayTreeRowView> =
5348                    unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5349                Retained::into_super(rv)
5350            }
5351        }
5352
5353        #[unsafe(method(outlineViewSelectionDidChange:))]
5354        fn selection_did_change(&self, notification: &NSNotification) {
5355            ffi_guard::contain((), || {
5356                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5357                    return;
5358                }
5359                let Some(obj) = (unsafe { notification.object() }) else {
5360                    return;
5361                };
5362                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5363                    return;
5364                };
5365                // Always the FULL token set (docs/tree.md): a tree cannot speak row indices.
5366                let idx = unsafe { ov.selectedRowIndexes() };
5367                let mut tokens = Vec::with_capacity(idx.count());
5368                let mut i = idx.firstIndex();
5369                while i != objc2_foundation::NSNotFound as usize {
5370                    if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5371                        && let Some(tok) = Self::token_of_item(&item)
5372                    {
5373                        tokens.push(tok);
5374                    }
5375                    i = unsafe { idx.indexGreaterThanIndex(i) };
5376                }
5377                emit(self.ivars().node, Event::TreeSelection(tokens));
5378            })
5379        }
5380
5381        #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5382        fn did_remove_row_view(
5383            &self,
5384            ov: &objc2_app_kit::NSOutlineView,
5385            row_view: &objc2_app_kit::NSTableRowView,
5386            _row: isize,
5387        ) {
5388            // The row went back to the reuse pool (a collapse, a reload dropping it): clear
5389            // its day element ids so it stops answering `find_by_id`. DEFERRED — this fires
5390            // inside collapse/reload stacks that hold the day-core borrow — and re-checked:
5391            // a cell already reused by the same turn's reload has a window again, and its
5392            // fresh ids must survive.
5393            ffi_guard::contain((), || {
5394                let mut cell_ptr: Option<usize> = None;
5395                for sub in row_view.subviews().iter() {
5396                    let is_cell = sub
5397                        .identifier()
5398                        .map(|i| i.to_string() == "day.tree.cell")
5399                        .unwrap_or(false);
5400                    if is_cell {
5401                        cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5402                    }
5403                }
5404                let Some(cell) = cell_ptr else { return };
5405                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5406                    return;
5407                };
5408                let key = Retained::as_ptr(&scroll) as usize;
5409                // Carry a RETAIN across the post as a raw +1 pointer (the boxed closure must
5410                // be Send, which Retained is not; we stay on the main thread throughout).
5411                // AppKit is free to dealloc removed row views — a bare pointer died here once.
5412                let retained =
5413                    unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5414                        as usize;
5415                <AppKit as Platform>::post(Box::new(move || {
5416                    // Reclaim the +1 first, unconditionally — every early return below must
5417                    // still balance the retain.
5418                    let cell_view: Retained<NSView> =
5419                        match unsafe { Retained::from_raw(retained as *mut NSView) } {
5420                            Some(v) => v,
5421                            None => return,
5422                        };
5423                    let recycle = tree_entry(key).and_then(|(_, data)| {
5424                        data.ivars()
5425                            .source
5426                            .borrow()
5427                            .as_ref()
5428                            .map(|s| s.recycle.clone())
5429                    });
5430                    let Some(recycle) = recycle else { return };
5431                    if cell_view.window().is_some() {
5432                        return; // reused already — its ids are the live row's
5433                    }
5434                    recycle(cell as RawHandle);
5435                }));
5436            })
5437        }
5438
5439        #[unsafe(method(outlineViewItemDidExpand:))]
5440        fn item_did_expand(&self, notification: &NSNotification) {
5441            self.report_disclosure(notification, true);
5442        }
5443
5444        #[unsafe(method(outlineViewItemDidCollapse:))]
5445        fn item_did_collapse(&self, notification: &NSNotification) {
5446            self.report_disclosure(notification, false);
5447        }
5448    }
5449);
5450
5451impl DayTreeData {
5452    fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5453        let this = Self::alloc(mtm).set_ivars(TreeIvars {
5454            node,
5455            source: RefCell::new(None),
5456            selectable: std::cell::Cell::new(selectable),
5457            suppress: std::cell::Cell::new(false),
5458            items: RefCell::new(HashMap::new()),
5459        });
5460        unsafe { msg_send![super(this), init] }
5461    }
5462
5463    /// The same NSNumber for a token, every time — NSOutlineView's item identity.
5464    fn intern(&self, token: u64) -> Retained<NSNumber> {
5465        self.ivars()
5466            .items
5467            .borrow_mut()
5468            .entry(token)
5469            .or_insert_with(|| NSNumber::new_u64(token))
5470            .clone()
5471    }
5472
5473    fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5474        item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
5475    }
5476
5477    /// A native disclosure (user click, keyboard left/right) → `Event::TreeExpanded`.
5478    /// Programmatic `TreePatch::Expand` applications are suppressed (the echo rule).
5479    fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5480        ffi_guard::contain((), || {
5481            if self.ivars().suppress.get() {
5482                return;
5483            }
5484            let token = unsafe { notification.userInfo() }
5485                .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
5486                .and_then(|item| Self::token_of_item(&item));
5487            if let Some(token) = token {
5488                emit(self.ivars().node, Event::TreeExpanded { token, expanded });
5489            }
5490        })
5491    }
5492
5493    /// The full drop proposal — `(dragged token, parent token, index)` — for a LOCAL drag
5494    /// from this outline; `None` for a foreign drag or an unparseable one. `index: None`
5495    /// means "ONTO the parent" (NSOutlineView's childIndex -1, `NSOutlineViewDropOnItemIndex`).
5496    fn drop_proposal(
5497        &self,
5498        ov: &objc2_app_kit::NSOutlineView,
5499        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5500        item: Option<&objc2::runtime::AnyObject>,
5501        child_index: isize,
5502    ) -> Option<(u64, Option<u64>, Option<usize>)> {
5503        let src = unsafe { info.draggingSource() }?;
5504        if Retained::as_ptr(&src) as *const std::ffi::c_void
5505            != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
5506        {
5507            return None;
5508        }
5509        let pb = unsafe { info.draggingPasteboard() };
5510        let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
5511            .to_string()
5512            .parse::<u64>()
5513            .ok()?;
5514        let parent = match item {
5515            Some(i) => Some(Self::token_of_item(i)?), // a non-token item is not ours
5516            None => None,
5517        };
5518        let index = (child_index >= 0).then_some(child_index as usize);
5519        Some((token, parent, index))
5520    }
5521
5522    /// The guard's live verdict through the sync seam.
5523    fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
5524        self.ivars()
5525            .source
5526            .borrow()
5527            .as_ref()
5528            .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
5529            .map(|v| v == MoveVerdict::Allow)
5530            .unwrap_or(false)
5531    }
5532}
5533
5534// DayOutlineView — an NSOutlineView that PINS its width to its clip on every layout pass.
5535// A table sizes itself from its COLUMNS, and the autoresizing mask only tracks deltas, so
5536// any early pass at a different pane width leaves a permanent offset (a 233pt table in a
5537// 220pt pane, whose selection pill then clips mid-corner). Enforcing it in `layout` — not
5538// in occasional deferred posts — closes every window where a stale width could draw.
5539define_class!(
5540    #[unsafe(super(objc2_app_kit::NSOutlineView))]
5541    #[thread_kind = MainThreadOnly]
5542    #[name = "DayOutlineView"]
5543    struct DayOutlineView;
5544
5545    impl DayOutlineView {
5546        #[unsafe(method(layout))]
5547        fn layout(&self) {
5548            sync_tree_width(self);
5549            let _: () = unsafe { msg_send![super(self), layout] };
5550        }
5551
5552        /// A summon-time ROW context menu (docs/menus.md, docs/tree.md): right-click asks
5553        /// the tree's `row_menu` provider for the row under the pointer.
5554        #[unsafe(method_id(menuForEvent:))]
5555        fn menu_for_event(
5556            &self,
5557            event: &objc2_app_kit::NSEvent,
5558        ) -> Option<Retained<NSMenu>> {
5559            ffi_guard::contain(None, || {
5560                let scroll = unsafe { self.enclosingScrollView() }?;
5561                let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
5562                let row_menu = data
5563                    .ivars()
5564                    .source
5565                    .borrow()
5566                    .as_ref()
5567                    .and_then(|s| s.row_menu.clone())?;
5568                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
5569                let row = unsafe { self.rowAtPoint(p) };
5570                if row < 0 {
5571                    return None;
5572                }
5573                let token =
5574                    unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
5575                let items = row_menu(token);
5576                if items.is_empty() {
5577                    return None;
5578                }
5579                Some(build_ns_menu(self.mtm(), "", &items))
5580            })
5581        }
5582    }
5583);
5584
5585// DayTreeRowView — a tree row with the MODERN selection: a rounded pill, inset from the
5586// pane's edges, in the system's semantic selection colors (accent when the tree has focus,
5587// the quiet gray otherwise). Drawn by hand rather than through `NSTableViewStyle::Inset`,
5588// whose machinery pads the table wider than its clip and fights day's fixed-frame layout —
5589// and a hand-drawn plain color also captures correctly offscreen, where materials go black
5590// (docs/navigation.md's sidebar-screenshot rule).
5591define_class!(
5592    #[unsafe(super(objc2_app_kit::NSTableRowView))]
5593    #[thread_kind = MainThreadOnly]
5594    #[name = "DayTreeRowView"]
5595    struct DayTreeRowView;
5596
5597    impl DayTreeRowView {
5598        #[unsafe(method(drawSelectionInRect:))]
5599        fn draw_selection_in_rect(&self, _dirty: NSRect) {
5600            if !unsafe { self.isSelected() } {
5601                return;
5602            }
5603            let color = if unsafe { self.isEmphasized() } {
5604                unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
5605            } else {
5606                unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
5607            };
5608            let b = self.bounds();
5609            let pill = NSRect::new(
5610                NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
5611                NSSize::new(
5612                    (b.size.width - 10.0).max(0.0),
5613                    (b.size.height - 2.0).max(0.0),
5614                ),
5615            );
5616            unsafe {
5617                color.setFill();
5618                objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
5619                    pill, 5.0, 5.0,
5620                )
5621                .fill();
5622            }
5623        }
5624    }
5625);
5626
5627// DayTreeCell — a tree row's flipped cell container. NSOutlineView frames it at the row's
5628// INDENTED position, so its width is per-row; every native layout pass re-lays the Day row
5629// content inside it at that width through the seam's `layout_cell`.
5630define_class!(
5631    #[unsafe(super(objc2_app_kit::NSTableCellView))]
5632    #[thread_kind = MainThreadOnly]
5633    #[name = "DayTreeCell"]
5634    struct DayTreeCell;
5635
5636    impl DayTreeCell {
5637        #[unsafe(method(isFlipped))]
5638        fn is_flipped(&self) -> bool {
5639            true
5640        }
5641
5642        #[unsafe(method(layout))]
5643        fn layout(&self) {
5644            let _: () = unsafe { msg_send![super(self), layout] };
5645            ffi_guard::contain((), || {
5646                let width = self.bounds().size.width;
5647                if width <= 0.0 {
5648                    return;
5649                }
5650                // This cell's tree: walk up to the outline, then to its scroll host, which
5651                // keys TREE_STATE. (The cell may be in the reuse pool — no outline — or the
5652                // tree may be mid-teardown; both just skip.)
5653                let mut cur = unsafe { self.superview() };
5654                let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
5655                while let Some(v) = cur {
5656                    cur = unsafe { v.superview() };
5657                    if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
5658                        outline = Some(ov);
5659                        break;
5660                    }
5661                }
5662                let Some(ov) = outline else { return };
5663                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5664                    return;
5665                };
5666                let f = tree_entry(Retained::as_ptr(&scroll) as usize)
5667                    .and_then(|(_, data)| {
5668                        data.ivars()
5669                            .source
5670                            .borrow()
5671                            .as_ref()
5672                            .map(|s| s.layout_cell_size.clone())
5673                    });
5674                if let Some(f) = f {
5675                    f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
5676                }
5677            })
5678        }
5679    }
5680);
5681
5682impl DayTreeCell {
5683    fn new(mtm: MainThreadMarker) -> Retained<Self> {
5684        unsafe { msg_send![Self::alloc(mtm), init] }
5685    }
5686}
5687
5688/// The private pasteboard type carrying a dragged day tree node's token (local moves only).
5689const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
5690
5691/// A realized TREE's scroll view ptr → (outline, data source).
5692type TreeEntry = (
5693    Retained<objc2_app_kit::NSOutlineView>,
5694    Retained<DayTreeData>,
5695);
5696
5697/// Clone a tree's (outline, data) out of `TREE_STATE` under a SHORT borrow — the same
5698/// re-entrancy rule as `list_entry` (its comment has the war story).
5699fn tree_entry(key: usize) -> Option<TreeEntry> {
5700    TREE_STATE.with(|m| m.borrow().get(&key).cloned())
5701}
5702
5703/// Keep the outline exactly as wide as its clip — DayOutlineView calls this on every layout
5704/// pass (its comment has the why). The list never noticed the width drift because it lays
5705/// row content at the HOST's width; tree rows lay out at the CELL's, which exposes it.
5706fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
5707    let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
5708        return;
5709    };
5710    let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
5711    let f = outline.frame();
5712    if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
5713        unsafe {
5714            outline.setFrameSize(NSSize::new(clip_w, f.size.height));
5715            outline.sizeLastColumnToFit();
5716        }
5717    }
5718}
5719
5720/// Realize the tree's visible rows on the next main-loop turn, outside any borrow — the
5721/// tree twin of `post_realize_visible_rows` (its comment explains the occluded-window trap).
5722fn post_realize_visible_tree_rows(key: usize) {
5723    <AppKit as Platform>::post(Box::new(move || {
5724        if let Some((outline, _)) = tree_entry(key) {
5725            let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
5726            for row in range.location..range.location + range.length {
5727                let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
5728            }
5729        }
5730        day_core::pump_events();
5731    }));
5732}
5733
5734/// A realized NAV_MENU's native outline view paired with its data-source object.
5735type NavMenuEntry = (
5736    Retained<objc2_app_kit::NSOutlineView>,
5737    Retained<DayNavMenuData>,
5738);
5739
5740fn ns_rect(r: day_spec::Rect) -> NSRect {
5741    NSRect::new(
5742        NSPoint::new(r.origin.x, r.origin.y),
5743        NSSize::new(r.size.width, r.size.height),
5744    )
5745}
5746
5747fn draw_op(op: &DrawOp) {
5748    unsafe {
5749        match op {
5750            // One path for the whole batch, then one fill or stroke: the template is appended
5751            // once per position, so the rasterizer is entered once however many copies there are
5752            // (docs/canvas.md "Stamping"). A gradient resolves against the batch's own bounds,
5753            // which is what makes a stamped scatter shade across the group rather than repeating
5754            // the ramp inside every dot.
5755            DrawOp::Stamp(st) => {
5756                let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
5757                for p in &st.at {
5758                    if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
5759                        unsafe { batch.appendBezierPath(&copy) };
5760                    }
5761                }
5762                let color = match &st.paint {
5763                    day_spec::Paint::Solid(c) => *c,
5764                    // A gradient over a stamped batch clips to the whole batch path; the solid
5765                    // fallback below keeps the marks visible on a backend path that cannot.
5766                    _ => day_spec::Color::WHITE,
5767                };
5768                match &st.stroke {
5769                    None => {
5770                        nscolor(color).setFill();
5771                        unsafe { batch.fill() };
5772                    }
5773                    Some(style) => {
5774                        nscolor(color).setStroke();
5775                        apply_stroke_style(&batch, style);
5776                        unsafe { batch.stroke() };
5777                    }
5778                }
5779            }
5780            DrawOp::Fill(shape, paint) => match paint {
5781                day_spec::Paint::Solid(color) => {
5782                    nscolor(*color).setFill();
5783                    if let Some(p) = bezier(shape) {
5784                        p.fill();
5785                    }
5786                }
5787                day_spec::Paint::Linear(g) => {
5788                    // Native linear gradient: clip to the shape's path, then NSGradient along
5789                    // the line resolved from the gradient's unit points in the shape's bounds.
5790                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5791                        let b = shape.bounds();
5792                        let (s, e) = (g.start.resolve(b), g.end.resolve(b));
5793                        NSGraphicsContext::saveGraphicsState_class();
5794                        p.addClip();
5795                        grad.drawFromPoint_toPoint_options(
5796                            NSPoint::new(s.x, s.y),
5797                            NSPoint::new(e.x, e.y),
5798                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5799                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5800                        );
5801                        NSGraphicsContext::restoreGraphicsState_class();
5802                    }
5803                }
5804                day_spec::Paint::Radial(g) => {
5805                    // Native radial gradient: clip to the path, map unit space onto the bounds
5806                    // (elliptical in non-square bounds), draw circular in unit coordinates.
5807                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5808                        let b = shape.bounds();
5809                        NSGraphicsContext::saveGraphicsState_class();
5810                        p.addClip();
5811                        concat_unit_to_bounds(b);
5812                        let c = NSPoint::new(g.center.x, g.center.y);
5813                        grad.drawFromCenter_radius_toCenter_radius_options(
5814                            c,
5815                            0.0,
5816                            c,
5817                            g.radius,
5818                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5819                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5820                        );
5821                        NSGraphicsContext::restoreGraphicsState_class();
5822                    }
5823                }
5824            },
5825            DrawOp::Stroke(shape, paint, style) => {
5826                if let Some(p) = bezier(shape) {
5827                    apply_stroke_style(&p, style);
5828                    match paint {
5829                        day_spec::Paint::Solid(color) => {
5830                            nscolor(*color).setStroke();
5831                            p.stroke();
5832                        }
5833                        // No gradient-stroke primitive here either: turn the stroke into the
5834                        // region it covers and draw the gradient through that clip.
5835                        // No gradient-stroke primitive: convert the stroke into the REGION it
5836                        // covers (CoreGraphics can, and NSGraphicsContext hands us its context),
5837                        // clip to that, then draw the gradient through it.
5838                        _ => {
5839                            let Some(ctx) = NSGraphicsContext::currentContext() else {
5840                                return;
5841                            };
5842                            let cg = ctx.CGContext();
5843                            NSGraphicsContext::saveGraphicsState_class();
5844                            objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
5845                            objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
5846                                &cg,
5847                            ));
5848                            objc2_core_graphics::CGContext::clip(Some(&cg));
5849                            draw_gradient_in(paint, shape.bounds());
5850                            NSGraphicsContext::restoreGraphicsState_class();
5851                        }
5852                    }
5853                }
5854            }
5855            DrawOp::Clip(shape) => {
5856                // `addClip` intersects with the current clip and honors the path's winding rule.
5857                if let Some(p) = bezier(shape) {
5858                    p.addClip();
5859                }
5860            }
5861            DrawOp::Text {
5862                text,
5863                at,
5864                size,
5865                color,
5866                anchor,
5867                font,
5868            } => {
5869                let font = canvas_nsfont(*size, font);
5870                let attrs = canvas_text_attrs(&font, *color);
5871                let ns = NSString::from_str(text);
5872                let mut origin = NSPoint::new(at.x, at.y);
5873                // `drawAtPoint:` takes the top-leading corner of the line box, so any other
5874                // anchor is an offset from it. The size comes from the attributes the draw is
5875                // about to use, which is why the alignment belongs here and not in the app: the
5876                // caller would have to ask for these same metrics through `measure_text` first.
5877                if *anchor != day_spec::TextAnchor::LEADING {
5878                    let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
5879                    let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
5880                    origin.x += dx;
5881                    origin.y += dy;
5882                }
5883                let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
5884            }
5885            // A released bitmap draws nothing rather than a placeholder: the canvas re-records
5886            // on every tracked read, so a handle can be dropped between the record and the
5887            // replay, and a frame that flashes a grey box is worse than one that omits the image.
5888            DrawOp::Image {
5889                image,
5890                rect,
5891                opacity,
5892            } => {
5893                let img = BITMAPS.with(|m| m.borrow().get(&image.0).map(|b| b.image.clone()));
5894                if let Some(img) = img {
5895                    let dest = NSRect::new(
5896                        NSPoint::new(rect.origin.x, rect.origin.y),
5897                        NSSize::new(rect.size.width, rect.size.height),
5898                    );
5899                    // DayCanvas is flipped (top-left origin). Respect that context so image
5900                    // rows stay upright, including under the canvas's rotation/zoom transforms.
5901                    // A zero `fromRect` means the whole image; `fraction` multiplies its alpha.
5902                    img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
5903                        dest,
5904                        NSRect::ZERO,
5905                        objc2_app_kit::NSCompositingOperation::SourceOver,
5906                        *opacity,
5907                        true,
5908                        None,
5909                    );
5910                }
5911            }
5912            DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
5913            DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
5914            DrawOp::Concat(m) => {
5915                let t = NSAffineTransform::new();
5916                t.setTransformStruct(NSAffineTransformStruct {
5917                    m11: m.a,
5918                    m12: m.b,
5919                    m21: m.c,
5920                    m22: m.d,
5921                    tX: m.tx,
5922                    tY: m.ty,
5923                });
5924                t.concat();
5925            }
5926        }
5927    }
5928}
5929
5930/// An `NSGradient` from a display-list gradient's stops (sRGB, like every canvas color).
5931fn nsgradient(
5932    stops: &[(f64, day_spec::Color)],
5933) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
5934    if stops.is_empty() {
5935        return None;
5936    }
5937    let colors = objc2_foundation::NSArray::from_retained_slice(
5938        &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
5939    );
5940    let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
5941    unsafe {
5942        objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
5943            objc2_app_kit::NSGradient::alloc(),
5944            &colors,
5945            locations.as_ptr(),
5946            &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
5947        )
5948    }
5949}
5950
5951/// Concat a bounds-mapping transform (unit gradient space → `b`) onto the current context, so a
5952/// circular gradient drawn in unit coordinates renders elliptically stretched to the bounds.
5953fn concat_unit_to_bounds(b: day_spec::Rect) {
5954    let t = NSAffineTransform::new();
5955    t.setTransformStruct(NSAffineTransformStruct {
5956        m11: b.size.width,
5957        m12: 0.0,
5958        m21: 0.0,
5959        m22: b.size.height,
5960        tX: b.origin.x,
5961        tY: b.origin.y,
5962    });
5963    unsafe { t.concat() };
5964}
5965
5966/// Put a [`day_spec::StrokeStyle`] onto a path.
5967///
5968/// NOTE: this backend used to force ROUND caps on every stroke. It now honors the style, whose
5969/// default is BUTT — the same default the spec and every other backend use. A line that wants
5970/// round ends asks for `StrokeStyle::round`.
5971fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
5972    use day_spec::{LineCap, LineJoin};
5973    unsafe {
5974        p.setLineWidth(style.width);
5975        p.setLineCapStyle(match style.cap {
5976            LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
5977            LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
5978            LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
5979        });
5980        if style.is_plain() {
5981            return;
5982        }
5983        p.setLineJoinStyle(match style.join {
5984            LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
5985            LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
5986            LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
5987        });
5988        p.setMiterLimit(style.miter_limit);
5989        if !style.dash.is_empty() {
5990            let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
5991            p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
5992        }
5993    }
5994}
5995
5996/// Draw a gradient through whatever clip is installed, in AppKit's own NSGradient terms.
5997/// Shared by the gradient FILL arms and the gradient STROKE arm, which differ only in what they
5998/// clipped to first.
5999fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
6000    let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6001        | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
6002    match paint {
6003        day_spec::Paint::Linear(g) => {
6004            if let Some(grad) = nsgradient(&g.stops) {
6005                let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
6006                unsafe {
6007                    grad.drawFromPoint_toPoint_options(
6008                        NSPoint::new(s.x, s.y),
6009                        NSPoint::new(e.x, e.y),
6010                        opts,
6011                    )
6012                };
6013            }
6014        }
6015        day_spec::Paint::Radial(g) => {
6016            if let Some(grad) = nsgradient(&g.stops) {
6017                NSGraphicsContext::saveGraphicsState_class();
6018                concat_unit_to_bounds(bounds);
6019                let c = NSPoint::new(g.center.x, g.center.y);
6020                unsafe {
6021                    grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
6022                };
6023                NSGraphicsContext::restoreGraphicsState_class();
6024            }
6025        }
6026        day_spec::Paint::Solid(_) => {}
6027    }
6028}
6029
6030fn apply_button_content(
6031    btn: &NSButton,
6032    title: &str,
6033    icon: Option<&day_spec::Icon>,
6034    icon_only: bool,
6035) {
6036    let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
6037    if let Some(image) = &image {
6038        let size = image.size();
6039        let longest = size.width.max(size.height);
6040        if longest > 0.0 {
6041            image.setSize(objc2_foundation::NSSize::new(
6042                size.width * 20.0 / longest,
6043                size.height * 20.0 / longest,
6044            ));
6045        }
6046    }
6047    let style = BUTTON_STYLES
6048        .with(|m| m.borrow().get(&ptr_of(btn)).copied())
6049        .unwrap_or_default();
6050    BUTTON_IMAGES.with(|images| {
6051        images.remove(ptr_of(btn));
6052        if let Some(image) = &image {
6053            images.insert(ptr_of(btn), image.clone());
6054        }
6055    });
6056    set_button_title(btn, title, style);
6057    // The position first: the image setter pads a glyph that sits beside a title, and leaves
6058    // an icon-only one alone, by reading it.
6059    unsafe {
6060        btn.setImagePosition(if image.is_none() {
6061            objc2_app_kit::NSCellImagePosition::NoImage
6062        } else if icon_only {
6063            objc2_app_kit::NSCellImagePosition::ImageOnly
6064        } else {
6065            objc2_app_kit::NSCellImagePosition::ImageLeading
6066        });
6067    }
6068    set_button_image(btn, style);
6069    unsafe {
6070        // The title is the spoken name (an icon-only button shows none), unless the app named
6071        // the button itself; overwriting that here replaced app labels on every title change.
6072        if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
6073            btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
6074        }
6075        let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
6076        btn.setToolTip(tooltip.as_deref());
6077    }
6078}
6079
6080/// Bordered buttons do not reliably apply contentTintColor to template images. Keep
6081/// the native button, but supply an image that draws the original vector's alpha in
6082/// the requested contrast color at the destination resolution.
6083fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
6084    use day_spec::props::ButtonStyleSpec as S;
6085    let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
6086    let image = image.map(|source| {
6087        let S::Tinted(fill) = style else {
6088            return source;
6089        };
6090        let size = source.size();
6091        let ink = nscolor(S::on_tint(fill));
6092        let draw = block2::RcBlock::new(move |rect: NSRect| {
6093            source.drawInRect_fromRect_operation_fraction(
6094                rect,
6095                NSRect::ZERO,
6096                objc2_app_kit::NSCompositingOperation::SourceOver,
6097                1.0,
6098            );
6099            unsafe {
6100                ink.setFill();
6101                objc2_app_kit::NSRectFillUsingOperation(
6102                    rect,
6103                    objc2_app_kit::NSCompositingOperation::SourceIn,
6104                );
6105            }
6106            objc2::runtime::Bool::YES
6107        });
6108        objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
6109    });
6110    unsafe {
6111        let position = btn.imagePosition();
6112        // Beside a title, the glyph gets a clear gap: AppKit draws a leading image flush
6113        // against the text, so the image carries the space itself (a template stays one, so
6114        // the label color still tints it). The cell centers the image in its slot, so half
6115        // the extra width lands on each side.
6116        let image = image.map(|source| {
6117            // The position is set after this on a fresh button, so an unset one counts as
6118            // "beside a title"; only an icon-only button keeps the glyph as drawn.
6119            if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
6120                return source;
6121            }
6122            let size = source.size();
6123            let template = source.isTemplate();
6124            let padded = NSSize::new(size.width + 8.0, size.height);
6125            let draw = block2::RcBlock::new(move |_rect: NSRect| {
6126                source.drawInRect_fromRect_operation_fraction(
6127                    NSRect::new(NSPoint::new(0.0, 0.0), size),
6128                    NSRect::ZERO,
6129                    objc2_app_kit::NSCompositingOperation::SourceOver,
6130                    1.0,
6131                );
6132                objc2::runtime::Bool::YES
6133            });
6134            let out =
6135                objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
6136            out.setTemplate(template);
6137            out
6138        });
6139        btn.setImage(image.as_deref());
6140        btn.setImagePosition(position);
6141        btn.setImageHugsTitle(true);
6142    }
6143}
6144
6145/// Put `ButtonProps::selected` on an `NSButton`, keeping it an NSButton. A momentary button
6146/// shows no state, so the first `true` makes it push-on/push-off, whose on state AppKit draws
6147/// as the bezel's highlighted fill and VoiceOver reads as selected; a button that never
6148/// selects keeps its momentary type. A click toggles the state natively before the action
6149/// runs, so the `action:` handler restores the value recorded here.
6150fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
6151    BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
6152    unsafe {
6153        if on {
6154            btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
6155        }
6156        btn.setState(if on {
6157            NSControlStateValueOn
6158        } else {
6159            NSControlStateValueOff
6160        });
6161    }
6162}
6163
6164/// The corner radius of the tint painted behind a tinted button's bezel: the rounded push
6165/// bezel's own, so the fill reads as the bezel rather than as a box around it.
6166const TINT_CORNER_RADIUS: f64 = 6.0;
6167
6168/// Put a [`day_spec::props::ButtonStyleSpec`] on an `NSButton`, keeping it an NSButton.
6169///
6170/// Prominent = the return-key default button. Tinted = `bezelColor`, which AppKit composites
6171/// through the button's own bezel — so the pressed darkening, the focus ring and the disabled
6172/// look all still come from the control rather than from us painting a rectangle. macOS 26
6173/// composites the push bezel as a system material that ignores `bezelColor` on screen (an
6174/// offscreen `cacheDisplay` still honors it), so the tint is also painted on the control's
6175/// backing layer, where the translucent material lets it through; on older systems the opaque
6176/// tinted bezel covers that layer, so nothing changes there.
6177fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
6178    use day_spec::props::ButtonStyleSpec as S;
6179    let title = unsafe { btn.title() }.to_string();
6180    unsafe {
6181        // Reset first, so a patch from one style to another leaves nothing of the old one.
6182        btn.setKeyEquivalent(&NSString::from_str(""));
6183        btn.setBezelColor(None);
6184        btn.setBordered(!matches!(style, S::Plain));
6185        match style {
6186            S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
6187            S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
6188            // Bordered is the stock NSButton look already; Automatic asks for nothing, and an
6189            // NSButton hugs a one-glyph title already, so Compact asks for nothing either.
6190            S::Bordered | S::Automatic | S::Compact | S::Plain => {}
6191        }
6192        btn.setWantsLayer(true);
6193        if let Some(layer) = btn.layer() {
6194            match style {
6195                S::Tinted(c) => {
6196                    layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
6197                    layer.setCornerRadius(TINT_CORNER_RADIUS);
6198                }
6199                _ => layer.setBackgroundColor(None),
6200            }
6201        }
6202    }
6203    BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6204    let ink = match style {
6205        S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6206        _ => None,
6207    };
6208    unsafe {
6209        btn.setContentTintColor(ink.as_deref());
6210    }
6211    set_button_title(btn, &title, style);
6212    set_button_image(btn, style);
6213}
6214
6215/// Set a button's title, coloring it for the tint where there is one.
6216///
6217/// `contentTintColor` is NOT the seam for this: on a bordered `NSButton`,
6218/// AppKit keeps drawing the title in its own control text color — which is how a
6219/// white-on-rust button came out black-on-rust. An ATTRIBUTED title is the documented way to
6220/// control the text color, so that is what a tinted button gets.
6221///
6222/// The button's own font is carried into the attributes: an attributed title supplies the whole
6223/// run, so leaving the font out would drop the control font and render at the system default.
6224fn set_button_title(
6225    btn: &objc2_app_kit::NSButton,
6226    title: &str,
6227    style: day_spec::props::ButtonStyleSpec,
6228) {
6229    use day_spec::props::ButtonStyleSpec as S;
6230    // Changing an attributed title can reset NSButton's image placement. A reactive
6231    // tint must keep an icon-only button icon-only, including its native template tint.
6232    let position = unsafe { btn.imagePosition() };
6233    let S::Tinted(fill) = style else {
6234        // Plain title: AppKit picks the label color that suits the bezel it is drawing.
6235        unsafe {
6236            btn.setTitle(&NSString::from_str(title));
6237            btn.setImagePosition(position);
6238        }
6239        return;
6240    };
6241    unsafe {
6242        let col = nscolor(S::on_tint(fill));
6243        let font = btn
6244            .font()
6245            .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6246        // Centered, matching a plain NSButton title: an attributed title carries its own
6247        // paragraph style, and the default is left-aligned.
6248        let para = objc2_app_kit::NSMutableParagraphStyle::new();
6249        para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6250        let keys: [&NSString; 3] = [
6251            objc2_app_kit::NSFontAttributeName,
6252            objc2_app_kit::NSForegroundColorAttributeName,
6253            objc2_app_kit::NSParagraphStyleAttributeName,
6254        ];
6255        let objs: [&objc2::runtime::AnyObject; 3] = [
6256            font.as_ref() as &objc2::runtime::AnyObject,
6257            col.as_ref() as &objc2::runtime::AnyObject,
6258            para.as_ref() as &objc2::runtime::AnyObject,
6259        ];
6260        let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6261        let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6262            objc2_foundation::NSAttributedString::alloc(),
6263            &NSString::from_str(title),
6264            Some(&attrs),
6265        );
6266        btn.setAttributedTitle(&s);
6267        btn.setImagePosition(position);
6268    }
6269}
6270
6271// NSImageView supports aspect-fit but not aspect-fill. Expand its native drawing about
6272// the center and clip to the view; this retains vector rendering and template tinting.
6273define_class!(
6274    #[unsafe(super(objc2_app_kit::NSImageView))]
6275    #[thread_kind = MainThreadOnly]
6276    #[name = "DayFillImageView"]
6277    struct FillImageView;
6278
6279    impl FillImageView {
6280        #[unsafe(method(drawRect:))]
6281        fn draw_rect(&self, dirty: NSRect) {
6282            let bounds = self.bounds();
6283            let image = unsafe { self.image() };
6284            let Some(size) = image.map(|image| image.size()).filter(|size| {
6285                size.width > 0.0 && size.height > 0.0
6286                    && bounds.size.width > 0.0 && bounds.size.height > 0.0
6287            }) else {
6288                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6289                return;
6290            };
6291            let x = bounds.size.width / size.width;
6292            let y = bounds.size.height / size.height;
6293            let scale = x.max(y) / x.min(y);
6294            let cx = bounds.origin.x + bounds.size.width / 2.0;
6295            let cy = bounds.origin.y + bounds.size.height / 2.0;
6296            NSGraphicsContext::saveGraphicsState_class();
6297            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6298            let transform = NSAffineTransform::transform();
6299            transform.translateXBy_yBy(cx, cy);
6300            transform.scaleBy(scale);
6301            transform.translateXBy_yBy(-cx, -cy);
6302            transform.concat();
6303            let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6304            NSGraphicsContext::restoreGraphicsState_class();
6305        }
6306
6307        #[unsafe(method(setFrameSize:))]
6308        fn set_frame_size(&self, size: NSSize) {
6309            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6310            NSView::setNeedsDisplay(self, true);
6311        }
6312    }
6313);
6314
6315fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6316    use day_spec::Shape;
6317    use objc2_app_kit::NSBezierPath;
6318    unsafe {
6319        Some(match shape {
6320            Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6321            Shape::RoundedRect(r, rad) => {
6322                NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6323            }
6324            Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6325            Shape::Arc {
6326                rect,
6327                start_deg,
6328                sweep_deg,
6329            } => {
6330                let p = NSBezierPath::new();
6331                let center = NSPoint::new(
6332                    rect.origin.x + rect.size.width / 2.0,
6333                    rect.origin.y + rect.size.height / 2.0,
6334                );
6335                let radius = rect.size.width.min(rect.size.height) / 2.0;
6336                // Flipped view: increasing angle is visually clockwise, matching the spec.
6337                p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6338                    center,
6339                    radius,
6340                    *start_deg,
6341                    *start_deg + *sweep_deg,
6342                );
6343                p
6344            }
6345            Shape::Line(a, b) => {
6346                let p = NSBezierPath::new();
6347                p.moveToPoint(NSPoint::new(a.x, a.y));
6348                p.lineToPoint(NSPoint::new(b.x, b.y));
6349                p
6350            }
6351            Shape::Polygon(pts) => {
6352                if pts.len() < 2 {
6353                    return None;
6354                }
6355                let p = NSBezierPath::new();
6356                p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6357                for pt in &pts[1..] {
6358                    p.lineToPoint(NSPoint::new(pt.x, pt.y));
6359                }
6360                p.closePath();
6361                p
6362            }
6363            Shape::Path(path) => {
6364                use day_spec::PathSeg;
6365                if path.segs.is_empty() {
6366                    return None;
6367                }
6368                let p = NSBezierPath::new();
6369                // NSBezierPath's own quadratic API is macOS 14+, so quads are ELEVATED to
6370                // cubics with the standard formula (c1 = p0 + 2/3(c - p0), c2 = p1 + 2/3(c -
6371                // p1)), which is exact rather than an approximation.
6372                let mut cur = NSPoint::new(0.0, 0.0);
6373                for seg in &path.segs {
6374                    match seg {
6375                        PathSeg::Move(a) => {
6376                            cur = NSPoint::new(a.x, a.y);
6377                            p.moveToPoint(cur);
6378                        }
6379                        PathSeg::Line(a) => {
6380                            cur = NSPoint::new(a.x, a.y);
6381                            p.lineToPoint(cur);
6382                        }
6383                        PathSeg::Quad(c, a) => {
6384                            let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6385                            let c1 = NSPoint::new(
6386                                cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6387                                cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6388                            );
6389                            let c2 = NSPoint::new(
6390                                end.x + 2.0 / 3.0 * (ctl.x - end.x),
6391                                end.y + 2.0 / 3.0 * (ctl.y - end.y),
6392                            );
6393                            p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6394                            cur = end;
6395                        }
6396                        PathSeg::Cubic(c1, c2, a) => {
6397                            cur = NSPoint::new(a.x, a.y);
6398                            p.curveToPoint_controlPoint1_controlPoint2(
6399                                cur,
6400                                NSPoint::new(c1.x, c1.y),
6401                                NSPoint::new(c2.x, c2.y),
6402                            );
6403                        }
6404                        PathSeg::Close => p.closePath(),
6405                    }
6406                }
6407                p.setWindingRule(match path.rule {
6408                    day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6409                    day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6410                });
6411                p
6412            }
6413        })
6414    }
6415}
6416
6417// ---------------------------------------------------------------------------
6418// DayUndoManager — the native FRONT of the app's one undo stack (docs/model.md)
6419// ---------------------------------------------------------------------------
6420
6421/// The mirrored [`day_spec::UndoState`]: what the stock Edit menu reads through the standard
6422/// `undo:`/`redo:` validation. The stack itself lives in day-model; this object only answers
6423/// questions and forwards invocations — two histories can never fork.
6424struct UndoIvars {
6425    state: std::cell::RefCell<day_spec::UndoState>,
6426}
6427
6428define_class!(
6429    #[unsafe(super(objc2_foundation::NSUndoManager))]
6430    #[thread_kind = MainThreadOnly]
6431    #[name = "DayUndoManager"]
6432    #[ivars = UndoIvars]
6433    struct DayUndoManager;
6434
6435    /// Overrides of the questions AppKit's menu validation asks, answered from the mirrored
6436    /// state — and of the two verbs, forwarded as `Event::Undo` (enqueue-only, like every
6437    /// other event). Registration/grouping machinery of the superclass is never used.
6438    impl DayUndoManager {
6439        #[unsafe(method(canUndo))]
6440        fn can_undo(&self) -> bool {
6441            self.ivars().state.borrow().can_undo
6442        }
6443
6444        #[unsafe(method(canRedo))]
6445        fn can_redo(&self) -> bool {
6446            self.ivars().state.borrow().can_redo
6447        }
6448
6449        #[unsafe(method(undo))]
6450        fn do_undo(&self) {
6451            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
6452        }
6453
6454        #[unsafe(method(redo))]
6455        fn do_redo(&self) {
6456            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
6457        }
6458
6459        #[unsafe(method_id(undoMenuItemTitle))]
6460        fn undo_menu_item_title(&self) -> Retained<NSString> {
6461            // Route through the superclass's own title former, so "Undo" itself comes out in
6462            // the system language; the action label arrived already localized from the app.
6463            let label = self.ivars().state.borrow().undo_label.clone();
6464            unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6465        }
6466
6467        #[unsafe(method_id(redoMenuItemTitle))]
6468        fn redo_menu_item_title(&self) -> Retained<NSString> {
6469            let label = self.ivars().state.borrow().redo_label.clone();
6470            unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6471        }
6472    }
6473);
6474
6475fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
6476    UNDO_FRONT.with(|u| {
6477        u.borrow_mut()
6478            .get_or_insert_with(|| {
6479                let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
6480                    state: std::cell::RefCell::new(day_spec::UndoState::default()),
6481                });
6482                unsafe { msg_send![super(this), init] }
6483            })
6484            .clone()
6485    })
6486}
6487
6488// ---------------------------------------------------------------------------
6489// DayWinDelegate — resize + close + key tracking, per window
6490// ---------------------------------------------------------------------------
6491
6492/// `node`: the day window-root id this delegate's window reports to. `None` = the PRIMARY
6493/// window — resize goes to `WINDOW_NODE` and close terminates the app; a secondary window
6494/// (docs/windows.md) reports to its own root and close tears down just that window.
6495struct WinIvars {
6496    node: Option<NodeId>,
6497    /// The tab group this window was opened in (`WindowTabbing::Group`/`Preferred`): the
6498    /// tab bar's "+" opens another window of the same group.
6499    group: Option<String>,
6500    /// The last display state reported (`WindowState::code`), so a resize that does not change
6501    /// the zoom state reports nothing.
6502    last_state: Cell<i32>,
6503}
6504
6505define_class!(
6506    #[unsafe(super(NSObject))]
6507    #[thread_kind = MainThreadOnly]
6508    #[name = "DayWinDelegate"]
6509    #[ivars = WinIvars]
6510    struct DayWinDelegate;
6511
6512    unsafe impl NSObjectProtocol for DayWinDelegate {}
6513
6514    /// The responder chain's last stop for the standard edit nav hosts: a focused text view
6515    /// answered `cut:`/`copy:`/`paste:` long before the window asked its delegate, so what
6516    /// arrives here is the app's to handle — the same precedence the undo manager route uses.
6517    impl DayWinDelegate {
6518        /// Edit ▸ Undo. The stock item's nil-target `undo:` finds no implementor among Day's
6519        /// plain views, so the delegate is where the chain lands — resolving through the
6520        /// acting manager keeps a focused field's typing undo ahead of the document stack.
6521        #[unsafe(method(undo:))]
6522        fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6523            ffi_guard::contain((), || {
6524                if let Some(m) = self.acting_undo_manager() {
6525                    unsafe { m.undo() };
6526                }
6527            });
6528        }
6529
6530        /// Edit ▸ Redo.
6531        #[unsafe(method(redo:))]
6532        fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6533            ffi_guard::contain((), || {
6534                if let Some(m) = self.acting_undo_manager() {
6535                    unsafe { m.redo() };
6536                }
6537            });
6538        }
6539
6540        #[unsafe(method(cut:))]
6541        fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6542            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
6543        }
6544
6545        #[unsafe(method(copy:))]
6546        fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6547            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
6548        }
6549
6550        #[unsafe(method(paste:))]
6551        fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6552            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
6553        }
6554
6555        #[unsafe(method(selectAll:))]
6556        fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6557            ffi_guard::contain((), || {
6558                emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
6559            });
6560        }
6561
6562        /// AppKit's menu validation, the same machinery that greys Edit items for text views:
6563        /// the bridge state answers for cut/copy, and paste additionally requires the
6564        /// pasteboard to actually hold text.
6565        #[unsafe(method(validateMenuItem:))]
6566        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
6567            ffi_guard::contain(false, || {
6568                let state = EDIT_STATE.with(|s| s.get());
6569                match unsafe { item.action() } {
6570                    // The undo pair enables from the acting manager and takes its titles
6571                    // ("Undo Move Shape"), exactly as AppKit's own windows do.
6572                    Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
6573                        Some(m) => {
6574                            item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
6575                            unsafe { m.canUndo() }
6576                        }
6577                        None => false,
6578                    },
6579                    Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
6580                        Some(m) => {
6581                            item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
6582                            unsafe { m.canRedo() }
6583                        }
6584                        None => false,
6585                    },
6586                    Some(a) if a == sel!(selectAll:) => state.can_select_all,
6587                    Some(a) if a == sel!(cut:) => state.can_cut,
6588                    Some(a) if a == sel!(copy:) => state.can_copy,
6589                    Some(a) if a == sel!(paste:) => {
6590                        state.can_paste && {
6591                            let pb = unsafe { NSPasteboard::generalPasteboard() };
6592                            pb.types().is_some_and(|types| !types.is_empty())
6593                        }
6594                    }
6595                    _ => true,
6596                }
6597            })
6598        }
6599    }
6600
6601    unsafe impl NSWindowDelegate for DayWinDelegate {
6602        #[unsafe(method(windowDidResize:))]
6603        fn window_did_resize(&self, notification: &NSNotification) {
6604            ffi_guard::contain((), || {
6605                if let Some(obj) = unsafe { notification.object() }
6606                    && let Ok(win) = obj.downcast::<NSWindow>()
6607                    && let Some(size) = pin_below_title_bar(&win)
6608                {
6609                    let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6610                    emit(target, Event::WindowResized(size));
6611                }
6612                // Zooming is a resize with no notification of its own.
6613                self.report_state_of(notification);
6614            })
6615        }
6616
6617        #[unsafe(method(windowShouldClose:))]
6618        fn window_should_close(&self, _window: &NSWindow) -> bool {
6619            ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
6620        }
6621
6622        #[unsafe(method(windowWillClose:))]
6623        fn window_will_close(&self, _notification: &NSNotification) {
6624            ffi_guard::contain((), || {
6625                match self.ivars().node {
6626                    // Secondary window: confirm the close to day-core, which tears the
6627                    // subtree down on a DEFERRED hop (never inside this AppKit close frame).
6628                    Some(node) => emit(node, Event::WindowClosed),
6629                    // Primary window: closing it quits, taking secondaries with it
6630                    // (docs/windows.md close policy), unless the app keeps running without a
6631                    // window (a status item, `KeepRunning::Always`): then it closes like any
6632                    // other window and day-core decides.
6633                    None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
6634                    None => {
6635                        let app = NSApplication::sharedApplication(self.mtm());
6636                        unsafe { app.terminate(None) };
6637                    }
6638                }
6639            })
6640        }
6641
6642        #[unsafe(method_id(windowWillReturnUndoManager:))]
6643        fn window_will_return_undo_manager(
6644            &self,
6645            _window: &NSWindow,
6646        ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6647            // The responder chain already gave a focused text field its OWN manager before
6648            // asking the window — typing undo stays the field's, the model stack gets the
6649            // rest, exactly the precedence the plan's typing rule wants.
6650            ffi_guard::contain(None, || {
6651                UNDO_FRONT.with(|u| {
6652                    u.borrow()
6653                        .as_ref()
6654                        .map(|m| Retained::into_super(m.clone()))
6655                })
6656            })
6657        }
6658
6659        #[unsafe(method(windowDidBecomeKey:))]
6660        fn window_did_become_key(&self, _notification: &NSNotification) {
6661            ffi_guard::contain((), || {
6662                if let Some(node) = self.ivars().node {
6663                    emit(node, Event::WindowFocused(true));
6664                }
6665            })
6666        }
6667
6668        #[unsafe(method(windowDidResignKey:))]
6669        fn window_did_resign_key(&self, _notification: &NSNotification) {
6670            ffi_guard::contain((), || {
6671                if let Some(node) = self.ivars().node {
6672                    emit(node, Event::WindowFocused(false));
6673                }
6674            })
6675        }
6676
6677        #[unsafe(method(windowDidMiniaturize:))]
6678        fn window_did_miniaturize(&self, notification: &NSNotification) {
6679            ffi_guard::contain((), || self.report_state_of(notification))
6680        }
6681
6682        #[unsafe(method(windowDidDeminiaturize:))]
6683        fn window_did_deminiaturize(&self, notification: &NSNotification) {
6684            ffi_guard::contain((), || self.report_state_of(notification))
6685        }
6686
6687        #[unsafe(method(windowDidEnterFullScreen:))]
6688        fn window_did_enter_full_screen(&self, notification: &NSNotification) {
6689            ffi_guard::contain((), || self.report_state_of(notification))
6690        }
6691
6692        #[unsafe(method(windowDidExitFullScreen:))]
6693        fn window_did_exit_full_screen(&self, notification: &NSNotification) {
6694            ffi_guard::contain((), || self.report_state_of(notification))
6695        }
6696    }
6697
6698    // The tab bar's "+" button walks the responder chain (window → delegate) for
6699    // `newWindowForTab:` — present only when the app registered a new-window builder
6700    // (otherwise automatic tabbing is off and no "+" exists).
6701    impl DayWinDelegate {
6702        #[unsafe(method(newWindowForTab:))]
6703        fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
6704            ffi_guard::contain((), || {
6705                // A window in a tab group of its own gets another window of that group
6706                // (`register_new_window_for`); everything else gets File ▸ New Window's.
6707                let _ = match self.ivars().group.as_deref() {
6708                    Some(group) => day_core::windows::open_new_window_for_group(group),
6709                    None => day_core::windows::open_new_window(),
6710                };
6711            })
6712        }
6713    }
6714);
6715
6716impl DayWinDelegate {
6717    fn report_state_of(&self, notification: &NSNotification) {
6718        if let Some(obj) = unsafe { notification.object() }
6719            && let Ok(win) = obj.downcast::<NSWindow>()
6720        {
6721            self.report_state(&win);
6722        }
6723    }
6724}
6725
6726/// The day name for a key press, or `None` for every key the route does not carry — the
6727/// [`day_spec::KeyEvent`] names (docs/menus.md).
6728fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
6729    match unsafe { event.keyCode() } {
6730        123 => Some("ArrowLeft"),
6731        124 => Some("ArrowRight"),
6732        125 => Some("ArrowDown"),
6733        126 => Some("ArrowUp"),
6734        // Not the delete keys. This backend draws a menu bar, so a Delete accelerator on a
6735        // menu item owns them (docs/menus.md) — and a focused piece that CLAIMS a key stops
6736        // that accelerator from ever seeing it, which is how a canvas ends up swallowing the
6737        // Delete its own Edit menu was going to act on.
6738        //
6739        // A digit, main row or keypad, named by what it types. Never under ⌘, ⌥ or ⌃: those
6740        // combinations are accelerators, and claiming one would starve the menu the same way.
6741        _ => {
6742            let held = NSEventModifierFlags::Command
6743                | NSEventModifierFlags::Option
6744                | NSEventModifierFlags::Control;
6745            if event.modifierFlags().intersects(held) {
6746                return None;
6747            }
6748            let typed = event.characters()?.to_string();
6749            let mut chars = typed.chars();
6750            match (chars.next(), chars.next()) {
6751                (Some(c), None) => day_spec::KeyEvent::digit_name(c),
6752                _ => None,
6753            }
6754        }
6755    }
6756}
6757
6758/// The web name for a key that types nothing, by its virtual key code, or `None` for a key
6759/// that types (docs/menus.md "The full route").
6760fn named_key(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
6761    Some(match unsafe { event.keyCode() } {
6762        123 => "ArrowLeft",
6763        124 => "ArrowRight",
6764        125 => "ArrowDown",
6765        126 => "ArrowUp",
6766        36 | 76 => "Enter",
6767        48 => "Tab",
6768        53 => "Escape",
6769        51 => "Backspace",
6770        117 => "Delete",
6771        115 => "Home",
6772        119 => "End",
6773        116 => "PageUp",
6774        121 => "PageDown",
6775        114 => "Insert",
6776        122 => "F1",
6777        120 => "F2",
6778        99 => "F3",
6779        118 => "F4",
6780        96 => "F5",
6781        97 => "F6",
6782        98 => "F7",
6783        100 => "F8",
6784        101 => "F9",
6785        109 => "F10",
6786        103 => "F11",
6787        111 => "F12",
6788        _ => return None,
6789    })
6790}
6791
6792/// A key press on the full route (`Decorate::keyboard`, docs/menus.md "The full route"), for
6793/// a canvas that took the whole keyboard. Answers whether the press was claimed.
6794///
6795/// The order is the policy: a ⌘ chord is the menu's and goes back to AppKit first, whatever
6796/// the key; a composition in progress owns every key until the input method commits or
6797/// cancels it; a key that types nothing is named; a ⌃ chord names its key and types nothing;
6798/// everything else is handed to the text input system, which turns a dead key into marked
6799/// text, an input method's keys into a composition, and a plain or ⌥ key into `insertText:`
6800/// with what it typed (⌥ types on a Mac: ⌥8 is "{" on a German layout; the piece still sees
6801/// [`day_spec::KeyEvent::ALT`] and decides).
6802fn full_route_key_down(view: &DayCanvas, node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
6803    let ptr = (view as *const DayCanvas).cast::<NSView>() as usize;
6804    let flags = event.modifierFlags();
6805    let mods = key_modifiers(flags);
6806    if flags.contains(NSEventModifierFlags::Command) {
6807        return false;
6808    }
6809    let composing = MARKED.with(|t| t.contains(ptr));
6810    if !composing && let Some(named) = named_key(event) {
6811        emit(node, Event::Key(day_spec::KeyEvent::named(named, mods)));
6812        return true;
6813    }
6814    let unmodified = unsafe { event.charactersIgnoringModifiers() }
6815        .map(|s| s.to_string())
6816        .unwrap_or_default();
6817    // A function or editing key the vocabulary lacks types a private-use glyph.
6818    let typeable = !unmodified.is_empty()
6819        && !unmodified
6820            .chars()
6821            .any(|c| c.is_control() || ('\u{f700}'..='\u{f8ff}').contains(&c));
6822    if !composing && flags.contains(NSEventModifierFlags::Control) {
6823        if typeable {
6824            emit(
6825                node,
6826                Event::Key(day_spec::KeyEvent::named(unmodified, mods)),
6827            );
6828        }
6829        return true;
6830    }
6831    if !composing && !typeable {
6832        return true;
6833    }
6834    INTERPRETING.with(|i| *i.borrow_mut() = Some((unmodified, mods)));
6835    view.interpretKeyEvents(&NSArray::from_slice(&[event]));
6836    INTERPRETING.with(|i| *i.borrow_mut() = None);
6837    true
6838}
6839
6840/// The text of an `NSString` or `NSAttributedString` the text input system hands over.
6841fn text_of_input_string(string: &AnyObject) -> String {
6842    if let Some(s) = string.downcast_ref::<NSString>() {
6843        s.to_string()
6844    } else if let Some(s) = string.downcast_ref::<objc2_foundation::NSAttributedString>() {
6845        s.string().to_string()
6846    } else {
6847        String::new()
6848    }
6849}
6850
6851/// AppKit's modifier flags as day's mask.
6852fn key_modifiers(f: NSEventModifierFlags) -> u8 {
6853    let mut modifiers = 0u8;
6854    if f.contains(NSEventModifierFlags::Shift) {
6855        modifiers |= day_spec::KeyEvent::SHIFT;
6856    }
6857    if f.contains(NSEventModifierFlags::Command) {
6858        modifiers |= day_spec::KeyEvent::PRIMARY;
6859    }
6860    if f.contains(NSEventModifierFlags::Option) {
6861        modifiers |= day_spec::KeyEvent::ALT;
6862    }
6863    if f.contains(NSEventModifierFlags::Control) {
6864        modifiers |= day_spec::KeyEvent::CONTROL;
6865    }
6866    modifiers
6867}
6868
6869impl DayWinDelegate {
6870    /// The manager AppKit's own undo mechanics act on: ask the FIRST RESPONDER, whose
6871    /// `undoManager` walks the chain itself — a field editor answers with its typing
6872    /// history, everything else falls through to `windowWillReturnUndoManager` and lands on
6873    /// the app's front. Falls back to the front when no window is key yet.
6874    fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6875        let responder = NSApplication::sharedApplication(self.mtm())
6876            .keyWindow()
6877            .and_then(|w| w.firstResponder());
6878        responder
6879            .and_then(|r| unsafe { r.undoManager() })
6880            .or_else(|| {
6881                UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
6882            })
6883    }
6884}
6885
6886impl DayWinDelegate {
6887    fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
6888        let this = Self::alloc(mtm).set_ivars(WinIvars {
6889            node,
6890            group,
6891            last_state: Cell::new(day_spec::WindowState::Normal.code()),
6892        });
6893        unsafe { msg_send![super(this), init] }
6894    }
6895
6896    /// Report the window's display state if it changed since the last report
6897    /// (docs/windows.md "Window properties"): to the window's root node, or `WINDOW_NODE` for the
6898    /// primary, the same routing as `WindowResized`.
6899    fn report_state(&self, window: &NSWindow) {
6900        let state = ns_window_state(window);
6901        if self.ivars().last_state.replace(state.code()) != state.code() {
6902            log::debug!("appkit: window state now {state:?}");
6903            let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6904            emit(target, Event::WindowStateChanged(state));
6905        }
6906    }
6907}
6908
6909/// What AppKit says a window is showing as: miniaturized wins (a fullscreen window can be
6910/// neither), then fullscreen (whose frame also reads as zoomed), then zoomed.
6911fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
6912    if window.isMiniaturized() {
6913        day_spec::WindowState::Minimized
6914    } else if window
6915        .styleMask()
6916        .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
6917    {
6918        day_spec::WindowState::Fullscreen
6919    } else if window.isZoomed() {
6920        day_spec::WindowState::Maximized
6921    } else {
6922        day_spec::WindowState::Normal
6923    }
6924}
6925
6926/// Ask AppKit for `state`, undoing whatever the window is in first: fullscreen and miniaturized
6927/// have to be left before a window can zoom, and each is its own toggle.
6928fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
6929    use day_spec::WindowState as S;
6930    let current = ns_window_state(window);
6931    if current == state {
6932        return;
6933    }
6934    unsafe {
6935        match current {
6936            S::Minimized => window.deminiaturize(None),
6937            // Leaving fullscreen animates; asking for another state in the same turn would be
6938            // dropped by AppKit mid-transition, so the request stops at leaving it. The state
6939            // signal reads back `Normal`, and a second request takes it from there.
6940            S::Fullscreen => {
6941                window.toggleFullScreen(None);
6942                return;
6943            }
6944            S::Maximized if state != S::Minimized => window.zoom(None),
6945            _ => {}
6946        }
6947        match state {
6948            S::Normal => {}
6949            S::Minimized => window.miniaturize(None),
6950            S::Maximized => {
6951                if !window.isZoomed() {
6952                    window.zoom(None)
6953                }
6954            }
6955            S::Fullscreen => window.toggleFullScreen(None),
6956        }
6957    }
6958}
6959
6960// ---------------------------------------------------------------------------
6961// The backend
6962// ---------------------------------------------------------------------------
6963
6964/// Renderers registered by external Day Piece crates (§8.2 layer 3 — linkme convenience).
6965#[distributed_slice]
6966pub static RENDERERS: [fn() -> Renderer<AppKit>];
6967
6968/// A live secondary window (docs/windows.md). The delegate is RETAINED here —
6969/// `setDelegate:` holds it weakly, and unlike the primary's (kept alive because `run`
6970/// never returns) a secondary's delegate would die at the end of `open_window` otherwise.
6971struct SecondaryWin {
6972    window: Retained<NSWindow>,
6973    #[allow(dead_code)] // held for lifetime only; AppKit talks to it via the weak delegate ref
6974    delegate: Retained<DayWinDelegate>,
6975    content: Handle,
6976}
6977
6978/// Deliver an explicitly registered Escape accelerator before a field editor swallows it.
6979/// The monitor is local to this process and removed with the backend.
6980struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
6981impl Drop for MenuEscapeMonitor {
6982    fn drop(&mut self) {
6983        unsafe { NSEvent::removeMonitor(&self.0) };
6984    }
6985}
6986
6987pub struct AppKit {
6988    menu_escape_monitor: Option<MenuEscapeMonitor>,
6989    sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
6990
6991    mtm: MainThreadMarker,
6992    registry: Registry<AppKit>,
6993    window: Option<Retained<NSWindow>>,
6994    content: Option<Handle>,
6995    secondary: Vec<SecondaryWin>,
6996    app_name: String,
6997    /// Where the next secondary window's top-left goes (docs/windows.md). macOS staggers new
6998    /// windows rather than stacking them: `cascadeTopLeftFromPoint:` places the window and
6999    /// answers the point after it, so threading that answer through here is the whole
7000    /// mechanism. `None` until the primary exists — the cascade starts from its corner.
7001    cascade: Option<NSPoint>,
7002    /// One tracking-area owner per view carrying a `.cursor()` (docs/cursor.md), keyed by the
7003    /// view pointer. Removed when the cursor goes back to `Default`.
7004    cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
7005}
7006
7007impl AppKit {
7008    /// Rebuild a `text_field` as the other class (plain ⇄ secure) and put the replacement
7009    /// where the old view was: same text, look and place among its siblings, same focus and
7010    /// selection, and every view-keyed entry moved to it. day-core drops the old handle
7011    /// without a `release`, so nothing keyed by it may stay behind.
7012    fn swap_text_field(
7013        &mut self,
7014        h: &Handle,
7015        old: &NSTextField,
7016        node: NodeId,
7017        secure: bool,
7018    ) -> Retained<NSTextField> {
7019        let new = new_text_field(self.mtm, node, secure);
7020        let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
7021        // Focus and selection first: reading them is only meaningful while the old field
7022        // still edits. `stringValue` below answers the field editor's live text.
7023        let window = h.window();
7024        let focused = window
7025            .as_deref()
7026            .is_some_and(|w| owns_first_responder(w, h));
7027        let selection = old.currentEditor().map(|e| e.selectedRange());
7028        unsafe {
7029            new.setStringValue(&old.stringValue());
7030            new.setPlaceholderString(old.placeholderString().as_deref());
7031            new.setEnabled(old.isEnabled());
7032            new.setFont(old.font().as_deref());
7033            new.setFrame(h.frame());
7034            new.setHidden(h.isHidden());
7035            new.setMenu(h.menu().as_deref());
7036            new.setToolTip(h.toolTip().as_deref());
7037            // Opacity and transform ride the layer (`set_opacity` / `set_transform`).
7038            if h.wantsLayer() {
7039                new.setWantsLayer(true);
7040                new.setAlphaValue(h.alphaValue());
7041                let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
7042                let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
7043                if !from.is_null() && !to.is_null() {
7044                    let t: CGAffineTransform = msg_send![from, affineTransform];
7045                    let _: () = msg_send![to, setAffineTransform: t];
7046                }
7047            }
7048            // Accessibility (`set_a11y`): only what was set explicitly, so the new class
7049            // keeps its own defaults (a secure field's role and hidden value) for the rest.
7050            if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
7051                new.setAccessibilityIdentifier(Some(&id));
7052            }
7053            if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
7054                new.setAccessibilityLabel(Some(&label));
7055            }
7056            if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
7057                new.setAccessibilityHelp(Some(&help));
7058            }
7059            if !h.isAccessibilityElement() {
7060                new.setAccessibilityElement(false);
7061            }
7062        }
7063        // Recognizers and the cursor's tracking area move as objects, keeping their targets.
7064        for r in unsafe { h.gestureRecognizers() }.iter() {
7065            unsafe {
7066                h.removeGestureRecognizer(&r);
7067                new.addGestureRecognizer(&r);
7068            }
7069        }
7070        GESTURES.with(|m| {
7071            let mut m = m.borrow_mut();
7072            if let Some(targets) = m.remove(&old_key) {
7073                m.insert(new_key, targets);
7074            }
7075        });
7076        if let Some((owner, area)) = self.cursors.remove(&old_key) {
7077            unsafe {
7078                h.removeTrackingArea(&area);
7079                new.addTrackingArea(&area);
7080            }
7081            self.cursors.insert(new_key, (owner, area));
7082        }
7083        PAN_NODES.with(|t| rekey(t, old_key, new_key));
7084        HOVER_NODES.with(|t| rekey(t, old_key, new_key));
7085        KEY_NODES.with(|t| rekey(t, old_key, new_key));
7086        FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
7087        CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
7088        transfer::moved(h, &new);
7089        // The old field goes silent before it leaves: ending its editing session would
7090        // otherwise report a focus loss for a node that keeps its focus.
7091        unsafe { old.setDelegate(None) };
7092        TARGETS.with(|m| {
7093            m.borrow_mut().remove(&old_key);
7094        });
7095        if let Some(parent) = unsafe { h.superview() } {
7096            unsafe {
7097                parent.addSubview_positioned_relativeTo(
7098                    &new,
7099                    objc2_app_kit::NSWindowOrderingMode::Above,
7100                    Some(h),
7101                );
7102                h.removeFromSuperview();
7103            }
7104        }
7105        if focused && let Some(window) = window {
7106            FIELD_SWAP.with(|s| s.set(true));
7107            let taken = window.makeFirstResponder(Some(&new));
7108            FIELD_SWAP.with(|s| s.set(false));
7109            // Taking focus selects the whole text; put back what was selected (the caret,
7110            // usually). Both classes count in UTF-16 units, so the range carries over.
7111            if taken && let Some(editor) = new.currentEditor() {
7112                let len = unsafe { new.stringValue() }.length();
7113                let range = selection
7114                    .filter(|r| r.location.saturating_add(r.length) <= len)
7115                    .unwrap_or(objc2_foundation::NSRange::new(len, 0));
7116                editor.setSelectedRange(range);
7117            }
7118        }
7119        // Whatever else was keyed by the old view goes with it.
7120        day_spec::sidetable::sweep(old_key);
7121        new
7122    }
7123
7124    pub fn new() -> Self {
7125        let mtm =
7126            MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
7127        let mut registry = Registry::default();
7128        for f in RENDERERS {
7129            registry.register(f());
7130        }
7131        AppKit {
7132            menu_escape_monitor: None,
7133            mtm,
7134            registry,
7135            window: None,
7136            sharing: None,
7137            content: None,
7138            secondary: Vec::new(),
7139            app_name: "Day".into(),
7140            cascade: None,
7141            cursors: HashMap::new(),
7142        }
7143    }
7144
7145    /// Public helper for external renderers.
7146    pub fn mtm(&self) -> MainThreadMarker {
7147        self.mtm
7148    }
7149
7150    /// The `NSWindow` whose content container is `host`: a secondary window, or the primary.
7151    fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
7152        if let Some(w) = self
7153            .secondary
7154            .iter()
7155            .find(|w| ptr_of(&w.content) == ptr_of(host))
7156        {
7157            return Some(w.window.clone());
7158        }
7159        self.content
7160            .as_ref()
7161            .filter(|c| ptr_of(c) == ptr_of(host))
7162            .and(self.window.clone())
7163    }
7164
7165    /// Build a Day window: titled + closable (Preferences kind drops resize/minimize and
7166    /// disallows tabbing per macOS convention; Normal windows share the `day.normal`
7167    /// tabbing group), a flipped content view, and a per-window delegate (`node`: `None` =
7168    /// primary). The window is NOT released-when-closed — Rust's `Retained` owns it, and
7169    /// the AppKit default would double-release under us on close.
7170    fn make_window(
7171        &self,
7172        options: &WindowOptions,
7173        prefs_style: bool,
7174        node: Option<NodeId>,
7175    ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
7176        let mtm = self.mtm;
7177        let (title, size, min_size, tabbing) = (
7178            options.title.as_str(),
7179            options.size,
7180            options.min_size,
7181            &options.tabbing,
7182        );
7183        let content_rect =
7184            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
7185        // The kind decides the controls, the chrome decides the frame (docs/window-chrome.md).
7186        let style = window_chrome::style_mask(options, prefs_style);
7187        let window = window_chrome::alloc_window(
7188            mtm,
7189            content_rect,
7190            style,
7191            options.chrome == day_spec::WindowChrome::Frameless,
7192        );
7193        unsafe { window.setReleasedWhenClosed(false) };
7194        window.setTitle(&NSString::from_str(title));
7195        if let Some(min) = min_size {
7196            unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
7197        }
7198        if let Some(max) = options.max_size {
7199            unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
7200        }
7201        use day_spec::WindowTabbing as T;
7202        use objc2_app_kit::NSWindowTabbingMode as M;
7203        let group = match tabbing {
7204            T::Group(g) | T::Preferred(g) => Some(g.clone()),
7205            T::Automatic | T::Disallowed => None,
7206        };
7207        match tabbing {
7208            _ if prefs_style => window.setTabbingMode(M::Disallowed),
7209            T::Disallowed => window.setTabbingMode(M::Disallowed),
7210            // Same-kind Day windows group as native tabs (System Settings "prefer tabs",
7211            // View ▸ Show Tab Bar, Merge All Windows) — meaningful once a second Normal
7212            // window can exist; inert while automatic tabbing is globally off (see `run`).
7213            T::Automatic => unsafe {
7214                window.setTabbingIdentifier(&NSString::from_str("day.normal"))
7215            },
7216            T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
7217            T::Preferred(g) => {
7218                unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
7219                window.setTabbingMode(M::Preferred);
7220            }
7221        }
7222        if group.is_some() {
7223            // A named group is the app asking for tabs, so the class-wide switch `run` may have
7224            // turned off (no New Window builder) goes back on for it.
7225            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
7226        }
7227        let delegate = DayWinDelegate::new(mtm, node, group);
7228        window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7229        let content = view_of(DayFlipped::new(mtm));
7230        window.setContentView(Some(&content));
7231        window_chrome::apply(&window, &content, options);
7232        // Tab / Shift-Tab (docs/focus.md). AppKit does NOT derive the key view loop from the view
7233        // hierarchy: `nextKeyView` is nil on a programmatically built window and the loop stays
7234        // empty, so Tab moves focus OUT of a text field and onto nothing — measured on the
7235        // showcase's Focus page, where three Tabs in a row left every field unfocused. Every other
7236        // Day backend gets traversal from its widget order for free; this is the one that has to
7237        // ask. Autorecalculation rather than a call at the end of each layout because Day's tree
7238        // is reactive: fields appear, move, and vanish between passes, and AppKit rebuilding the
7239        // loop on hierarchy changes is the same rule expressed once.
7240        window.setAutorecalculatesKeyViewLoop(true);
7241        (window, delegate, content)
7242    }
7243}
7244
7245impl Default for AppKit {
7246    fn default() -> Self {
7247        Self::new()
7248    }
7249}
7250
7251fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
7252    Retained::from(x.as_ref())
7253}
7254
7255fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
7256    unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
7257}
7258
7259/// The macOS native semantic text style for a logical [`Font`] (`None` for a custom size).
7260/// `NSFont.preferredFont(forTextStyle:)` gives the OS's own typography, tracking the system settings.
7261fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
7262    use objc2_app_kit::*;
7263    unsafe {
7264        Some(match f {
7265            Font::LargeTitle => NSFontTextStyleLargeTitle,
7266            Font::Title => NSFontTextStyleTitle1,
7267            Font::Title2 => NSFontTextStyleTitle2,
7268            Font::Title3 => NSFontTextStyleTitle3,
7269            Font::Headline => NSFontTextStyleHeadline,
7270            Font::Subheadline => NSFontTextStyleSubheadline,
7271            Font::Body => NSFontTextStyleBody,
7272            Font::Callout => NSFontTextStyleCallout,
7273            Font::Footnote => NSFontTextStyleFootnote,
7274            Font::Caption => NSFontTextStyleCaption1,
7275            Font::Caption2 => NSFontTextStyleCaption2,
7276            Font::System(_) | Font::Custom(..) => return None,
7277        })
7278    }
7279}
7280
7281fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
7282    use day_spec::FontWeight as W;
7283    use objc2_app_kit::*;
7284    unsafe {
7285        match w {
7286            W::UltraLight => NSFontWeightUltraLight,
7287            W::Thin => NSFontWeightThin,
7288            W::Light => NSFontWeightLight,
7289            W::Regular => NSFontWeightRegular,
7290            W::Medium => NSFontWeightMedium,
7291            W::Semibold => NSFontWeightSemibold,
7292            W::Bold => NSFontWeightBold,
7293            W::Heavy => NSFontWeightHeavy,
7294            W::Black => NSFontWeightBlack,
7295        }
7296    }
7297}
7298
7299/// The `NSFontManager` weight rung (0 … 15) for a Day weight — the scale
7300/// `fontWithFamily:traits:weight:size:` matches faces on (5 = regular, 9 = bold).
7301fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7302    use day_spec::FontWeight as W;
7303    match w {
7304        W::UltraLight => 2,
7305        W::Thin => 3,
7306        W::Light => 4,
7307        W::Regular => 5,
7308        W::Medium => 6,
7309        W::Semibold => 8,
7310        W::Bold => 9,
7311        W::Heavy => 10,
7312        W::Black => 12,
7313    }
7314}
7315
7316/// Resolve a canvas font (docs/fonts.md) at an absolute size: the system face for `None`,
7317/// else the family's nearest member through `NSFontManager` (which also synthesizes a bold or
7318/// italic the family lacks), falling back to a PostScript/full-name lookup (a bundled font
7319/// registered in `run`) and then to the system font with one warning.
7320fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7321    use objc2_app_kit::*;
7322    let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7323    let mtm = objc2::MainThreadMarker::new().expect("canvas draws on the main thread");
7324    let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7325    let mut traits = NSFontTraitMask::empty();
7326    if weight >= day_spec::FontWeight::Semibold {
7327        traits |= NSFontTraitMask::BoldFontMask;
7328    }
7329    if font.italic {
7330        traits |= NSFontTraitMask::ItalicFontMask;
7331    }
7332    let Some(family) = font.family.as_deref() else {
7333        let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7334        return if font.italic {
7335            unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7336        } else {
7337            base
7338        };
7339    };
7340    let ns_family = NSString::from_str(family);
7341    if let Some(f) = unsafe {
7342        manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7343    } {
7344        return f;
7345    }
7346    if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7347        return if traits.is_empty() {
7348            f
7349        } else {
7350            unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7351        };
7352    }
7353    log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7354    unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7355}
7356
7357/// The attribute dictionary canvas text draws and measures with (the same one, so
7358/// `measure_text` and `replay` agree on the line box).
7359fn canvas_text_attrs(
7360    font: &NSFont,
7361    color: day_spec::Color,
7362) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7363    let col = nscolor(color);
7364    // SAFETY: both are AppKit's own attribute-name constants, valid for the process lifetime.
7365    let keys: [&NSString; 2] = unsafe {
7366        [
7367            objc2_app_kit::NSFontAttributeName,
7368            objc2_app_kit::NSForegroundColorAttributeName,
7369        ]
7370    };
7371    let objs: [&objc2::runtime::AnyObject; 2] = [
7372        font as &objc2::runtime::AnyObject,
7373        col.as_ref() as &objc2::runtime::AnyObject,
7374    ];
7375    objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7376}
7377
7378/// Resolve a [`FontSpec`] to a native `NSFont`: a semantic style via `preferredFont(forTextStyle:)`
7379/// (or a custom system size), then an optional weight override (at the same size) and italic trait.
7380fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7381    use objc2_app_kit::*;
7382    let base: Retained<NSFont> = match spec.style {
7383        Font::System(pt) => {
7384            let w = spec
7385                .weight
7386                .map(ns_weight)
7387                .unwrap_or(unsafe { NSFontWeightRegular });
7388            unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7389        }
7390        // A bundled family (§18.4), registered with CoreText in run(). fontWithName resolves
7391        // family, full, and PostScript names. A weight override maps to the bold trait (the
7392        // family decides what it can supply); unknown families fall back to the system font.
7393        Font::Custom(name, pt) => {
7394            match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7395                Some(f) => {
7396                    if spec
7397                        .weight
7398                        .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7399                    {
7400                        let mtm = objc2::MainThreadMarker::new()
7401                            .expect("labels realize on the main thread");
7402                        unsafe {
7403                            NSFontManager::sharedFontManager(mtm)
7404                                .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
7405                        }
7406                    } else {
7407                        f
7408                    }
7409                }
7410                None => {
7411                    log::warn!(
7412                        "unknown font family {name:?} — falling back to the system font \
7413                         (is the file in the project's fonts/ directory?)"
7414                    );
7415                    let w = spec
7416                        .weight
7417                        .map(ns_weight)
7418                        .unwrap_or(unsafe { NSFontWeightRegular });
7419                    unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7420                }
7421            }
7422        }
7423        style => {
7424            // Invariant: System/Custom matched above, so only the semantic styles — which
7425            // `ns_text_style` maps exhaustively — can reach this arm.
7426            let ts = ns_text_style(style).expect("semantic style");
7427            let opts = objc2_foundation::NSDictionary::new();
7428            let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
7429            match spec.weight {
7430                // A weight override keeps the style's (system-resolved) size but re-picks the weight.
7431                Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
7432                None => f,
7433            }
7434        }
7435    };
7436    // Tabular figures. Cocoa exposes them as a whole font, not a trait, so this re-picks the
7437    // system font at the resolved size/weight rather than converting — which is why it only
7438    // applies to the system styles: a bundled `Font::Custom` family keeps its own figures (asking
7439    // for the system's monospaced-digit face there would silently swap the typeface).
7440    let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
7441        let w = spec
7442            .weight
7443            .map(ns_weight)
7444            .unwrap_or(unsafe { NSFontWeightRegular });
7445        unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
7446    } else {
7447        base
7448    };
7449    // Monospace, by the same rule as tabular: Cocoa ships it as a whole font, so this re-picks
7450    // the system's monospaced face at the resolved size and weight. Skipped for a bundled family
7451    // — swapping a chosen typeface for the system mono would be a surprise, not a refinement.
7452    let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
7453        let w = spec
7454            .weight
7455            .map(ns_weight)
7456            .unwrap_or(unsafe { NSFontWeightRegular });
7457        unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
7458    } else {
7459        base
7460    };
7461    // Relative size (`FontSpec::scale`). Applied last, over whatever face the traits above
7462    // settled on, and through `convertFont_toSize` so a bundled family keeps its typeface —
7463    // re-picking the system font here would undo the Custom/monospace/tabular work above.
7464    let base = if spec.scale != 1.0 {
7465        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7466        let pts = spec.resolved_points(base.pointSize());
7467        unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
7468    } else {
7469        base
7470    };
7471    if spec.italic {
7472        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7473        unsafe {
7474            NSFontManager::sharedFontManager(mtm)
7475                .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
7476        }
7477    } else {
7478        base
7479    }
7480}
7481
7482/// Build an `NSAttributedString` for a label's text + runs (docs/text-runs.md).
7483///
7484/// Ranges arrive as BYTE offsets into a Rust `str`; `NSAttributedString` indexes UTF-16. The
7485/// conversion is per-run rather than a blanket assumption: any text with an emoji or a CJK
7486/// character makes the two disagree, and an off-by-N range there styles the wrong words.
7487/// Stamp a paragraph alignment across a label's whole attributed string.
7488///
7489/// Separate from `setAlignment:` because the two live in different places: the cell has a
7490/// paragraph style, the attributed string carries its own, and the string's wins.
7491fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
7492    use objc2_foundation::{NSMutableAttributedString, NSRange};
7493    unsafe {
7494        let cur = tf.attributedStringValue();
7495        let m = NSMutableAttributedString::initWithAttributedString(
7496            NSMutableAttributedString::alloc(),
7497            &cur,
7498        );
7499        let style = objc2_app_kit::NSMutableParagraphStyle::new();
7500        style.setAlignment(align);
7501        // Wrapping is what makes alignment observable at all, and the default paragraph style a
7502        // fresh NSMutableParagraphStyle carries would otherwise reset it to clipping.
7503        style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
7504        m.addAttribute_value_range(
7505            objc2_app_kit::NSParagraphStyleAttributeName,
7506            &style,
7507            NSRange::new(0, cur.length()),
7508        );
7509        tf.setAttributedStringValue(&m);
7510    }
7511}
7512
7513fn attributed_label(
7514    text: &str,
7515    base_font: &NSFont,
7516    color: Option<day_spec::Color>,
7517    role: day_spec::props::TextRole,
7518    runs: &[day_spec::TextRun],
7519) -> Retained<objc2_foundation::NSAttributedString> {
7520    use objc2_foundation::{NSMutableAttributedString, NSRange};
7521    let ns = NSString::from_str(text);
7522    let s = unsafe {
7523        NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
7524    };
7525    let whole = NSRange::new(0, ns.length());
7526    unsafe {
7527        s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
7528        // Always a foreground: an attributed range with no color attribute draws in black,
7529        // which is unreadable in dark mode. `labelColor` is the adaptive default the field
7530        // would have used on its own.
7531        // An explicit color wins; otherwise the ROLE picks which adaptive system color to use.
7532        // Both are adaptive, which is the point of asking for a role instead of a grey: the
7533        // secondary label is legible against either appearance's background, and a literal one
7534        // cannot be.
7535        let fg = color.map(nscolor).unwrap_or_else(|| match role {
7536            day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
7537            day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
7538        });
7539        s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
7540    }
7541    for r in runs {
7542        let Some(range) = utf16_range(text, &r.range) else {
7543            continue;
7544        };
7545        unsafe {
7546            s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
7547            if let Some(c) = r.color {
7548                s.addAttribute_value_range(
7549                    objc2_app_kit::NSForegroundColorAttributeName,
7550                    &nscolor(c),
7551                    range,
7552                );
7553            }
7554            if let Some(c) = r.background {
7555                s.addAttribute_value_range(
7556                    objc2_app_kit::NSBackgroundColorAttributeName,
7557                    &nscolor(c),
7558                    range,
7559                );
7560            }
7561            if r.underline.is_on() {
7562                let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
7563                s.addAttribute_value_range(
7564                    objc2_app_kit::NSUnderlineStyleAttributeName,
7565                    &style,
7566                    range,
7567                );
7568            }
7569            if r.strikethrough {
7570                let one = objc2_foundation::NSNumber::new_i64(1);
7571                s.addAttribute_value_range(
7572                    objc2_app_kit::NSStrikethroughStyleAttributeName,
7573                    &one,
7574                    range,
7575                );
7576            }
7577            if let Some(url) = r.link.as_deref() {
7578                // The native field editor hit-tests this attribute; DayLabel handles its
7579                // delegate callback and reports LinkActivated without opening the URL itself.
7580                let value = NSString::from_str(url);
7581                s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
7582            }
7583        }
7584    }
7585    s.into_super()
7586}
7587
7588/// [`Underline`](day_spec::Underline) as an `NSUnderlineStyle` bitmask: the line style in the low
7589/// byte, the pattern in the second. `Dotted`/`Wavy` are patterns over a single line, which is
7590/// exactly how AppKit spells them.
7591fn ns_underline(u: day_spec::Underline) -> i64 {
7592    use day_spec::Underline as U;
7593    match u {
7594        U::None => 0,
7595        U::Single => 0x01,
7596        U::Double => 0x09,
7597        U::Dotted => 0x01 | 0x0100,
7598        U::Wavy => 0x01 | 0x0400,
7599    }
7600}
7601
7602/// A byte range in `text` as an `NSRange` in UTF-16 units, or `None` if it is out of bounds.
7603fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
7604    let start = text.get(..r.start)?.encode_utf16().count();
7605    let len = text.get(r.clone())?.encode_utf16().count();
7606    Some(objc2_foundation::NSRange::new(start, len))
7607}
7608
7609/// Register every bundled font file (the project's `fonts/`, staged per §18.4) with CoreText for
7610/// this process, so `Font::Custom` family names resolve through `NSFont::fontWithName`. Called
7611/// once from `run()`; a failure (already registered on a hot relaunch, or a broken file) only
7612/// means that family won't resolve, so it logs and moves on.
7613fn register_bundled_fonts() {
7614    // CFURLRef is toll-free bridged with NSURL, so the NSURL pointer passes straight through.
7615    #[link(name = "CoreText", kind = "framework")]
7616    unsafe extern "C" {
7617        fn CTFontManagerRegisterFontsForURL(
7618            font_url: *const std::ffi::c_void,
7619            scope: u32, // kCTFontManagerScopeProcess = 1
7620            error: *mut *const std::ffi::c_void,
7621        ) -> bool;
7622    }
7623    for path in day_spec::fonts::bundled_fonts() {
7624        let url = unsafe {
7625            objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
7626        };
7627        let ok = unsafe {
7628            CTFontManagerRegisterFontsForURL(
7629                Retained::as_ptr(&url) as *const std::ffi::c_void,
7630                1,
7631                std::ptr::null_mut(),
7632            )
7633        };
7634        if !ok {
7635            log::warn!("could not register bundled font {}", path.display());
7636        }
7637    }
7638}
7639
7640/// `TextAlign` → AppKit. `Natural` rather than `Left` for the leading case: it follows the
7641/// writing direction, so an RTL locale aligns right without the app asking (docs/localization.md).
7642fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
7643    match a {
7644        day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
7645        day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
7646        day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
7647    }
7648}
7649
7650fn configure_label_cell(tf: &NSTextField) {
7651    if let Some(cell) = unsafe { tf.cell() } {
7652        unsafe {
7653            cell.setWraps(true);
7654            cell.setUsesSingleLineMode(false);
7655            cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
7656        }
7657    }
7658}
7659
7660/// If `parent` is a scroll view, children go into its (flipped) document view.
7661fn content_of(parent: &Handle) -> Retained<NSView> {
7662    if let Some(sv) = parent.downcast_ref::<NSScrollView>()
7663        && let Some(doc) = unsafe { sv.documentView() }
7664    {
7665        return doc;
7666    }
7667    parent.clone()
7668}
7669
7670/// Run `body` (which sets animatable properties on a layer-backed view) inside an
7671/// `NSAnimationContext` group so AppKit interpolates the change on the render server with the
7672/// curve's timing function, or immediately when `anim` is `None` (§8.4). `allowsImplicitAnimation`
7673/// makes direct property changes on layer-backed views animate. A spring maps to an overshooting
7674/// cubic-bezier timing function (a visible bounce without an explicit `CASpringAnimation`).
7675fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
7676    let Some(a) = anim else {
7677        body();
7678        return;
7679    };
7680    let (dur, timing) = appkit_timing(a);
7681    unsafe {
7682        NSAnimationContext::beginGrouping();
7683        let ctx = NSAnimationContext::currentContext();
7684        ctx.setDuration(dur);
7685        ctx.setTimingFunction(Some(&timing));
7686        ctx.setAllowsImplicitAnimation(true);
7687        body();
7688        NSAnimationContext::endGrouping();
7689    }
7690}
7691
7692/// The `(duration_secs, timing function)` for a curve. Springs render as an overshooting bezier
7693/// (control point y > 1) whose overshoot grows as damping falls, over a response-derived duration.
7694fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
7695    unsafe {
7696        let named = |n| {
7697            (
7698                a.duration_secs().max(0.01),
7699                CAMediaTimingFunction::functionWithName(n),
7700            )
7701        };
7702        match a.curve {
7703            Curve::Linear => named(kCAMediaTimingFunctionLinear),
7704            Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
7705            Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
7706            Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
7707            Curve::Spring { damping, .. } => {
7708                // Overshoot bezier over exactly the specified duration (authoritative timing).
7709                let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
7710                (
7711                    a.duration_secs().max(0.05),
7712                    CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
7713                )
7714            }
7715        }
7716    }
7717}
7718
7719/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
7720/// a visible placeholder. A missing renderer usually means the piece's `appkit` feature wasn't enabled
7721/// (Tier A.2 derives it automatically under `day build`; a bare `cargo` build may miss it). Deduped
7722/// per kind so a placeholder rendered every frame doesn't spam the log.
7723fn warn_missing_renderer(kind: PieceKind) {
7724    day_spec::placeholder::report(kind, "appkit");
7725}
7726
7727/// The visible-but-harmless placeholder label the unregistered-kind arm renders. Shared with
7728/// the [`props_of`] mismatch fallback, so a wrong props payload degrades to the same surface
7729/// (the warning is already reported by `props_of` itself).
7730pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
7731    view_of(unsafe {
7732        NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
7733    })
7734}
7735
7736impl Toolkit for AppKit {
7737    /// Settled unless a toolbar edit is still painting (toolbar.rs `CHROME_SETTLE`); AppKit's
7738    /// own transitions (sheets, nav pushes) complete within the turn that starts them.
7739    fn ui_idle(&mut self) -> bool {
7740        toolbar::chrome_settled()
7741    }
7742
7743    type Handle = Handle;
7744
7745    fn dark_mode(&mut self) -> bool {
7746        // The app's EFFECTIVE appearance — one source for the system setting, the DAY_THEME
7747        // launch force (applied as an NSApp override at startup), and a set_appearance call.
7748        let app = NSApplication::sharedApplication(self.mtm());
7749        app.effectiveAppearance()
7750            .name()
7751            .to_string()
7752            .contains("Dark")
7753    }
7754
7755    /// System Settings › Accessibility › Display › "Reduce motion", as NSWorkspace reports it
7756    /// (docs/accessibility.md). `install_reduce_motion_observer` re-reads it on a flip.
7757    fn reduce_motion(&mut self) -> bool {
7758        objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
7759    }
7760
7761    /// macOS is the one platform whose badge takes arbitrary text: `NSDockTile.badgeLabel` is a
7762    /// `String`, so `Text` renders literally and a count is just its decimal form. A nil label
7763    /// clears it (docs/badge.md).
7764    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
7765        use day_spec::AppBadge;
7766        let label = match badge {
7767            AppBadge::None => None,
7768            // Zero clears, matching the platform convention the doc states.
7769            AppBadge::Count(0) => None,
7770            AppBadge::Count(n) => Some(n.to_string()),
7771            AppBadge::Text(t) if t.is_empty() => None,
7772            AppBadge::Text(t) => Some(t.clone()),
7773            // No dedicated dot on the Dock; the smallest honest mark is a single bullet.
7774            AppBadge::Dot => Some("\u{2022}".to_string()),
7775        };
7776        let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
7777        let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
7778        unsafe { tile.setBadgeLabel(ns.as_deref()) };
7779        tile.display();
7780    }
7781
7782    fn set_appearance(&mut self, dark: Option<bool>) {
7783        let app = NSApplication::sharedApplication(self.mtm());
7784        let appearance = dark.and_then(|d| {
7785            objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
7786                if d {
7787                    objc2_app_kit::NSAppearanceNameDarkAqua
7788                } else {
7789                    objc2_app_kit::NSAppearanceNameAqua
7790                }
7791            })
7792        });
7793        // `None` clears the override — back to the system appearance.
7794        unsafe { app.setAppearance(appearance.as_deref()) };
7795    }
7796
7797    fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
7798        controls::refresh_gesture::attach(handle, host);
7799    }
7800
7801    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
7802        unsafe {
7803            handle.setHidden(!visible);
7804        }
7805    }
7806
7807    fn capability(&self, cap: Cap) -> Support {
7808        match cap {
7809            Cap::SearchField => Support::Native,
7810            Cap::ComboBox => Support::Native,
7811            Cap::Stepper => Support::Native,
7812            Cap::DateTimePicker => Support::Native,
7813            Cap::ColorPicker => Support::Native,
7814            Cap::PullRefresh => Support::Emulated,
7815            Cap::Pager => Support::Emulated,
7816            Cap::PullRefreshGesture => Support::Emulated,
7817            // A tracking-area owner sets an `NSCursor` per view (docs/cursor.md). Wait, progress,
7818            // help, and move take the arrow — AppKit draws no such shapes — and the zoom and
7819            // diagonal-resize cursors need macOS 15.
7820            Cap::Cursor => Support::Native,
7821            // `NSFontManager` enumerates every family and member (docs/fonts.md).
7822            Cap::FontList => Support::Native,
7823            // An image-and-text table cell's content (docs/list.md "List items").
7824            Cap::ListItem => Support::Native,
7825            // ImageIO behind `NSBitmapImageRep` reads every container macOS knows and writes
7826            // back PNG/JPEG/TIFF/BMP/GIF, and carries the container's own metadata dictionary
7827            // (docs/images.md).
7828            Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
7829            // Canvas export (docs/canvas.md "Exporting"): the canvas painter replayed into a
7830            // CGBitmapContext, or a CGPDFContext that keeps shapes and text vector.
7831            Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
7832            // The announcement-requested notification, posted from the primary window
7833            // (docs/accessibility.md).
7834            Cap::Announce => Support::Native,
7835            // `NSWorkspace.accessibilityDisplayShouldReduceMotion`, re-read when the workspace
7836            // posts its display-options change (docs/accessibility.md).
7837            Cap::ReduceMotion => Support::Native,
7838            Cap::Snapshot
7839            | Cap::NativeSymbols
7840            // The rows as chrome: `Rail` is the same source list pinned narrow, `Tabs` an
7841            // NSSegmentedControl docked below the pages. AppKit has no app-level tab bar —
7842            // NSTabView owns its own page content, the opposite of Day's model — so the bar
7843            // is composed from the control a Mac uses for a one-of-N switch this size.
7844            //
7845            // `Cap::NavTabsAdaptive` is deliberately NOT here: a Mac app may PIN a tab bar, but
7846            // a narrow Mac window hides its sidebar and pushes rather than growing one. It falls
7847            // through to the `Unsupported` arm below.
7848            | Cap::NavTabs
7849            | Cap::NavSplit
7850            // Both presentations are the same NSSplitViewController — a stack is that split with
7851            // its sidebar item collapsed — so re-presenting is a collapse plus one `addSubview`
7852            // that re-parents the sidebar page (docs/size-classes.md).
7853            | Cap::NavRepresent
7854            // A REAL `contentList` NSSplitViewItem between sidebar and detail; the pane
7855            // persists through every presentation (docs/navigation.md).
7856            | Cap::NavContentList
7857            | Cap::Dialogs
7858            | Cap::FileDialogs
7859            // NSOpenPanel with `canChooseDirectories` (docs/files.md).
7860            | Cap::FolderDialog
7861            | Cap::Animation
7862            // NSTextView natively honors all three text-area attributes.
7863            | Cap::TextEditable
7864            | Cap::TextSelectable
7865            | Cap::TextSpellCheck
7866            // NSTableView's own drag pipeline, with the `.gap` placeholder (docs/list.md), in
7867            // lists and in the source-list sidebar itself (docs/navigation.md).
7868            | Cap::NavReorder | Cap::ListReorder
7869            // NSTableView's view-based reuse queue (`makeViewWithIdentifier`) hands Day's cells
7870            // back for new rows; `didRemoveRowView` recycles them (docs/list.md).
7871            | Cap::ListRecycling
7872            // NSTableView row actions: reveal-as-you-swipe buttons with the native full-slide
7873            // activation (docs/list.md).
7874            | Cap::ListSwipeActions
7875            // NSTableView group rows with `floatsGroupRows` (docs/list.md "Sections").
7876            | Cap::ListSections
7877            // NSOutlineView hosts Day-built rows natively, drag-reparent included
7878            // (docs/tree.md).
7879            | Cap::Tree
7880            | Cap::TreeSections
7881            | Cap::TreeMove
7882            // Real NSWindows with native tabbing + the Windows menu (docs/windows.md).
7883            | Cap::MultiWindow
7884            // `miniaturize:` / `zoom:` / `toggleFullScreen:`, reported back through the window
7885            // delegate's notifications (docs/windows.md "Window properties").
7886            | Cap::WindowStates
7887            | Cap::WindowFullscreen
7888            // `NSWindowSharingNone`: captures, recordings and screen sharing see an empty window.
7889            | Cap::ContentProtection
7890            // Per-window `tabbingIdentifier` / `tabbingMode`, with the "+" opening the group's
7891            // own builder.
7892            | Cap::WindowTabbing
7893            // `applicationDockMenu:` on the app delegate (docs/menus.md).
7894            | Cap::DockMenu
7895            // Borderless windows that still take key, a transparent title bar over the
7896            // content, a clear window background, and `NSVisualEffectView` materials behind the
7897            // content (docs/window-chrome.md).
7898            | Cap::FramelessWindow
7899            | Cap::OverlayTitleBar
7900            | Cap::TransparentWindow
7901            | Cap::WindowMaterial
7902            // `performWindowDragWithEvent:` from a press on the region's own background.
7903            | Cap::DragRegion
7904            // `NSStatusItem`s in the menu bar, a progress bar drawn on the Dock tile, and the
7905            // accessory activation policy (docs/status-item.md).
7906            | Cap::StatusItem
7907            | Cap::AppProgress
7908            | Cap::DockVisibility
7909            // Frame, limits, level, Spaces, style-mask controls, per-window appearance, Dock
7910            // bounces, and `NSScreen` (docs/windows.md "Window properties").
7911            | Cap::WindowGeometry
7912            | Cap::WindowPosition
7913            | Cap::WindowLevel
7914            | Cap::WindowAppearance
7915            | Cap::RequestAttention
7916            | Cap::Monitors
7917            // Run-time shortcuts appear in the Dock menu beside the declared ones.
7918            | Cap::DynamicShortcuts
7919            // A real NSToolbar in the title bar (docs/toolbars.md).
7920            | Cap::Toolbar
7921            // The bar holds a native search field (docs/search.md).
7922            | Cap::ToolbarSearch
7923            | Cap::AppMenu
7924            // NSDockTile.badgeLabel is an arbitrary String, so all three payloads render — the
7925            // only backend where Text is real (docs/badge.md).
7926            | Cap::AppBadgeCount
7927            | Cap::AppBadgeText
7928            // NSUndoManager fronted by DayUndoManager: the stock Edit menu retitles and
7929            // enables itself, ⌘Z/⇧⌘Z land through the responder chain (docs/model.md).
7930            | Cap::UndoBridge
7931            | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
7932            | Cap::AppBadgeDot
7933            | Cap::Appearance
7934            // firstBaselineOffsetFromTop — the platform's own answer (docs/baseline.md).
7935            | Cap::BaselineAlignment
7936            // A REAL inspector NSSplitViewItem (`inspectorWithViewController:`): the system
7937            // trailing-pane material and full-height layout (docs/inspector.md).
7938            | Cap::Inspector
7939            // A plain NSSplitView with two arranged panes (docs/split.md).
7940            | Cap::Split
7941            | Cap::TextRuns
7942            | Cap::TextLinks => Support::Native,
7943            // A topmost autoresizing child of the content view — not a system modal
7944            // (docs/cover.md's ArkUI tier).
7945            Cap::Cover => Support::Emulated,
7946            // `.sheet()` is a window sheet on the primary window (docs/cover.md "Modal sheet").
7947            Cap::CoverSheet => Support::Native,
7948            _ => Support::Unsupported,
7949        }
7950    }
7951
7952    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
7953        let mtm = self.mtm;
7954        match Builtin::from_key(kind) {
7955            Some(Builtin::Container) => {
7956                let v = DayFlipped::new(mtm);
7957                if let Some(p) = props.downcast_ref::<ContainerProps>() {
7958                    if p.role == Some(day_spec::SurfaceRole::SectionCard) {
7959                        v.set_section_card(p.corner_radius);
7960                    } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
7961                        v.set_surface(p.background, p.corner_radius, p.clips);
7962                    }
7963                }
7964                view_of(v)
7965            }
7966            Some(Builtin::Scroll) => {
7967                let horizontal = props
7968                    .downcast_ref::<day_spec::props::ScrollProps>()
7969                    .map(|p| p.horizontal)
7970                    .unwrap_or(false);
7971                let sv = unsafe { NSScrollView::new(mtm) };
7972                unsafe {
7973                    sv.setHasVerticalScroller(!horizontal);
7974                    sv.setHasHorizontalScroller(horizontal);
7975                    sv.setDrawsBackground(false);
7976                    // Overlay scrollers ALWAYS: day lays content out at the scroll's full frame
7977                    // width, and a legacy scroller (the "always show scroll bars" system
7978                    // setting, or a mouse attached) would reserve ~15pt and clip trailing
7979                    // content. Overlay floats above content instead — and matches the GTK/Qt
7980                    // backends.
7981                    sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
7982                }
7983                let doc = DayFlipped::new(mtm);
7984                unsafe { sv.setDocumentView(Some(doc.as_ref())) };
7985                view_of(sv)
7986            }
7987            Some(Builtin::Label) => {
7988                // `props_of`, not a panicking downcast, for every typed-props arm: a mismatch
7989                // (a piece registered under a builtin key, or a day-core regression) warns once
7990                // per kind and degrades to the placeholder — realize runs inside native
7991                // up-calls, where a panic is a process kill.
7992                let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
7993                    return placeholder_view(mtm, kind);
7994                };
7995                let tf = DayLabel::new(mtm, id, &p.text);
7996                configure_label_cell(&tf);
7997                if !p.wraps || p.max_lines > 0 {
7998                    unsafe {
7999                        tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
8000                        if !p.wraps || p.max_lines == 1 {
8001                            tf.setUsesSingleLineMode(true);
8002                            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
8003                        }
8004                    }
8005                }
8006                unsafe { tf.setFont(Some(&nsfont(p.font))) };
8007                // The PLAIN path needs the role as much as the attributed one below: a label
8008                // with no runs never reaches `attributed_label`, and reading the role only there
8009                // left every ordinary `.secondary()` label rendering in the primary color.
8010                match (p.color, p.role) {
8011                    (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
8012                    (None, day_spec::props::TextRole::Secondary) => unsafe {
8013                        tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
8014                    },
8015                    (None, day_spec::props::TextRole::Primary) => {}
8016                }
8017                if !p.runs.is_empty() {
8018                    let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
8019                    unsafe { tf.setAttributedStringValue(&s) };
8020                }
8021                tf.ivars().has_runs.set(!p.runs.is_empty());
8022                tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
8023                // Alignment goes on last and, for a runs label, has to reach inside the
8024                // attributed string. `setAlignment:` writes the cell's paragraph style, which an
8025                // attributed string then overrides wholesale with its own — so a markdown label
8026                // set only through the cell comes out leading-aligned no matter what was asked.
8027                if p.align != day_spec::props::TextAlign::Leading {
8028                    unsafe { tf.setAlignment(nstextalign(p.align)) };
8029                    if !p.runs.is_empty() {
8030                        set_paragraph_alignment(&tf, nstextalign(p.align));
8031                    }
8032                }
8033                view_of(Retained::into_super(tf))
8034            }
8035            Some(Builtin::Button) => {
8036                let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
8037                    return placeholder_view(mtm, kind);
8038                };
8039                let target = DayTarget::new(mtm, id);
8040                let btn = unsafe {
8041                    NSButton::buttonWithTitle_target_action(
8042                        &NSString::from_str(&p.title),
8043                        Some(&*target),
8044                        Some(sel!(action:)),
8045                        mtm,
8046                    )
8047                };
8048                apply_button_style(&btn, p.style);
8049                if p.icon.is_some() {
8050                    apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
8051                }
8052                unsafe { btn.setEnabled(p.enabled) };
8053                set_button_selected(&btn, p.selected);
8054                let view = view_of(btn);
8055                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8056                view
8057            }
8058            Some(Builtin::Toggle) => {
8059                let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
8060                    return placeholder_view(mtm, kind);
8061                };
8062                let target = DayTarget::new(mtm, id);
8063                let sw = unsafe { NSSwitch::new(mtm) };
8064                unsafe {
8065                    sw.setState(if p.on { 1 } else { 0 });
8066                    sw.setEnabled(p.enabled);
8067                    sw.setTarget(Some(&*target));
8068                    sw.setAction(Some(sel!(action:)));
8069                }
8070                let view = view_of(sw);
8071                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8072                view
8073            }
8074            Some(Builtin::Slider) => {
8075                let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
8076                    return placeholder_view(mtm, kind);
8077                };
8078                let target = DayTarget::new(mtm, id);
8079                let sl = unsafe {
8080                    NSSlider::sliderWithValue_minValue_maxValue_target_action(
8081                        p.value,
8082                        p.min,
8083                        p.max,
8084                        Some(&*target),
8085                        Some(sel!(action:)),
8086                        mtm,
8087                    )
8088                };
8089                unsafe { sl.setContinuous(true) };
8090                let view = view_of(sl);
8091                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8092                view
8093            }
8094            Some(Builtin::Picker) => picker::realize_any(self, props, id),
8095            Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
8096            Some(Builtin::TextField) => {
8097                let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
8098                    return placeholder_view(mtm, kind);
8099                };
8100                let tf = new_text_field(mtm, id, false);
8101                unsafe {
8102                    tf.setStringValue(&NSString::from_str(&p.text));
8103                    tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
8104                }
8105                view_of(tf)
8106            }
8107            Some(Builtin::Divider) => {
8108                let b = unsafe { NSBox::new(mtm) };
8109                unsafe { b.setBoxType(NSBoxType::Separator) };
8110                view_of(b)
8111            }
8112            Some(Builtin::Progress) => {
8113                let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
8114                    return placeholder_view(mtm, kind);
8115                };
8116                if p.value.is_none() {
8117                    return crate::controls::spinner::make(self, p, id);
8118                }
8119                let pi = unsafe { NSProgressIndicator::new(mtm) };
8120                unsafe {
8121                    match p.value {
8122                        Some(v) => {
8123                            pi.setStyle(NSProgressIndicatorStyle::Bar);
8124                            pi.setIndeterminate(false);
8125                            pi.setMinValue(0.0);
8126                            pi.setMaxValue(1.0);
8127                            pi.setDoubleValue(v);
8128                        }
8129                        None => {
8130                            pi.setStyle(NSProgressIndicatorStyle::Spinning);
8131                            pi.setIndeterminate(true);
8132                            pi.startAnimation(None);
8133                        }
8134                    }
8135                }
8136                view_of(pi)
8137            }
8138            Some(Builtin::Canvas) => {
8139                let canvas = DayCanvas::new(mtm);
8140                KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
8141                view_of(canvas)
8142            }
8143            Some(Builtin::Inspector) => {
8144                let (visible, width, leading) = props
8145                    .downcast_ref::<InspectorProps>()
8146                    .map(|p| {
8147                        (
8148                            p.visible,
8149                            p.width,
8150                            p.edge == day_spec::props::PaneEdge::Leading,
8151                        )
8152                    })
8153                    .unwrap_or((false, 280.0, false));
8154                let content_wrap = view_of(DayFlipped::new(mtm));
8155                let panel_flipped = DayFlipped::new(mtm);
8156                // The panel draws an opaque window-background backdrop over the item's
8157                // vibrancy material — without it the section cards' thin quaternary fill
8158                // composites into near-black in dark mode (see `FlippedIvars`).
8159                panel_flipped.set_pane_backdrop();
8160                let panel_wrap = view_of(panel_flipped);
8161                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8162                // Force loadView before the items go in — the same lifecycle rule the nav
8163                // host below documents.
8164                let _ = unsafe { split_vc.view() };
8165                let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8166                let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8167                unsafe {
8168                    content_vc.setView(&content_wrap);
8169                    panel_vc.setView(&panel_wrap);
8170                }
8171                let content_item = unsafe {
8172                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
8173                };
8174                // A TRAILING pane is a real inspector item (the system treatment). A LEADING
8175                // one is a plain item placed first: `sidebarWithViewController:` would bring
8176                // sidebar material, which captures black offscreen (docs/navigation.md), and
8177                // the panel wrap already paints its own backdrop.
8178                let panel_item = unsafe {
8179                    if leading {
8180                        objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
8181                    } else {
8182                        objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
8183                    }
8184                };
8185                unsafe {
8186                    // Day's signal is the only visibility driver: with the pinned width the
8187                    // divider has nothing to drag and the pane cannot be user-collapsed, so
8188                    // there is no native-initiated change to report back.
8189                    panel_item.setCanCollapse(false);
8190                    panel_item.setCollapsed(!visible);
8191                    panel_item.setMinimumThickness(width);
8192                    panel_item.setMaximumThickness(width);
8193                    panel_item.setAllowsFullHeightLayout(true);
8194                    if leading {
8195                        split_vc.addSplitViewItem(&panel_item);
8196                        split_vc.addSplitViewItem(&content_item);
8197                    } else {
8198                        split_vc.addSplitViewItem(&content_item);
8199                        split_vc.addSplitViewItem(&panel_item);
8200                    }
8201                }
8202                let split = unsafe { split_vc.splitView() };
8203                unsafe {
8204                    split.setVertical(true);
8205                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8206                    // The same Auto Layout hand-back as the nav host below: Day owns this
8207                    // view's frame outside the split; the controller's own constraints keep
8208                    // doing the pane sizing inside it.
8209                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
8210                }
8211                let view = view_of(split);
8212                INSPECTOR_STATE.with(|m| {
8213                    m.borrow_mut().insert(
8214                        ptr_of(&view),
8215                        InspectorState {
8216                            content_wrap,
8217                            panel_wrap,
8218                            _split_vc: split_vc,
8219                            panel_item,
8220                        },
8221                    )
8222                });
8223                view
8224            }
8225            Some(Builtin::InspectorPane) => {
8226                // A DayNavPage for its `setFrameSize:` → `FrameChanged` report: the pane's
8227                // frame is native-owned (the split sizes it), exactly like a nav page —
8228                // NAV_PAGES membership is what makes `set_frame` skip it.
8229                let pane = view_of(DayNavPage::new(mtm, id));
8230                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8231                let panel = props
8232                    .downcast_ref::<InspectorPaneProps>()
8233                    .map(|p| p.panel)
8234                    .unwrap_or(false);
8235                INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
8236                pane
8237            }
8238            Some(Builtin::Split) => {
8239                let (axis, fraction, min_pane) = props
8240                    .downcast_ref::<SplitProps>()
8241                    .map(|p| (p.axis, p.fraction, p.min_pane))
8242                    .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
8243                let wrap = view_of(DayFlipped::new(mtm));
8244                let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
8245                let first_wrap = view_of(DayFlipped::new(mtm));
8246                let second_wrap = view_of(DayFlipped::new(mtm));
8247                unsafe {
8248                    // AppKit's "vertical" is the divider's orientation: panes side by side.
8249                    split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
8250                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8251                    split.addArrangedSubview(&first_wrap);
8252                    split.addArrangedSubview(&second_wrap);
8253                    split.setFrame(wrap.bounds());
8254                    split.setAutoresizingMask(
8255                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8256                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8257                    );
8258                    wrap.addSubview(&split);
8259                }
8260                let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
8261                split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
8262                SPLIT_STATE.with(|m| {
8263                    m.borrow_mut().insert(
8264                        ptr_of(&wrap),
8265                        SplitState {
8266                            split,
8267                            first_wrap,
8268                            second_wrap,
8269                            delegate,
8270                        },
8271                    )
8272                });
8273                wrap
8274            }
8275            Some(Builtin::SplitPane) => {
8276                // A DayNavPage, as an inspector pane: the splitter owns its frame, and its
8277                // `setFrameSize:` reports `FrameChanged`.
8278                let pane = view_of(DayNavPage::new(mtm, id));
8279                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8280                let second = props
8281                    .downcast_ref::<SplitPaneProps>()
8282                    .map(|p| p.second)
8283                    .unwrap_or(false);
8284                SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
8285                pane
8286            }
8287            Some(Builtin::Nav) => {
8288                let presentation = props
8289                    .downcast_ref::<NavProps>()
8290                    .map(|p| p.presentation)
8291                    .unwrap_or(NavPresentation::Split);
8292                let is_split = presentation.is_split();
8293                // The host is an NSSplitViewController, not a bare NSSplitView. Handing the
8294                // sidebar pane to `NSSplitViewItem::sidebarWithViewController:` is what buys
8295                // the system treatment: AppKit installs its own backing material and vibrancy
8296                // (so no hand-rolled NSVisualEffectView), pins the thickness with a sidebar
8297                // holding priority, animates collapse/expand, and drives the window's titlebar
8298                // separator. Day still owns the CONTENT of each pane — the two wraps below are
8299                // the item view controllers' views, so `insert`/`remove`/the NAV patches are
8300                // unchanged.
8301                let sidebar_wrap = view_of(DayFlipped::new(mtm));
8302                let detail_wrap = view_of(DayFlipped::new(mtm));
8303                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8304                // Force loadView/viewDidLoad before the items go in. NSSplitViewController
8305                // installs an item's view into the split as the item is added, which it can
8306                // only do once its own view exists — and reading `splitView` does not trigger
8307                // the lifecycle the way reading `view` does. Skipping this leaves a split view
8308                // with zero subviews: correct frame, nothing in it.
8309                let _ = unsafe { split_vc.view() };
8310                // Plain NSViewControllers with their view set explicitly: setting `view` up
8311                // front is what stops NSViewController looking for a nib named after itself.
8312                let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8313                let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8314                unsafe {
8315                    sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8316                    detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8317                }
8318                let sidebar_item = unsafe {
8319                    objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8320                };
8321                let detail_item = unsafe {
8322                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8323                };
8324                // The content-list pane (docs/navigation.md): a REAL `contentList`
8325                // NSSplitViewItem between the sidebar and the detail — Mail's own machinery,
8326                // holding priorities included. Its `Pane::List` page fills `list_wrap` exactly
8327                // as the sidebar page fills its own wrap, and the pane persists through every
8328                // presentation (only `NavPatch::ListVisible` collapses it).
8329                let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8330                // Set before the item joins the split, exactly as the sidebar's is below. A
8331                // collapsed state applied afterwards — by `NavPatch::ListVisible`, on a window
8332                // that has not been displayed — reports as collapsed and is then laid back out
8333                // from the item's holding priorities, which is how an app whose first
8334                // destination has no list opened with one beside it anyway.
8335                let list_visible = props
8336                    .downcast_ref::<NavProps>()
8337                    .is_none_or(|p| p.list_visible);
8338                let (list_wrap, list_item) = match list_width {
8339                    Some(w) => {
8340                        let wrap = view_of(DayFlipped::new(mtm));
8341                        let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8342                        unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8343                        let item = unsafe {
8344                            objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8345                        };
8346                        unsafe {
8347                            item.setCanCollapse(true);
8348                            item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8349                            item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8350                            item.setCollapsed(!list_visible);
8351                        }
8352                        (Some(wrap), Some(item))
8353                    }
8354                    None => (None, None),
8355                };
8356                unsafe {
8357                    // A stack presentation has no sidebar to show: collapse the (empty) pane
8358                    // and refuse the drag, so the detail owns the full width.
8359                    sidebar_item.setCanCollapse(is_split);
8360                    sidebar_item.setCollapsed(!is_split);
8361                    if is_split {
8362                        // Run the sidebar's material to the top of the window, under the
8363                        // titlebar, the way Mail and Finder do. Pairs with the unified toolbar
8364                        // style the window already uses (toolbar.rs).
8365                        sidebar_item.setAllowsFullHeightLayout(true);
8366                        sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8367                        sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8368                    } else {
8369                        sidebar_item.setMinimumThickness(0.0);
8370                        sidebar_item.setMaximumThickness(0.0);
8371                    }
8372                    split_vc.addSplitViewItem(&sidebar_item);
8373                    if let Some(item) = list_item.as_ref() {
8374                        split_vc.addSplitViewItem(item);
8375                    }
8376                    split_vc.addSplitViewItem(&detail_item);
8377                }
8378                let split = unsafe { split_vc.splitView() };
8379                // NSToolbarToggleSidebarItem sends `toggleSidebar:` down the RESPONDER chain,
8380                // and NSSplitViewController implements it — but a view controller only patches
8381                // itself into that chain when it is parented (a window's contentViewController
8382                // or another controller's child), and Day's tree is view-based all the way to
8383                // the window. Insert it by hand, directly after the split view, so a first
8384                // responder anywhere inside either pane walks up through it.
8385                unsafe {
8386                    let after = split.nextResponder();
8387                    split.setNextResponder(Some(&split_vc));
8388                    // The controller must never end up aiming at itself or at its OWN view,
8389                    // or its dealloc aborts the process: `-[NSViewController dealloc]`
8390                    // splices itself out with `view.nextResponder = self.nextResponder`, and
8391                    // if that lands the view on itself AppKit raises "The next responder
8392                    // should never be yourself!" — an NSException that unwinds into Rust and
8393                    // aborts. Both shapes occur here naturally: before macOS 15 the freshly
8394                    // loaded split view's next IS the controller, and on 15+ `view` is a
8395                    // WRAPPER above `splitView` whose auto-wiring makes the split's next
8396                    // that wrapper. Neither is a real upstream hop, so drop them.
8397                    let own_view = split_vc.view();
8398                    let vc_resp: *const objc2_app_kit::NSResponder = {
8399                        let r: &objc2_app_kit::NSResponder = &split_vc;
8400                        r
8401                    };
8402                    let view_resp: *const objc2_app_kit::NSResponder = {
8403                        let r: &objc2_app_kit::NSResponder = &own_view;
8404                        r
8405                    };
8406                    let upstream = after.filter(|a| {
8407                        let p: *const objc2_app_kit::NSResponder = &**a;
8408                        p != vc_resp && p != view_resp
8409                    });
8410                    split_vc.setNextResponder(upstream.as_deref());
8411                }
8412                unsafe {
8413                    split.setVertical(true);
8414                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8415                    // Day owns this view's frame (`set_frame`). A split view vended by
8416                    // NSSplitViewController arrives switched over to Auto Layout, which
8417                    // ignores that frame and lays the split out at zero — a window with
8418                    // chrome and nothing under it. Hand it back to autoresizing translation
8419                    // so Day stays the layout owner outside the split; the constraints the
8420                    // controller installs BETWEEN the split and its panes are untouched and
8421                    // keep doing the pane sizing.
8422                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
8423                }
8424                let root_title = props
8425                    .downcast_ref::<NavProps>()
8426                    .map(|p| p.title.clone())
8427                    .unwrap_or_default();
8428                // Stack presentation: a back header (hidden at root) — desktop has no system
8429                // back affordance, so a pushed page needs its own way out (docs/navigation.md).
8430                let header = if presentation == NavPresentation::Stack {
8431                    Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
8432                } else {
8433                    None
8434                };
8435                // A tabs host: the Mac's own tab control fills the detail pane and takes the
8436                // detail pages as its items (`TabHost`).
8437                let tabs = (presentation == NavPresentation::Tabs).then(|| {
8438                    let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
8439                    // Inset from the pane, the way a tab view sits in any Mac window: its
8440                    // tabs stand above the bezel, so flush to the top they run into the
8441                    // toolbar's edge, and flush to the sides the bezel hugs the sidebar. The
8442                    // autoresizing mask keeps the margins as the pane resizes.
8443                    let b = detail_wrap.bounds();
8444                    let frame = NSRect::new(
8445                        NSPoint::new(NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP),
8446                        NSSize::new(
8447                            (b.size.width - 2.0 * NAV_TABVIEW_INSET).max(0.0),
8448                            (b.size.height - NAV_TABVIEW_INSET_TOP - NAV_TABVIEW_INSET).max(0.0),
8449                        ),
8450                    );
8451                    unsafe {
8452                        tv.setTabViewType(
8453                            if props
8454                                .downcast_ref::<NavProps>()
8455                                .is_some_and(|p| p.documents.is_some())
8456                            {
8457                                objc2_app_kit::NSTabViewType::NoTabsNoBorder
8458                            } else {
8459                                objc2_app_kit::NSTabViewType::TopTabsBezelBorder
8460                            },
8461                        );
8462                        tv.setFrame(frame);
8463                        tv.setAutoresizingMask(
8464                            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8465                                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8466                        );
8467                        detail_wrap.addSubview(&tv);
8468                    }
8469                    TabHost {
8470                        view: tv,
8471                        target: None,
8472                    }
8473                });
8474                let view = view_of(split);
8475                NAV_STATE.with(|m| {
8476                    m.borrow_mut().insert(
8477                        ptr_of(&view),
8478                        NavState {
8479                            sidebar_wrap,
8480                            detail_wrap,
8481                            _split_vc: split_vc,
8482                            sidebar_item,
8483                            list_wrap,
8484                            list_item,
8485                            pages: Vec::new(),
8486                            list_page: None,
8487                            sidebar_page: None,
8488                            list_width,
8489                            list_visible,
8490                            list_positioned: false,
8491                            positioned: false,
8492                            presentation,
8493                            selected: 0,
8494                            tabs,
8495                            header,
8496                            root_title,
8497                            node: id,
8498                            title_strip: 0.0,
8499                        },
8500                    )
8501                });
8502                view
8503            }
8504            Some(Builtin::NavPage) => {
8505                let page = view_of(DayNavPage::new(mtm, id));
8506                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
8507                if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
8508                    PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
8509                }
8510                page
8511            }
8512            // Emulated fullscreen cover (docs/cover.md, the ArkUI tier): a DayNavPage — its
8513            // setFrameSize: override reports FrameChanged, so a window resize re-lays the cover
8514            // content for free — parked hidden until CoverPatch::Present re-homes it on top.
8515            Some(Builtin::Cover) => {
8516                let page = DayNavPage::new(mtm, id);
8517                let cover_props = props.downcast_ref::<CoverProps>();
8518                // A half sheet is a sheet here: macOS has no half-height presentation of its
8519                // own, so the window sheet stands in, at half the parent's height.
8520                page.ivars()
8521                    .sheet
8522                    .set(cover_props.is_some_and(|p| p.sheet || p.half));
8523                page.ivars().half.set(cover_props.is_some_and(|p| p.half));
8524                page.ivars().large.set(cover_props.is_some_and(|p| p.large));
8525                unsafe { page.setHidden(true) };
8526                view_of(page)
8527            }
8528            Some(Builtin::NavMenu) => {
8529                let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
8530                    return placeholder_view(mtm, kind);
8531                };
8532                let data = DayNavMenuData::new(
8533                    mtm,
8534                    id,
8535                    &p.items,
8536                    &p.icons,
8537                    &p.badges,
8538                    &p.badge_icons,
8539                    &p.badge_tints,
8540                    &p.sections,
8541                    &p.tints,
8542                    &p.menus,
8543                );
8544                *data.ivars().movable.borrow_mut() = p.movable.clone();
8545                data.ivars().regroup.set(p.regroup);
8546                *data.ivars().sorted.borrow_mut() = p.sorted.clone();
8547                // The Day subclass serves per-row context menus via menuForEvent:.
8548                let outline: Retained<objc2_app_kit::NSOutlineView> = {
8549                    let o: Retained<DayNavOutlineView> =
8550                        unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
8551                    NAV_OUTLINE_MENUS
8552                        .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
8553                    unsafe { msg_send![&*o, self] }
8554                };
8555                let col = unsafe {
8556                    objc2_app_kit::NSTableColumn::initWithIdentifier(
8557                        objc2_app_kit::NSTableColumn::alloc(mtm),
8558                        &NSString::from_str("item"),
8559                    )
8560                };
8561                unsafe {
8562                    outline.addTableColumn(&col);
8563                    outline.setOutlineTableColumn(Some(&col));
8564                    outline.setHeaderView(None);
8565                    // SourceList: the real sidebar treatment (Finder/Mail). The outline now
8566                    // lives inside a sidebar NSSplitViewItem, so AppKit supplies the backing
8567                    // material and the vibrancy the source-list selection composites through.
8568                    // This was Inset until 2026-08 because the earlier hand-rolled
8569                    // NSVisualEffectView blended behind the window, and an offscreen capture
8570                    // (`cacheDisplayInRect`) has no backdrop to sample — the selection came out
8571                    // a black pill that swallowed the row label. The material is AppKit's own
8572                    // now, and captures go through the window server (`snapshot_view`), which
8573                    // composites the material for real instead of guessing at it.
8574                    // `style = SourceList` is the whole switch: the matching
8575                    // `selectionHighlightStyle` constant is deprecated precisely because the
8576                    // style property now implies it.
8577                    outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8578                    // The default row size style follows the system's Sidebar icon size
8579                    // (Small, Medium, Large), live, as Finder's and Mail's sidebars do: AppKit
8580                    // sets the row height, the label's font and the icon's size. A table made
8581                    // in code starts at Custom, which ignores the setting.
8582                    outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
8583                    // Section headers pin to the top of the scroll as their group passes under
8584                    // it, the way Finder's sidebar groups do.
8585                    outline.setFloatsGroupRows(true);
8586                    outline.setIndentationPerLevel(0.0);
8587                    // Drag-to-reorder within this sidebar only (docs/navigation.md): rows that
8588                    // cannot move offer no drag, so registering costs a plain sidebar nothing.
8589                    outline.registerForDraggedTypes(
8590                        &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8591                            DAY_NAV_PASTEBOARD_TYPE,
8592                        )]),
8593                    );
8594                    outline.setDraggingSourceOperationMask_forLocal(
8595                        objc2_app_kit::NSDragOperation::Move,
8596                        true,
8597                    );
8598                    outline.setDraggingSourceOperationMask_forLocal(
8599                        objc2_app_kit::NSDragOperation::None,
8600                        false,
8601                    );
8602                    outline.setDraggingDestinationFeedbackStyle(
8603                        objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8604                    );
8605                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8606                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8607                    outline.reloadData();
8608                }
8609                let scroll = unsafe { NSScrollView::new(mtm) };
8610                unsafe {
8611                    scroll.setDrawsBackground(false);
8612                    scroll.setHasVerticalScroller(true);
8613                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
8614                    // clip the trailing edge of rows laid out at the full frame width (see
8615                    // the SCROLL realize).
8616                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8617                    // One column, sized to the pane: a sidebar never scrolls sideways.
8618                    scroll.setHasHorizontalScroller(false);
8619                    outline.setAutoresizingMask(
8620                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8621                    );
8622                    outline.setColumnAutoresizingStyle(
8623                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8624                    );
8625                    scroll.setDocumentView(Some(&outline));
8626                }
8627                let view = view_of(scroll);
8628                // Day selects by ITEM index; section headers make that differ from the
8629                // outline's row index, so every programmatic selection maps through `rows`.
8630                if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
8631                    data.ivars().suppress.set(true);
8632                    unsafe {
8633                        outline.selectRowIndexes_byExtendingSelection(
8634                            &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8635                            false,
8636                        )
8637                    };
8638                    data.ivars().suppress.set(false);
8639                }
8640                NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8641                view
8642            }
8643            Some(Builtin::List) => {
8644                let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
8645                    return placeholder_view(mtm, kind);
8646                };
8647                // Every list reports responder changes, even without an activation handler.
8648                let table: Retained<DayListView> =
8649                    unsafe { msg_send![DayListView::alloc(mtm), init] };
8650                let table = Retained::into_super(table);
8651                let col = unsafe {
8652                    NSTableColumn::initWithIdentifier(
8653                        NSTableColumn::alloc(mtm),
8654                        &NSString::from_str("day.list.col"),
8655                    )
8656                };
8657                let data = DayListData::new(
8658                    mtm,
8659                    id,
8660                    p.selectable,
8661                    p.multi_select,
8662                    p.row_height == RowHeight::Automatic,
8663                    p.sections,
8664                );
8665                unsafe {
8666                    if p.multi_select {
8667                        table.setAllowsMultipleSelection(true);
8668                    }
8669                    table.addTableColumn(&col);
8670                    table.setHeaderView(None);
8671                    // PLAIN, the classic edge-to-edge style: the macOS 11+ decorated styles
8672                    // (automatic ~14pt, FullWidth ~6pt) inset every cell view, clipping day
8673                    // row content laid out at the host's full frame width. This table ran
8674                    // FullWidth with a custom NSTableRowView pinning cells back to the row
8675                    // bounds until 2026-08 — and that pin also clobbered the cell-frame slide
8676                    // AppKit performs for row-action swipes, so the actions revealed behind a
8677                    // row whose CONTENT never moved. Plain has no inset to fight: standard
8678                    // row views, standard cell frames, and the swipe slide works untouched.
8679                    table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
8680                    // ...and the default intercell spacing (3pt × 2pt) shaves the column the
8681                    // same way — the last few points of a trailing control. Day rows own all
8682                    // of their spacing.
8683                    table.setIntercellSpacing(NSSize::new(0.0, 0.0));
8684                    // Host-drawn row separators (docs/list.md): the native horizontal grid
8685                    // line, which sits exactly at the row boundary — aligned with the
8686                    // selection, stationary under a row-action swipe, the Mail look.
8687                    if p.separators == Some(true) {
8688                        table.setGridStyleMask(
8689                            objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
8690                        );
8691                        table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
8692                    }
8693                    table.setColumnAutoresizingStyle(
8694                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8695                    );
8696                    // Section headers pin to the top while their section scrolls under them,
8697                    // the way Mail's and Finder's group rows do (docs/list.md "Sections").
8698                    table.setFloatsGroupRows(p.sections);
8699                    match p.row_height {
8700                        RowHeight::Uniform(h) => table.setRowHeight(h),
8701                        RowHeight::Automatic => table.setRowHeight(44.0),
8702                    }
8703                    if !p.selectable {
8704                        table.setSelectionHighlightStyle(
8705                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8706                        );
8707                    }
8708                    // Transparent: day panes own their backgrounds — the stock
8709                    // controlBackgroundColor would paint an appearance-colored slab that
8710                    // fights a themed app (visible whenever rows don't fill the viewport).
8711                    table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8712                    table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8713                    table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8714                    table.setTarget(Some(&*data));
8715                    if p.activatable {
8716                        table.setDoubleAction(Some(sel!(doubleClickRow:)));
8717                    }
8718                    if p.reorderable {
8719                        // Native drag-to-reorder (docs/list.md): rows drag within this table
8720                        // only (move locally, nothing leaves the app), and the drop target shows
8721                        // macOS's temporary placeholder GAP while the drag is over the table.
8722                        table.registerForDraggedTypes(
8723                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8724                                DAY_ROW_PASTEBOARD_TYPE,
8725                            )]),
8726                        );
8727                        table.setDraggingSourceOperationMask_forLocal(
8728                            objc2_app_kit::NSDragOperation::Move,
8729                            true,
8730                        );
8731                        table.setDraggingSourceOperationMask_forLocal(
8732                            objc2_app_kit::NSDragOperation::None,
8733                            false,
8734                        );
8735                        table.setDraggingDestinationFeedbackStyle(
8736                            objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8737                        );
8738                    }
8739                }
8740                let scroll = unsafe { NSScrollView::new(mtm) };
8741                unsafe {
8742                    scroll.setDrawsBackground(false);
8743                    scroll.setHasVerticalScroller(true);
8744                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
8745                    // clip the trailing edge of rows laid out at the full frame width (see
8746                    // the SCROLL realize).
8747                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8748                    scroll.setDocumentView(Some(&table));
8749                    let clip = scroll.contentView();
8750                    clip.setPostsBoundsChangedNotifications(true);
8751                    objc2_foundation::NSNotificationCenter::defaultCenter()
8752                        .addObserver_selector_name_object(
8753                            &data,
8754                            sel!(listViewportChanged:),
8755                            Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
8756                            Some(&clip),
8757                        );
8758                }
8759                let view = view_of(scroll);
8760                LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
8761                view
8762            }
8763            Some(Builtin::Tree) => {
8764                let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
8765                    return placeholder_view(mtm, kind);
8766                };
8767                // The width-pinning subclass (see DayOutlineView).
8768                let outline: Retained<objc2_app_kit::NSOutlineView> = {
8769                    let o: Retained<DayOutlineView> =
8770                        unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
8771                    unsafe { msg_send![&*o, self] }
8772                };
8773                let col = unsafe {
8774                    NSTableColumn::initWithIdentifier(
8775                        NSTableColumn::alloc(mtm),
8776                        &NSString::from_str("day.tree.col"),
8777                    )
8778                };
8779                let data = DayTreeData::new(mtm, id, p.selectable);
8780                unsafe {
8781                    if p.multi_select {
8782                        outline.setAllowsMultipleSelection(true);
8783                    }
8784                    outline.addTableColumn(&col);
8785                    outline.setOutlineTableColumn(Some(&col));
8786                    outline.setHeaderView(None);
8787                    if p.section_headers {
8788                        // Real source-list groups use AppKit's trailing, hover-revealed
8789                        // show/hide button and float over their children while scrolling.
8790                        outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8791                        outline.setFloatsGroupRows(true);
8792                    } else {
8793                        // Generic trees keep their existing full-width cells and rounded
8794                        // DayTreeRowView selection. Source lists use native row drawing.
8795                        outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
8796                        outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
8797                    }
8798                    outline.setColumnAutoresizingStyle(
8799                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8800                    );
8801                    outline.setAutoresizesOutlineColumn(true);
8802                    if let Some(indent) = p.indent {
8803                        outline.setIndentationPerLevel(indent);
8804                    }
8805                    match p.row_height {
8806                        RowHeight::Uniform(h) => outline.setRowHeight(h),
8807                        RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
8808                        RowHeight::Automatic => {}
8809                    }
8810                    if !p.selectable {
8811                        outline.setSelectionHighlightStyle(
8812                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8813                        );
8814                    }
8815                    outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8816                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8817                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8818                    if p.movable {
8819                        // Native drag-to-move (docs/tree.md): nodes drag within this outline
8820                        // only. The REGULAR feedback style (not the list's Gap): a tree drop
8821                        // must distinguish "between rows" (insertion line) from "ONTO a row"
8822                        // (the highlighted-parent drop), and Gap has no onto affordance.
8823                        outline.registerForDraggedTypes(
8824                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8825                                DAY_TREE_PASTEBOARD_TYPE,
8826                            )]),
8827                        );
8828                        outline.setDraggingSourceOperationMask_forLocal(
8829                            objc2_app_kit::NSDragOperation::Move,
8830                            true,
8831                        );
8832                        outline.setDraggingSourceOperationMask_forLocal(
8833                            objc2_app_kit::NSDragOperation::None,
8834                            false,
8835                        );
8836                    }
8837                }
8838                let scroll = unsafe { NSScrollView::new(mtm) };
8839                unsafe {
8840                    scroll.setDrawsBackground(false);
8841                    scroll.setHasVerticalScroller(true);
8842                    scroll.setHasHorizontalScroller(false);
8843                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8844                    outline.setAutoresizingMask(
8845                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8846                    );
8847                    scroll.setDocumentView(Some(&outline));
8848                }
8849                let view = view_of(scroll);
8850                TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8851                view
8852            }
8853            Some(Builtin::Image) => {
8854                let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
8855                    return placeholder_view(mtm, kind);
8856                };
8857                let iv: Retained<objc2_app_kit::NSImageView> =
8858                    if p.content_mode == ContentMode::Fill {
8859                        let view: Retained<FillImageView> =
8860                            unsafe { msg_send![FillImageView::alloc(mtm), init] };
8861                        Retained::from(
8862                            <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
8863                        )
8864                    } else {
8865                        unsafe { objc2_app_kit::NSImageView::new(mtm) }
8866                    };
8867                // Fill expands the native aspect-fit drawing in FillImageView; Stretch
8868                // scales each axis independently, and Fit keeps the stock image view.
8869                let scaling = match p.content_mode {
8870                    ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
8871                    _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
8872                };
8873                unsafe { iv.setImageScaling(scaling) };
8874                if let Some(img) = appkit_image_for(&p.source) {
8875                    // Vector-glyph tint (docs/vectors.md): template rendering + the view's
8876                    // content tint — AppKit recolors the alpha mask natively. A template with
8877                    // no tint keeps the view's nil tint: the neutral template color the nav
8878                    // menu's own rows draw with, light in dark mode, dark in light.
8879                    if p.tint.is_some() || p.template {
8880                        unsafe { img.setTemplate(true) };
8881                    }
8882                    unsafe { iv.setImage(Some(&img)) };
8883                }
8884                if let Some(t) = p.tint {
8885                    unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
8886                }
8887                IMAGE_MODES.with(|t| {
8888                    t.insert(
8889                        ptr_of(&iv),
8890                        ImageMode {
8891                            template: p.template,
8892                            tinted: p.tint.is_some(),
8893                        },
8894                    )
8895                });
8896                view_of(iv)
8897            }
8898            Some(Builtin::ListItem) => {
8899                let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
8900                else {
8901                    return placeholder_view(mtm, kind);
8902                };
8903                make_list_item(p, mtm)
8904            }
8905            // A recycled list cell is ADOPTED from the native list, never realized
8906            // through this path; anything else is an extension piece.
8907            Some(Builtin::ListCell) | None => {
8908                if let Some(make) = self.registry.get(kind).map(|r| r.make) {
8909                    return make(self, props, id);
8910                }
8911                // Unregistered kind: LOUD once-per-kind warning, then a visible-but-harmless
8912                // placeholder (§8.2's debug check will panic first in debug builds once the
8913                // required-kinds set lands).
8914                warn_missing_renderer(kind);
8915                placeholder_view(mtm, kind)
8916            }
8917        }
8918    }
8919
8920    fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
8921        match kind {
8922            kinds::LIST_ITEM => {
8923                let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
8924                    return;
8925                };
8926                let props = LIST_ITEMS.with(|m| {
8927                    let mut m = m.borrow_mut();
8928                    let props = m.get_mut(&ptr_of(h))?;
8929                    use day_spec::props::ListItemPatch as P;
8930                    match p {
8931                        P::Title(t) => props.title = t.clone(),
8932                        P::Subtitle(t) => props.subtitle = t.clone(),
8933                        P::Detail(t) => props.detail = t.clone(),
8934                        P::Icon(i) => props.icon = i.clone(),
8935                        P::IconTint(c) => props.icon_tint = *c,
8936                        P::Checked(on) => props.checked = *on,
8937                    }
8938                    Some(props.clone())
8939                });
8940                if let Some(props) = props {
8941                    dress_list_item(h, &props, self.mtm());
8942                }
8943            }
8944            kinds::IMAGE => {
8945                if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
8946                    match p {
8947                        day_spec::props::ImagePatch::Tint(c) => {
8948                            // Template rendering + the view's content tint, exactly as at realize
8949                            // — the glyph repaints in place rather than being rebuilt
8950                            // (docs/vectors.md). A template glyph stays one when the tint goes.
8951                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8952                                let key = ptr_of(&iv);
8953                                let template = IMAGE_MODES
8954                                    .with(|t| {
8955                                        t.with(key, |m| {
8956                                            m.tinted = c.is_some();
8957                                            m.renders_template()
8958                                        })
8959                                    })
8960                                    .unwrap_or(c.is_some());
8961                                if let Some(img) = unsafe { iv.image() } {
8962                                    unsafe { img.setTemplate(template) };
8963                                }
8964                                unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
8965                            }
8966                        }
8967                        // A source swap repaints the same view (docs/images.md), so an `image()`
8968                        // bound to a signal shows new pixels without rebuilding its subtree —
8969                        // which is what makes a decode-then-show flow a patch and not a rebuild.
8970                        day_spec::props::ImagePatch::Source(source) => {
8971                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8972                                // A source that will not load leaves the view showing what it
8973                                // was — the patch's contract, and what GTK, Qt and Android do.
8974                                // The new image renders the way the view does: a tinted or
8975                                // template glyph stays one, so a recycled sidebar row shows the
8976                                // icon it was rebound to in the same color.
8977                                if let Some(img) = appkit_image_for(source) {
8978                                    let template = IMAGE_MODES
8979                                        .with(|t| t.get(ptr_of(&iv)))
8980                                        .is_some_and(|m| m.renders_template());
8981                                    unsafe {
8982                                        img.setTemplate(template);
8983                                        iv.setImage(Some(&img));
8984                                    }
8985                                }
8986                            }
8987                        }
8988                    }
8989                }
8990            }
8991            kinds::CONTAINER => {
8992                if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
8993                    patch.downcast_ref::<ContainerPatch>(),
8994                    h.clone().downcast::<DayFlipped>(),
8995                ) {
8996                    // A background patch only targets a background container (corner radius 0).
8997                    // The AnimSpec is not honored: the fill is drawRect content
8998                    // (rasterized by our own drawing code so dynamic system colors re-resolve
8999                    // per appearance), not a CALayer property, and Core Animation only
9000                    // interpolates layer properties, so there is nothing for the render server
9001                    // to tween. Day animates only what the toolkit's animator can execute
9002                    // (§8.4), so an animated background change applies at commit here.
9003                    v.set_surface(*c, 0.0, false);
9004                }
9005            }
9006            kinds::LABEL => {
9007                if let (Some(p), Ok(tf)) = (
9008                    patch.downcast_ref::<LabelPatch>(),
9009                    h.clone().downcast::<NSTextField>(),
9010                ) {
9011                    match p {
9012                        LabelPatch::Text(t) => {
9013                            unsafe { tf.setStringValue(&NSString::from_str(t)) };
9014                            if let Some(label) = h.downcast_ref::<DayLabel>() {
9015                                label.ivars().has_runs.set(false);
9016                                label.set_links(false);
9017                            }
9018                        }
9019                        LabelPatch::Color(c) => unsafe {
9020                            tf.setTextColor(c.map(nscolor).as_deref())
9021                        },
9022                        LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
9023                        LabelPatch::Runs(text, runs) => {
9024                            // The field's current font is the base the runs sit on, taken as the
9025                            // live object rather than rebuilt from a `FontSpec`, which would lose
9026                            // the semantic style behind the resolved size.
9027                            let base = unsafe { tf.font() };
9028                            let s = match base.as_deref() {
9029                                Some(f) => {
9030                                    attributed_label(text, f, None, Default::default(), runs)
9031                                }
9032                                None => attributed_label(
9033                                    text,
9034                                    &nsfont(day_spec::FontSpec::default()),
9035                                    None,
9036                                    Default::default(),
9037                                    runs,
9038                                ),
9039                            };
9040                            unsafe { tf.setAttributedStringValue(&s) };
9041                            // Preserve paragraph alignment and activate links introduced by a
9042                            // reactive markdown update without replacing the native label.
9043                            set_paragraph_alignment(&tf, unsafe { tf.alignment() });
9044                            if let Some(label) = h.downcast_ref::<DayLabel>() {
9045                                label.ivars().has_runs.set(!runs.is_empty());
9046                                label.set_links(runs.iter().any(|r| r.link.is_some()));
9047                            }
9048                        }
9049                    }
9050                }
9051            }
9052            kinds::BUTTON => {
9053                if let (Some(p), Ok(btn)) = (
9054                    patch.downcast_ref::<ButtonPatch>(),
9055                    h.clone().downcast::<NSButton>(),
9056                ) {
9057                    match p {
9058                        ButtonPatch::Content(c) => {
9059                            apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
9060                        }
9061                        ButtonPatch::Title(t) => {
9062                            let style = BUTTON_STYLES
9063                                .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
9064                                .unwrap_or_default();
9065                            set_button_title(&btn, t, style);
9066                        }
9067                        ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
9068                        ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
9069                        ButtonPatch::Style(s) => apply_button_style(&btn, *s),
9070                    }
9071                }
9072            }
9073            kinds::TOGGLE => {
9074                if let (Some(p), Ok(sw)) = (
9075                    patch.downcast_ref::<TogglePatch>(),
9076                    h.clone().downcast::<NSSwitch>(),
9077                ) {
9078                    match p {
9079                        TogglePatch::On(on) => {
9080                            let want = if *on { 1 } else { 0 };
9081                            if unsafe { sw.state() } != want {
9082                                unsafe { sw.setState(want) };
9083                            }
9084                        }
9085                        TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
9086                    }
9087                }
9088            }
9089            kinds::SLIDER => {
9090                if let (Some(p), Ok(sl)) = (
9091                    patch.downcast_ref::<SliderPatch>(),
9092                    h.clone().downcast::<NSSlider>(),
9093                ) {
9094                    match p {
9095                        SliderPatch::Value(v) => {
9096                            if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
9097                                unsafe { sl.setDoubleValue(*v) };
9098                            }
9099                        }
9100                        SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
9101                    }
9102                }
9103            }
9104            kinds::PROGRESS => {
9105                if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
9106                {
9107                    crate::controls::spinner::update(self, h, p);
9108                    return;
9109                }
9110
9111                if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
9112                    patch.downcast_ref::<ProgressPatch>(),
9113                    h.clone().downcast::<NSProgressIndicator>(),
9114                ) {
9115                    unsafe {
9116                        match v {
9117                            Some(val) => {
9118                                if pi.isIndeterminate() {
9119                                    pi.stopAnimation(None);
9120                                    pi.setIndeterminate(false);
9121                                    pi.setStyle(NSProgressIndicatorStyle::Bar);
9122                                    pi.setMinValue(0.0);
9123                                    pi.setMaxValue(1.0);
9124                                }
9125                                if (pi.doubleValue() - val).abs() > 0.0001 {
9126                                    pi.setDoubleValue(*val);
9127                                }
9128                            }
9129                            None => {
9130                                pi.setIndeterminate(true);
9131                                pi.setStyle(NSProgressIndicatorStyle::Spinning);
9132                                pi.startAnimation(None);
9133                            }
9134                        }
9135                    }
9136                }
9137            }
9138            kinds::NAV_MENU => {
9139                if let Some(NavMenuPatch::Items {
9140                    items,
9141                    icons,
9142                    badges,
9143                    badge_icons,
9144                    badge_tints,
9145                    sections,
9146                    tints,
9147                    menus,
9148                    movable,
9149                    sorted,
9150                    selected,
9151                    rows_changed,
9152                    ..
9153                }) = patch.downcast_ref::<NavMenuPatch>()
9154                {
9155                    NAV_MENUS.with(|m| {
9156                        let m = m.borrow();
9157                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
9158                            return;
9159                        };
9160                        *data.ivars().movable.borrow_mut() = movable.clone();
9161                        *data.ivars().sorted.borrow_mut() = sorted.clone();
9162                        data.set_items(
9163                            items,
9164                            icons,
9165                            badges,
9166                            badge_icons,
9167                            badge_tints,
9168                            sections,
9169                            tints,
9170                            menus,
9171                        );
9172                        data.ivars().suppress.set(true);
9173                        // The same rows with new words or counts: reload just those rows, which
9174                        // keeps the selection and every other row's view.
9175                        if let Some(rows) = rows_changed {
9176                            let set = objc2_foundation::NSMutableIndexSet::new();
9177                            for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
9178                                unsafe { set.addIndex(row) };
9179                            }
9180                            unsafe {
9181                                outline.reloadDataForRowIndexes_columnIndexes(
9182                                    &set,
9183                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
9184                                )
9185                            };
9186                            data.ivars().suppress.set(false);
9187                            return;
9188                        }
9189                        unsafe {
9190                            outline.reloadData();
9191                            match selected.and_then(|i| data.row_of_item(i)) {
9192                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
9193                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9194                                    false,
9195                                ),
9196                                None => outline.deselectAll(None),
9197                            }
9198                        }
9199                        data.ivars().suppress.set(false);
9200                    });
9201                    // The rows are a tabs host's labels where the menu sits in one.
9202                    adopt_menu_for_tabs(self.mtm(), h);
9203                } else if let Some(NavMenuPatch::IconProgress(progress)) =
9204                    patch.downcast_ref::<NavMenuPatch>()
9205                {
9206                    NAV_MENUS.with(|menus| {
9207                        let menus = menus.borrow();
9208                        let Some((outline, data)) = menus.get(&ptr_of(h)) else {
9209                            return;
9210                        };
9211                        let previous = data.ivars().icon_progress.replace(progress.clone());
9212                        for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
9213                            let Some(index) = item else {
9214                                continue;
9215                            };
9216                            let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
9217                            if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
9218                                continue;
9219                            }
9220                            if let Some(view) = unsafe {
9221                                outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
9222                            } && let Some(cell) =
9223                                view.downcast_ref::<objc2_app_kit::NSTableCellView>()
9224                                && let Some(icon) = unsafe { cell.imageView() }
9225                            {
9226                                nav_progress::update(&icon, value);
9227                            }
9228                        }
9229                    });
9230                } else if let Some(NavMenuPatch::Selected(sel)) =
9231                    patch.downcast_ref::<NavMenuPatch>()
9232                {
9233                    NAV_MENUS.with(|m| {
9234                        let m = m.borrow();
9235                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
9236                            return;
9237                        };
9238                        data.ivars().suppress.set(true);
9239                        unsafe {
9240                            match sel.and_then(|i| data.row_of_item(i)) {
9241                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
9242                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9243                                    false,
9244                                ),
9245                                None => outline.deselectAll(None),
9246                            }
9247                        }
9248                        data.ivars().suppress.set(false);
9249                    });
9250                }
9251            }
9252            kinds::INSPECTOR => {
9253                if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
9254                    INSPECTOR_STATE.with(|m| {
9255                        if let Some(state) = m.borrow().get(&ptr_of(h)) {
9256                            // Directly, not through the animator proxy: a screenshot must not
9257                            // catch a mid-animation pane (the sidebar-toggle rule).
9258                            state.panel_item.setCollapsed(!*v);
9259                        }
9260                    });
9261                }
9262            }
9263            kinds::SPLIT => {
9264                if let Some(p) = patch.downcast_ref::<SplitPatch>() {
9265                    SPLIT_STATE.with(|m| {
9266                        let m = m.borrow();
9267                        let Some(state) = m.get(&ptr_of(h)) else {
9268                            return;
9269                        };
9270                        let iv = state.delegate.ivars();
9271                        match p {
9272                            SplitPatch::Fraction(f) => {
9273                                iv.share.set(f.clamp(0.0, 1.0));
9274                                if iv.positioned.get() {
9275                                    split_place(&state.split, iv);
9276                                }
9277                            }
9278                            SplitPatch::Axis(axis) => unsafe {
9279                                state
9280                                    .split
9281                                    .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
9282                                state.split.adjustSubviews();
9283                                if iv.positioned.get() {
9284                                    split_place(&state.split, iv);
9285                                }
9286                            },
9287                        }
9288                    });
9289                }
9290            }
9291            kinds::NAV => {
9292                if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
9293                    nav_present(self.mtm(), h, *next);
9294                    return;
9295                }
9296                if let Some(p) = patch.downcast_ref::<NavPatch>() {
9297                    NAV_STATE.with(|m| {
9298                        let mut m = m.borrow_mut();
9299                        let Some(state) = m.get_mut(&ptr_of(h)) else {
9300                            return;
9301                        };
9302                        match p {
9303                            NavPatch::Pushed { title, .. } => {
9304                                // Only the new top detail page stays visible.
9305                                let last = state.pages.len().saturating_sub(1);
9306                                state.selected = last;
9307                                for (i, page) in state.pages.iter().enumerate() {
9308                                    page.setHidden(i != last);
9309                                }
9310                                if let Some(hdr) = state.header.as_mut() {
9311                                    hdr.titles.push(title.clone());
9312                                    sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9313                                }
9314                            }
9315                            NavPatch::Popped => {
9316                                // Hide the outgoing top; reveal its predecessor (Day
9317                                // removes the popped page right after this patch).
9318                                let n = state.pages.len();
9319                                if let Some(top) = state.pages.last() {
9320                                    top.setHidden(true);
9321                                }
9322                                if n >= 2 {
9323                                    state.pages[n - 2].setHidden(false);
9324                                }
9325                                state.selected = n.saturating_sub(2);
9326                                if let Some(hdr) = state.header.as_mut() {
9327                                    if hdr.titles.len() > 1 {
9328                                        hdr.titles.pop();
9329                                    }
9330                                    // The popped page is still in `pages` here (Day removes
9331                                    // it right after this patch), so frame for depth-after-pop.
9332                                    let after: Vec<Retained<NSView>> = state
9333                                        .pages
9334                                        .iter()
9335                                        .take(n.saturating_sub(1))
9336                                        .cloned()
9337                                        .collect();
9338                                    sync_nav_header(hdr, &state.detail_wrap, &after);
9339                                }
9340                            }
9341                            NavPatch::Title(t) => {
9342                                if let Some(hdr) = state.header.as_mut() {
9343                                    if let Some(last) = hdr.titles.last_mut() {
9344                                        *last = t.clone();
9345                                    }
9346                                    unsafe {
9347                                        hdr.title.setStringValue(&NSString::from_str(t));
9348                                    }
9349                                }
9350                            }
9351                            // The custom back header always routes back through Day
9352                            // (NavBack{already_popped:false}), so there is no native auto-pop to
9353                            // suppress; the guard runs in the pieces layer (docs/navigation.md).
9354                            NavPatch::GuardTop(_) => {}
9355                            NavPatch::Reorder(order) => {
9356                                let old = state.pages.clone();
9357                                state.pages =
9358                                    order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9359                                if let Some(tabs) = &state.tabs {
9360                                    TAB_PICK_SUPPRESS.with(|s| s.set(true));
9361                                    unsafe {
9362                                        let items = tabs.view.tabViewItems();
9363                                        for item in items.iter() {
9364                                            tabs.view.removeTabViewItem(&item);
9365                                        }
9366                                        for i in order {
9367                                            if let Some(item) = items.iter().nth(*i) {
9368                                                tabs.view.addTabViewItem(&item);
9369                                            }
9370                                        }
9371                                    }
9372                                    TAB_PICK_SUPPRESS.with(|s| s.set(false));
9373                                }
9374                            }
9375                            // Handled outside this borrow (it re-homes views and builds chrome).
9376                            NavPatch::Presentation(_) => {}
9377                            // Resident-page switch (docs/navigation.md): every page stays in the
9378                            // view hierarchy and only one is unhidden, so switching tabs keeps
9379                            // each page's scroll position and first responder exactly as left.
9380                            NavPatch::Select(i) => {
9381                                state.selected = *i;
9382                                match state.tabs.as_ref() {
9383                                    // The tab view shows exactly its selected item's page.
9384                                    Some(tabs) => {
9385                                        let n = unsafe { tabs.view.numberOfTabViewItems() };
9386                                        if (*i as isize) < n {
9387                                            TAB_PICK_SUPPRESS.with(|s| s.set(true));
9388                                            unsafe {
9389                                                tabs.view.selectTabViewItemAtIndex(*i as isize)
9390                                            };
9391                                            TAB_PICK_SUPPRESS.with(|s| s.set(false));
9392                                        }
9393                                    }
9394                                    None => {
9395                                        for (n, page) in state.pages.iter().enumerate() {
9396                                            page.setHidden(n != *i);
9397                                        }
9398                                    }
9399                                }
9400                            }
9401                            // Per-destination pane visibility (docs/navigation.md). Directly,
9402                            // not through the animator proxy: a screenshot must not catch a
9403                            // mid-animation pane (the sidebar-toggle rule), and settled now,
9404                            // like a re-present, so the detail's frame is right the instant
9405                            // the patch returns rather than one layout pass later.
9406                            NavPatch::ListVisible(v) => {
9407                                state.list_visible = *v;
9408                                if let Some(item) = state.list_item.as_ref() {
9409                                    item.setCollapsed(!*v);
9410                                    let split = unsafe { state._split_vc.splitView() };
9411                                    unsafe { split.layoutSubtreeIfNeeded() };
9412                                    // First time this pane is actually on screen: give it the
9413                                    // width the app asked for. The frame pass that would
9414                                    // otherwise do it has already run, back when there was no
9415                                    // pane to size.
9416                                    if let Some(w) = take_list_placement(state) {
9417                                        unsafe {
9418                                            split.setPosition_ofDividerAtIndex(
9419                                                day_spec::NAV_SIDEBAR_WIDTH + w,
9420                                                1,
9421                                            );
9422                                        }
9423                                    }
9424                                    // Re-frame the pane's page to the wrap it fills. A page
9425                                    // inserted while the pane was collapsed got a zero-width
9426                                    // frame, and `ViewWidthSizable` scales zero to zero however
9427                                    // wide the wrap becomes, so the list stayed invisible while
9428                                    // its rows were still there to click. An app opening on a
9429                                    // full-page section hits this on the first reveal.
9430                                    if *v
9431                                        && let Some(wrap) = state.list_wrap.as_ref()
9432                                        && let Some(page) = state.list_page.as_ref()
9433                                    {
9434                                        unsafe {
9435                                            wrap.layoutSubtreeIfNeeded();
9436                                            page.setFrame(wrap.bounds());
9437                                        }
9438                                    }
9439                                }
9440                            }
9441                            // Never arrives here: the pane persists through every presentation
9442                            // (`Cap::NavContentList` = Native), so the pieces layer never asks
9443                            // for the merged-stack shape.
9444                            NavPatch::ListInStack(_) => {}
9445                        }
9446                    });
9447                }
9448            }
9449            // Emulated cover (docs/cover.md): present = re-home onto the window's content view
9450            // at full bounds, topmost, autoresized with the window (the DayNavPage handle
9451            // reports FrameChanged on every resize). Dismiss = hide + report `CoverHidden`
9452            // immediately (no transition on this tier). Interactive dismissal doesn't exist on
9453            // this backend, so DismissDisabled has nothing to disable.
9454            kinds::COVER => {
9455                if let (Some(p), Ok(page)) = (
9456                    patch.downcast_ref::<CoverPatch>(),
9457                    h.clone().downcast::<DayNavPage>(),
9458                ) {
9459                    let node = page.ivars().node;
9460                    match p {
9461                        CoverPatch::Present { background, .. } => {
9462                            if page.ivars().sheet.get() {
9463                                if let Some(parent) =
9464                                    primary_content().and_then(|v| unsafe { v.window() })
9465                                {
9466                                    let bounds = parent.frame().size;
9467                                    let max = if page.ivars().large.get() {
9468                                        day_spec::props::LARGE_SHEET_MAX
9469                                    } else {
9470                                        day_spec::props::SHEET_MAX
9471                                    };
9472                                    let height = if page.ivars().half.get() {
9473                                        (bounds.height * 0.5).clamp(160.0, max.height)
9474                                    } else {
9475                                        (bounds.height - 80.0).clamp(300.0, max.height)
9476                                    };
9477                                    let size = NSSize::new(
9478                                        (bounds.width - 40.0).clamp(320.0, max.width),
9479                                        height,
9480                                    );
9481                                    let window = unsafe {
9482                                        NSWindow::initWithContentRect_styleMask_backing_defer(
9483                                            NSWindow::alloc(MainThreadMarker::new().unwrap()),
9484                                            NSRect::new(NSPoint::new(0.0, 0.0), size),
9485                                            NSWindowStyleMask::Titled,
9486                                            NSBackingStoreType::Buffered,
9487                                            false,
9488                                        )
9489                                    };
9490                                    unsafe {
9491                                        window.setReleasedWhenClosed(false);
9492                                        page.removeFromSuperview();
9493                                        page.setHidden(false);
9494                                        page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
9495                                        window.setContentView(Some(&page));
9496                                    }
9497                                    let key = ptr_of(h);
9498                                    SHEET_NODES.with(|t| {
9499                                        t.insert(Retained::as_ptr(&window) as usize, node)
9500                                    });
9501                                    install_sheet_escape_monitor();
9502                                    COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
9503                                    dispatch2::DispatchQueue::main().exec_async(move || {
9504                                        ffi_guard::contain((), || {
9505                                            let window =
9506                                                COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
9507                                            if let (Some(window), Some(parent)) = (
9508                                                window,
9509                                                primary_content()
9510                                                    .and_then(|v| unsafe { v.window() }),
9511                                            ) {
9512                                                unsafe {
9513                                                    parent.beginSheet_completionHandler(
9514                                                        &window, None,
9515                                                    );
9516                                                }
9517                                            }
9518                                        });
9519                                    });
9520                                    emit(
9521                                        node,
9522                                        Event::FrameChanged(Size::new(size.width, size.height)),
9523                                    );
9524                                }
9525                                return;
9526                            }
9527                            // A cover must occlude the window (the native tiers' modal surfaces
9528                            // are opaque): default to the window background when the app sets
9529                            // no explicit color.
9530                            unsafe {
9531                                page.setWantsLayer(true);
9532                                if let Some(layer) = page.layer() {
9533                                    let color = match background {
9534                                        Some(bg) => nscolor(*bg),
9535                                        None => NSColor::windowBackgroundColor(),
9536                                    };
9537                                    layer.setBackgroundColor(Some(&color.CGColor()));
9538                                }
9539                            }
9540                            // The primary window's content, specifically: firstObject()
9541                            // is arbitrary once secondary windows exist (docs/windows.md).
9542                            if let Some(content) = primary_content() {
9543                                if let Some(window) = unsafe { content.window() } {
9544                                    toolbar::cover_presented(ptr_of(h), &window);
9545                                }
9546                                // Edge to edge like the root's own background, laid out below
9547                                // the title bar like the root's content: the page starts at the
9548                                // top of the window (above the pinned content origin) and
9549                                // keeps the same strip above its own layout origin.
9550                                let top = title_bar_inset(&content);
9551                                let full = content.frame().size;
9552                                page.ivars().top_inset.set(top);
9553                                unsafe {
9554                                    page.removeFromSuperview();
9555                                    content.addSubview(&page);
9556                                    page.setFrame(NSRect::new(
9557                                        NSPoint::new(0.0, -top),
9558                                        NSSize::new(full.width, full.height),
9559                                    ));
9560                                    page.setBoundsOrigin(NSPoint::new(0.0, -top));
9561                                    page.setAutoresizingMask(
9562                                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9563                                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9564                                    );
9565                                    page.setHidden(false);
9566                                }
9567                                emit(
9568                                    node,
9569                                    Event::FrameChanged(Size::new(
9570                                        full.width,
9571                                        (full.height - top).max(0.0),
9572                                    )),
9573                                );
9574                            }
9575                        }
9576                        CoverPatch::DismissDisabled(_) => {}
9577                        CoverPatch::Dismiss => {
9578                            COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
9579                            toolbar::cover_dismissed(ptr_of(h));
9580                            unsafe {
9581                                page.setHidden(true);
9582                                page.removeFromSuperview();
9583                            }
9584                            emit(node, Event::CoverHidden);
9585                        }
9586                    }
9587                }
9588            }
9589            kinds::PICKER => picker::update_any(self, h, patch),
9590            kinds::TEXT_AREA => textarea::update_any(self, h, patch),
9591            kinds::TEXT_FIELD => {
9592                if let (Some(p), Ok(tf)) = (
9593                    patch.downcast_ref::<TextFieldPatch>(),
9594                    h.clone().downcast::<NSTextField>(),
9595                ) {
9596                    match p {
9597                        TextFieldPatch::Text { text, from_native } => {
9598                            // Origin-tagged echo suppression (§4.4).
9599                            if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
9600                                unsafe { tf.setStringValue(&NSString::from_str(text)) };
9601                            }
9602                        }
9603                        TextFieldPatch::Placeholder(t) => unsafe {
9604                            tf.setPlaceholderString(Some(&NSString::from_str(t)))
9605                        },
9606                        TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
9607                    }
9608                }
9609            }
9610            kinds::LIST => match patch.downcast_ref::<ListPatch>() {
9611                Some(ListPatch::Splice(deltas)) => {
9612                    // The set changed by exactly these deltas: animate each row in, out, or
9613                    // across, the thing a reload cannot express. Indexes are sequential, so
9614                    // each delta gets its own begin/endUpdates batch (NSTableView's combined
9615                    // batch semantics re-interpret indexes; one-at-a-time stays literal).
9616                    // Row realization stays deferred, as with Reload.
9617                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9618                        use objc2_app_kit::NSTableViewAnimationOptions;
9619                        for d in deltas {
9620                            unsafe {
9621                                table.beginUpdates();
9622                                match d {
9623                                    day_spec::props::RowDelta::Insert(i) => table
9624                                        .insertRowsAtIndexes_withAnimation(
9625                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9626                                            NSTableViewAnimationOptions::SlideDown,
9627                                        ),
9628                                    day_spec::props::RowDelta::Remove(i) => table
9629                                        .removeRowsAtIndexes_withAnimation(
9630                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9631                                            NSTableViewAnimationOptions::SlideUp,
9632                                        ),
9633                                    day_spec::props::RowDelta::Move(from, to) => {
9634                                        table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
9635                                    }
9636                                }
9637                                table.endUpdates();
9638                            }
9639                        }
9640                        // The displayed order matches the source again: refresh the cache a
9641                        // committed drag keeps in step and `permutation_moves` compares, or the
9642                        // next Reload finds a stale length and reloads flat instead of animating.
9643                        if let Some(source) = data.ivars().source.borrow().as_ref() {
9644                            let n = (source.len)();
9645                            *data.ivars().tokens.borrow_mut() =
9646                                (0..n).map(|i| (source.token_at)(i)).collect();
9647                        }
9648                    }
9649                    post_realize_visible_rows(ptr_of(h));
9650                }
9651                Some(ListPatch::Reload) => {
9652                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9653                        // NSTableView reloadData clears selection for this view-based source.
9654                        // Preserve identities, not indexes, across refreshes/reorders; removed
9655                        // items disappear from the selection without selecting their successor.
9656                        let selected = unsafe { table.selectedRowIndexes() };
9657                        let tokens: Vec<u64> = data
9658                            .ivars()
9659                            .tokens
9660                            .borrow()
9661                            .iter()
9662                            .enumerate()
9663                            .filter(|(row, _)| selected.containsIndex(*row))
9664                            .map(|(_, token)| *token)
9665                            .collect();
9666                        data.ivars().suppress.set(true);
9667                        // A reload whose rows are the same set in a new order (a shuffle,
9668                        // a programmatic sort) animates as native row moves instead of a
9669                        // blink: a `moveRowAtIndex` batch, the same animation a drag commit
9670                        // gets. Anything else (insert/remove/content change) reloads flat.
9671                        // reloadData queries numberOfRows synchronously (snapshot only, no
9672                        // tree) and defers viewForRow, so both paths are safe in with_tree.
9673                        if let Some(moves) = data.permutation_moves(&table) {
9674                            unsafe {
9675                                table.beginUpdates();
9676                                for (from, to) in moves {
9677                                    table.moveRowAtIndex_toIndex(from as isize, to as isize);
9678                                }
9679                                table.endUpdates();
9680                            }
9681                        } else {
9682                            unsafe { table.reloadData() };
9683                        }
9684                        let restored = objc2_foundation::NSMutableIndexSet::new();
9685                        for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
9686                            if tokens.contains(token) {
9687                                restored.addIndex(row);
9688                            }
9689                        }
9690                        unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
9691                        data.ivars().suppress.set(false);
9692                    }
9693                    // Realize the visible rows on the next main-loop turn, outside this borrow.
9694                    // An occluded window (locked screen, covered, headless CI) gets no normal
9695                    // draw pass; NSTableView would first realize these rows inside a snapshot's
9696                    // `cacheDisplayInRect`, where `bind_row` must skip the held borrow and the
9697                    // table would cache permanently blank cells.
9698                    post_realize_visible_rows(ptr_of(h));
9699                }
9700                Some(ListPatch::ScrollToRow(row)) => {
9701                    // Same deferral discipline as ScrollToEnd: the scroll tiles target rows
9702                    // synchronously, which must happen outside this `with_tree` borrow.
9703                    let (key, row) = (ptr_of(h), *row);
9704                    <AppKit as Platform>::post(Box::new(move || {
9705                        if let Some((table, _)) = list_entry(key) {
9706                            let rows = unsafe { table.numberOfRows() };
9707                            if rows > 0 {
9708                                unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
9709                            }
9710                        }
9711                    }));
9712                    post_realize_visible_rows(ptr_of(h));
9713                }
9714                Some(ListPatch::ScrollToEnd) => {
9715                    // Deferred to the next main-loop turn: an actual scroll forces NSTableView
9716                    // to tile (realize) the target rows synchronously, and this patch arrives
9717                    // inside a `with_tree` borrow where `bind_row` must skip; the table would
9718                    // cache blank cells for every newly exposed row (see Reload above).
9719                    let key = ptr_of(h);
9720                    <AppKit as Platform>::post(Box::new(move || {
9721                        if let Some((table, _)) = list_entry(key) {
9722                            let rows = unsafe { table.numberOfRows() };
9723                            if rows > 0 {
9724                                unsafe { table.scrollRowToVisible(rows - 1) };
9725                            }
9726                        }
9727                    }));
9728                    // ...and realize whatever the scroll exposed, still outside the borrow.
9729                    post_realize_visible_rows(ptr_of(h));
9730                }
9731                Some(ListPatch::Selected(rows)) => {
9732                    // Programmatic selection sync (empty = clear), suppressed so the
9733                    // delegate does not echo it back as a selection event.
9734                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9735                        data.ivars().suppress.set(true);
9736                        unsafe {
9737                            if rows.is_empty() {
9738                                table.deselectAll(None);
9739                            } else {
9740                                let set = objc2_foundation::NSMutableIndexSet::new();
9741                                let count = table.numberOfRows().max(0) as usize;
9742                                for r in rows.iter().copied().filter(|r| *r < count) {
9743                                    set.addIndex(r);
9744                                }
9745                                table.selectRowIndexes_byExtendingSelection(&set, false);
9746                            }
9747                        }
9748                        data.ivars().suppress.set(false);
9749                    }
9750                }
9751                Some(ListPatch::RowSizeInvalidated { cell, height }) => {
9752                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9753                        data.row_resized(&table, *cell, *height);
9754                    }
9755                }
9756                // `None` = a patch for another kind's enum. A desktop table has no editing mode
9757                // (Cap::ListEditing is Unsupported).
9758                Some(ListPatch::Editing(_)) | None => {}
9759            },
9760            kinds::TREE => match patch.downcast_ref::<TreePatch>() {
9761                Some(TreePatch::Reload) => {
9762                    // Interned items keep their identity across reloadData, so NSOutlineView
9763                    // itself preserves expansion; the piece re-asserts it (and the selection)
9764                    // by token right after, belt and braces. reloadData queries the child
9765                    // counts synchronously (snapshot only, no tree) and defers viewForItem.
9766                    if let Some((outline, _)) = tree_entry(ptr_of(h)) {
9767                        unsafe { outline.reloadData() };
9768                    }
9769                    post_realize_visible_tree_rows(ptr_of(h));
9770                }
9771                Some(TreePatch::Expand(token, on)) => {
9772                    // Deferred: expandItem/collapseItem realize (or remove) the disclosed
9773                    // rows synchronously, and this patch arrives inside a `with_tree` borrow
9774                    // where `bind_row` must skip; the outline would cache permanently blank,
9775                    // id-less rows (the ScrollToEnd rule, one arm over).
9776                    let (key, token, on) = (ptr_of(h), *token, *on);
9777                    <AppKit as Platform>::post(Box::new(move || {
9778                        if let Some((outline, data)) = tree_entry(key) {
9779                            let item = data.intern(token);
9780                            // Suppressed: a programmatic disclosure must not echo back as
9781                            // `Event::TreeExpanded`. Redundant applications are AppKit no-ops.
9782                            data.ivars().suppress.set(true);
9783                            unsafe {
9784                                if on {
9785                                    outline.expandItem(Some(&item));
9786                                } else {
9787                                    outline.collapseItem(Some(&item));
9788                                }
9789                            }
9790                            data.ivars().suppress.set(false);
9791                        }
9792                        day_core::pump_events();
9793                    }));
9794                    post_realize_visible_tree_rows(ptr_of(h));
9795                }
9796                Some(TreePatch::Selected(tokens)) => {
9797                    if let Some((outline, data)) = tree_entry(ptr_of(h)) {
9798                        data.ivars().suppress.set(true);
9799                        unsafe {
9800                            if tokens.is_empty() {
9801                                outline.deselectAll(None);
9802                            } else {
9803                                let set = objc2_foundation::NSMutableIndexSet::new();
9804                                for t in tokens {
9805                                    // A token under a collapsed ancestor has no row, so it is
9806                                    // skipped; the piece re-applies after expansion changes.
9807                                    let row = outline.rowForItem(Some(&data.intern(*t)));
9808                                    if row >= 0 {
9809                                        set.addIndex(row as usize);
9810                                    }
9811                                }
9812                                outline.selectRowIndexes_byExtendingSelection(&set, false);
9813                            }
9814                        }
9815                        data.ivars().suppress.set(false);
9816                    }
9817                }
9818                Some(TreePatch::Reveal(token)) => {
9819                    // Deferred: the scroll tiles target rows synchronously, which must
9820                    // happen outside this `with_tree` borrow (the ScrollToRow rule).
9821                    let (key, token) = (ptr_of(h), *token);
9822                    <AppKit as Platform>::post(Box::new(move || {
9823                        if let Some((outline, data)) = tree_entry(key) {
9824                            let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
9825                            if row >= 0 {
9826                                unsafe { outline.scrollRowToVisible(row) };
9827                            }
9828                        }
9829                    }));
9830                    post_realize_visible_tree_rows(ptr_of(h));
9831                }
9832                None => {}
9833            },
9834            _ => {
9835                if let Some(update) = self.registry.get(kind).map(|r| r.update) {
9836                    update(self, h, patch);
9837                }
9838            }
9839        }
9840    }
9841
9842    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
9843    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
9844        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
9845        // the hook needs it mutably.
9846        let f = self.registry.get(kind).and_then(|r| r.release);
9847        if let Some(f) = f {
9848            f(self, h);
9849        }
9850    }
9851    fn release(&mut self, h: Handle) {
9852        LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
9853        // A released window content = that window is gone (docs/windows.md teardown):
9854        // drop the SecondaryWin (closing a straggler NSWindow) and its delegate with it.
9855        // (A re-fired windowWillClose emits to a torn-down node: dropped, harmless.)
9856        self.secondary.retain(|w| {
9857            if ptr_of(&w.content) == ptr_of(&h) {
9858                w.window.close();
9859                // The window's keyed state goes with it: its toolbar (toolbar.rs BARS,
9860                // keyed by the window pointer) used to survive a secondary close, and its
9861                // items, targets, retained NSToolbar and delegate all leaked.
9862                day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
9863                false
9864            } else {
9865                true
9866            }
9867        });
9868        TARGETS.with(|m| {
9869            m.borrow_mut().remove(&ptr_of(&h));
9870        });
9871        LIST_STATE.with(|m| {
9872            m.borrow_mut().remove(&ptr_of(&h));
9873        });
9874        TREE_STATE.with(|m| {
9875            m.borrow_mut().remove(&ptr_of(&h));
9876        });
9877        GESTURES.with(|m| {
9878            m.borrow_mut().remove(&ptr_of(&h));
9879        });
9880        NAV_STATE.with(|m| {
9881            if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
9882                // Unhook the split view controller from the responder chain before the drop
9883                // deallocs it. AppKit rewires these pointers behind day's back (mounting the
9884                // split resets its next to the superview; the controller's own view keeps
9885                // aiming at the controller), and a controller whose next responder is its own
9886                // view dies in dealloc's chain splice with the "next responder should never
9887                // be yourself" NSException, foreign to Rust, so it aborts the process
9888                // instead of unwinding (the Stack-page teardown crash, 2026-08).
9889                unsafe {
9890                    nav._split_vc.setNextResponder(None);
9891                    let split = nav._split_vc.splitView();
9892                    if split.nextResponder().is_some_and(|r| {
9893                        core::ptr::eq::<objc2::runtime::AnyObject>(
9894                            r.as_ref(),
9895                            nav._split_vc.as_ref(),
9896                        )
9897                    }) {
9898                        split.setNextResponder(None);
9899                    }
9900                }
9901            }
9902        });
9903        NAV_PAGES.with(|set| {
9904            set.borrow_mut().remove(&ptr_of(&h));
9905        });
9906        SPLIT_STATE.with(|m| {
9907            if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
9908                state.split.setDelegate(None);
9909            }
9910        });
9911        INSPECTOR_STATE.with(|m| {
9912            if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
9913                // The same dealloc-splice guard as the nav host above: never let the
9914                // controller (or its split) dealloc aiming at itself.
9915                unsafe {
9916                    insp._split_vc.setNextResponder(None);
9917                    let split = insp._split_vc.splitView();
9918                    if split.nextResponder().is_some_and(|r| {
9919                        core::ptr::eq::<objc2::runtime::AnyObject>(
9920                            r.as_ref(),
9921                            insp._split_vc.as_ref(),
9922                        )
9923                    }) {
9924                        split.setNextResponder(None);
9925                    }
9926                }
9927            }
9928        });
9929        NAV_MENUS.with(|m| {
9930            if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
9931                // The outline registers under its pointer (`menuForEvent:` resolves by
9932                // outline, not by this scroll handle): sweep that auxiliary key too, so
9933                // NAV_OUTLINE_MENUS, and any future outline-keyed table, drops it. A
9934                // surviving entry served the dead menu's rows once the address was recycled.
9935                day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
9936            }
9937        });
9938        // One call reclaims this handle's entry from every SideTable on this thread (canvas
9939        // OPS, PAGE_PANE, the picker/textarea state, and whatever lands later), running each
9940        // table's teardown hook (day-spec sidetable). The explicit removals above are the
9941        // older per-map checklist; new per-view maps should be SideTables so this sweep covers
9942        // them without another line here.
9943        day_spec::sidetable::sweep(ptr_of(&h));
9944        unsafe { h.removeFromSuperview() };
9945    }
9946
9947    fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
9948        // A nav menu that has just gained ancestors: if one of them is a tabs host, its rows
9949        // Are that host's tab labels (`adopt_menu_for_tabs`). The menu is built after its rows
9950        // page joined the host, so this is the first moment the host can see its rows.
9951        if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
9952            unsafe { content_of(parent).addSubview(child) };
9953            adopt_menu_for_tabs(self.mtm(), child);
9954            return;
9955        }
9956        // Nav host: pages land by their pane, not their position (docs/size-classes.md). Pages
9957        // fill their pane via autoresizing; the pane, not Day, owns their frames.
9958        let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
9959        let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
9960        let handled = NAV_STATE.with(|m| {
9961            let mut m = m.borrow_mut();
9962            let Some(state) = m.get_mut(&ptr_of(parent)) else {
9963                return false;
9964            };
9965            // The content-list page fills its pane at every presentation
9966            // (docs/navigation.md), never a member of the detail stack.
9967            if page_pane == Some(day_spec::props::Pane::List)
9968                && let Some(wrap) = state.list_wrap.as_ref()
9969            {
9970                state.list_page = Some(child.clone());
9971                unsafe {
9972                    child.setFrame(wrap.bounds());
9973                    child.setAutoresizingMask(
9974                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9975                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9976                    );
9977                    wrap.addSubview(child);
9978                }
9979                return true;
9980            }
9981            if is_sidebar_page {
9982                state.sidebar_page = Some(child.clone());
9983            }
9984            // Split (nav host Sidebar): the sidebar pane's page goes in the sidebar; the rest are
9985            // detail pages. Stack: every page, including the sidebar's, which is the stack's
9986            // root, lives in the detail pane so push/pop visibility covers them all.
9987            // The rows page goes to the sidebar pane in every presentation but `Stack`, where
9988            // it is the stack root and joins the detail pages instead.
9989            let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
9990            // A tabs host's detail page becomes an item of its tab view, which frames it (the
9991            // page's `setFrameSize:` reports the size to Day). Its label comes with the
9992            // menu's rows: already here when a page joins a live host, otherwise when the
9993            // menu is inserted (`adopt_menu_for_tabs`).
9994            if !to_pane && let Some(tabs) = state.tabs.as_ref() {
9995                state.pages.push(child.clone());
9996                let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
9997                unsafe {
9998                    child.setAutoresizingMask(
9999                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10000                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10001                    );
10002                    item.setView(Some(child));
10003                    tabs.view.addTabViewItem(&item);
10004                }
10005                if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
10006                    sync_tab_labels(tabs, &titles, state.selected);
10007                }
10008                return true;
10009            }
10010            let (wrap, frame) = if to_pane {
10011                (&state.sidebar_wrap, state.sidebar_wrap.bounds())
10012            } else {
10013                state.pages.push(child.clone());
10014                let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
10015                (
10016                    &state.detail_wrap,
10017                    nav_page_frame(&state.detail_wrap, visible),
10018                )
10019            };
10020            unsafe {
10021                child.setFrame(frame);
10022                child.setAutoresizingMask(
10023                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10024                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10025                );
10026                wrap.addSubview(child);
10027            }
10028            true
10029        });
10030        if handled {
10031            return;
10032        }
10033        // Split host (docs/split.md): each pane fills its wrap, an arranged subview the
10034        // splitter sizes; the pane's own `setFrameSize:` reports the size to Day.
10035        let split_pane = SPLIT_STATE.with(|m| {
10036            let m = m.borrow();
10037            let Some(state) = m.get(&ptr_of(parent)) else {
10038                return false;
10039            };
10040            let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
10041            let wrap = if second {
10042                &state.second_wrap
10043            } else {
10044                &state.first_wrap
10045            };
10046            unsafe {
10047                child.setFrame(wrap.bounds());
10048                child.setAutoresizingMask(
10049                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10050                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10051                );
10052                wrap.addSubview(child);
10053            }
10054            true
10055        });
10056        if split_pane {
10057            return;
10058        }
10059        // Inspector host: each pane fills its wrap via autoresizing, the nav-page contract;
10060        // the split, not Day, owns the pane frames (docs/inspector.md).
10061        let inspected = INSPECTOR_STATE.with(|m| {
10062            let m = m.borrow();
10063            let Some(state) = m.get(&ptr_of(parent)) else {
10064                return false;
10065            };
10066            let panel = INSPECTOR_PANES
10067                .with(|t| t.get(ptr_of(child)))
10068                .unwrap_or(false);
10069            let wrap = if panel {
10070                &state.panel_wrap
10071            } else {
10072                &state.content_wrap
10073            };
10074            unsafe {
10075                child.setFrame(wrap.bounds());
10076                child.setAutoresizingMask(
10077                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10078                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10079                );
10080                wrap.addSubview(child);
10081            }
10082            true
10083        });
10084        if !inspected {
10085            // Absolute positioning: z-order is build order; index is irrelevant for
10086            // non-overlapping frames (stack_z will need ordered insertion later).
10087            unsafe { content_of(parent).addSubview(child) };
10088        }
10089    }
10090
10091    fn remove(&mut self, parent: &Handle, child: &Handle) {
10092        PAGE_PANE.with(|t| t.remove(ptr_of(child)));
10093        let mtm = self.mtm();
10094        NAV_STATE.with(|m| {
10095            if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
10096                // A tabs host: the page leaves with its tab item.
10097                if let Some(tabs) = state.tabs.as_ref() {
10098                    unsafe {
10099                        let n = tabs.view.numberOfTabViewItems();
10100                        for i in 0..n {
10101                            let item = tabs.view.tabViewItemAtIndex(i);
10102                            if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
10103                                tabs.view.removeTabViewItem(&item);
10104                                break;
10105                            }
10106                        }
10107                    }
10108                }
10109                state.pages.retain(|p| ptr_of(p) != ptr_of(child));
10110                if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
10111                    state.sidebar_page = None;
10112                }
10113            }
10114        });
10115        unsafe { child.removeFromSuperview() };
10116    }
10117
10118    fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
10119        unsafe { content_of(parent).addSubview(child) };
10120    }
10121
10122    fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
10123        match kind {
10124            kinds::LABEL => {
10125                if let Some(tf) = h.downcast_ref::<NSTextField>() {
10126                    let w = p.width.unwrap_or(1.0e6);
10127                    // The field owns maximumNumberOfLines; measuring its cell bypasses it.
10128                    let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
10129                    let mut height = s.height.ceil();
10130                    // AppKit's truncating single-line mode still measures explicit newlines
10131                    // as multiple lines. Bound that case using AppKit's own font metrics.
10132                    if tf.maximumNumberOfLines() == 1 {
10133                        thread_local! {
10134                            static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
10135                        }
10136                        if let Some(font) = unsafe { tf.font() } {
10137                            height = height.min(
10138                                METRICS
10139                                    .with(|metrics| metrics.defaultLineHeightForFont(&font))
10140                                    .ceil(),
10141                            );
10142                        }
10143                    }
10144                    return Size::new(s.width.ceil().min(w), height);
10145                }
10146                Size::ZERO
10147            }
10148            kinds::BUTTON | kinds::TOGGLE => {
10149                let s = unsafe { h.fittingSize() };
10150                Size::new(s.width.ceil(), s.height.ceil())
10151            }
10152            kinds::SLIDER => {
10153                let s = unsafe { h.fittingSize() };
10154                Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
10155            }
10156            kinds::PICKER => picker::measure_any(self, h, p),
10157            kinds::TEXT_AREA => textarea::measure_any(self, h, p),
10158            kinds::TEXT_FIELD => {
10159                let s = unsafe { h.fittingSize() };
10160                Size::new(
10161                    p.width.unwrap_or(s.width.max(160.0)),
10162                    s.height.max(22.0).ceil(),
10163                )
10164            }
10165            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
10166            // The stack's own fitting size, at least a table row's 28pt; the words truncate to
10167            // the row's width.
10168            kinds::LIST_ITEM => {
10169                let s = h.fittingSize();
10170                Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
10171            }
10172            kinds::PROGRESS => {
10173                // Indeterminate spinner is a fixed square; determinate bar fills width.
10174                let indeterminate = h
10175                    .clone()
10176                    .downcast::<NSProgressIndicator>()
10177                    .map(|pi| unsafe { pi.isIndeterminate() })
10178                    .unwrap_or(false);
10179                if indeterminate {
10180                    let large = h
10181                        .downcast_ref::<NSProgressIndicator>()
10182                        .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
10183                    let side = if large { 32.0 } else { 20.0 };
10184                    Size::new(side, side)
10185                } else {
10186                    Size::new(p.width.unwrap_or(180.0), 20.0)
10187                }
10188            }
10189            kinds::NAV_MENU => {
10190                let rows = NAV_MENUS.with(|m| {
10191                    m.borrow()
10192                        .get(&ptr_of(h))
10193                        .map(|(_, d)| d.ivars().items.borrow().len())
10194                        .unwrap_or(0)
10195                });
10196                Size::new(
10197                    p.width.unwrap_or(220.0),
10198                    p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
10199                )
10200            }
10201            // The recycling list fills the space it is offered (its native scroll owns overflow).
10202            kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
10203            _ => {
10204                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
10205                    measure(self, h, p)
10206                } else {
10207                    let s = unsafe { h.fittingSize() };
10208                    Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
10209                }
10210            }
10211        }
10212    }
10213
10214    fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
10215        unsafe {
10216            h.setWantsLayer(true);
10217        }
10218        let v = h.clone();
10219        with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
10220    }
10221
10222    fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
10223        // Expressed in the view's own geometry (see `TRANSFORMS`), so hit-testing follows the
10224        // drawing, as UIKit's does. Without a laid-out frame yet, `set_frame` applies it.
10225        TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
10226        let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
10227        let v = h.clone();
10228        with_appkit_anim(anim, move || {
10229            if let Some(base) = base {
10230                apply_geometry(&v, base, t);
10231            }
10232        });
10233    }
10234
10235    fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
10236        if let Some(label) = h.downcast_ref::<DayLabel>() {
10237            label.ivars().selectable.set(selectable);
10238            label.set_links(label.ivars().has_links.get());
10239        } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
10240            unsafe { tf.setSelectable(selectable) };
10241        }
10242        None
10243    }
10244
10245    fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
10246        let node = text_field_node(h)?;
10247        let old = h.downcast_ref::<NSTextField>()?;
10248        // Hidden characters are a class on AppKit. A field already of the right class is
10249        // dressed in place; otherwise its replacement is, and the node moves to it.
10250        let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
10251            .then(|| self.swap_text_field(h, old, node, traits.secure));
10252        let tf = swapped.as_deref().unwrap_or(old);
10253        unsafe {
10254            // Read-only keeps the bezel and the ordinary text color; the text stays
10255            // selectable, so it can still be copied.
10256            tf.setEditable(!traits.read_only);
10257            tf.setSelectable(true);
10258        }
10259        // The purpose is AutoFill's hint on the desktop: which saved credential or contact
10260        // detail the system offers. `Number` and `Decimal` have no content type. A constant
10261        // newer than the running system leaves the field untyped.
10262        let content_type = match traits.purpose {
10263            InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
10264            InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
10265            InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
10266            InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
10267            InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
10268            InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
10269            InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
10270            InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
10271            InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
10272        };
10273        unsafe {
10274            tf.setContentType(content_type);
10275            // Only free text wants the system finishing words; a name, an address or a code
10276            // is typed exactly.
10277            tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
10278        }
10279        // No on-screen keyboard, so no action key to label; and no native length limit:
10280        // day-pieces holds `max_length`.
10281        swapped.map(view_of)
10282    }
10283
10284    fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
10285        let key = Retained::as_ptr(h) as usize;
10286        if cursor == Cursor::Default {
10287            // Release: drop the tracking area, and the hide if this owner holds one.
10288            if let Some((owner, area)) = self.cursors.remove(&key) {
10289                unsafe { h.removeTrackingArea(&area) };
10290                if owner.ivars().hiding.replace(false) {
10291                    NSCursor::unhide();
10292                }
10293            }
10294            return;
10295        }
10296        let hidden = cursor == Cursor::None;
10297        let shape = if hidden { None } else { ns_cursor(&cursor) };
10298        let mtm = self.mtm;
10299        let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
10300            let owner = DayCursorOwner::new(mtm);
10301            // InVisibleRect: the area follows the view's bounds, so no rect to keep in step
10302            // with layout. ActiveInKeyWindow: the shape belongs to the window taking input.
10303            let opts = NSTrackingAreaOptions::CursorUpdate
10304                | NSTrackingAreaOptions::MouseEnteredAndExited
10305                | NSTrackingAreaOptions::ActiveInKeyWindow
10306                | NSTrackingAreaOptions::InVisibleRect;
10307            let any: &objc2::runtime::AnyObject = &owner;
10308            let area = unsafe {
10309                NSTrackingArea::initWithRect_options_owner_userInfo(
10310                    NSTrackingArea::alloc(),
10311                    NSRect::ZERO,
10312                    opts,
10313                    Some(any),
10314                    None,
10315                )
10316            };
10317            unsafe { h.addTrackingArea(&area) };
10318            (owner, area)
10319        });
10320        let changed = {
10321            let iv = owner.ivars();
10322            let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10323                (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10324                (None, None) => true,
10325                _ => false,
10326            };
10327            *iv.cursor.borrow_mut() = shape;
10328            let was_hidden = iv.hidden.replace(hidden);
10329            !same || was_hidden != hidden
10330        };
10331        // A reactive change while the pointer is already inside: AppKit only asks on entry,
10332        // so ask it to re-evaluate now.
10333        if changed && let Some(w) = h.window() {
10334            unsafe { w.invalidateCursorRectsForView(h) };
10335        }
10336    }
10337
10338    /// Where the control actually draws its first line of text (docs/baseline.md).
10339    ///
10340    /// AppKit publishes `firstBaselineOffsetFromTop`, but it is measured from the top of the
10341    /// view's alignment rect and it is rounded to whole points, and that rounding is visible.
10342    /// An `NSDatePicker` in a 26pt frame insets its alignment rect 4pt and answers 15, i.e. 19
10343    /// in frame terms, while it paints at 19.9; a label beside it then sits a point high, which
10344    /// is exactly the drift baseline alignment exists to remove.
10345    ///
10346    /// So derive it from the metrics AppKit rounded: a single line of the control's own font,
10347    /// centered in its alignment rect, with the baseline an ascender below the line's top. That
10348    /// reproduces AppKit's own numbers for a plain label and a bezeled field (12.91 → its 13,
10349    /// 19.91 → its 20) while keeping the fractional part that makes a picker land on the line.
10350    /// Controls with no font of their own keep AppKit's answer.
10351    fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
10352        if !day_spec::kind_has_baseline(kind) {
10353            return None;
10354        }
10355        // The view has to be at the height the row settled on before it answers: a control
10356        // that centers its text vertically moves its baseline with its box.
10357        let current = unsafe { h.frame() };
10358        if (current.size.height - size.height).abs() > 0.5 {
10359            unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
10360        }
10361        let insets = unsafe { h.alignmentRectInsets() };
10362        let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
10363        let font = h
10364            .downcast_ref::<NSControl>()
10365            .and_then(|c| unsafe { c.font() });
10366        let offset = match font {
10367            // A multi-line editor's first line sits at the top of its text container, not
10368            // centered in it, so the centering model would put its baseline half a box too low.
10369            Some(_) if kind == kinds::TEXT_AREA => reported,
10370            Some(f) => {
10371                let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
10372                let line = ascender - descender;
10373                let align_h = (size.height - insets.top - insets.bottom).max(0.0);
10374                insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
10375            }
10376            None => reported,
10377        };
10378        // AppKit's documented "no baseline" answer is the view's own height.
10379        (offset > 0.0 && offset < size.height).then_some(offset)
10380    }
10381
10382    fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
10383        // Nav pages: the splitter pane / nav container owns the frame (autoresized).
10384        if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
10385            return;
10386        }
10387        // Every Day parent is flipped (DayFlipped containers, flipped scroll document views),
10388        // so top-left frames apply directly.
10389        let r = NSRect::new(
10390            NSPoint::new(frame.origin.x, frame.origin.y),
10391            NSSize::new(frame.size.width, frame.size.height),
10392        );
10393        // Nav host: the sidebar holds its width when the window resizes and the detail pane
10394        // absorbs the change. That is now the sidebar NSSplitViewItem's behavior, so the
10395        // only thing left to do here is give the split its frame and place the divider once;
10396        // re-placing it on every resize would fight the item and undo a user's drag.
10397        if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
10398            // A host at the top of a window's pinned content reaches up under the title bar,
10399            // where its controller expects to be (see `pane_under_title_bar`); its panes keep
10400            // their content below the strip, so nothing Day laid out moves.
10401            let strip = unsafe { split.superview() }
10402                .and_then(|sup| {
10403                    let content = unsafe { sup.window() }?.contentView()?;
10404                    // Layout wrappers (for example zstack with a reader cover) may sit
10405                    // between the window root and its navigation host. A direct-parent
10406                    // check misses them and puts AppKit's frosted pocket over page text.
10407                    let mut ancestor = Some(sup.clone());
10408                    while let Some(view) = ancestor {
10409                        if std::ptr::eq(&*view, &*content) {
10410                            break;
10411                        }
10412                        if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
10413                            return None; // nested navigation belongs to the outer pane
10414                        }
10415                        ancestor = unsafe { view.superview() };
10416                    }
10417                    let point = unsafe {
10418                        sup.convertPoint_toView(
10419                            NSPoint::new(frame.origin.x, frame.origin.y),
10420                            Some(&content),
10421                        )
10422                    };
10423                    (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
10424                })
10425                .unwrap_or(0.0);
10426            let r = NSRect::new(
10427                NSPoint::new(r.origin.x, r.origin.y - strip),
10428                NSSize::new(r.size.width, r.size.height + strip),
10429            );
10430            let wraps = NAV_STATE.with(|m| {
10431                m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
10432                    (s.title_strip != strip).then(|| {
10433                        s.title_strip = strip;
10434                        let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
10435                        w.extend(s.list_wrap.clone());
10436                        w
10437                    })
10438                })
10439            });
10440            let first = NAV_STATE.with(|m| {
10441                m.borrow_mut()
10442                    .get_mut(&ptr_of(h))
10443                    .map(|s| {
10444                        if !s.presentation.is_split() {
10445                            return (false, None);
10446                        }
10447                        let sidebar = !std::mem::replace(&mut s.positioned, true);
10448                        // The list's divider waits for the pane to be showing. Placing it while
10449                        // the pane is collapsed re-opens it (which is how an app whose first
10450                        // destination has no list opened with one beside it) and spends the one
10451                        // placement the pane gets, leaving it at the solver's width later on.
10452                        (sidebar, take_list_placement(s))
10453                    })
10454                    .unwrap_or((false, None))
10455            });
10456            unsafe {
10457                split.setFrame(r);
10458                split.layoutSubtreeIfNeeded();
10459            }
10460            // After the panes have their new size, so each wrap is placed in the final pane;
10461            // autoresizing keeps the strip from then on.
10462            for wrap in wraps.iter().flatten() {
10463                place_below_strip(wrap, strip);
10464            }
10465            unsafe {
10466                if first.0 {
10467                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
10468                }
10469                // A triple split has a second divider, and nothing else places it: left alone,
10470                // the controller's initial constraint pass lands it wherever the solver liked, so
10471                // the content list opens at an arbitrary width and the detail pane gets the
10472                // leftovers until the first manual drag re-settles them.
10473                if let Some(w) = first.1 {
10474                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
10475                }
10476            }
10477        } else {
10478            BASE_FRAMES.with(|m| {
10479                m.insert(
10480                    ptr_of(h),
10481                    [
10482                        frame.origin.x,
10483                        frame.origin.y,
10484                        frame.size.width,
10485                        frame.size.height,
10486                    ],
10487                )
10488            });
10489            // A transform (`set_transform`) is applied to the frame Day laid out.
10490            match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
10491                Some(t) => apply_geometry(
10492                    h,
10493                    [
10494                        frame.origin.x,
10495                        frame.origin.y,
10496                        frame.size.width,
10497                        frame.size.height,
10498                    ],
10499                    t,
10500                ),
10501                None => unsafe { h.setFrame(r) },
10502            }
10503        }
10504    }
10505
10506    fn set_scroll_content(&mut self, h: &Handle, content: Size) {
10507        if let Some(sv) = h.downcast_ref::<NSScrollView>()
10508            && let Some(doc) = unsafe { sv.documentView() }
10509        {
10510            unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
10511        }
10512    }
10513
10514    /// A macOS table row: the dense rows of a Finder or Mail list, 28pt for an icon and a line of body text.
10515    fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
10516        day_spec::RowMetrics {
10517            insets: day_spec::Insets {
10518                top: 4.0,
10519                leading: 8.0,
10520                bottom: 4.0,
10521                trailing: 8.0,
10522            },
10523            min_height: 28.0,
10524        }
10525    }
10526
10527    fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
10528        if let Some(sv) = h.downcast_ref::<NSScrollView>()
10529            && let Some(doc) = unsafe { sv.documentView() }
10530        {
10531            unsafe {
10532                doc.scrollRectToVisible(NSRect::new(
10533                    NSPoint::new(target.origin.x, target.origin.y),
10534                    NSSize::new(target.size.width, target.size.height),
10535                ))
10536            };
10537        }
10538    }
10539
10540    fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
10541        let Some(window) = h.window() else { return };
10542        // A list's public handle is its scroll view; keyboard focus belongs to the table.
10543        let list = list_entry(ptr_of(h));
10544        let responder: &NSResponder = match &list {
10545            Some((table, _)) => table,
10546            None => h,
10547        };
10548        let responder_ptr = responder as *const NSResponder as usize;
10549        if focused {
10550            window.makeFirstResponder(Some(responder));
10551            return;
10552        }
10553        // Resign only while this view still owns focus, so a stale release can't blur a
10554        // sibling.
10555        let owns = window
10556            .firstResponder()
10557            .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
10558            || owns_first_responder(&window, h);
10559        if owns {
10560            window.makeFirstResponder(None);
10561        }
10562    }
10563
10564    fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
10565        // The overrides live on `DayFlipped` (the container view); registering any other
10566        // view is harmless but inert, the graceful silence the duty documents.
10567        if focusable {
10568            FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
10569        } else {
10570            FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
10571        }
10572    }
10573
10574    fn set_event_sink(&mut self, sink: EventSink) {
10575        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
10576    }
10577
10578    fn set_edit_state(&mut self, state: &day_spec::EditState) {
10579        EDIT_STATE.with(|s| s.set(*state));
10580    }
10581
10582    fn modifiers(&mut self) -> day_spec::Modifiers {
10583        let f = NSEvent::modifierFlags_class();
10584        day_spec::Modifiers {
10585            shift: f.contains(NSEventModifierFlags::Shift),
10586            primary: f.contains(NSEventModifierFlags::Command),
10587            alt: f.contains(NSEventModifierFlags::Option),
10588        }
10589    }
10590
10591    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
10592        let front = undo_front(self.mtm);
10593        *front.ivars().state.borrow_mut() = state.clone();
10594    }
10595
10596    fn attach_list(&mut self, host: &Handle, source: ListSource) {
10597        let key = ptr_of(host);
10598        if let Some((table, data)) = list_entry(key) {
10599            data.ivars().source.replace(Some(source));
10600            // Initial fill: numberOfRows reads the snapshot only; viewForRow is deferred.
10601            unsafe { table.reloadData() };
10602        }
10603        // Force the table to realize its visible row views on the next main-loop turn, outside
10604        // any `with_tree` borrow, so `viewForRow`/`bind_row` build the cells then. Otherwise a
10605        // headless CI window never lays the table out until a snapshot's `cacheDisplayInRect`
10606        // forces it *inside* the snapshot borrow, where `bind_row` must skip (blank rows).
10607        post_realize_visible_rows(key);
10608    }
10609
10610    fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
10611        let key = ptr_of(host);
10612        if let Some((outline, data)) = tree_entry(key) {
10613            data.ivars().source.replace(Some(source));
10614            // Initial fill: child counts read the snapshot only; viewForItem is deferred.
10615            unsafe { outline.reloadData() };
10616        }
10617        // Realize visible rows on the next main-loop turn, outside any borrow (the
10618        // attach_list comment has the occluded-window story).
10619        <AppKit as Platform>::post(Box::new(move || {
10620            if let Some((outline, _)) = tree_entry(key) {
10621                unsafe { outline.layoutSubtreeIfNeeded() };
10622            }
10623        }));
10624    }
10625
10626    fn adopt(&mut self, raw: RawHandle) -> Handle {
10627        // A recycling NSTableView cell view; Day builds/rebinds its row content in place.
10628        // Invariant, not app input: day-core only passes back the cell pointer this backend
10629        // itself vended through `bind_row`, so a null here is a framework bug worth stopping on.
10630        let ptr = raw as *mut NSView;
10631        unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
10632    }
10633
10634    fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
10635        self.edit_toolbar(h, ops)
10636    }
10637
10638    fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
10639        self.patch_toolbar(h, patch);
10640    }
10641
10642    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
10643        let mtm = self.mtm;
10644        if self.menu_escape_monitor.is_none() {
10645            let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
10646                ffi_guard::contain(event.as_ptr(), || {
10647                    let event_ref = unsafe { event.as_ref() };
10648                    let app = NSApplication::sharedApplication(mtm);
10649                    // Native dialogs retain their cancellation behavior. Only an enabled
10650                    // menu key equivalent can consume Escape, never the general key stream.
10651                    if app.modalWindow().is_none()
10652                        && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
10653                        && unsafe { event_ref.charactersIgnoringModifiers() }
10654                            .is_some_and(|s| s.to_string() == "\u{1b}")
10655                        && app
10656                            .mainMenu()
10657                            .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
10658                    {
10659                        std::ptr::null_mut()
10660                    } else {
10661                        event.as_ptr()
10662                    }
10663                })
10664            });
10665            self.menu_escape_monitor = unsafe {
10666                NSEvent::addLocalMonitorForEventsMatchingMask_handler(
10667                    objc2_app_kit::NSEventMask::KeyDown,
10668                    &block,
10669                )
10670            }
10671            .map(MenuEscapeMonitor);
10672        }
10673        let app = NSApplication::sharedApplication(mtm);
10674        let menubar = NSMenu::new(mtm);
10675        // macOS owns the application menu; relocate app-level roles while preserving
10676        // their callbacks, shortcuts, and enabled state.
10677        let mut items = items.to_vec();
10678        let about = extract_app_role(&mut items, day_spec::MenuRole::About);
10679        let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
10680        let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
10681        let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
10682        let services =
10683            install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
10684        // Fill the standard slots the app did not claim, in the platform's bar order
10685        // (day-core owns that policy so every backend arranges its bar the same way).
10686        // Fill the standard slots the app left open, in macOS's bar order. The Window menu is
10687        // installed natively below, so the style deliberately supplies none.
10688        let items =
10689            day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
10690        let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
10691        // Each top-level entry becomes a menu-bar menu.
10692        for item in &items {
10693            match item {
10694                day_spec::MenuItem::Submenu { label, items, role } => {
10695                    let sub = build_ns_menu(mtm, label, items);
10696                    let it = NSMenuItem::new(mtm);
10697                    // Help is held back: the Window menu is installed natively after this loop
10698                    // (AppKit owns it so it can append the live window list), and Help sits
10699                    // last on every Mac menu bar.
10700                    if *role == Some(day_spec::MenuBarRole::Help)
10701                        || *label == day_localization::t(day_localization::key::day_help)
10702                    {
10703                        help_menu = Some((label.clone(), sub));
10704                        continue;
10705                    }
10706                    it.setTitle(&NSString::from_str(label));
10707                    it.setSubmenu(Some(&sub));
10708                    menubar.addItem(&it);
10709                }
10710                other => {
10711                    // A bare top-level action → wrap in a one-item menu so it has a submenu.
10712                    let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
10713                    let it = NSMenuItem::new(mtm);
10714                    it.setSubmenu(Some(&sub));
10715                    menubar.addItem(&it);
10716                }
10717            }
10718        }
10719        // The Window menu (docs/windows.md): auto-installed unless the app's model owns
10720        // `MenuRole::Minimize` (then the app is composing its own window management).
10721        if !model_has_role(&items, day_spec::MenuRole::Minimize) {
10722            install_windows_menu(mtm, &app, &menubar);
10723        }
10724        if let Some((label, help)) = help_menu {
10725            let it = NSMenuItem::new(mtm);
10726            it.setTitle(&NSString::from_str(&label));
10727            it.setSubmenu(Some(&help));
10728            menubar.addItem(&it);
10729            // Registering it makes AppKit add the Help search field and index the help book —
10730            // behavior no hand-built menu reproduces.
10731            unsafe { app.setHelpMenu(Some(&help)) };
10732        }
10733        app.setMainMenu(Some(&menubar));
10734        unsafe { app.setServicesMenu(Some(&services)) };
10735    }
10736
10737    fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
10738        let Some(view) = h.downcast_ref::<NSView>() else {
10739            return;
10740        };
10741        if items.is_empty() {
10742            unsafe { view.setMenu(None) };
10743            return;
10744        }
10745        let menu = build_ns_menu(self.mtm, "", items);
10746        // Attach to the view AND its current subviews: a right-click that hit-tests a child
10747        // control (the label inside a padded target) must find the menu on the view it hit —
10748        // AppKit does not walk ancestors for `.menu`, and controls swallow the event.
10749        // DayFlipped's `rightMouseDown:` pops the menu explicitly; native controls (labels)
10750        // show their `.menu` through their own default path.
10751        unsafe { view.setMenu(Some(&menu)) };
10752        fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
10753            for sub in v.subviews() {
10754                unsafe { sub.setMenu(Some(menu)) };
10755                apply_to_subviews(&sub, menu);
10756            }
10757        }
10758        apply_to_subviews(view, &menu);
10759    }
10760
10761    fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
10762        transfer::source(h, source);
10763    }
10764    fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
10765        transfer::target(h, target);
10766    }
10767    fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
10768        // Consulted by the classes that override `menuForEvent:` (the canvas; docs/menus.md
10769        // "Dynamic context menus" lists the covered surfaces per backend).
10770        CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
10771    }
10772
10773    fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
10774        let key = ptr_of(h);
10775        // Pan is not a recognizer on macOS: the two-finger idiom is the trackpad SCROLL, so
10776        // the canvas view's own `scrollWheel:` override reports it for registered nodes.
10777        // Containers use a horizontal-only monitor so nested vertical scrolling still works.
10778        if kind == day_spec::GestureKind::Pan {
10779            PAN_NODES.with(|t| t.insert(key, node));
10780            install_container_pan_monitor();
10781            return;
10782        }
10783        // Nor is hover: it is a tracking area plus `mouseEntered:`/`mouseMoved:`/`mouseExited:`,
10784        // which only `DayCanvas` overrides — a hover enabled on another view emits nothing, the
10785        // same limitation Pan has.
10786        if kind == day_spec::GestureKind::Hover {
10787            // Idempotent, and it has to be checked here rather than falling through to the
10788            // recognizer guard below: day-core re-enables a gesture on rebuild, and a second
10789            // tracking area on the same view means a second copy of every hover event.
10790            let first = HOVER_NODES.with(|t| t.get(key)).is_none();
10791            HOVER_NODES.with(|t| t.insert(key, node));
10792            if first {
10793                install_tracking_area(h);
10794            }
10795            return;
10796        }
10797        // Idempotent: attach each kind at most once per view.
10798        let already = GESTURES.with(|m| {
10799            m.borrow()
10800                .get(&key)
10801                .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
10802        });
10803        if already {
10804            return;
10805        }
10806        let mtm = self.mtm;
10807        let target = DayGesture::new(mtm, node, kind);
10808        let recognizer: Retained<NSGestureRecognizer> = unsafe {
10809            match kind {
10810                day_spec::GestureKind::Drag => {
10811                    Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
10812                        NSPanGestureRecognizer::alloc(mtm),
10813                        Some(&target),
10814                        Some(sel!(fire:)),
10815                    ))
10816                }
10817                day_spec::GestureKind::Pinch => Retained::into_super(
10818                    objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
10819                        objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
10820                        Some(&target),
10821                        Some(sel!(fire:)),
10822                    ),
10823                ),
10824                _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
10825                    NSClickGestureRecognizer::alloc(mtm),
10826                    Some(&target),
10827                    Some(sel!(fire:)),
10828                )),
10829            }
10830        };
10831        unsafe { h.addGestureRecognizer(&recognizer) };
10832        GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
10833    }
10834
10835    fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
10836        unsafe {
10837            if let Some(id) = &a11y.identifier {
10838                h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
10839            }
10840            if let Some(label) = &a11y.label {
10841                h.setAccessibilityLabel(Some(&NSString::from_str(label)));
10842                APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
10843            } else {
10844                APP_LABELED.with(|t| t.remove(ptr_of(h)));
10845            }
10846            if let Some(hint) = &a11y.hint {
10847                h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
10848            }
10849            if let Some(value) = &a11y.value {
10850                let ns = NSString::from_str(value);
10851                h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
10852            }
10853            // Only apply an EXPLICIT role (canvas/custom pieces, e.g. a Meter): native controls
10854            // already report the right role, so Day records but doesn't override theirs (§13).
10855            if let Some(role) = ns_role(a11y.role) {
10856                h.setAccessibilityRole(Some(role));
10857            }
10858            if a11y.role == day_spec::Role::Tab {
10859                h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
10860            }
10861            if let Some(on) = a11y.selected {
10862                h.setAccessibilitySelected(on);
10863            }
10864            // Decorative / hidden: drop from the AX tree entirely. An ignored view alone is
10865            // not enough — AppKit promotes an ignored element's children into its parent's
10866            // list — so the subtree is cut off too, which also covers subviews added later
10867            // (list rows, re-created children). Hidden never flips back, so the override is
10868            // never lifted.
10869            if a11y.hidden {
10870                h.setAccessibilityElement(false);
10871                h.setAccessibilityChildren(Some(&NSArray::new()));
10872            }
10873        }
10874    }
10875
10876    /// The announcement request goes out from the primary window (any live element will
10877    /// do; the app object stands in before the window exists). Without VoiceOver nothing
10878    /// observes the notification, so posting is free.
10879    fn announce(&mut self, text: &str, urgent: bool) {
10880        use objc2_app_kit::{
10881            NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
10882            NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
10883            NSAccessibilityPriorityLevel,
10884        };
10885        let app = NSApplication::sharedApplication(self.mtm());
10886        let window = primary_content().and_then(|content| content.window());
10887        let element: &objc2::runtime::AnyObject = match &window {
10888            Some(window) => window,
10889            None => &app,
10890        };
10891        // High priority interrupts the current sentence; medium waits its turn.
10892        let priority = if urgent {
10893            NSAccessibilityPriorityLevel::High
10894        } else {
10895            NSAccessibilityPriorityLevel::Medium
10896        };
10897        let announcement = NSString::from_str(text);
10898        let priority = NSNumber::new_isize(priority.0);
10899        let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
10900        // SAFETY: the keys are AppKit's constants and both values are the types the
10901        // announcement notification documents (an NSString and an NSNumber).
10902        unsafe {
10903            let user_info = NSDictionary::from_slices::<NSString>(
10904                &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
10905                &values,
10906            );
10907            NSAccessibilityPostNotificationWithUserInfo(
10908                element,
10909                NSAccessibilityAnnouncementRequestedNotification,
10910                Some(&user_info),
10911            );
10912        }
10913    }
10914
10915    fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
10916        unsafe {
10917            let role = h
10918                .accessibilityRole()
10919                .map(|r| day_role_from_ns(&r.to_string()))
10920                .unwrap_or(day_spec::Role::None);
10921            // A picker answers its displayed selection and its enabled state itself: the
10922            // inline style is a stack of radios, not one control.
10923            let picker = picker::read_native(h);
10924            day_spec::NativeSnapshot {
10925                found: true,
10926                role,
10927                label: h.accessibilityLabel().map(|s| s.to_string()),
10928                value: h
10929                    .accessibilityValue()
10930                    .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
10931                identifier: h
10932                    .accessibilityIdentifier()
10933                    .map(|s| s.to_string())
10934                    .filter(|s| !s.is_empty()),
10935                text: match &picker {
10936                    Some((text, _)) => text.clone(),
10937                    None => native_text(h),
10938                },
10939                number: native_number(h),
10940                checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
10941                    match sw.state() {
10942                        s if s == NSControlStateValueOn => Some(true),
10943                        s if s == NSControlStateValueOff => Some(false),
10944                        // Mixed is neither on nor off.
10945                        _ => None,
10946                    }
10947                } else if let Some(btn) = h.downcast_ref::<NSButton>() {
10948                    // A Day button's selected state (`ButtonProps::selected`): its own
10949                    // `state`, which a momentary button holds off at rest.
10950                    BUTTON_SELECTED
10951                        .with(|m| m.borrow().contains_key(&ptr_of(h)))
10952                        .then(|| btn.state() == NSControlStateValueOn)
10953                } else {
10954                    None
10955                },
10956                // A label is a non-editable NSTextField whose `isEnabled` says nothing about
10957                // input; every other control answers for itself.
10958                enabled: match (&picker, h.downcast_ref::<NSControl>()) {
10959                    (Some((_, on)), _) => *on,
10960                    (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
10961                    (None, Some(c)) => Some(c.isEnabled()),
10962                    (None, None) => None,
10963                },
10964                // Off-window counts as not shown: nothing of it reaches the screen.
10965                visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
10966                frame: native_frame(h),
10967            }
10968        }
10969    }
10970
10971    fn request_frame(
10972        &mut self,
10973        host: &Handle,
10974        cb: day_spec::FrameCallback,
10975    ) -> day_spec::CancelFrame {
10976        frame::request(host, cb)
10977    }
10978
10979    fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
10980        OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
10981        unsafe { h.setNeedsDisplay(true) };
10982    }
10983    fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
10984        NAV_STATE.with(|m| {
10985            let m = m.borrow();
10986            let Some(st) = m.get(&ptr_of(host)) else {
10987                return false;
10988            };
10989            // A pane to toggle exists in `Split` and `Rail`; a stack has none and a tab bar
10990            // keeps its rows in the chrome, where hiding them would strand the user.
10991            if !matches!(
10992                st.presentation,
10993                NavPresentation::Split | NavPresentation::Rail
10994            ) {
10995                return false;
10996            }
10997            let item = &st.sidebar_item;
10998            // Set directly, not through the `animator` proxy. The proxy defers the change to
10999            // an animation the dayscript screenshot step does not wait on, so a scripted
11000            // toggle captured a sidebar that had not moved yet. AppKit's own
11001            // NSToolbarToggleSidebarItem still animates — it runs `toggleSidebar:` on the
11002            // controller and never comes through here.
11003            let collapsed = unsafe { item.isCollapsed() };
11004            unsafe { item.setCollapsed(!collapsed) };
11005            true
11006        })
11007    }
11008
11009    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
11010        let content = self.content.as_ref().ok_or("no window content")?;
11011        snapshot_view(content)
11012    }
11013
11014    /// Decode bytes into an `NSImage` (docs/images.md).
11015    ///
11016    /// `NSBitmapImageRep` is asked first and kept: it is what actually reads the container, it
11017    /// answers in PIXELS (`NSImage.size` is in points and reports a 144-DPI photo at
11018    /// two-thirds its real width), and it is the only thing here that can re-encode later.
11019    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
11020        use objc2::AllocAnyThread as _;
11021        let data = NSData::with_bytes(bytes);
11022        let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
11023        else {
11024            emit(
11025                WINDOW_NODE,
11026                Event::ImageDecoded {
11027                    req,
11028                    result: Err(day_spec::ImageError::Decode),
11029                },
11030            );
11031            return;
11032        };
11033        let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
11034        let info = day_spec::BitmapInfo {
11035            pixels: Size::new(w, h),
11036            // Decoded bytes carry no density — a PNG is simply its pixels. Only a staged @2x
11037            // asset has a scale, and that arrives through the named path instead.
11038            scale: 1.0,
11039            format: day_spec::ImageFormat::sniff(bytes),
11040            has_alpha: unsafe { rep.hasAlpha() },
11041        };
11042        // Built AT the rep's pixel size so it draws 1:1 by default: an NSImage otherwise adopts
11043        // the rep's own `size`, which ImageIO derives from the file's DPI — that is what shrinks
11044        // a 144-DPI photo for no reason the app asked for.
11045        let image = unsafe {
11046            objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
11047        };
11048        unsafe { image.addRepresentation(&rep) };
11049        BITMAPS.with(|m| {
11050            m.borrow_mut().insert(
11051                id.0,
11052                AppKitBitmap {
11053                    image,
11054                    rep: Some(rep),
11055                    info,
11056                },
11057            )
11058        });
11059        emit(
11060            WINDOW_NODE,
11061            Event::ImageDecoded {
11062                req,
11063                result: Ok(info),
11064            },
11065        );
11066    }
11067
11068    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
11069        BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
11070    }
11071
11072    /// The container's own metadata (docs/images.md).
11073    ///
11074    /// DPI is DERIVED rather than read from a tag: AppKit has already resolved the file's
11075    /// resolution into the rep's point size, so pixels-per-point × 72 is the number the platform
11076    /// itself believes — and it is right for containers that record resolution in ways EXIF
11077    /// does not.
11078    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
11079        let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
11080        let mut out = day_spec::ImageProperties::default();
11081        let size = unsafe { rep.size() };
11082        if size.width > 0.0 {
11083            let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
11084            // 72 is "no resolution recorded" wearing a number; reporting it would read as a fact
11085            // the file never stated.
11086            if (dpi - 72.0).abs() > 0.5 {
11087                out.dpi = Some(dpi);
11088            }
11089        }
11090        // EXIF arrives as a dictionary of the format's own keys. It is walked through
11091        // `msg_send!` rather than a downcast because a generic `NSDictionary` is not a
11092        // `DowncastTarget`.
11093        if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
11094            let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
11095            for key in keys.iter() {
11096                let value: Option<Retained<objc2::runtime::AnyObject>> =
11097                    unsafe { msg_send![&*exif, objectForKey: &*key] };
11098                let Some(value) = value else { continue };
11099                let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
11100                let (k, v) = (key.to_string(), text.to_string());
11101                match k.as_str() {
11102                    "Orientation" => out.orientation = v.parse().ok(),
11103                    "DateTimeOriginal" => out.created = Some(v.clone()),
11104                    _ => {}
11105                }
11106                // Keys stay in EXIF's own vocabulary, passed through rather than translated —
11107                // the doc for `extra` promises exactly that.
11108                out.extra.push((k, v));
11109            }
11110        }
11111        Some(out)
11112    }
11113
11114    /// What `NSBitmapImageRep` WRITES. It reads more than this — WebP and HEIF among them — and
11115    /// the asymmetry is the platform's own, which is exactly why this duty exists instead of
11116    /// letting `Cap::ImageEncode` imply every format round-trips.
11117    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
11118        use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
11119        vec![Png, Jpeg, Tiff, Bmp, Gif]
11120    }
11121
11122    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
11123        let result = encode_bitmap(id, spec);
11124        emit(WINDOW_NODE, Event::ImageEncoded { req, result });
11125    }
11126
11127    fn release_image(&mut self, id: day_spec::BitmapId) {
11128        release_bitmap(id);
11129    }
11130
11131    /// Replay `ops` offscreen through the canvas's own painter (docs/canvas.md "Exporting") and
11132    /// keep the result in the decode table, so `image`, `encode_image` and `DrawOp::Image` take
11133    /// it like any decoded bitmap.
11134    fn render_bitmap(
11135        &mut self,
11136        req: u64,
11137        id: day_spec::BitmapId,
11138        ops: &[DrawOp],
11139        size: Size,
11140        scale: f64,
11141    ) {
11142        let result = render_bitmap_image(ops, size, scale).map(|bitmap| {
11143            let info = bitmap.info;
11144            BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
11145            info
11146        });
11147        emit(WINDOW_NODE, Event::BitmapRendered { req, result });
11148    }
11149
11150    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
11151        let result = render_pdf_bytes(pages, info);
11152        emit(WINDOW_NODE, Event::PdfRendered { req, result });
11153    }
11154
11155    /// `NSFontManager.availableFontFamilies` + `availableMembersOfFontFamily:`, whose members
11156    /// are `[postscriptName, styleName, weight 0 … 15, traits]` (docs/fonts.md). The `.`-prefixed
11157    /// families are the system's private UI faces and are skipped, as Font Book skips them.
11158    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
11159        use day_spec::FontWeight as W;
11160        let mtm =
11161            objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
11162        let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
11163        let mut out = Vec::new();
11164        for family in unsafe { manager.availableFontFamilies() }.iter() {
11165            let name = family.to_string();
11166            if name.starts_with('.') {
11167                continue;
11168            }
11169            let mut faces = Vec::new();
11170            if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
11171                for member in members.iter() {
11172                    if member.count() < 4 {
11173                        continue;
11174                    }
11175                    let style = member
11176                        .objectAtIndex(1)
11177                        .downcast_ref::<NSString>()
11178                        .map(|s| s.to_string())
11179                        .unwrap_or_default();
11180                    let weight = member
11181                        .objectAtIndex(2)
11182                        .downcast_ref::<objc2_foundation::NSNumber>()
11183                        .map(|n| n.integerValue())
11184                        .unwrap_or(5);
11185                    let traits = member
11186                        .objectAtIndex(3)
11187                        .downcast_ref::<objc2_foundation::NSNumber>()
11188                        .map(|n| n.integerValue())
11189                        .unwrap_or(0);
11190                    let weight = match weight {
11191                        ..=2 => W::UltraLight,
11192                        3 => W::Thin,
11193                        4 => W::Light,
11194                        5 => W::Regular,
11195                        6 => W::Medium,
11196                        7 | 8 => W::Semibold,
11197                        9 => W::Bold,
11198                        10 | 11 => W::Heavy,
11199                        _ => W::Black,
11200                    };
11201                    let italic = traits & 0x1 != 0; // NSItalicFontMask
11202                    faces.push(day_spec::FontFace {
11203                        name: if style.is_empty() {
11204                            day_spec::FontFace::synthesized_name(weight, italic)
11205                        } else {
11206                            style
11207                        },
11208                        weight,
11209                        italic,
11210                    });
11211                }
11212            }
11213            out.push(day_spec::FontFamilyInfo {
11214                family: name,
11215                faces,
11216            });
11217        }
11218        out
11219    }
11220
11221    /// `sizeWithAttributes:` with the attributes `replay` draws with; the ascent is the
11222    /// font's own, so `at.y + ascent` is where the glyphs' baseline lands.
11223    fn measure_text(
11224        &mut self,
11225        text: &str,
11226        size: f64,
11227        font: &day_spec::CanvasFont,
11228    ) -> Option<day_spec::TextMetrics> {
11229        let nsfont = canvas_nsfont(size, font);
11230        let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
11231        let ns = NSString::from_str(text);
11232        let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
11233        // The INK box: `NSStringDrawingUsesDeviceMetrics` is what turns `boundingRectWithSize:`
11234        // from the layout box into the glyphs' own bounds, and it comes back baseline-relative
11235        // with y up — hence the flip. An unbounded size so nothing wraps: this measures one line.
11236        let unbounded = NSSize::new(f64::MAX, f64::MAX);
11237        let ink: NSRect = unsafe {
11238            msg_send![
11239                &ns,
11240                boundingRectWithSize: unbounded,
11241                options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
11242                attributes: &*attrs,
11243            ]
11244        };
11245        Some(day_spec::TextMetrics::from_baseline(
11246            sz.width,
11247            nsfont.ascender(),
11248            sz.height - nsfont.ascender(),
11249            nsfont.capHeight(),
11250            day_spec::Rect::new(
11251                ink.origin.x,
11252                -(ink.origin.y + ink.size.height),
11253                ink.size.width,
11254                ink.size.height,
11255            ),
11256        ))
11257    }
11258
11259    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
11260        let content = self.content.as_ref().ok_or("no window content")?;
11261        snapshot_view_chrome(content)
11262    }
11263
11264    fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
11265        snapshot_view(host)
11266    }
11267
11268    fn open_window(
11269        &mut self,
11270        id: NodeId,
11271        options: &WindowOptions,
11272        kind: day_spec::WindowKind,
11273    ) -> day_spec::WindowOpenReply<Handle> {
11274        let prefs = kind.is_panel();
11275        let (window, delegate, content) = self.make_window(options, prefs, Some(id));
11276        if prefs {
11277            // A settings panel is one-of-a-kind and centered, and it stays OUT of the Window
11278            // menu — the macOS convention every stock app follows (docs/windows.md).
11279            window.center();
11280            unsafe { window.setExcludedFromWindowsMenu(true) };
11281        } else {
11282            // Stagger, don't stack. Without this every window opens at the same centered frame
11283            // and the one underneath is invisible — which is exactly what two Day windows did.
11284            //
11285            // `cascadeTopLeftFromPoint:` puts the window AT the point it is given and answers
11286            // the point for the one after, so the series has to be primed from the primary
11287            // rather than seeded with its corner — seeding lands the first new window exactly
11288            // on top of the primary, which is the bug this replaces.
11289            let from = match self.cascade {
11290                Some(p) => p,
11291                None => self
11292                    .window
11293                    .as_ref()
11294                    .map(|w| {
11295                        let f = w.frame();
11296                        let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
11297                        // Asking the primary to cascade from where it already is leaves it
11298                        // there and answers the next slot — the offset the first new window wants.
11299                        unsafe { w.cascadeTopLeftFromPoint(top_left) }
11300                    })
11301                    .unwrap_or(NSPoint::new(0.0, 0.0)),
11302            };
11303            self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
11304        }
11305        window_chrome::place(&window, options.placement);
11306        // `center` (a settings panel's, or a `Centered` placement's) uses the main screen, the
11307        // one with the keyboard focus, which on a Mac with several displays need not be the
11308        // app's: such a window goes to the primary's screen instead. A scripted run on the
11309        // capture display relies on this to keep the window in its captures.
11310        if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
11311            center_on_screen_of(&window, self.window.as_deref());
11312        }
11313        // Secondary windows need the same initial client-coordinate pinning as the
11314        // primary. Native document pages may move here before any resize notification.
11315        let _ = pin_below_title_bar(&window);
11316        if !options.start_hidden {
11317            window.makeKeyAndOrderFront(None);
11318        }
11319        // Same macOS 26 quirk as the primary (`run`): a window ordered front before its
11320        // first turn drops pre-run layer displays — nudge every layer once.
11321        mark_tree_needs_display(&content);
11322        self.secondary.push(SecondaryWin {
11323            window,
11324            delegate,
11325            content: content.clone(),
11326        });
11327        day_spec::WindowOpenReply::Open(content)
11328    }
11329
11330    fn native_window_tabs(&self) -> bool {
11331        true
11332    }
11333    fn group_windows(&mut self, hosts: &[Handle]) {
11334        let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
11335        let Some(first) = windows.first() else {
11336            return;
11337        };
11338        unsafe {
11339            NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
11340        }
11341        // Explicit insertion respects the model even when system automatic tabbing is off.
11342        for window in windows.iter().skip(1) {
11343            unsafe {
11344                first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
11345            }
11346        }
11347        if let Some(group) = first.tabGroup() {
11348            if !group.isTabBarVisible() {
11349                unsafe {
11350                    first.toggleTabBar(None);
11351                }
11352            }
11353            for (i, window) in windows.iter().enumerate() {
11354                group.insertWindow_atIndex(window, i as isize);
11355            }
11356        }
11357        // Adding/showing a native tab strip changes contentLayoutRect without necessarily
11358        // resizing the window. Re-pin every member and tell the layout tree its usable size.
11359        for window in &windows {
11360            if let Some(size) = pin_below_title_bar(window) {
11361                let node = window
11362                    .delegate()
11363                    .and_then(|d| d.downcast::<DayWinDelegate>().ok())
11364                    .and_then(|d| d.ivars().node)
11365                    .unwrap_or(WINDOW_NODE);
11366                emit(node, Event::WindowResized(size));
11367            }
11368        }
11369    }
11370    fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
11371        let Some(window) = self.ns_window_for(host) else {
11372            return Vec::new();
11373        };
11374        let windows = window.tabGroup().map(|g| g.windows());
11375        let Some(windows) = windows else {
11376            return Vec::new();
11377        };
11378        windows
11379            .iter()
11380            .filter_map(|window| {
11381                self.secondary
11382                    .iter()
11383                    .find(|w| std::ptr::eq(&*w.window, &*window))
11384                    .and_then(|w| w.delegate.ivars().node)
11385            })
11386            .collect()
11387    }
11388
11389    fn close_window(&mut self, host: &Handle) {
11390        // `close()` runs the full native path — windowWillClose → `WindowClosed` →
11391        // day-core teardown — so programmatic and title-bar closes are one code path.
11392        if let Some(w) = self
11393            .secondary
11394            .iter()
11395            .find(|w| ptr_of(&w.content) == ptr_of(host))
11396        {
11397            w.window.close();
11398        }
11399    }
11400
11401    fn focus_window(&mut self, host: &Handle) {
11402        if let Some(w) = self
11403            .secondary
11404            .iter()
11405            .find(|w| ptr_of(&w.content) == ptr_of(host))
11406        {
11407            w.window.makeKeyAndOrderFront(None);
11408        }
11409    }
11410
11411    fn fit_window(&mut self, host: &Handle, size: Size) {
11412        let Some(w) = self
11413            .secondary
11414            .iter()
11415            .find(|w| ptr_of(&w.content) == ptr_of(host))
11416        else {
11417            return;
11418        };
11419        unsafe {
11420            // `setContentSize:` rather than `setFrame:`: Day measured the CONTENT, and AppKit
11421            // adds the title bar itself. Sizing the frame instead would eat the bar's height out
11422            // of the panel and clip the last row by exactly that much.
11423            w.window
11424                .setContentSize(NSSize::new(size.width, size.height));
11425            // A settings panel that fits its content has no reason to be resizable, and macOS
11426            // panels are not — dropping the mask also stops the user dragging it back to a size
11427            // the content does not fill.
11428            let mask = w.window.styleMask();
11429            w.window
11430                .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
11431            w.window.center();
11432        }
11433        center_on_screen_of(&w.window, self.window.as_deref());
11434    }
11435
11436    fn set_window_title(&mut self, host: &Handle, title: &str) {
11437        if let Some(w) = self
11438            .secondary
11439            .iter()
11440            .find(|w| ptr_of(&w.content) == ptr_of(host))
11441        {
11442            w.window.setTitle(&NSString::from_str(title));
11443            return;
11444        }
11445        // The PRIMARY window is retitlable too. It is an ordinary window (docs/windows.md), so
11446        // `window_title` in the first window's shell and `set_title` on `initial_window()` both
11447        // arrive here — and searching only the secondary list silently dropped them.
11448        if self
11449            .content
11450            .as_ref()
11451            .is_some_and(|c| ptr_of(c) == ptr_of(host))
11452            && let Some(w) = self.window.as_ref()
11453        {
11454            w.setTitle(&NSString::from_str(title));
11455        }
11456    }
11457
11458    fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
11459        use day_spec::WindowChange as C;
11460        let Some(window) = self.ns_window_for(host) else {
11461            return;
11462        };
11463        match change {
11464            C::State(state) => set_ns_window_state(&window, *state),
11465            // Screen capture, recording and sharing see an empty window; the user still does.
11466            C::ContentProtected(on) => window.setSharingType(if *on {
11467                objc2_app_kit::NSWindowSharingType::None
11468            } else {
11469                objc2_app_kit::NSWindowSharingType::ReadOnly
11470            }),
11471            other => window_chrome::apply_property(&window, other),
11472        }
11473    }
11474
11475    fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
11476        self.ns_window_for(host)
11477            .map(|w| window_chrome::frame_of(&w))
11478    }
11479
11480    fn monitors(&self) -> Vec<day_spec::Monitor> {
11481        window_chrome::monitors(self.mtm)
11482    }
11483
11484    /// The Dock menu lists them: day-core folds the run-time shortcuts into the model it sends
11485    /// through `set_dock_menu`, so there is nothing more to install here.
11486    fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
11487
11488    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
11489        dock::set_app_items(self.mtm, items);
11490    }
11491
11492    fn set_drag_region(&mut self, h: &Handle, drag: bool) {
11493        window_chrome::set_drag_region(h, drag);
11494    }
11495
11496    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
11497        status_item::set_items(self.mtm, items);
11498    }
11499
11500    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
11501        status_item::set_progress(self.mtm, progress);
11502    }
11503
11504    fn set_dock_visible(&mut self, visible: bool) {
11505        status_item::set_dock_visible(self.mtm, visible);
11506    }
11507
11508    fn set_keep_running(&mut self, keep: bool) {
11509        status_item::set_keep_running(keep);
11510    }
11511
11512    fn quit_app(&mut self) {
11513        let app = NSApplication::sharedApplication(self.mtm);
11514        unsafe { app.terminate(None) };
11515    }
11516
11517    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
11518        use present::PresentSpec;
11519        let mtm = self.mtm;
11520        // Sheets attach to the KEY window at present time (docs/windows.md) — a dialog
11521        // raised from a secondary/preferences window belongs on it; primary is the
11522        // fallback when no DAY window is key (a system panel may hold key status).
11523        let app = NSApplication::sharedApplication(mtm);
11524        let key = app.keyWindow().filter(|k| {
11525            let mut owner = k.clone();
11526            while let Some(parent) = owner.sheetParent() {
11527                owner = parent;
11528            }
11529            self.window
11530                .as_deref()
11531                .is_some_and(|w| std::ptr::eq(w, &*owner))
11532                || self
11533                    .secondary
11534                    .iter()
11535                    .any(|s| std::ptr::eq(&*s.window, &*owner))
11536        });
11537        let Some(mut window) = key.or_else(|| self.window.clone()) else {
11538            emit(
11539                WINDOW_NODE,
11540                Event::PresentResult {
11541                    req,
11542                    result: present::PresentResult::Dismissed,
11543                },
11544            );
11545            return;
11546        };
11547        // A dialog opened from a modal cover belongs on the active sheet, not behind it.
11548        while let Some(sheet) = window.attachedSheet() {
11549            window = sheet;
11550        }
11551        // File pickers use a different native object (NSOpen/NSSavePanel), not an NSAlert.
11552        match spec {
11553            PresentSpec::OpenFile {
11554                filters, multiple, ..
11555            } => {
11556                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11557                unsafe {
11558                    panel.setCanChooseFiles(true);
11559                    panel.setCanChooseDirectories(false);
11560                    panel.setAllowsMultipleSelection(*multiple);
11561                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11562                }
11563                apply_allowed_file_types(&panel, filters);
11564                let p = panel.clone();
11565                // Completion blocks run inside a C ABI frame, so their bodies are contained
11566                // like every other trampoline (§8.5) — this one and the four below.
11567                let handler: block2::RcBlock<dyn Fn(isize)> =
11568                    block2::RcBlock::new(move |resp: isize| {
11569                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11570                    });
11571                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11572                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11573                return;
11574            }
11575            // The folder chooser is the same NSOpenPanel with files and directories swapped.
11576            PresentSpec::OpenFolder { .. } => {
11577                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11578                unsafe {
11579                    panel.setCanChooseFiles(false);
11580                    panel.setCanChooseDirectories(true);
11581                    panel.setCanCreateDirectories(true);
11582                    panel.setAllowsMultipleSelection(false);
11583                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11584                }
11585                let p = panel.clone();
11586                let handler: block2::RcBlock<dyn Fn(isize)> =
11587                    block2::RcBlock::new(move |resp: isize| {
11588                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11589                    });
11590                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11591                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11592                return;
11593            }
11594            PresentSpec::SaveFile { suggested_name, .. } => {
11595                let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
11596                unsafe {
11597                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11598                    panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
11599                }
11600                apply_allowed_file_types(&panel, spec.filters());
11601                let p = panel.clone();
11602                let handler: block2::RcBlock<dyn Fn(isize)> =
11603                    block2::RcBlock::new(move |resp: isize| {
11604                        // The pieces layer copies the staged bytes to the chosen local path.
11605                        ffi_guard::contain((), || emit_panel_result(req, resp, &p));
11606                    });
11607                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11608                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
11609                return;
11610            }
11611            _ => {}
11612        }
11613        let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
11614        unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
11615        if let Some(msg) = spec.message() {
11616            unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
11617        }
11618        // The completion handler must outlive this call, so it's a heap (Rc) block.
11619        let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
11620            PresentSpec::Dialog { buttons, .. } => {
11621                if buttons
11622                    .iter()
11623                    .any(|b| b.role == present::ButtonRole::Destructive)
11624                {
11625                    unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
11626                }
11627                for b in buttons {
11628                    unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
11629                }
11630                block2::RcBlock::new(move |resp: isize| {
11631                    ffi_guard::contain((), || {
11632                        // NSAlertFirstButtonReturn = 1000; add order == spec order.
11633                        let idx = resp - 1000;
11634                        emit(
11635                            WINDOW_NODE,
11636                            Event::PresentResult {
11637                                req,
11638                                result: present::PresentResult::Button(idx as i64),
11639                            },
11640                        );
11641                        PRESENT_ALERTS.with(|m| {
11642                            m.borrow_mut().remove(&req);
11643                        });
11644                    })
11645                })
11646            }
11647            PresentSpec::Prompt {
11648                placeholder,
11649                initial,
11650                ok,
11651                cancel,
11652                ..
11653            } => {
11654                let tf = unsafe { NSTextField::new(mtm) };
11655                unsafe {
11656                    tf.setFrame(NSRect::new(
11657                        NSPoint::new(0.0, 0.0),
11658                        NSSize::new(260.0, 24.0),
11659                    ));
11660                    tf.setEditable(true);
11661                    tf.setBezeled(true);
11662                    tf.setStringValue(&NSString::from_str(initial));
11663                    tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
11664                    alert.setAccessoryView(Some(&tf));
11665                    alert.addButtonWithTitle(&NSString::from_str(ok)); // resp 1000
11666                    alert.addButtonWithTitle(&NSString::from_str(cancel)); // resp 1001
11667                }
11668                block2::RcBlock::new(move |resp: isize| {
11669                    ffi_guard::contain((), || {
11670                        let result = if resp == 1000 {
11671                            present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
11672                        } else {
11673                            present::PresentResult::Dismissed
11674                        };
11675                        emit(WINDOW_NODE, Event::PresentResult { req, result });
11676                        PRESENT_ALERTS.with(|m| {
11677                            m.borrow_mut().remove(&req);
11678                        });
11679                    })
11680                })
11681            }
11682            // File pickers returned early above.
11683            PresentSpec::OpenFile { .. }
11684            | PresentSpec::OpenFolder { .. }
11685            | PresentSpec::SaveFile { .. } => unreachable!(),
11686        };
11687        unsafe {
11688            alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
11689        }
11690        PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
11691    }
11692
11693    fn dismiss(&mut self, req: u64) {
11694        // Close the sheet; its completion handler fires but its (native) result is dropped
11695        // because day-core already removed the pending request when it resolved.
11696        let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
11697        if let Some(alert) = alert {
11698            let sheet = alert.window();
11699            if let Some(parent) = sheet.sheetParent() {
11700                unsafe { parent.endSheet(&sheet) };
11701            }
11702        }
11703        // File-picker sheets are their own NSWindow.
11704        let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
11705        if let Some(panel) = panel
11706            && let Some(parent) = panel.sheetParent()
11707        {
11708            unsafe { parent.endSheet(&panel) };
11709        }
11710    }
11711
11712    fn application_handlers(
11713        &mut self,
11714        query: &day_spec::applications::HandlerQuery,
11715    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
11716    {
11717        applications::handlers(query)
11718    }
11719
11720    fn open_url_with_application(
11721        &mut self,
11722        url: &str,
11723        application: &str,
11724        completion: day_spec::applications::OpenApplicationCompletion,
11725    ) {
11726        applications::open(url, application, completion);
11727    }
11728
11729    fn share_support(&self) -> day_spec::Support {
11730        day_spec::Support::Native
11731    }
11732    fn share_url(&mut self, url: &str, _title: &str) -> bool {
11733        use objc2::{msg_send, runtime::AnyObject};
11734        use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
11735        let Some(mtm) = objc2::MainThreadMarker::new() else {
11736            return false;
11737        };
11738        let Some(url) = NSURL::URLWithString(&NSString::from_str(url)) else {
11739            return false;
11740        };
11741        let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
11742        let Some(view) = app.keyWindow().and_then(|w| w.contentView()) else {
11743            return false;
11744        };
11745        unsafe {
11746            let items = NSArray::from_retained_slice(&[url]);
11747            let picker: objc2::rc::Allocated<AnyObject> =
11748                msg_send![objc2::class!(NSSharingServicePicker), alloc];
11749            let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
11750            let bounds = view.bounds();
11751            let y = if view.isFlipped() {
11752                30.0
11753            } else {
11754                bounds.size.height - 30.0
11755            };
11756            let rect = NSRect::new(
11757                NSPoint::new(bounds.size.width - 30.0, y),
11758                NSSize::new(1.0, 1.0),
11759            );
11760            let _: () = msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: 3usize];
11761            self.sharing = Some(picker);
11762        }
11763        true
11764    }
11765    fn open_url(&mut self, url: &str) {
11766        // NSWorkspace opens the URL in the user's default handler (Safari for http(s), Mail for
11767        // mailto:, …). An unparseable string yields no NSURL and is silently ignored.
11768        let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
11769        if let Some(nsurl) = nsurl {
11770            unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
11771        }
11772    }
11773}
11774
11775/// Apply a file dialog's extension filters (`allowedFileTypes` — deprecated but still the simplest
11776/// extension-based API; `UTType` would pull in another framework crate for no benefit here).
11777#[allow(deprecated)]
11778fn apply_allowed_file_types(
11779    panel: &objc2_app_kit::NSSavePanel,
11780    filters: &[day_spec::present::FileFilter],
11781) {
11782    let exts: Vec<Retained<NSString>> = filters
11783        .iter()
11784        .flat_map(|f| f.extensions.iter())
11785        .map(|e| NSString::from_str(e))
11786        .collect();
11787    if !exts.is_empty() {
11788        let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
11789        let arr = objc2_foundation::NSArray::from_slice(&refs);
11790        unsafe { panel.setAllowedFileTypes(Some(&arr)) };
11791    }
11792}
11793
11794/// Turn an open panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1):
11795/// every chosen URL, so a multiple-selection pick reports all of its files (and a folder
11796/// chooser its one directory).
11797fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
11798    let mut paths = Vec::new();
11799    if resp == 1 {
11800        for url in unsafe { panel.URLs() }.iter() {
11801            if let Some(p) = unsafe { url.path() } {
11802                paths.push(p.to_string());
11803            }
11804        }
11805    }
11806    let result = if paths.is_empty() {
11807        present::PresentResult::Dismissed
11808    } else {
11809        present::PresentResult::Files(paths)
11810    };
11811    emit(WINDOW_NODE, Event::PresentResult { req, result });
11812    PRESENT_PANELS.with(|m| {
11813        m.borrow_mut().remove(&req);
11814    });
11815}
11816
11817/// Turn a save panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1).
11818fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
11819    let result = if resp == 1 {
11820        unsafe { panel.URL() }
11821            .and_then(|url| unsafe { url.path() })
11822            .map(|p| present::PresentResult::Files(vec![p.to_string()]))
11823            .unwrap_or(present::PresentResult::Dismissed)
11824    } else {
11825        present::PresentResult::Dismissed
11826    };
11827    emit(WINDOW_NODE, Event::PresentResult { req, result });
11828    PRESENT_PANELS.with(|m| {
11829        m.borrow_mut().remove(&req);
11830    });
11831}
11832
11833impl Platform for AppKit {
11834    const TARGET: &'static str = "macos-appkit";
11835    const TOOLKIT: &'static str = "appkit";
11836
11837    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
11838        let mtm = self.mtm;
11839        // The App menu / About use the app's display name. `app_name` overrides the (possibly
11840        // decorated) window title; setting the process name also makes the standard About panel and
11841        // the bold App-menu title show it (an unbundled binary otherwise shows the exe name).
11842        self.app_name = options
11843            .app_name
11844            .clone()
11845            .unwrap_or_else(|| options.title.clone());
11846        // The bold App-menu title, the About panel and Quit all show the app's NAME. Always set
11847        // it, not just when `app_name` was given explicitly — an app that only set `title` was
11848        // showing its kebab-case cargo target ("day-sheets") where its name belongs.
11849        //
11850        // Two sources, because AppKit consults them in order: the main bundle's CFBundleName
11851        // wins when there is one, and `day launch` runs the binary UNBUNDLED during development,
11852        // where the name falls back to the executable's file name. Writing the info dictionary
11853        // covers the bundled case; the process name covers the unbundled one.
11854        unsafe {
11855            objc2_foundation::NSProcessInfo::processInfo()
11856                .setProcessName(&NSString::from_str(&self.app_name));
11857            let bundle = objc2_foundation::NSBundle::mainBundle();
11858            let info: Option<Retained<objc2_foundation::NSDictionary>> =
11859                msg_send![&bundle, infoDictionary];
11860            if let Some(info) = info {
11861                let key = NSString::from_str("CFBundleName");
11862                let value = NSString::from_str(&self.app_name);
11863                // `infoDictionary` is documented immutable, but the instance backing an
11864                // unbundled process is a mutable dictionary; guard the send so a genuinely
11865                // immutable one is left alone instead of raising.
11866                if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
11867                    let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
11868                }
11869            }
11870        }
11871        // RTL locales (docs/localization): AppleTextDirection flips AppKit's app-wide
11872        // userInterfaceLayoutDirection (label alignment, slider fill, control mirroring) —
11873        // read at NSApplication init, so register before sharedApplication. Registration
11874        // domain only: volatile, never persisted to the app's defaults.
11875        if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
11876            unsafe {
11877                use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
11878                let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
11879                    .into_super()
11880                    .into_super()
11881                    .into_super();
11882                let dict = NSDictionary::from_retained_objects(
11883                    &[
11884                        &*NSString::from_str("AppleTextDirection"),
11885                        &*NSString::from_str("NSForceRightToLeftWritingDirection"),
11886                    ],
11887                    &[yes.clone(), yes],
11888                );
11889                NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
11890            }
11891        }
11892        let app = NSApplication::sharedApplication(mtm);
11893        // A menu-bar app keeps out of the Dock from the first frame (docs/status-item.md): its
11894        // bundle carries LSUIElement, and an unbundled `day launch` run hears DAY_MACOS_DOCK=0.
11895        let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
11896            || unsafe {
11897                let bundle = objc2_foundation::NSBundle::mainBundle();
11898                let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
11899                    &bundle,
11900                    objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
11901                ];
11902                value.is_some_and(|v| {
11903                    let on: bool = msg_send![&v, boolValue];
11904                    on
11905                })
11906            };
11907        app.setActivationPolicy(if menu_bar_app {
11908            NSApplicationActivationPolicy::Accessory
11909        } else {
11910            NSApplicationActivationPolicy::Regular
11911        });
11912        let document_delegate = documents::delegate(mtm);
11913        app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
11914        // DAY_THEME=light|dark forces the appearance app-wide (themed CI screenshot runs and
11915        // local theme checks); unset ⇒ follow the system.
11916        if let Ok(theme) = std::env::var("DAY_THEME") {
11917            let name = match theme.as_str() {
11918                "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11919                "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11920                _ => None,
11921            };
11922            if let Some(name) = name {
11923                let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
11924                unsafe { app.setAppearance(appearance.as_deref()) };
11925            }
11926        }
11927        // Bundled custom fonts (§18.4) must be registered before the first label realizes.
11928        register_bundled_fonts();
11929
11930        // Default menu bar (standard app menu + Edit) so ⌘Q / Cut-Copy-Paste work before the app
11931        // installs its own via `app_menu(...)`. Rebuilt after `ready` for the items that depend
11932        // on the app's registrations — see there.
11933        let app_name = self.app_name.clone();
11934        install_main_menu(mtm, &app, &app_name);
11935        // App activation / termination → day lifecycle events (docs/lifecycle.md).
11936        install_lifecycle_observers();
11937        install_appearance_observer();
11938        install_reduce_motion_observer();
11939
11940        let (window, delegate, content) = self.make_window(&options, false, None);
11941        // Optional window-appearance override (opt-in via env). An app with a fixed light/dark
11942        // palette sets `DAY_APPEARANCE=light|dark` so native controls (list, fields, editor) match
11943        // its own colors instead of following the system appearance. Unset = follow the system.
11944        let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
11945            Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11946            Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11947            _ => None,
11948        };
11949        if let Some(name) = appearance_name
11950            && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
11951        {
11952            window.setAppearance(Some(&appearance));
11953        }
11954        // The primary delegate lives for the process (this frame never returns); secondary
11955        // delegates are retained in `self.secondary`.
11956        std::mem::forget(delegate);
11957
11958        self.window = Some(window.clone());
11959        self.content = Some(content.clone());
11960        PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
11961
11962        // The root lays out below the title bar, not under it (§7.7).
11963        let layout = pin_below_title_bar(&window)
11964            .unwrap_or(Size::new(options.size.width, options.size.height));
11965        ready(self, content, layout);
11966
11967        // `ready` ran the app's root() — registrations are in. Without a new-window
11968        // builder only one Normal window can ever exist: turn automatic tabbing off so no
11969        // tab bar, "+" button, or dead tab menu items appear (docs/windows.md).
11970        if day_core::windows::new_window_action_id() == 0
11971            && options.tabbing == day_spec::WindowTabbing::Automatic
11972        {
11973            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
11974        }
11975        // The DEFAULT menu bar was built before `root()` ran, so its registration-dependent
11976        // items — Settings…/⌘, and File ▸ New Window — could not exist yet. Rebuild it now that
11977        // they can. An app with its own `app_menu` model already replaced the whole bar and
11978        // gets its items through the injection path instead.
11979        if !day_core::has_app_menu() {
11980            install_main_menu(mtm, &app, &app_name);
11981        }
11982
11983        // Reopen where the user left it (docs/windows.md). AppKit persists the frame under an
11984        // autosave name and hands it back on request; `setFrameUsingName` answers false the
11985        // first time, which is when centering is the right answer.
11986        //
11987        // NOT while a dayscript is driving or `DAY_WINDOW` has forced a size: a restored frame
11988        // would make every captured screenshot's dimensions depend on where the developer last
11989        // dragged the window, and the capture suites compare those across machines.
11990        let deterministic =
11991            std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
11992        let autosave = NSString::from_str("day.main");
11993        if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
11994            window.center();
11995            // An explicit placement wins over centering, but not over the frame the user left.
11996            window_chrome::place(&window, options.placement);
11997        }
11998        // A scripted run whose capture needs a display scale this host's displays lack opens on
11999        // the one `day launch` made for it (`DAY_WINDOW_SCREEN`, a CGDirectDisplayID): a
12000        // capture is the window server's pixels, so it has the scale of the display under it.
12001        if let Some(screen) = capture_screen(mtm) {
12002            let (visible, frame) = (screen.visibleFrame(), window.frame());
12003            window.setFrameOrigin(NSPoint::new(
12004                visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12005                visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
12006            ));
12007        }
12008        if !deterministic {
12009            unsafe { window.setFrameAutosaveName(&autosave) };
12010        }
12011        if !options.start_hidden {
12012            window.makeKeyAndOrderFront(None);
12013            app.activate();
12014        }
12015        // The root was mounted before the window was shown (ready() runs first), and on
12016        // macOS 26 layer displays requested pre-run are dropped for a window ordered front
12017        // before the app finishes launching — the window stays blank until the next real
12018        // event. Re-mark the whole tree so the first run-loop turn commits a full frame.
12019        if let Some(content) = window.contentView() {
12020            mark_tree_needs_display(&content);
12021        }
12022        if std::env::var_os("DAY_DUMP").is_some() {
12023            std::thread::spawn(|| {
12024                std::thread::sleep(std::time::Duration::from_millis(2000));
12025                Self::post(Box::new(|| {
12026                    // The primary's content specifically (docs/windows.md).
12027                    if let Some(content) = primary_content() {
12028                        let desc: Retained<NSString> =
12029                            unsafe { msg_send![&*content, _subtreeDescription] };
12030                        log::warn!("{desc}");
12031                    }
12032                }));
12033            });
12034        }
12035        app.run();
12036    }
12037
12038    fn post(f: Box<dyn FnOnce() + Send>) {
12039        // Posted-closure trampoline (§8.5): the closure runs inside dispatch's C frame, so a
12040        // panic is contained here rather than unwinding into libdispatch.
12041        dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
12042    }
12043
12044    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
12045        // The timer door behind `day::sleep` (docs/async.md): `dispatch_after` on the main
12046        // queue, so a sleep is a dispatch timer rather than a parked helper thread. Contained
12047        // like `post`. A delay too large for dispatch's clock runs at the far horizon instead.
12048        let when =
12049            dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
12050                .unwrap_or(dispatch2::DispatchTime::FOREVER);
12051        if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
12052            ffi_guard::contain((), f);
12053        }) {
12054            log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
12055        }
12056    }
12057
12058    fn locale_hints(&self) -> Vec<String> {
12059        // The user's ordered language preference from Settings ("fr-FR", "en-US", …), which is
12060        // the ambient locale Day negotiates its catalogs against (§12.2, docs/localization.md).
12061        objc2_foundation::NSLocale::preferredLanguages()
12062            .iter()
12063            .map(|s| s.to_string())
12064            .collect()
12065    }
12066}
12067
12068// `CGWindowListCreateImage` is obsoleted as of the macOS 15 SDK (ScreenCaptureKit is the
12069// sanctioned replacement) but still resolves and answers on macOS 26. It is declared here rather
12070// than taken from a binding because the availability attribute would refuse the call outright,
12071// and every use below treats a NULL return as "ask the offscreen path instead".
12072unsafe extern "C" {
12073    fn CGWindowListCreateImage(
12074        bounds: objc2_core_foundation::CGRect,
12075        list_option: u32,
12076        window_id: u32,
12077        image_option: u32,
12078    ) -> *mut objc2_core_graphics::CGImage;
12079}
12080
12081/// kCGWindowListOptionIncludingWindow — composite only this window, so whatever is stacked over
12082/// it (another app, a CI runner's stray window) cannot appear in the capture.
12083const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
12084/// kCGWindowImageBoundsIgnoreFraming — the window's own frame, without its drop shadow, which
12085/// makes the returned image exactly `window.frame()` at the backing scale.
12086const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
12087
12088/// Encode a captured rep as PNG, in sRGB.
12089///
12090/// A capture arrives in the color space of the display it was composited for, and a PNG of it
12091/// embeds that display's ICC profile: the same color then has different sample values on every
12092/// machine, and on every other Day target, which all capture sRGB. Converting first makes a
12093/// macOS capture's samples comparable with theirs and independent of the capturing display.
12094fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
12095    let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
12096        &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
12097        objc2_app_kit::NSColorRenderingIntent::Default,
12098    );
12099    let rep = srgb.as_deref().unwrap_or(rep);
12100    let data = unsafe {
12101        rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
12102    }
12103    .ok_or("png encode failed")?;
12104    Ok(data.to_vec())
12105}
12106
12107/// Capture `content` by asking the WINDOW SERVER for the composited window and cropping to it.
12108///
12109/// This exists because an offscreen render cannot draw macOS's own materials. As of macOS 26 a
12110/// sidebar `NSSplitViewItem` is a Liquid Glass surface the window server composites from what is
12111/// behind it; `cacheDisplayInRect` has no backdrop to sample, so it renders the sidebar as an
12112/// opaque white slab with none of its rows in it — every macos-appkit gallery shot had a blank
12113/// sidebar. The window server has the real pixels, including the rows.
12114///
12115/// It answers only while the window is actually on screen. A hidden, minimized or
12116/// never-composited window has no image to hand back (verified: hiding the app makes this return
12117/// NULL while the offscreen path still produces a frame), so this returns `Err` and the caller
12118/// falls back rather than failing the capture.
12119fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
12120    let window = content.window().ok_or("view is not in a window")?;
12121    // An attached sheet is the active modal surface and has its own composited window.
12122    // Capturing only the parent's window would show dimmed content without the modal UI.
12123    if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
12124        return snapshot_via_window_server(&sheet, chrome);
12125    }
12126    let number = window.windowNumber();
12127    if number <= 0 {
12128        return Err(format!("window {number} is not on screen"));
12129    }
12130    // The server hands back the frame it last COMPOSITED, which is the previous one whenever the
12131    // app has changed the view tree since. A capture taken right after a state change then shows
12132    // the state before it — a `when` whose outgoing arm is already gone from the tree and from the
12133    // view hierarchy still appears in the image, so a walkthrough asserting on pixels reads a
12134    // stale frame as "the change did not happen". Push the pending work out first: lay out, draw,
12135    // then commit the layer tree to the render server.
12136    unsafe { content.layoutSubtreeIfNeeded() };
12137    window.displayIfNeeded();
12138    CATransaction::flush();
12139    // CGRectNull asks for the window's own bounds rather than a screen region.
12140    let null_rect = objc2_core_foundation::CGRect::new(
12141        objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
12142        objc2_core_foundation::CGSize::new(0.0, 0.0),
12143    );
12144    let shot = unsafe {
12145        CGWindowListCreateImage(
12146            null_rect,
12147            CG_WINDOW_LIST_INCLUDING_WINDOW,
12148            number as u32,
12149            CG_WINDOW_IMAGE_IGNORE_FRAMING,
12150        )
12151    };
12152    if shot.is_null() {
12153        return Err("the window server has no image for this window".into());
12154    }
12155    // SAFETY: non-NULL CGImageRef owned by this call (Create rule); CFRetained takes that
12156    // ownership over, so it is released exactly once.
12157    let shot = unsafe {
12158        objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
12159    };
12160
12161    // A chrome capture is the window image as the server composited it — titlebar, toolbar and
12162    // rounded corners included — so it is done here, before the crop.
12163    if chrome {
12164        let rep = unsafe {
12165            objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12166                objc2_app_kit::NSBitmapImageRep::alloc(),
12167                &shot,
12168            )
12169        };
12170        return png_of_rep(&rep);
12171    }
12172
12173    // Crop the window frame down to the content view. Keeping the framing identical to the
12174    // offscreen path is the point: the titlebar has never been part of a Day capture, and every
12175    // published gallery shot would otherwise change size.
12176    let frame = window.frame();
12177    if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
12178        return Err("zero-size window".into());
12179    }
12180    let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
12181    // Cocoa rects are bottom-left origin; a CGImage's are top-left, so the content's distance
12182    // from the window top is what the crop needs.
12183    let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
12184    let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
12185    let crop = objc2_core_foundation::CGRect::new(
12186        objc2_core_foundation::CGPoint::new(
12187            (in_window.origin.x * scale).round(),
12188            (from_top * scale).round(),
12189        ),
12190        objc2_core_foundation::CGSize::new(
12191            (in_window.size.width * scale).round(),
12192            (in_window.size.height * scale).round(),
12193        ),
12194    );
12195    let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
12196        .ok_or("crop to the content view failed")?;
12197    let rep = unsafe {
12198        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12199            objc2_app_kit::NSBitmapImageRep::alloc(),
12200            &cropped,
12201        )
12202    };
12203    png_of_rep(&rep)
12204}
12205
12206/// Capture a window content view as PNG (the dayscript screenshot seam, §14).
12207///
12208/// The window server first, because it is the only one of the two that can show macOS's own
12209/// composited materials; the offscreen render when it declines, because it is the only one of the
12210/// two that works with no window on screen. See each for why.
12211/// Put a [`Transform`] on a view through its own geometry rather than its layer: the frame is
12212/// the laid-out `base` scaled about its center and moved by the translation, the bounds keep the
12213/// laid-out size (so the content draws at the scale), and the rotation is the frame's center
12214/// rotation (positive is clockwise on screen: Day's parents are flipped, y down).
12215fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
12216    let [x, y, w, h] = base;
12217    let (sw, sh) = (w * t.sx, h * t.sy);
12218    let frame = NSRect::new(
12219        NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
12220        NSSize::new(sw, sh),
12221    );
12222    unsafe {
12223        // The rotation goes first and comes back last: a rotated view's frame is its bounding
12224        // box, so setting the frame of a rotated view would scale it.
12225        v.setFrameCenterRotation(0.0);
12226        v.setFrame(frame);
12227        v.setBoundsSize(NSSize::new(w, h));
12228        if t.rotate_deg != 0.0 {
12229            v.setFrameCenterRotation(t.rotate_deg);
12230        }
12231    }
12232}
12233
12234fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
12235    let modal = content
12236        .window()
12237        .and_then(|w| w.attachedSheet())
12238        .and_then(|s| s.contentView());
12239    let content = modal.as_deref().unwrap_or(content);
12240    match snapshot_via_window_server(content, false) {
12241        Ok(bytes) => Ok(bytes),
12242        Err(_) => snapshot_view_cache(content),
12243    }
12244}
12245
12246/// Capture a window *with* its chrome — the titlebar and toolbar the content capture crops away
12247/// (`day::window_image().chrome()`, docs/window-image.md).
12248///
12249/// Only the window server can produce this: the offscreen path renders the content view's own
12250/// hierarchy, which the titlebar is not part of. When it declines (an offscreen or hidden window)
12251/// the content capture stands in — a smaller image beats no image, and it is what the caller
12252/// would have got from the plain duty.
12253fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
12254    let modal = content
12255        .window()
12256        .and_then(|w| w.attachedSheet())
12257        .and_then(|s| s.contentView());
12258    let content = modal.as_deref().unwrap_or(content);
12259    match snapshot_via_window_server(content, true) {
12260        Ok(bytes) => Ok(bytes),
12261        Err(_) => snapshot_view_cache(content),
12262    }
12263}
12264
12265/// The offscreen fallback: `cacheDisplayInRect` over a window-background pre-fill resolved for
12266/// the view's light/dark appearance. Renders the view hierarchy Day drew, and nothing the window
12267/// server composites (see `snapshot_via_window_server`).
12268fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
12269    let bounds = content.bounds();
12270    let rep =
12271        unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
12272    // Day containers are transparent (the window server paints the backdrop), so pre-fill
12273    // the rep with the window background — resolved for the window's light/dark appearance —
12274    // before compositing the view hierarchy over it (§14).
12275    let ctx =
12276        NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
12277    NSGraphicsContext::saveGraphicsState_class();
12278    NSGraphicsContext::setCurrentContext(Some(&ctx));
12279    content
12280        .effectiveAppearance()
12281        .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
12282            NSColor::windowBackgroundColor().setFill();
12283            objc2_app_kit::NSRectFill(bounds);
12284        }));
12285    NSGraphicsContext::restoreGraphicsState_class();
12286    unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
12287    png_of_rep(&rep)
12288}
12289
12290/// The screen a scripted run asked to open on: `DAY_WINDOW_SCREEN`, the CGDirectDisplayID of the
12291/// capture display `day launch --script` provides when no attached display has the capture's
12292/// scale. `None` when unset or when no screen has that id, which leaves the window where it was.
12293/// Center `window` on `primary`'s screen when `center` put it on another, as high as `center`
12294/// places a window (a third of the free height above it, two below).
12295fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
12296    let Some(screen) = primary.and_then(|w| w.screen()) else {
12297        return;
12298    };
12299    if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
12300        return;
12301    }
12302    let (visible, frame) = (screen.visibleFrame(), window.frame());
12303    window.setFrameOrigin(NSPoint::new(
12304        visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12305        visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
12306    ));
12307}
12308
12309fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
12310    let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
12311        .ok()?
12312        .trim()
12313        .parse()
12314        .ok()?;
12315    let key = NSString::from_str("NSScreenNumber");
12316    objc2_app_kit::NSScreen::screens(mtm)
12317        .into_iter()
12318        .find(|screen| {
12319            let number: Option<Retained<objc2_foundation::NSNumber>> =
12320                unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
12321            number.is_some_and(|n| n.unsignedIntValue() == wanted)
12322        })
12323}
12324
12325/// Recursively mark a view tree as needing display (startup first-frame fix, see `run`).
12326fn mark_tree_needs_display(view: &NSView) {
12327    view.setNeedsDisplay(true);
12328    for sub in view.subviews() {
12329        mark_tree_needs_display(&sub);
12330    }
12331}
12332
12333/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
12334/// macOS has no true background/foreground or memory-warning lifecycle. `const` so
12335/// `day::require_lifecycle!` can reject unsupported phases at compile time. Must agree with the
12336/// `Toolkit::supports_lifecycle` default (which also returns `is_universal`).
12337pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
12338    phase.is_universal()
12339}
12340
12341/// Follow the SYSTEM appearance while the app runs: macOS posts the distributed
12342/// "AppleInterfaceThemeChangedNotification" on a theme switch, and AppKit updates
12343/// `effectiveAppearance` just after — so re-read on the next main-queue turn and refresh
12344/// day-core's reactive dark-mode signal (palette closures recolor live instead of going
12345/// stale until the next rebuild). The token is leaked to observe for the app's lifetime.
12346fn install_appearance_observer() {
12347    use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
12348    let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
12349    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12350        dispatch2::DispatchQueue::main()
12351            .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
12352    });
12353    let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
12354    let token = unsafe {
12355        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
12356    };
12357    std::mem::forget(token);
12358}
12359
12360/// Follow the SYSTEM reduce-motion switch while the app runs: NSWorkspace posts
12361/// `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification` on its own notification
12362/// center when any Accessibility › Display option flips, and
12363/// `accessibilityDisplayShouldReduceMotion` already answers the new value by then. The
12364/// notification arrives on the main thread; the main-queue hop keeps the re-read off the
12365/// poster's stack, as the appearance observer does. The token is leaked to observe for the
12366/// app's lifetime.
12367fn install_reduce_motion_observer() {
12368    use objc2_foundation::NSNotification;
12369    let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
12370    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12371        dispatch2::DispatchQueue::main()
12372            .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
12373    });
12374    let token = unsafe {
12375        center.addObserverForName_object_queue_usingBlock(
12376            Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
12377            None,
12378            None,
12379            &block,
12380        )
12381    };
12382    std::mem::forget(token);
12383}
12384
12385/// Bridge the NSApplication activation/termination notifications to day lifecycle events
12386/// (docs/lifecycle.md). The observer tokens are leaked to live for the whole app.
12387fn install_lifecycle_observers() {
12388    use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
12389    let center = unsafe { NSNotificationCenter::defaultCenter() };
12390    let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
12391        let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12392            ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
12393        });
12394        let token = unsafe {
12395            center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
12396        };
12397        std::mem::forget(token); // observe for the app's lifetime
12398    };
12399    unsafe {
12400        observe(
12401            NSApplicationDidBecomeActiveNotification,
12402            day_spec::Lifecycle::DidBecomeActive,
12403        );
12404        observe(
12405            NSApplicationWillResignActiveNotification,
12406            day_spec::Lifecycle::WillResignActive,
12407        );
12408        observe(
12409            NSApplicationWillTerminateNotification,
12410            day_spec::Lifecycle::WillTerminate,
12411        );
12412        // `terminate:` exits the process from inside the run loop, so the loop never returns to
12413        // `launch_with`: the last Day code to run is this notification's second observer, which
12414        // NSNotificationCenter calls after the first (docs/lifecycle.md).
12415        observe(
12416            NSApplicationWillTerminateNotification,
12417            day_spec::Lifecycle::DidExit,
12418        );
12419    }
12420}
12421
12422day_localization_ui::locales!();
12423
12424/// Shared by the initial menu and every reactive replacement. AppKit owns Services
12425/// and the hide actions; these commands must not depend on a window or app callback.
12426fn install_application_menu(
12427    mtm: MainThreadMarker,
12428    menubar: &NSMenu,
12429    title: &str,
12430    about: Option<day_spec::MenuItem>,
12431    updates: Option<day_spec::MenuItem>,
12432    prefs: Option<day_spec::MenuItem>,
12433    quit: Option<day_spec::MenuItem>,
12434) -> Retained<NSMenu> {
12435    let app = NSApplication::sharedApplication(mtm);
12436    use day_spec::{MenuItem as M, MenuRole as R};
12437    let standard = |role, label| M::Action {
12438        id: None,
12439        action: 0,
12440        label,
12441        shortcut: None,
12442        enabled: true,
12443        checked: None,
12444        role: Some(role),
12445        icon: None,
12446    };
12447    let mut about =
12448        about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
12449    let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
12450    for (item, title) in [
12451        (&mut about, res::str::about_app(title).format()),
12452        (&mut quit, res::str::quit_app(title).format()),
12453    ] {
12454        if let M::Action { label, .. } = item {
12455            *label = title;
12456        }
12457    }
12458    // A registered Day About (docs/settings.md) replaces the stock Info.plist panel: the
12459    // item fires the dispatch action instead of `orderFrontStandardAboutPanel:`.
12460    if let M::Action { action, .. } = &mut about
12461        && *action == 0
12462    {
12463        *action = day_core::windows::about_action_id();
12464    }
12465    // Check for Updates… sits directly under About (the Sparkle convention), whether the app
12466    // placed the role itself or the updater only registered its action.
12467    let updates_id = day_core::windows::check_for_updates_action_id();
12468    let updates = updates.or_else(|| {
12469        (updates_id != 0).then(|| {
12470            standard(
12471                R::CheckForUpdates,
12472                day_localization::t(day_localization::key::day_check_for_updates),
12473            )
12474        })
12475    });
12476    let mut head = vec![about];
12477    if let Some(mut updates) = updates {
12478        if let M::Action { action, .. } = &mut updates
12479            && *action == 0
12480        {
12481            *action = updates_id;
12482        }
12483        head.push(updates);
12484    }
12485    head.push(M::Separator);
12486    let menu = build_ns_menu(mtm, title, &head);
12487    if let Some(mut prefs) = prefs {
12488        if let M::Action { label, .. } = &mut prefs {
12489            *label = res::str::settings().format();
12490        }
12491        let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
12492        for item in section.itemArray() {
12493            section.removeItem(&item);
12494            menu.addItem(&item);
12495        }
12496    }
12497    // AppKit keeps the registered Services menu across main-menu replacements.
12498    // Move that same menu to the new bar rather than abandoning its system-populated items.
12499    let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
12500    if let Some(parent) = unsafe { services.supermenu() } {
12501        let index = parent.indexOfItemWithSubmenu(Some(&services));
12502        if index >= 0 {
12503            parent.itemAtIndex(index).unwrap().setSubmenu(None);
12504        }
12505    }
12506    let services_item = NSMenuItem::new(mtm);
12507    services_item.setTitle(&NSString::from_str(&res::str::services().format()));
12508    services_item.setSubmenu(Some(&services));
12509    menu.addItem(&services_item);
12510    menu.addItem(&NSMenuItem::separatorItem(mtm));
12511    for (label, selector, shortcut) in [
12512        (
12513            res::str::hide_app(title).format(),
12514            sel!(hide:),
12515            Some(day_spec::Shortcut::primary("h")),
12516        ),
12517        (
12518            res::str::hide_others().format(),
12519            sel!(hideOtherApplications:),
12520            Some(day_spec::Shortcut::primary("h").alt()),
12521        ),
12522        (
12523            res::str::show_all().format(),
12524            sel!(unhideAllApplications:),
12525            None,
12526        ),
12527    ] {
12528        let item = unsafe {
12529            NSMenuItem::initWithTitle_action_keyEquivalent(
12530                NSMenuItem::alloc(mtm),
12531                &NSString::from_str(&label),
12532                Some(selector),
12533                &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
12534            )
12535        };
12536        if let Some(shortcut) = shortcut {
12537            item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
12538        }
12539        // Explicitly target the application so window responders cannot override Hide.
12540        unsafe { item.setTarget(Some(&app)) };
12541        menu.addItem(&item);
12542    }
12543    menu.addItem(&NSMenuItem::separatorItem(mtm));
12544    let section = build_ns_menu(mtm, title, &[quit]);
12545    let quit = section.itemAtIndex(0).unwrap();
12546    section.removeItem(&quit);
12547    menu.addItem(&quit);
12548    let item = NSMenuItem::new(mtm);
12549    item.setSubmenu(Some(&menu));
12550    menubar.addItem(&item);
12551    services
12552}
12553
12554/// The default main menu (§21.2 M2): standard application menu; Edit menu wired to the responder
12555/// chain so Cmd+C/V/X/A work in NSTextFields; Window menu basics.
12556fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
12557    let menubar = NSMenu::new(mtm);
12558
12559    let prefs_id = day_core::windows::preferences_action_id();
12560    let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
12561        id: None,
12562        action: prefs_id,
12563        label: res::str::settings().format(),
12564        shortcut: None,
12565        enabled: true,
12566        checked: None,
12567        role: Some(day_spec::MenuRole::Preferences),
12568        icon: None,
12569    });
12570    let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
12571
12572    // File ▸ New Window / Close, when the app registered a new-window builder — the same
12573    // zero-menu-code rule as Settings…/⌘, above (docs/windows.md). Without this an app that
12574    // never calls `app_menu` gets the tab-bar "+" and the Window menu's tab commands but no
12575    // File ▸ New Window, because the default menu bar has no File menu to put it in.
12576    let new_window_id = day_core::windows::new_window_action_id();
12577    if new_window_id != 0 {
12578        let file_item = NSMenuItem::new(mtm);
12579        let file_menu = unsafe {
12580            NSMenu::initWithTitle(
12581                NSMenu::alloc(mtm),
12582                &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
12583            )
12584        };
12585        let new_window = unsafe {
12586            NSMenuItem::initWithTitle_action_keyEquivalent(
12587                NSMenuItem::alloc(mtm),
12588                &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
12589                Some(sel!(fire:)),
12590                &NSString::from_str("n"),
12591            )
12592        };
12593        let target = menu_target(mtm);
12594        let tobj: &objc2::runtime::AnyObject = target.as_ref();
12595        unsafe { new_window.setTarget(Some(tobj)) };
12596        new_window.setTag(new_window_id as isize);
12597        file_menu.addItem(&new_window);
12598        file_menu.addItem(&NSMenuItem::separatorItem(mtm));
12599        // Nil-targeted, so it closes whatever window is key — the standard responder route.
12600        let close = unsafe {
12601            NSMenuItem::initWithTitle_action_keyEquivalent(
12602                NSMenuItem::alloc(mtm),
12603                &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
12604                Some(sel!(performClose:)),
12605                &NSString::from_str("w"),
12606            )
12607        };
12608        file_menu.addItem(&close);
12609        file_item.setSubmenu(Some(&file_menu));
12610        menubar.addItem(&file_item);
12611    }
12612
12613    let edit_item = NSMenuItem::new(mtm);
12614    let edit_menu = unsafe {
12615        NSMenu::initWithTitle(
12616            NSMenu::alloc(mtm),
12617            &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
12618        )
12619    };
12620    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12621        let item = unsafe {
12622            NSMenuItem::initWithTitle_action_keyEquivalent(
12623                NSMenuItem::alloc(mtm),
12624                &NSString::from_str(&day_localization::t(key)),
12625                Some(action),
12626                &NSString::from_str(accel),
12627            )
12628        };
12629        edit_menu.addItem(&item);
12630    };
12631    add("day_undo", sel!(undo:), "z");
12632    add("day_redo", sel!(redo:), "Z");
12633    edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
12634    add("day_cut", sel!(cut:), "x");
12635    add("day_copy", sel!(copy:), "c");
12636    add("day_paste", sel!(paste:), "v");
12637    add("day_select_all", sel!(selectAll:), "a");
12638    edit_item.setSubmenu(Some(&edit_menu));
12639    menubar.addItem(&edit_item);
12640
12641    install_windows_menu(mtm, app, &menubar);
12642
12643    app.setMainMenu(Some(&menubar));
12644    unsafe { app.setServicesMenu(Some(&services)) };
12645}
12646
12647/// The standard Window menu (docs/windows.md): Minimize ⌘M / Zoom / Bring All to Front,
12648/// registered as `NSApp.windowsMenu` — AppKit then appends the open-window list and, with
12649/// tabbing live, the tab commands (Show Next/Previous Tab, Merge All Windows) itself. All
12650/// nav hosts are nil-targeted (responder chain), so they act on the key window.
12651fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
12652    let menu = unsafe {
12653        NSMenu::initWithTitle(
12654            NSMenu::alloc(mtm),
12655            &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
12656        )
12657    };
12658    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12659        let item = unsafe {
12660            NSMenuItem::initWithTitle_action_keyEquivalent(
12661                NSMenuItem::alloc(mtm),
12662                &NSString::from_str(&day_localization::t(key)),
12663                Some(action),
12664                &NSString::from_str(accel),
12665            )
12666        };
12667        menu.addItem(&item);
12668    };
12669    add("day_minimize", sel!(performMiniaturize:), "m");
12670    add("day_zoom", sel!(performZoom:), "");
12671    menu.addItem(&NSMenuItem::separatorItem(mtm));
12672    add("day_bring_all_front", sel!(arrangeInFront:), "");
12673    let item = NSMenuItem::new(mtm);
12674    item.setTitle(&NSString::from_str(&day_localization::t(
12675        day_localization::key::day_window,
12676    )));
12677    item.setSubmenu(Some(&menu));
12678    menubar.addItem(&item);
12679    unsafe { app.setWindowsMenu(Some(&menu)) };
12680}
12681
12682/// Hoist application roles even from nested menus. First declaration wins; remove
12683/// duplicates and empty containers, then normalize separators left by the move.
12684fn extract_app_role(
12685    items: &mut Vec<day_spec::MenuItem>,
12686    role: day_spec::MenuRole,
12687) -> Option<day_spec::MenuItem> {
12688    use day_spec::MenuItem as M;
12689    let mut found = None;
12690    let mut remaining = Vec::new();
12691    for mut item in items.drain(..) {
12692        match &mut item {
12693            M::Action { role: Some(r), .. } if *r == role => {
12694                found.get_or_insert(item);
12695                continue;
12696            }
12697            M::Submenu { items, .. } => {
12698                let nested = extract_app_role(items, role);
12699                if found.is_none() {
12700                    found = nested;
12701                }
12702                if items.is_empty() {
12703                    continue;
12704                }
12705            }
12706            M::Separator
12707                if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
12708            {
12709                continue;
12710            }
12711            _ => {}
12712        }
12713        remaining.push(item);
12714    }
12715    while matches!(remaining.last(), Some(M::Separator)) {
12716        remaining.pop();
12717    }
12718    *items = remaining;
12719    found
12720}
12721
12722/// Whether any action in the model (recursively) carries `role`.
12723fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
12724    items.iter().any(|it| match it {
12725        day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
12726        day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
12727        day_spec::MenuItem::Separator => false,
12728    })
12729}
12730
12731// ---------------------------------------------------------------------------
12732// Menus (§ menus): render day's MenuItem model with NSMenu. Custom items route to a shared
12733// DayMenuTarget (id in the item's tag → Event::MenuAction); role items use the native selector.
12734// ---------------------------------------------------------------------------
12735
12736define_class!(
12737    #[unsafe(super(NSObject))]
12738    #[thread_kind = MainThreadOnly]
12739    #[name = "DayMenuTarget"]
12740    #[ivars = ()]
12741    struct DayMenuTarget;
12742
12743    unsafe impl NSObjectProtocol for DayMenuTarget {}
12744
12745    impl DayMenuTarget {
12746        #[unsafe(method(fire:))]
12747        fn fire(&self, sender: &NSMenuItem) {
12748            ffi_guard::contain((), || {
12749                let id = sender.tag() as u64;
12750                if id != 0 {
12751                    emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
12752                }
12753            })
12754        }
12755    }
12756);
12757
12758/// The primary window's content view (set once in `run`).
12759/// Pin the window's content coordinate space under its title bar and toolbar (§7.7). The
12760/// content view is full-size (`FullSizeContentView`, for the unified toolbar), so it runs
12761/// beneath the bar; moving its bounds origin up by that strip makes Day's root, laid out from
12762/// (0, 0), start below the bar — the way UIKit pins the root inside `safeAreaInsets` — while
12763/// the view's own background still paints edge to edge. Returns the size Day lays out at, the
12764/// window's `contentLayoutRect`. Called wherever that rect can change: window creation, every
12765/// resize, and a toolbar coming or going.
12766pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
12767    let content = window.contentView()?;
12768    let full = content.frame().size;
12769    let layout = unsafe { window.contentLayoutRect() }.size;
12770    let top = (full.height - layout.height).max(0.0);
12771    // An overlay title bar (docs/window-chrome.md) is the one place the content belongs under
12772    // the bar: it keeps the full height, and the bar's height goes to the app as a safe-area
12773    // inset so it can pad its own content.
12774    if window_chrome::is_overlay(window) {
12775        unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
12776        window_chrome::report_title_bar_inset(window, top);
12777        return Some(Size::new(full.width, full.height));
12778    }
12779    unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
12780    Some(Size::new(full.width, (full.height - top).max(0.0)))
12781}
12782
12783/// The text a widget displays, for `read_native`: a label's or text field's string, a
12784/// button's title, a text area's contents. `None` for a secure field (it masks its text), an
12785/// icon-only button (its title is a tooltip), and every other view.
12786fn native_text(h: &NSView) -> Option<String> {
12787    if h.downcast_ref::<NSSecureTextField>().is_some() {
12788        return None;
12789    }
12790    if let Some(tf) = h.downcast_ref::<NSTextField>() {
12791        // `stringValue` answers the field editor's live text while the field edits.
12792        return Some(tf.stringValue().to_string());
12793    }
12794    if let Some(btn) = h.downcast_ref::<NSButton>() {
12795        if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
12796            return None;
12797        }
12798        return Some(btn.title().to_string());
12799    }
12800    // A text area is an NSTextView inside the scroll view its handle names (textarea.rs).
12801    let sv = h.downcast_ref::<NSScrollView>()?;
12802    let doc = sv.documentView()?;
12803    let tv = doc.downcast_ref::<NSTextView>()?;
12804    Some(tv.string().to_string())
12805}
12806
12807/// A slider's value or a determinate progress bar's fraction, for `read_native`. Both native
12808/// ranges are the ones Day gave: the slider is built with Day's min and max, the bar runs 0–1.
12809fn native_number(h: &NSView) -> Option<f64> {
12810    if let Some(sl) = h.downcast_ref::<NSSlider>() {
12811        return Some(sl.doubleValue());
12812    }
12813    let pi = h.downcast_ref::<NSProgressIndicator>()?;
12814    (!pi.isIndeterminate()).then(|| pi.doubleValue())
12815}
12816
12817/// The view's frame in its window's content coordinates, origin top left, for `read_native`.
12818/// The content view is flipped and pinned below the title bar (`pin_below_title_bar`), so
12819/// converting into it gives Day's layout space; an unflipped content view is flipped here.
12820fn native_frame(h: &NSView) -> Option<Rect> {
12821    let content = h.window()?.contentView()?;
12822    let r = h.convertRect_toView(h.bounds(), Some(&content));
12823    let y = if content.isFlipped() {
12824        r.origin.y
12825    } else {
12826        let b = content.bounds();
12827        b.origin.y + b.size.height - (r.origin.y + r.size.height)
12828    };
12829    Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
12830}
12831
12832/// The strip a pinned content view keeps above its layout origin (see `pin_below_title_bar`).
12833fn title_bar_inset(content: &NSView) -> f64 {
12834    (-content.bounds().origin.y).max(0.0)
12835}
12836
12837fn primary_content() -> Option<Retained<NSView>> {
12838    PRIMARY_CONTENT.with(|c| c.borrow().clone())
12839}
12840
12841fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
12842    MENU_TARGET.with(|t| {
12843        t.borrow_mut()
12844            .get_or_insert_with(|| {
12845                let this = DayMenuTarget::alloc(mtm).set_ivars(());
12846                let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
12847                obj
12848            })
12849            .clone()
12850    })
12851}
12852
12853fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
12854    use objc2_app_kit::NSEventModifierFlags as F;
12855    let mut m = F::empty();
12856    if s.primary {
12857        m |= F::Command;
12858    }
12859    if s.shift {
12860        m |= F::Shift;
12861    }
12862    if s.alt {
12863        m |= F::Option;
12864    }
12865    if s.control {
12866        m |= F::Control;
12867    }
12868    m
12869}
12870
12871/// A shortcut's key-equivalent string. Single chars pass through (lowercased); a few named keys map
12872/// to their control characters. Modifiers ride separately via `setKeyEquivalentModifierMask`.
12873fn ns_key_equivalent(key: &str) -> String {
12874    match key {
12875        "Return" | "Enter" => "\r".into(),
12876        "Tab" => "\t".into(),
12877        "Delete" | "Backspace" => "\u{8}".into(),
12878        "Escape" => "\u{1b}".into(),
12879        "Space" => " ".into(),
12880        k if k.chars().count() == 1 => k.to_lowercase(),
12881        _ => String::new(), // named keys we don't map get no key-equivalent (still shown in menu)
12882    }
12883}
12884
12885/// A standard role → (default label, nav host, default shortcut). Nav host `None` = no native action
12886/// (the app should attach its own via a custom item); the role then only supplies label placement.
12887fn role_spec(
12888    role: day_spec::MenuRole,
12889) -> (
12890    &'static str,
12891    Option<objc2::runtime::Sel>,
12892    Option<day_spec::Shortcut>,
12893) {
12894    use day_spec::MenuRole as R;
12895    use day_spec::Shortcut as S;
12896    match role {
12897        R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
12898        R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
12899        R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
12900        R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
12901        R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
12902        R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
12903        R::Delete => ("Delete", Some(sel!(delete:)), None),
12904        R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
12905        R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
12906        R::Preferences => ("Settings…", None, Some(S::primary(","))),
12907        R::Minimize => (
12908            "Minimize",
12909            Some(sel!(performMiniaturize:)),
12910            Some(S::primary("m")),
12911        ),
12912        R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
12913        R::Fullscreen => (
12914            "Enter Full Screen",
12915            Some(sel!(toggleFullScreen:)),
12916            Some(S::primary("f").control()),
12917        ),
12918        // No native selector (docs/windows.md): the item dispatches the registered
12919        // new-window action through the ordinary custom-item path (`fire:`).
12920        R::NewWindow => ("New Window", None, Some(S::primary("n"))),
12921        // Likewise: no selector, the registered updater action fires through `fire:`.
12922        R::CheckForUpdates => ("Check for Updates…", None, None),
12923    }
12924}
12925
12926pub(crate) fn build_ns_menu(
12927    mtm: MainThreadMarker,
12928    title: &str,
12929    items: &[day_spec::MenuItem],
12930) -> Retained<NSMenu> {
12931    use day_spec::MenuItem as MI;
12932    let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
12933    let target = menu_target(mtm);
12934    for item in items {
12935        match item {
12936            MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
12937            MI::Submenu { label, items, .. } => {
12938                let sub = build_ns_menu(mtm, label, items);
12939                let it = NSMenuItem::new(mtm);
12940                it.setTitle(&NSString::from_str(label));
12941                it.setSubmenu(Some(&sub));
12942                menu.addItem(&it);
12943            }
12944            MI::Action {
12945                action,
12946                label,
12947                shortcut,
12948                enabled,
12949                checked,
12950                role,
12951                icon,
12952                ..
12953            } => {
12954                // Resolve label/nav host/shortcut, folding in the role's native defaults.
12955                let (mut lbl, sel, mut sc) = match role {
12956                    Some(r) => {
12957                        let (dl, ds, dsc) = role_spec(*r);
12958                        (dl.to_string(), ds, dsc)
12959                    }
12960                    None => (String::new(), None, None),
12961                };
12962                if !label.is_empty() {
12963                    lbl = label.clone();
12964                }
12965                if shortcut.is_some() {
12966                    sc = shortcut.clone();
12967                }
12968                // Custom action (nonzero id) overrides any role nav host and targets our
12969                // trampoline — except the responder-routed set (undo pair, clipboard trio),
12970                // whose nonzero ids are only the other platforms' fallback dispatchers: here
12971                // the nil-target nav hosts must stay, so the responder chain resolves the
12972                // acting object (a focused text field before the app's bridge).
12973                let responder_role = matches!(
12974                    role,
12975                    Some(
12976                        day_spec::MenuRole::Undo
12977                            | day_spec::MenuRole::Redo
12978                            | day_spec::MenuRole::Cut
12979                            | day_spec::MenuRole::Copy
12980                            | day_spec::MenuRole::Paste
12981                            | day_spec::MenuRole::SelectAll
12982                    )
12983                );
12984                let custom = *action != 0 && !responder_role;
12985                let key = sc
12986                    .as_ref()
12987                    .map(|s| ns_key_equivalent(&s.key))
12988                    .unwrap_or_default();
12989                let it = unsafe {
12990                    NSMenuItem::initWithTitle_action_keyEquivalent(
12991                        NSMenuItem::alloc(mtm),
12992                        &NSString::from_str(&lbl),
12993                        if custom { Some(sel!(fire:)) } else { sel },
12994                        &NSString::from_str(&key),
12995                    )
12996                };
12997                if let Some(s) = &sc {
12998                    it.setKeyEquivalentModifierMask(ns_modifiers(s));
12999                    // AppKit's own per-layout/per-language adjustments (macOS 12+): remap a
13000                    // key equivalent the current keyboard layout cannot type, and MIRROR
13001                    // directional pairs (⌘[ / ⌘]) under RTL languages — the system half of
13002                    // shortcut localization; the catalog half is the `.key` attribute
13003                    // (docs/localization.md).
13004                    it.setAllowsAutomaticKeyEquivalentLocalization(true);
13005                    it.setAllowsAutomaticKeyEquivalentMirroring(true);
13006                }
13007                if custom {
13008                    let tobj: &objc2::runtime::AnyObject = target.as_ref();
13009                    unsafe { it.setTarget(Some(tobj)) };
13010                    it.setTag(*action as isize);
13011                }
13012                it.setEnabled(*enabled);
13013                // A checkable item takes NSMenuItem's own state, so macOS draws the ✓ it draws
13014                // everywhere else and reserves the mark's column when it is off (docs/menus.md).
13015                if let Some(on) = checked {
13016                    it.setState(if *on {
13017                        NSControlStateValueOn
13018                    } else {
13019                        NSControlStateValueOff
13020                    });
13021                }
13022                // The item's glyph, drawn the way NSMenuItem draws its own (docs/menus.md):
13023                // template-tinted, sized to the menu's text.
13024                if let Some(icon) = icon
13025                    && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
13026                {
13027                    img.setSize(NSSize::new(16.0, 16.0));
13028                    it.setImage(Some(&img));
13029                }
13030                menu.addItem(&it);
13031            }
13032        }
13033    }
13034    menu
13035}
13036
13037// AppKit's TLS may be destroyed before the reactive arena drops its last Bitmap.
13038// The registry already released the native images in that case.
13039fn release_bitmap(id: day_spec::BitmapId) {
13040    let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
13041}
13042
13043#[cfg(test)]
13044mod bitmap_teardown_tests {
13045    use super::*;
13046
13047    #[test]
13048    fn releasing_after_bitmap_registry_teardown_does_not_abort() {
13049        // Isolate destructor panics: Rust aborts the process when a TLS destructor unwinds.
13050        const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
13051        if std::env::var_os(CHILD).is_some() {
13052            struct LateRelease;
13053            impl Drop for LateRelease {
13054                fn drop(&mut self) {
13055                    assert!(BITMAPS.try_with(|_| ()).is_err());
13056                    // Same duty called by Bitmap::drop; no NSApplication is needed.
13057                    release_bitmap(day_spec::BitmapId(1));
13058                }
13059            }
13060            std::thread_local! {
13061                static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
13062            }
13063            std::thread::spawn(|| {
13064                LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
13065                BITMAPS.with(|_| ()); // initialized last, destroyed first
13066            })
13067            .join()
13068            .unwrap();
13069            return;
13070        }
13071        let output = std::process::Command::new(std::env::current_exe().unwrap())
13072            .args([
13073                "--exact",
13074                "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
13075                "--nocapture",
13076            ])
13077            .env(CHILD, "1")
13078            .output()
13079            .unwrap();
13080        assert!(
13081            output.status.success(),
13082            "{}",
13083            String::from_utf8_lossy(&output.stderr)
13084        );
13085    }
13086}