Skip to main content

day_toolkit_appkit/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-appkit: the macos-appkit backend (DESIGN.md §9). objc2, pure Rust, no shim.
5//!
6//! `Handle = Retained<NSView>`. Containers are flipped `NSView`s (top-left origin, so Day's
7//! frames apply directly and survive diffing). One custom target class (`DayTarget`) forwards
8//! target/action + text-delegate callbacks into the Day event sink, node-id keyed (§8.3).
9
10#![allow(unused_unsafe)]
11#![cfg(target_os = "macos")]
12
13mod controls;
14
15mod applications;
16mod nav_progress;
17
18use std::any::Any;
19use std::cell::{Cell, RefCell};
20use std::collections::HashMap;
21use std::rc::Rc;
22
23use linkme::distributed_slice;
24use objc2::Message as _;
25use objc2::rc::Retained;
26use objc2::runtime::{NSObjectProtocol, ProtocolObject};
27use objc2::{
28    AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
29};
30use objc2_app_kit::NSAccessibility as _;
31use objc2_app_kit::NSAppearanceCustomization as _;
32use objc2_app_kit::NSDraggingInfo as _;
33use objc2_app_kit::NSSplitViewDelegate;
34use objc2_app_kit::NSTextContent as _;
35use objc2_app_kit::NSUserInterfaceItemIdentification as _;
36use objc2_app_kit::{
37    NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
38    NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
39};
40use objc2_app_kit::{
41    NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
42    NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
43    NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
44    NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
45    NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
46    NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
47    NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
48    NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
49    NSWindowDelegate, NSWindowStyleMask,
50};
51use objc2_app_kit::{
52    NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
53    NSApplicationWillTerminateNotification,
54};
55use objc2_app_kit::{
56    NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
57};
58use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
59use objc2_core_foundation::CGAffineTransform;
60use objc2_foundation::{
61    NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
62    NSNumber, NSObject, NSPoint, NSRect, NSSize, NSString,
63};
64use objc2_quartz_core::{
65    CAMediaTimingFunction, CATransaction, kCAMediaTimingFunctionEaseIn,
66    kCAMediaTimingFunctionEaseInEaseOut, kCAMediaTimingFunctionEaseOut,
67    kCAMediaTimingFunctionLinear,
68};
69
70use day_spec::ffi_guard;
71use day_spec::present;
72use day_spec::props::*;
73use day_spec::sidetable::SideTable;
74use day_spec::{
75    A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
76    InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
77    Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
78    WindowOptions, kinds, props_of,
79};
80
81pub type Handle = Retained<NSView>;
82
83/// Icon resolution for a piece renderer's own `NSToolbar` items (see `toolbar::image_for`).
84pub use toolbar::image_for as toolbar_image;
85
86// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
87mod dock;
88mod documents;
89mod frame;
90mod picker;
91mod status_item;
92mod textarea;
93mod toolbar;
94mod transfer;
95mod window_chrome;
96use objc2_app_kit::NSDraggingSource;
97
98pub mod ext;
99pub use ext::*;
100
101// ---------------------------------------------------------------------------
102// Event plumbing: node-id keyed sink, thread-local (single UI thread)
103// ---------------------------------------------------------------------------
104
105/// The day-core event sink (node-id keyed).
106type Sink = Rc<dyn Fn(NodeId, Event)>;
107
108day_core::tls_group! {
109    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
110    /// Keeps each control's `DayTarget` alive (target/action holds it weakly).
111    static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
112    /// The style each button currently carries, keyed by its view pointer.
113    ///
114    /// Needed because a tinted title is an attributed string (see `set_button_title`), and
115    /// `ButtonPatch::Title` would otherwise replace it with a plain one and lose the color.
116    static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
117        RefCell::new(HashMap::new());
118    /// Original template images, retained across tint changes and swept on view release.
119    static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
120    /// Each button's selected state (`ButtonProps::selected`), keyed by its view pointer: what
121    /// the `action:` handler restores after a click toggles a push-on/push-off button, and the
122    /// buttons whose `state` `read_native` reports as `checked`.
123    static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
124
125    /// Canvas ptr → its display list. A [`SideTable`], so the release sweep reclaims it
126    /// (replay inserted but nothing ever removed).
127    static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
128    /// Views the app gave an accessibility label (`set_a11y`): a button's title change must then
129    /// leave the label alone (`apply_button_content`). Swept on release like the other tables.
130    static APP_LABELED: SideTable<()> = SideTable::new();
131    /// How each image view renders its glyph (docs/vectors.md "Tint", "Template"): whether it
132    /// was realized as a template, and whether a tint is on it now. Template rendering is a
133    /// property of the NSImage, so a source swap has to re-apply it, and a tint patch of `None`
134    /// keeps a template in the neutral tint rather than returning to the authored art. Swept
135    /// on release.
136    static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
137    /// Each transformed view's `Transform` (`set_transform`). AppKit owns a layer-backed view's
138    /// layer geometry and re-syncs it from the view, so a transform written into the layer
139    /// never showed. It is expressed in the view's own geometry instead (`apply_geometry`).
140    static TRANSFORMS: SideTable<Transform> = SideTable::new();
141    /// Each view's frame as Day laid it out, before any translation, so a translation change can
142    /// move the view without waiting for the next layout.
143    static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
144    static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
145    /// View ptr → node for `GestureKind::Pan` (docs/shapes.md): macOS pans arrive as trackpad
146    /// scroll events, so `DayCanvas::scrollWheel:` reports them here instead of a recognizer.
147    static PAN_NODES: SideTable<NodeId> = SideTable::new();
148    static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
149    /// View ptr → node for `GestureKind::Hover` (docs/canvas.md "Interaction"). Hover is not a
150    /// recognizer on macOS either: it is an `NSTrackingArea` plus the three mouse methods, so
151    /// like [`PAN_NODES`] this holds the canvases that asked and `DayCanvas` reports for them.
152    static HOVER_NODES: SideTable<NodeId> = SideTable::new();
153    /// Canvas view ptr → its node, so the view's own `keyDown:` knows who to report to. Every
154    /// canvas is registered at realize (unlike [`PAN_NODES`], which only holds the ones that
155    /// asked for a pan) because focus, not a gesture, is what decides who hears a key.
156    static KEY_NODES: SideTable<NodeId> = SideTable::new();
157    /// Focusable container view ptr → its node (docs/focus.md): `Decorate::focusable` opts a
158    /// `DayFlipped` into the canvas contract (accepts first responder, takes focus on a
159    /// press, reports both directions, hears the arrows). Empty for every container that
160    /// never asked, whose behavior is exactly as before.
161    static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
162
163    /// Keeps each view's gesture targets alive + records which gestures are attached (idempotent).
164    static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
165        RefCell::new(HashMap::new());
166
167    static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
168    /// Handles whose frames are native-owned (nav pages): set_frame skips them.
169    static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
170        RefCell::new(std::collections::HashSet::new());
171    /// Each nav page's pane, recorded at realize because `insert` sees only handles
172    /// (docs/size-classes.md). Identity rather than position: a re-present re-homes the pages
173    /// without changing their order, so "index 0 is the sidebar" stops being true the moment a
174    /// host can morph. A [`SideTable`]: `remove` clears it on the normal path, and the release
175    /// sweep catches a page released without one (a stale entry could mis-pane a recycled ptr).
176    static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
177
178    static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
179    /// INSPECTOR_PANE ptr → is-panel, recorded at realize because `insert` sees only handles.
180    /// A [`SideTable`]: the release sweep drops it with the view.
181    static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
182
183    /// Split host (the wrap around an `NSSplitView`, docs/split.md) ptr → its state.
184    static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
185    /// SPLIT_PANE ptr → is-second, recorded at realize because `insert` sees only handles.
186    static SPLIT_PANES: SideTable<bool> = SideTable::new();
187
188    /// Outline ptr → its data source, for [`DayNavOutlineView::menu_for_event`]'s row lookup.
189    /// A [`SideTable`], reclaimed by the outline-keyed auxiliary sweep in `release`: the entry
190    /// used to outlive its host, so a recycled outline address served the dead menu's rows.
191    static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
192
193    static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
194    /// Tree host scroll-view ptr → (outline, data source) (docs/tree.md).
195    static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
196
197    /// `BitmapId` → the decoded image (docs/images.md). Keyed by the id day-core minted, not by
198    /// a view pointer: a bitmap outlives any one view and may be drawn by several at once.
199    /// Entries leave only through `release_image`, which day-core calls when the app drops its
200    /// last `Bitmap` handle.
201    static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
202    /// View ptr → its summon-time context-menu provider (docs/menus.md). Swept on release
203    /// via `day_spec::sidetable`.
204    static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
205
206    /// NAV_MENU scroll-view ptr → (outline, data source) for patches and measure.
207    static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
208
209    /// The app's edit-bridge state (`set_edit_state`), which validateMenuItem consults.
210    static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
211        const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
212    static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
213        const { std::cell::RefCell::new(None) };
214
215    /// Live modal sheets keyed by request id (for programmatic dismissal).
216    static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
217        RefCell::new(HashMap::new());
218    /// Live file-picker sheets (NSOpenPanel is stored via its NSSavePanel supertype).
219    static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
220        RefCell::new(HashMap::new());
221
222    // NSMenuItem does not retain its target, so one shared target is kept alive for the app's
223    // lifetime.
224    static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
225        const { std::cell::RefCell::new(None) };
226    /// The primary window's content view, for call sites without backend access that must
227    /// address the main window specifically (cover re-homing, DAY_DUMP). With secondary
228    /// windows open, `app.windows().firstObject()` is arbitrary (docs/windows.md).
229    static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
230        const { std::cell::RefCell::new(None) };
231
232}
233
234/// Emit an event into day-core's queue (public: external Day Piece renderers use this too).
235pub fn emit(id: NodeId, ev: Event) {
236    let sink = SINK.with(|s| s.borrow().clone());
237    if let Some(sink) = sink {
238        sink(id, ev);
239    }
240}
241
242fn ptr_of(v: &NSView) -> usize {
243    (v as *const NSView).cast::<()>() as usize
244}
245
246/// An image view's rendering (`IMAGE_MODES`).
247#[derive(Clone, Copy)]
248struct ImageMode {
249    template: bool,
250    tinted: bool,
251}
252
253impl ImageMode {
254    /// Template rendering: the glyph's alpha as a mask, filled with the tint or the neutral
255    /// template color.
256    fn renders_template(self) -> bool {
257        self.template || self.tinted
258    }
259}
260
261/// A decoded bitmap (docs/images.md), held until day-core drops its last handle.
262///
263/// The `NSBitmapImageRep` is kept beside the image rather than fetched on demand for two
264/// reasons: it is the only thing here that can re-encode to other formats, and it is the only
265/// accurate source of pixel dimensions, since `NSImage.size` is in points and reports a @2x
266/// asset at half its real width.
267struct AppKitBitmap {
268    image: Retained<objc2_app_kit::NSImage>,
269    rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
270    info: day_spec::BitmapInfo,
271}
272
273/// Draw a decoded image into a fresh bitmap `scale`× its pixel size, for [`day_spec::EncodeSpec`]'s
274/// `fit`.
275///
276/// 8 bits across 4 samples with alpha is the one layout every writer here accepts, and the only
277/// one that carries transparency through a PNG round-trip intact.
278fn scaled_rep(
279    image: &objc2_app_kit::NSImage,
280    pixels: Size,
281    scale: f64,
282) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
283    use objc2::AllocAnyThread as _;
284    let w = (pixels.width * scale).round().max(1.0);
285    let h = (pixels.height * scale).round().max(1.0);
286    let rep = unsafe {
287        objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
288            objc2_app_kit::NSBitmapImageRep::alloc(),
289            std::ptr::null_mut(),
290            w as isize,
291            h as isize,
292            8,
293            4,
294            true,
295            false,
296            objc2_app_kit::NSDeviceRGBColorSpace,
297            0,
298            0,
299        )
300    }?;
301    let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
302    NSGraphicsContext::saveGraphicsState_class();
303    objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
304    unsafe {
305        image.drawInRect_fromRect_operation_fraction(
306            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
307            NSRect::ZERO,
308            objc2_app_kit::NSCompositingOperation::SourceOver,
309            1.0,
310        );
311    }
312    NSGraphicsContext::restoreGraphicsState_class();
313    Some(rep)
314}
315
316/// Re-encode a decoded bitmap (docs/images.md).
317///
318/// A free function rather than the duty's body so each refusal reads as an early return instead
319/// of another copy of the same emit.
320fn encode_bitmap(
321    id: day_spec::BitmapId,
322    spec: &day_spec::EncodeSpec,
323) -> Result<Vec<u8>, day_spec::ImageError> {
324    use day_spec::ImageFormat as F;
325    use objc2_app_kit::NSBitmapImageFileType as T;
326    let file_type = match spec.format {
327        F::Png => T::PNG,
328        F::Jpeg => T::JPEG,
329        F::Tiff => T::TIFF,
330        F::Bmp => T::BMP,
331        F::Gif => T::GIF,
332        // Readable here but not writable: `NSBitmapImageRep` ships no WebP or HEIF writer. That
333        // asymmetry is why `encode_formats` exists instead of letting `Cap::ImageEncode` imply
334        // that everything decodable is also encodable.
335        _ => return Err(day_spec::ImageError::Encode),
336    };
337    let held = BITMAPS.with(|m| {
338        m.borrow()
339            .get(&id.0)
340            .map(|b| (b.rep.clone(), b.image.clone(), b.info))
341    });
342    let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
343    let rep = rep.ok_or(day_spec::ImageError::Encode)?;
344
345    // `fit` scales the longest side down first. A box larger than the original is ignored:
346    // upscaling on an export path inflates the bytes without adding any detail.
347    let rep = match spec.fit {
348        Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
349            let scale = (fit.width / info.pixels.width)
350                .min(fit.height / info.pixels.height)
351                .min(1.0);
352            if scale < 1.0 {
353                scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
354            } else {
355                rep
356            }
357        }
358        _ => rep,
359    };
360
361    let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
362        // AppKit's own compression-factor property; a lossless writer ignores it.
363        Some(q) => {
364            let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
365            let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
366            let value: &objc2::runtime::AnyObject = &number;
367            NSDictionary::from_slices::<NSString>(&[key], &[value])
368        }
369        None => NSDictionary::new(),
370    };
371    let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
372        .ok_or(day_spec::ImageError::Encode)?;
373    Ok(data.to_vec())
374}
375
376/// Replay a display list into the current graphics context. The one painter both the on-screen
377/// `DayCanvas` (its `drawRect:`) and the canvas exports run, so the two cannot drift apart
378/// (docs/canvas.md "Exporting").
379fn paint_ops(ops: &[DrawOp]) {
380    for op in ops {
381        draw_op(op);
382    }
383}
384
385/// Paint `ops` into `cg` with a top-left origin and y down, as the flipped `DayCanvas` sees
386/// them. `height` is the context's own height in its base units (pixels for a bitmap, points for
387/// a PDF page) and `scale` its units per canvas point.
388///
389/// The CTM flip turns the geometry the right way up; wrapping the context as a FLIPPED
390/// `NSGraphicsContext` is what tells AppKit's text and image drawing to keep glyphs and pictures
391/// upright inside that flip, exactly as they are in a flipped view's `drawRect:`.
392fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
393    use objc2_core_graphics::CGContext;
394    CGContext::save_g_state(Some(cg));
395    CGContext::translate_ctm(Some(cg), 0.0, height);
396    CGContext::scale_ctm(Some(cg), scale, -scale);
397    let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
398    NSGraphicsContext::saveGraphicsState_class();
399    NSGraphicsContext::setCurrentContext(Some(&ns));
400    paint_ops(ops);
401    NSGraphicsContext::restoreGraphicsState_class();
402    CGContext::restore_g_state(Some(cg));
403}
404
405/// Render a canvas display list offscreen (docs/canvas.md "Exporting"): `export_pixels` of
406/// transparent sRGB, premultiplied RGBA, painted at `scale` pixels per point.
407///
408/// A `CGBitmapContext` rather than `NSGraphicsContext(bitmapImageRep:)`: it carries a real sRGB
409/// color space, so the `NSBitmapImageRep` built from its image is tagged sRGB like every canvas
410/// color, shows on the display through the same color matching the live canvas gets, and writes
411/// that profile into a PNG.
412fn render_bitmap_image(
413    ops: &[DrawOp],
414    size: Size,
415    scale: f64,
416) -> Result<AppKitBitmap, day_spec::ExportError> {
417    use objc2::AllocAnyThread as _;
418    use objc2_core_graphics::{
419        CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
420    };
421    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
422    let (pw, ph) = day_spec::export_pixels(size, scale);
423    // SAFETY: `kCGColorSpaceSRGB` is an immutable CoreGraphics constant, valid for the process.
424    let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
425        .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
426    // SAFETY: a null data pointer asks CoreGraphics to allocate (and own) the buffer, and a zero
427    // row stride lets it choose one; 8 bits × RGBA premultiplied is a supported layout.
428    let cg = unsafe {
429        CGBitmapContextCreate(
430            std::ptr::null_mut(),
431            pw as usize,
432            ph as usize,
433            8,
434            0,
435            Some(&space),
436            CGImageAlphaInfo::PremultipliedLast.0,
437        )
438    }
439    .ok_or_else(|| {
440        day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
441    })?;
442    // A new bitmap context starts zeroed, which is the transparent background.
443    paint_flipped(&cg, ph as f64, scale, ops);
444    let cg_image = CGBitmapContextCreateImage(Some(&cg))
445        .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))?;
446    let rep = unsafe {
447        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
448            objc2_app_kit::NSBitmapImageRep::alloc(),
449            &cg_image,
450        )
451    };
452    // Sized in POINTS, pixels over scale, so the image draws at the drawing's size and stays
453    // sharp at `scale`× — the same shape as a staged @2x asset.
454    let points = NSSize::new(pw as f64 / scale, ph as f64 / scale);
455    unsafe { rep.setSize(points) };
456    let image =
457        unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
458    unsafe { image.addRepresentation(&rep) };
459    Ok(AppKitBitmap {
460        image,
461        rep: Some(rep),
462        info: day_spec::BitmapInfo {
463            pixels: Size::new(pw as f64, ph as f64),
464            scale,
465            format: None,
466            has_alpha: true,
467        },
468    })
469}
470
471/// Write `pages` as one PDF document (docs/canvas.md "Exporting"): a `CGPDFContext` on a
472/// `CGDataConsumer` over memory, one page per drawing with its own media box, the title and
473/// author in the document info. Shapes and text stay vector: the same painter draws into the PDF
474/// context, and AppKit's string drawing there emits real glyphs from embedded font subsets.
475fn render_pdf_bytes(
476    pages: &[day_spec::PdfPage],
477    info: &day_spec::PdfInfo,
478) -> Result<Vec<u8>, day_spec::ExportError> {
479    use objc2_core_foundation::{
480        CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
481    };
482    use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
483    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
484    let media =
485        |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
486    let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
487    let data = CFMutableData::new(None, 0)
488        .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
489    let consumer = CGDataConsumer::with_cf_data(Some(&data))
490        .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
491
492    let mut keys: Vec<&CFString> = Vec::new();
493    let mut values: Vec<CFRetained<CFString>> = Vec::new();
494    // SAFETY: the auxiliary-info keys are immutable CoreGraphics constants.
495    let (title_key, author_key) = unsafe {
496        (
497            objc2_core_graphics::kCGPDFContextTitle,
498            objc2_core_graphics::kCGPDFContextAuthor,
499        )
500    };
501    for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
502        if let Some(value) = value {
503            keys.push(key);
504            values.push(CFString::from_str(value));
505        }
506    }
507    let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
508    let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
509
510    let first_box = media(first.size);
511    // SAFETY: `first_box` outlives the call, and the dictionary maps the documented
512    // auxiliary-info string keys to strings, which is the type those keys take.
513    let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
514        .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
515    for page in pages {
516        let page_box = media(page.size);
517        // SAFETY: `page_box` outlives the call; in a PDF context it becomes the page's MediaBox.
518        unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
519        paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
520        CGContext::end_page(Some(&pdf));
521    }
522    // Closing flushes the trailer into the consumer; the bytes are complete only after it.
523    CGPDFContextClose(Some(&pdf));
524    drop(pdf);
525    drop(consumer);
526    Ok(data.to_vec())
527}
528
529thread_local! {
530    /// Each realized list item's current props, by its view: a patch updates one part and the
531    /// item is re-dressed from the whole (docs/list.md "List items").
532    static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
533        std::cell::RefCell::new(std::collections::HashMap::new());
534}
535
536/// A list row's standard content (docs/list.md "List items"), as an image-and-text table cell
537/// draws it: a 16pt template image, the title in the system font with a smaller secondary
538/// subtitle under it, a secondary trailing value, and the accent checkmark, in a horizontal
539/// stack at least 28pt tall. Parts that are absent are hidden, and the stack closes up around
540/// them.
541///
542/// The row's width is spoken for explicitly, as an image-and-text cell's is: the stack fills
543/// its frame edge to edge, the words take every spare point and give way first, and the
544/// trailing parts keep their own size. Left to the stack's default gravity areas, the spare
545/// width had two equally weak claims, the words' column and the gap before the trailing parts,
546/// so Auto Layout settled it from whatever the row's last layout had been: a checkmark landed
547/// beside the title in one row and at the trailing edge in the next, and stayed put.
548fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
549    use objc2_app_kit::{
550        NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
551    };
552    let label = |text: &str, size: f64, secondary: bool| {
553        let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
554        unsafe {
555            tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
556            if secondary {
557                tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
558            }
559            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
560        }
561        tf
562    };
563    let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
564    let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
565    const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
566        objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
567    // Hugging: the words stretch (1), the trailing parts hold their size (750), and the stack
568    // keeps its edges on its first and last parts (750), so exactly one part takes the slack.
569    const STRETCH: f32 = 1.0;
570    const HOLD: f32 = 750.0;
571    let stack = NSStackView::new(mtm);
572    stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
573    stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
574    stack.setAlignment(NSLayoutAttribute::CenterY);
575    stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
576    stack.setSpacing(6.0);
577    // A table row's breathing room above and below; the list gives the sides.
578    stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
579        top: 4.0,
580        left: 0.0,
581        bottom: 4.0,
582        right: 0.0,
583    });
584    let icon = unsafe { NSImageView::new(mtm) };
585    unsafe {
586        icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
587        icon.widthAnchor()
588            .constraintEqualToConstant(16.0)
589            .setActive(true);
590        icon.heightAnchor()
591            .constraintEqualToConstant(16.0)
592            .setActive(true);
593    }
594    stack.addArrangedSubview(&icon);
595    // The title and subtitle span the words' column (Width alignment), so the column's width is
596    // theirs and nothing is left over inside it.
597    let texts = NSStackView::new(mtm);
598    texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
599    texts.setAlignment(NSLayoutAttribute::Width);
600    texts.setSpacing(1.0);
601    // Its height is its lines', centered in the row, not the row's height with the lines
602    // floating somewhere inside it.
603    texts.setHuggingPriority_forOrientation(
604        HOLD,
605        objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
606    );
607    let title = label("", size, false);
608    let subtitle = label("", small, true);
609    // The words take the width and give way first, truncating, before the trailing parts.
610    for line in [&title, &subtitle] {
611        line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
612        line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
613    }
614    texts.addArrangedSubview(&title);
615    texts.addArrangedSubview(&subtitle);
616    stack.addArrangedSubview(&texts);
617    let detail = label("", size, true);
618    detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
619    detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
620    stack.addArrangedSubview(&detail);
621    let check = unsafe { NSImageView::new(mtm) };
622    unsafe {
623        check.setImage(
624            objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
625                &NSString::from_str("checkmark"),
626                None,
627            )
628            .as_deref(),
629        );
630        check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
631    }
632    check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
633    check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
634    stack.addArrangedSubview(&check);
635    let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
636    LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
637    dress_list_item(&view, p, mtm);
638    view
639}
640
641/// Show `p` on a list item's stack (see [`make_list_item`]), as one accessibility element.
642fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
643    use objc2_app_kit::{NSImageView, NSStackView};
644    let Some(stack) = view.downcast_ref::<NSStackView>() else {
645        return;
646    };
647    let parts = stack.arrangedSubviews();
648    if parts.len() < 4 {
649        return;
650    }
651    let icon = parts.objectAtIndex(0);
652    if let Some(iv) = icon.downcast_ref::<NSImageView>() {
653        let image = p
654            .icon
655            .as_ref()
656            .and_then(|i| toolbar::image_for(i, &p.title, mtm));
657        unsafe {
658            iv.setImage(image.as_deref());
659            iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
660        }
661    }
662    icon.setHidden(p.icon.is_none());
663    if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
664        let lines = texts.arrangedSubviews();
665        if lines.len() == 2 {
666            if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
667                tf.setStringValue(&NSString::from_str(&p.title));
668            }
669            let sub = lines.objectAtIndex(1);
670            if let Some(tf) = sub.downcast_ref::<NSTextField>() {
671                tf.setStringValue(&NSString::from_str(&p.subtitle));
672            }
673            sub.setHidden(p.subtitle.is_empty());
674        }
675    }
676    let detail = parts.objectAtIndex(2);
677    if let Some(tf) = detail.downcast_ref::<NSTextField>() {
678        tf.setStringValue(&NSString::from_str(&p.detail));
679    }
680    detail.setHidden(p.detail.is_empty());
681    parts.objectAtIndex(3).setHidden(!p.checked);
682    let words = [&p.title, &p.subtitle, &p.detail]
683        .into_iter()
684        .filter(|w| !w.is_empty())
685        .map(String::as_str)
686        .collect::<Vec<_>>()
687        .join(", ");
688    unsafe {
689        view.setAccessibilityElement(true);
690        view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
691        view.setAccessibilitySelected(p.checked);
692    }
693}
694
695/// The `NSImage` behind an [`day_spec::ImageSource`] (docs/images.md).
696///
697/// Shared by realize and the `Source` patch: a swapped source must load exactly what a fresh
698/// realize would have, or a piece would show different pixels depending on whether it was
699/// built or updated.
700fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
701    use objc2::AllocAnyThread as _;
702    match source {
703        // A vector glyph's SVG first (docs/vectors.md): NSImage renders SVG at display size
704        // (macOS 11+), so vectors stay vector with no build-time raster resampling. Then the
705        // shared image-file resolver (images/ then assets/ then bundle), which is macOS's native
706        // path: a bundle file loaded straight into NSImage (§18.3).
707        day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
708            .or_else(|| day_spec::resource::resolve_image_file(name))
709            .and_then(|path| unsafe {
710                objc2_app_kit::NSImage::initWithContentsOfFile(
711                    objc2_app_kit::NSImage::alloc(),
712                    &NSString::from_str(&path.to_string_lossy()),
713                )
714            }),
715        // Bytes the app already holds (a download, a picked file, a paste) with no staged
716        // resource behind them.
717        day_spec::ImageSource::Bytes(bytes) => unsafe {
718            objc2_app_kit::NSImage::initWithData(
719                objc2_app_kit::NSImage::alloc(),
720                &NSData::with_bytes(bytes),
721            )
722        },
723        // Already decoded: share the one NSImage rather than parsing the same bytes twice.
724        day_spec::ImageSource::Decoded(id) => {
725            BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
726        }
727    }
728}
729
730/// Day `Role` → the `NSAccessibilityRole` constant to apply (§13). `None` for `Role::None`:
731/// Day leaves native controls' roles untouched and only applies explicit canvas/custom roles.
732fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
733    use day_spec::Role;
734    use objc2_app_kit::{
735        NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
736        NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
737        NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
738        NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
739    };
740    unsafe {
741        Some(match role {
742            Role::Button => NSAccessibilityButtonRole,
743            Role::Toggle => NSAccessibilityCheckBoxRole,
744            // A tab is a radio button with the tab-button subrole (`set_a11y` adds it), which
745            // is how NSTabView's own tabs read to VoiceOver; the strip is a tab group.
746            Role::Tab => NSAccessibilityRadioButtonRole,
747            Role::TabList => NSAccessibilityTabGroupRole,
748            Role::Slider => NSAccessibilitySliderRole,
749            Role::TextInput => NSAccessibilityTextFieldRole,
750            // `AXHeading` lands the label in VoiceOver's headings rotor. The level has no
751            // AppKit attribute of its own: the only convention (the level as `AXValue`) would
752            // displace the text an NSTextField reports as its value, so the level stays
753            // unspoken.
754            Role::Heading(_) => NSAccessibilityHeadingRole,
755            Role::Image => NSAccessibilityImageRole,
756            Role::Meter => NSAccessibilityLevelIndicatorRole,
757            Role::Group => NSAccessibilityGroupRole,
758            // NSOutlineView already reports these itself; the mapping is for the audit's
759            // expectation and for any composed stand-in (docs/tree.md).
760            Role::Tree => NSAccessibilityOutlineRole,
761            Role::TreeItem => NSAccessibilityRowRole,
762            Role::None => return None,
763        })
764    }
765}
766
767/// Native `AXRole` string → Day `Role` (best-effort, for `read_native`/`a11y_audit`).
768fn day_role_from_ns(ax: &str) -> day_spec::Role {
769    use day_spec::Role;
770    match ax {
771        "AXButton" => Role::Button,
772        "AXCheckBox" => Role::Toggle,
773        "AXSlider" => Role::Slider,
774        "AXTextField" => Role::TextInput,
775        // Plain text is ambiguous with a heading, and neither carries a level; the audit
776        // ignores the level either way.
777        "AXStaticText" | "AXHeading" => Role::Heading(0),
778        "AXOutline" => Role::Tree,
779        "AXImage" => Role::Image,
780        "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
781        "AXGroup" => Role::Group,
782        "AXRadioButton" => Role::Tab,
783        "AXTabGroup" => Role::TabList,
784        _ => Role::None,
785    }
786}
787
788// ---------------------------------------------------------------------------
789// DayTarget: target/action + text delegate trampoline
790// ---------------------------------------------------------------------------
791
792struct TargetIvars {
793    node: NodeId,
794}
795
796define_class!(
797    #[unsafe(super(NSObject))]
798    #[thread_kind = MainThreadOnly]
799    #[name = "DayTarget"]
800    #[ivars = TargetIvars]
801    struct DayTarget;
802
803    unsafe impl NSObjectProtocol for DayTarget {}
804    unsafe impl NSTextFieldDelegate for DayTarget {}
805
806    /// A tabs host's `NSTabView` (docs/navigation.md). A pick emits against the NAV_MENU's
807    /// node, exactly as the sidebar's outline view does, so as far as everything above this
808    /// backend is concerned, picking a tab and clicking a sidebar row are the same event, and
809    /// neither the pieces layer nor dayscript needs to know which chrome the window wears.
810    unsafe impl NSTabViewDelegate for DayTarget {
811        #[unsafe(method(tabView:didSelectTabViewItem:))]
812        fn tab_view_did_select(
813            &self,
814            tab_view: &objc2_app_kit::NSTabView,
815            item: Option<&objc2_app_kit::NSTabViewItem>,
816        ) {
817            ffi_guard::contain((), || {
818                if TAB_PICK_SUPPRESS.with(|s| s.get()) {
819                    return;
820                }
821                if let Some(item) = item {
822                    let idx = unsafe { tab_view.indexOfTabViewItem(item) };
823                    if idx >= 0 {
824                        emit(self.ivars().node, Event::SelectionChanged(idx as i64));
825                    }
826                }
827            })
828        }
829    }
830
831    impl DayTarget {
832        // Every trampoline that dispatches into the sink (and through it, app handlers) runs
833        // its body through `ffi_guard::contain` (§8.5): a Rust panic unwinding out of an ObjC
834        // frame is an abort, so it is caught, reported, and the reactive runtime recovered.
835        // The same guard wraps every other target/delegate entry in this backend.
836        #[unsafe(method(action:))]
837        fn action(&self, sender: &NSControl) {
838            ffi_guard::contain((), || {
839                let node = self.ivars().node;
840                if sender.downcast_ref::<NSSwitch>().is_some() {
841                    emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
842                } else if sender.downcast_ref::<NSSlider>().is_some() {
843                    let value = unsafe { sender.doubleValue() };
844                    // The live value first: bindings follow this, so the UI tracks the thumb.
845                    emit(node, Event::ValueChanged(value));
846                    // Then, once, the value the user settled on. The slider is `continuous`, so
847                    // this action fires on every tick of a drag; AppKit's way to tell where in the
848                    // gesture you are is the event that provoked it. A mouse-up ends a drag; a key
849                    // press (arrow keys) moves the value by one discrete step and is already settled;
850                    // anything else (mouse-down, mouse-dragged) is mid-gesture and commits nothing.
851                    if slider_value_settled() {
852                        emit(node, Event::ValueCommitted(value));
853                    }
854                } else {
855                    emit(node, Event::Pressed);
856                    // A push-on/push-off button toggled its state on the click; Day owns the
857                    // selected state (`set_button_selected`), so put back what it last asked.
858                    let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
859                    if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
860                        unsafe {
861                            btn.setState(if on {
862                                NSControlStateValueOn
863                            } else {
864                                NSControlStateValueOff
865                            })
866                        };
867                    }
868                }
869            })
870        }
871
872        /// The stack-nav back header's button (docs/navigation.md): a day-initiated pop. The
873        /// nav host's handler writes it into the path signal, which reconciles the pop.
874        #[unsafe(method(navBack:))]
875        fn nav_back(&self, _sender: &NSControl) {
876            ffi_guard::contain((), || {
877                emit(
878                    self.ivars().node,
879                    Event::NavBack {
880                        already_popped: false,
881                    },
882                );
883            })
884        }
885    }
886
887    unsafe impl NSControlTextEditingDelegate for DayTarget {
888        #[unsafe(method(controlTextDidChange:))]
889        fn control_text_did_change(&self, notification: &NSNotification) {
890            ffi_guard::contain((), || {
891                let node = self.ivars().node;
892                if let Some(obj) = unsafe { notification.object() }
893                    && let Ok(tf) = obj.downcast::<NSTextField>() {
894                        emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
895                    }
896            })
897        }
898
899        /// End of an editing session (docs/focus.md). Return submits: AppKit keeps the field
900        /// first responder and re-selects, so it is not a focus loss; every other movement
901        /// (tab, click-away, cancel) reports `FocusChanged(false)`.
902        #[unsafe(method(controlTextDidEndEditing:))]
903        fn control_text_did_end_editing(&self, notification: &NSNotification) {
904            ffi_guard::contain((), || {
905                let node = self.ivars().node;
906                let movement = unsafe { notification.userInfo() }
907                    .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
908                    .and_then(|n| n.downcast::<NSNumber>().ok())
909                    .map(|n| NSTextMovement(n.integerValue()))
910                    .unwrap_or(NSTextMovement::Other);
911                if movement == NSTextMovement::Return {
912                    emit(node, Event::Submitted);
913                } else {
914                    emit(node, Event::FocusChanged(false));
915                }
916            })
917        }
918    }
919);
920
921impl DayTarget {
922    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
923        let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
924        unsafe { msg_send![super(this), init] }
925    }
926}
927
928// ---------------------------------------------------------------------------
929// DayCursorOwner: the `.cursor()` decorator's tracking-area owner (docs/cursor.md)
930// ---------------------------------------------------------------------------
931
932struct CursorIvars {
933    /// The shape to set on `cursorUpdate:`; `None` leaves the platform's own choice.
934    cursor: RefCell<Option<Retained<NSCursor>>>,
935    /// `Cursor::None`: hide the pointer while it is inside, unhide on exit.
936    hidden: Cell<bool>,
937    /// Whether this owner is the one that hid the pointer (balanced by `unhide`).
938    hiding: Cell<bool>,
939}
940
941// AppKit only re-evaluates the pointer's shape on `cursorUpdate:`, which it sends to a
942// tracking area's owner when the pointer enters the area (and on request through
943// `invalidateCursorRectsForView:`). One owner per view keeps the view class untouched: a label,
944// a button, or a plain container all get the same treatment without subclassing. Nested areas
945// resolve by entry order: the innermost is entered last, so its shape is the one that stays.
946define_class!(
947    #[unsafe(super(NSObject))]
948    #[thread_kind = MainThreadOnly]
949    #[name = "DayCursorOwner"]
950    #[ivars = CursorIvars]
951    struct DayCursorOwner;
952
953    unsafe impl NSObjectProtocol for DayCursorOwner {}
954
955    impl DayCursorOwner {
956        #[unsafe(method(cursorUpdate:))]
957        fn cursor_update(&self, _event: &NSEvent) {
958            let iv = self.ivars();
959            if iv.hidden.get() {
960                if !iv.hiding.replace(true) {
961                    NSCursor::hide();
962                }
963                return;
964            }
965            if let Some(c) = iv.cursor.borrow().as_ref() {
966                c.set();
967            }
968        }
969
970        #[unsafe(method(mouseExited:))]
971        fn mouse_exited(&self, _event: &NSEvent) {
972            if self.ivars().hiding.replace(false) {
973                NSCursor::unhide();
974            }
975        }
976    }
977);
978
979impl DayCursorOwner {
980    fn new(mtm: MainThreadMarker) -> Retained<Self> {
981        let this = Self::alloc(mtm).set_ivars(CursorIvars {
982            cursor: RefCell::new(None),
983            hidden: Cell::new(false),
984            hiding: Cell::new(false),
985        });
986        unsafe { msg_send![super(this), init] }
987    }
988}
989
990/// The `NSCursor` for a [`Cursor`], or `None` where the platform's own choice should stand
991/// (`Cursor::None`, which the owner hides instead, and a native name AppKit does not have).
992/// AppKit has no wait, progress, help, or move shape, so those take the arrow; the zoom, frame
993/// (diagonal) resize, and column/row resize cursors arrived in macOS 15 and are probed by
994/// nav host, with the nearest older shape below it.
995// `resizeLeftRightCursor` and `resizeUpDownCursor` are deprecated in favor of the macOS 15
996// column/row resize cursors, which are probed above them; below 15 they are the shape.
997#[allow(deprecated)]
998fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
999    let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1000    Some(match c {
1001        Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1002        Cursor::Pointer => NSCursor::pointingHandCursor(),
1003        Cursor::Text => NSCursor::IBeamCursor(),
1004        Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1005        Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1006        Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1007        Cursor::Grabbing => NSCursor::closedHandCursor(),
1008        Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1009        Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1010        Cursor::Copy => NSCursor::dragCopyCursor(),
1011        Cursor::Alias => NSCursor::dragLinkCursor(),
1012        Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1013        Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1014        Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1015        Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1016        Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1017        Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1018            NSCursor::frameResizeCursorFromPosition_inDirections(
1019                NSCursorFrameResizePosition::TopRight,
1020                NSCursorFrameResizeDirections::All,
1021            )
1022        }
1023        Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1024            NSCursor::frameResizeCursorFromPosition_inDirections(
1025                NSCursorFrameResizePosition::TopLeft,
1026                NSCursorFrameResizeDirections::All,
1027            )
1028        }
1029        Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1030        Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1031        Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1032        Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1033        Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1034        Cursor::None => return None,
1035        Cursor::Native(name) => match &**name {
1036            "disappearingItem" => NSCursor::disappearingItemCursor(),
1037            "dragCopy" => NSCursor::dragCopyCursor(),
1038            "dragLink" => NSCursor::dragLinkCursor(),
1039            "contextualMenu" => NSCursor::contextualMenuCursor(),
1040            "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1041            _ => return None,
1042        },
1043    })
1044}
1045
1046/// Whether the NSEvent currently being dispatched ends a slider's interaction (see the
1047/// `ValueCommitted` emission in `DayTarget::action:`). AppKit gives a continuous slider no
1048/// "drag ended" callback, so the event that provoked the action is what says where in the gesture
1049/// we are: a mouse-up ends a drag, an arrow key moves one discrete step and is already settled,
1050/// and mouse-down/mouse-dragged are mid-gesture. No current event at all (a programmatic
1051/// `setDoubleValue:` that fires the action) is not a user commit either.
1052fn slider_value_settled() -> bool {
1053    let Some(mtm) = MainThreadMarker::new() else {
1054        return false;
1055    };
1056    let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1057        return false;
1058    };
1059    matches!(
1060        unsafe { event.r#type() },
1061        NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1062    )
1063}
1064
1065// ---------------------------------------------------------------------------
1066// DayTextField: NSTextField that reports focus gain (docs/focus.md)
1067// ---------------------------------------------------------------------------
1068
1069struct FieldIvars {
1070    node: NodeId,
1071}
1072
1073define_class!(
1074    #[unsafe(super(NSTextField))]
1075    #[thread_kind = MainThreadOnly]
1076    #[name = "DayTextField"]
1077    #[ivars = FieldIvars]
1078    struct DayTextField;
1079
1080    impl DayTextField {
1081        /// Focus gain. Key events go to the shared field editor, but the field itself receives
1082        /// `becomeFirstResponder` first, the reliable gain hook (`controlTextDidBeginEditing:`
1083        /// waits for the first keystroke). Loss comes from `controlTextDidEndEditing:` on the
1084        /// delegate.
1085        #[unsafe(method(becomeFirstResponder))]
1086        fn become_first_responder(&self) -> bool {
1087            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1088            if ok {
1089                field_gained_focus(self.ivars().node);
1090            }
1091            ok
1092        }
1093    }
1094);
1095
1096impl DayTextField {
1097    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1098        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1099        unsafe { msg_send![super(this), init] }
1100    }
1101}
1102
1103// The secure twin (docs/textfield.md). AppKit hides characters with a class, not a property:
1104// `NSSecureTextField` brings its own cell and field editor, which keep the text out of the
1105// pasteboard, the spelling checker and the accessibility value. A `text_field` that turns
1106// `secure` is rebuilt as this class (`set_input_traits`), with the same focus hook.
1107define_class!(
1108    #[unsafe(super(NSSecureTextField))]
1109    #[thread_kind = MainThreadOnly]
1110    #[name = "DaySecureTextField"]
1111    #[ivars = FieldIvars]
1112    struct DaySecureTextField;
1113
1114    impl DaySecureTextField {
1115        /// Focus gain, as on `DayTextField`.
1116        #[unsafe(method(becomeFirstResponder))]
1117        fn become_first_responder(&self) -> bool {
1118            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1119            if ok {
1120                field_gained_focus(self.ivars().node);
1121            }
1122            ok
1123        }
1124    }
1125);
1126
1127impl DaySecureTextField {
1128    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1129        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1130        unsafe { msg_send![super(this), init] }
1131    }
1132}
1133
1134thread_local! {
1135    /// A plain/secure class swap in flight (`set_input_traits`): focus moves from the old
1136    /// field to its replacement, which the app must not see as a focus change.
1137    static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1138}
1139
1140/// Report a text field's focus gain, unless it is a class swap handing focus to the
1141/// replacement of a field that already had it.
1142fn field_gained_focus(node: NodeId) {
1143    if FIELD_SWAP.with(|s| s.get()) {
1144        return;
1145    }
1146    // Guard only the sink dispatch: the responder change already happened, so a contained
1147    // panic must not flip the answer AppKit acts on.
1148    ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1149}
1150
1151/// The node a `text_field`'s view reports against, or `None` when the view is not one
1152/// (a label is an `NSTextField` too).
1153fn text_field_node(v: &NSView) -> Option<NodeId> {
1154    v.downcast_ref::<DayTextField>()
1155        .map(|f| f.ivars().node)
1156        .or_else(|| {
1157            v.downcast_ref::<DaySecureTextField>()
1158                .map(|f| f.ivars().node)
1159        })
1160}
1161
1162/// Build a `text_field`'s view, plain or secure, with its delegate wired and registered.
1163/// `realize` and the class swap in `set_input_traits` both come through here, so both classes
1164/// report text, submit and focus the same way against the same node.
1165fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1166    let target = DayTarget::new(mtm, node);
1167    // Up to `NSTextField` (the declared superclass of both), so the AsRef<NSView> bound on
1168    // `view_of` resolves and every `NSTextField` downcast sees either class.
1169    let tf: Retained<NSTextField> = if secure {
1170        Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1171    } else {
1172        Retained::into_super(DayTextField::new(mtm, node))
1173    };
1174    unsafe {
1175        tf.setEditable(true);
1176        tf.setBezeled(true);
1177        tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1178    }
1179    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1180    tf
1181}
1182
1183/// Whether `h` (a text field, or the field editor's client) holds its window's focus. A
1184/// focused `NSTextField`'s first responder is the shared field editor, so unwrap it back to
1185/// the field via its delegate.
1186fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1187    window.firstResponder().is_some_and(|fr| {
1188        if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
1189            return true;
1190        }
1191        fr.downcast::<NSText>().is_ok_and(|text| {
1192            unsafe { text.delegate() }
1193                .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
1194        })
1195    })
1196}
1197
1198/// An `NSTextContentType` constant by symbol name, or `None` on a system that predates it.
1199/// Looked up at run time because most of the vocabulary arrived in macOS 14: a direct
1200/// reference binds at launch, and one missing symbol would keep the whole app from starting
1201/// on an older system.
1202fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1203    unsafe extern "C" {
1204        fn dlsym(
1205            handle: *mut std::ffi::c_void,
1206            symbol: *const std::ffi::c_char,
1207        ) -> *mut std::ffi::c_void;
1208    }
1209    // <dlfcn.h>: search every image loaded in the process.
1210    const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1211    // SAFETY: `symbol` is NUL-terminated. Each name passed here is an AppKit
1212    // `NSString * const`, so a non-null result is the address of a pointer to an immortal
1213    // constant string.
1214    unsafe {
1215        let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1216        if slot.is_null() {
1217            None
1218        } else {
1219            (*slot).as_ref()
1220        }
1221    }
1222}
1223
1224/// Move a view-keyed entry to the view that replaces it.
1225fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1226    if let Some(v) = table.take(old) {
1227        table.insert(new, v);
1228    }
1229}
1230
1231/// A label is the shared field editor's delegate. AppKit does not forward
1232/// `textView:clickedOnLink:atIndex:` to an NSTextField's separate control delegate, so the
1233/// label itself must handle it to prevent the field editor from opening the target externally.
1234/// See Apple's "Working With the Field Editor" and docs/text-runs.md.
1235struct LabelIvars {
1236    node: NodeId,
1237    has_links: Cell<bool>,
1238    has_runs: Cell<bool>,
1239    selectable: Cell<bool>,
1240}
1241
1242define_class!(
1243    #[unsafe(super(NSTextField))]
1244    #[thread_kind = MainThreadOnly]
1245    #[name = "DayLabel"]
1246    #[ivars = LabelIvars]
1247    struct DayLabel;
1248
1249    impl DayLabel {
1250        #[unsafe(method_id(menuForEvent:))]
1251        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1252            ffi_guard::contain(None, || {
1253                if !self.isSelectable()
1254                    && let Some(menu) = inherited_context_menu(self, event)
1255                {
1256                    return menu;
1257                }
1258                unsafe { msg_send![super(self), menuForEvent: event] }
1259            })
1260        }
1261
1262        #[unsafe(method(drawRect:))]
1263        fn draw_rect(&self, dirty: NSRect) {
1264            // AppKit cannot propagate a table cell's background style through arbitrary
1265            // Day containers. Resolve selection at paint time so keyboard focus, window
1266            // activation, and cell reuse all use the actual native row state.
1267            let mut ancestor = unsafe { self.superview() };
1268            let mut selection_color = None;
1269            if !self.ivars().has_runs.get() {
1270                while let Some(view) = ancestor {
1271                    if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1272                        if unsafe { row.isSelected() } {
1273                            selection_color = Some(unsafe {
1274                                if row.isEmphasized() {
1275                                    objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1276                                } else {
1277                                    objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1278                                }
1279                            });
1280                        }
1281                        break;
1282                    }
1283                    ancestor = unsafe { view.superview() };
1284                }
1285            }
1286            let cell = unsafe { self.cell() }
1287                .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1288            if let (Some(color), Some(cell)) = (selection_color, cell) {
1289                let original = unsafe { cell.textColor() };
1290                // Mutate the cell only for this paint; changing the field would invalidate
1291                // the view again. Keep the app's normal color for deselection and reuse.
1292                unsafe {
1293                    cell.setTextColor(Some(&color));
1294                    let _: () = msg_send![super(self), drawRect: dirty];
1295                    cell.setTextColor(original.as_deref());
1296                }
1297            } else {
1298                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1299            }
1300        }
1301    }
1302
1303    unsafe impl NSObjectProtocol for DayLabel {}
1304    unsafe impl NSTextDelegate for DayLabel {}
1305
1306    unsafe impl NSTextViewDelegate for DayLabel {
1307        #[unsafe(method(textView:clickedOnLink:atIndex:))]
1308        fn clicked_on_link(
1309            &self,
1310            _tv: &NSTextView,
1311            link: &objc2::runtime::AnyObject,
1312            _index: usize,
1313        ) -> bool {
1314            ffi_guard::contain(true, || {
1315                // NSString targets stay verbatim (including #route); accept NSURL too.
1316                let url: Retained<NSString> = unsafe { msg_send![link, description] };
1317                emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1318                true // Handled: AppKit must never also open the target itself.
1319            })
1320        }
1321    }
1322);
1323
1324impl DayLabel {
1325    fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1326        let this = Self::alloc(mtm).set_ivars(LabelIvars {
1327            node,
1328            has_links: Cell::new(false),
1329            has_runs: Cell::new(false),
1330            selectable: Cell::new(false),
1331        });
1332        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1333        unsafe {
1334            this.setStringValue(&NSString::from_str(text));
1335            this.setEditable(false);
1336            this.setSelectable(false);
1337            this.setBordered(false);
1338            this.setBezeled(false);
1339            this.setDrawsBackground(false);
1340        }
1341        this
1342    }
1343
1344    fn set_links(&self, has_links: bool) {
1345        self.ivars().has_links.set(has_links);
1346        unsafe {
1347            self.setSelectable(has_links || self.ivars().selectable.get());
1348            self.setAllowsEditingTextAttributes(has_links);
1349        }
1350    }
1351}
1352
1353struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1354impl Drop for PanMonitor {
1355    fn drop(&mut self) {
1356        unsafe { NSEvent::removeMonitor(&self.0) };
1357    }
1358}
1359
1360// A container pan observes horizontal wheel events over its descendants, including native
1361// scroll views. Leave vertical scrolling and canvas 2D pans to their existing handlers.
1362fn install_container_pan_monitor() {
1363    PAN_MONITOR.with(|slot| {
1364        if slot.borrow().is_some() {
1365            return;
1366        }
1367        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1368            let event = unsafe { raw.as_ref() };
1369            ffi_guard::contain(raw.as_ptr(), || {
1370                let dx = unsafe { event.scrollingDeltaX() };
1371                let dy = unsafe { event.scrollingDeltaY() };
1372                if dx.abs() <= dy.abs() {
1373                    return raw.as_ptr();
1374                }
1375                let Some(mtm) = MainThreadMarker::new() else {
1376                    return raw.as_ptr();
1377                };
1378                let Some(window) = event.window(mtm) else {
1379                    return raw.as_ptr();
1380                };
1381                let Some(content) = window.contentView() else {
1382                    return raw.as_ptr();
1383                };
1384                let point =
1385                    content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1386                let mut view = content.hitTest(point);
1387                while let Some(v) = view {
1388                    if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1389                        if v.downcast_ref::<DayCanvas>().is_some() {
1390                            return raw.as_ptr();
1391                        }
1392                        let raw_phase = unsafe { event.phase() };
1393                        let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1394                            day_spec::DragPhase::Began
1395                        } else if raw_phase.intersects(
1396                            objc2_app_kit::NSEventPhase::Ended
1397                                | objc2_app_kit::NSEventPhase::Cancelled,
1398                        ) {
1399                            day_spec::DragPhase::Ended
1400                        } else {
1401                            day_spec::DragPhase::Changed
1402                        };
1403                        let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1404                        emit(
1405                            node,
1406                            Event::Pan {
1407                                phase,
1408                                delta: Point::new(dx, dy),
1409                                location: Point::new(p.x, p.y),
1410                            },
1411                        );
1412                        return std::ptr::null_mut();
1413                    }
1414                    view = unsafe { v.superview() };
1415                }
1416                raw.as_ptr()
1417            })
1418        });
1419        *slot.borrow_mut() = unsafe {
1420            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1421                objc2_app_kit::NSEventMask::ScrollWheel,
1422                &block,
1423            )
1424        }
1425        .map(PanMonitor);
1426    });
1427}
1428
1429// ---------------------------------------------------------------------------
1430// DayFlipped: top-left-origin container view
1431// ---------------------------------------------------------------------------
1432
1433/// A `background(..)` fill: `(r, g, b, a, corner_radius)`, painted in `drawRect` with NSColor.
1434type Surface = (f64, f64, f64, f64, f64);
1435
1436#[derive(Default)]
1437struct FlippedIvars {
1438    surface: Cell<Option<Surface>>,
1439    /// SurfaceRole::SectionCard: `(radius,)`, drawn with a dynamic system fill resolved at
1440    /// draw time, so the card tracks light/dark appearance changes automatically.
1441    section_card: Cell<Option<f64>>,
1442    /// Paint the whole view with the dynamic window background before anything else: the
1443    /// inspector panel wrap (docs/inspector.md). The inspector NSSplitViewItem backs its pane
1444    /// with a vibrancy material, and the section cards' thin quaternary fill composites over
1445    /// it into near-black in dark mode (and the material itself captures black offscreen; see
1446    /// the sidebar-screenshot rule, docs/navigation.md). An opaque appearance-resolved
1447    /// backdrop gives the cards the same ground System Settings draws them on.
1448    pane_backdrop: Cell<bool>,
1449}
1450
1451define_class!(
1452    #[unsafe(super(NSView))]
1453    #[thread_kind = MainThreadOnly]
1454    #[name = "DayFlipped"]
1455    #[ivars = FlippedIvars]
1456    struct DayFlipped;
1457
1458    impl DayFlipped {
1459        #[unsafe(method_id(menuForEvent:))]
1460        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1461            ffi_guard::contain(None, || {
1462                inherited_context_menu(self, event)
1463                    .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1464            })
1465        }
1466
1467        #[unsafe(method(isFlipped))]
1468        fn is_flipped(&self) -> bool {
1469            true
1470        }
1471
1472        // Focus, and with it the keyboard (docs/focus.md): the canvas contract, opted into by
1473        // `Decorate::focusable`. A container never in FOCUSABLE_NODES behaves exactly as
1474        // before (refuses first responder, forwards every key).
1475        #[unsafe(method(acceptsFirstResponder))]
1476        fn accepts_first_responder(&self) -> bool {
1477            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1478            FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1479        }
1480
1481        // Clicking a focusable container focuses it, the way clicking a table does. The
1482        // gesture recognizers still see the press: this runs before `super`, which is what
1483        // forwards it to them.
1484        #[unsafe(method(mouseDown:))]
1485        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1486            if transfer::pressed(self, event) { return; }
1487            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1488            if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1489                && let Some(window) = self.window()
1490            {
1491                window.makeFirstResponder(Some(self));
1492            }
1493            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1494        }
1495
1496        #[unsafe(method(becomeFirstResponder))]
1497        fn become_first_responder(&self) -> bool {
1498            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1499            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1500                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1501            }
1502            true
1503        }
1504
1505        #[unsafe(method(resignFirstResponder))]
1506        fn resign_first_responder(&self) -> bool {
1507            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1508            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
1509                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1510            }
1511            true
1512        }
1513
1514        /// The arrows, delivered here while this container is the first responder. Anything
1515        /// else (and every arrow when the app registered no key handler for the node) goes
1516        /// to `super`, which walks the responder chain exactly as it would have without us.
1517        #[unsafe(method(keyDown:))]
1518        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1519            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1520            let handled = ffi_guard::contain(false, || {
1521                let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
1522                    return false;
1523                };
1524                let Some(key) = key_name(event) else {
1525                    return false;
1526                };
1527                if !day_spec::keys::handled(node) {
1528                    return false;
1529                }
1530                emit(
1531                    node,
1532                    Event::Key(day_spec::KeyEvent {
1533                        key: key.to_string(),
1534                        modifiers: key_modifiers(event.modifierFlags()),
1535                    }),
1536                );
1537                true
1538            });
1539            if !handled {
1540                let _: () = unsafe { msg_send![super(self), keyDown: event] };
1541            }
1542        }
1543
1544        /// Show the attached context menu (docs/menus.md) explicitly rather than relying on
1545        /// `NSResponder`'s default `.menu` display: popping it ourselves is deterministic
1546        /// regardless of how the click threads through Day's container hierarchy.
1547        #[unsafe(method(rightMouseDown:))]
1548        fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1549            if let Some(menu) = self.menuForEvent(event) {
1550                unsafe {
1551                    objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
1552                };
1553            } else {
1554                let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
1555            }
1556        }
1557
1558        #[unsafe(method(drawRect:))]
1559        fn draw_rect(&self, _dirty: NSRect) {
1560            let paint = || {
1561                if self.ivars().pane_backdrop.get() {
1562                    let bounds = self.bounds();
1563                    unsafe {
1564                        // Resolved at draw time, like the section fill below, so the backdrop
1565                        // follows light/dark appearance changes automatically.
1566                        NSColor::windowBackgroundColor().setFill();
1567                        objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
1568                    }
1569                }
1570                if let Some(radius) = self.ivars().section_card.get() {
1571                    let bounds = self.bounds();
1572                    unsafe {
1573                        // quaternarySystemFill (macOS 14+) is the grouped-card material System
1574                        // Settings uses; older systems fall back to the control background.
1575                        let cls = objc2::class!(NSColor);
1576                        let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
1577                        let color: objc2::rc::Retained<NSColor> = if has {
1578                            msg_send![cls, quaternarySystemFillColor]
1579                        } else {
1580                            msg_send![cls, controlBackgroundColor]
1581                        };
1582                        color.setFill();
1583                        let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1584                            bounds, radius, radius,
1585                        );
1586                        path.fill();
1587                    }
1588                }
1589                if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
1590                    let bounds = self.bounds();
1591                    unsafe {
1592                        NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
1593                        let path = if radius > 0.0 {
1594                            objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
1595                                bounds, radius, radius,
1596                            )
1597                        } else {
1598                            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
1599                        };
1600                        path.fill();
1601                    }
1602                }
1603            };
1604            // Paint under the standard counterpart of this view's appearance. Inside an
1605            // NSVisualEffectView subtree (the inspector pane) the effective appearance is
1606            // a vibrant one (NSAppearanceNameVibrantDark/-Light), and the system fills'
1607            // vibrant variants are opaque blend colors that only composite correctly in an
1608            // `allowsVibrancy` view: drawn plainly, dark-mode quaternary fill comes out
1609            // near-black instead of lightening. Resolving under aqua/darkAqua gives exactly
1610            // the fills System Settings draws with, and re-resolves on every theme change
1611            // (this runs per draw, and appearance flips redraw).
1612            unsafe {
1613                let names = objc2_foundation::NSArray::from_slice(&[
1614                    objc2_app_kit::NSAppearanceNameAqua,
1615                    objc2_app_kit::NSAppearanceNameDarkAqua,
1616                ]);
1617                let standard = self
1618                    .effectiveAppearance()
1619                    .bestMatchFromAppearancesWithNames(&names)
1620                    .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
1621                match standard {
1622                    Some(appearance) => {
1623                        let block = block2::StackBlock::new(paint);
1624                        appearance.performAsCurrentDrawingAppearance(&block);
1625                    }
1626                    None => paint(),
1627                }
1628            }
1629        }
1630    }
1631    unsafe impl NSObjectProtocol for DayFlipped {}
1632    unsafe impl NSDraggingSource for DayFlipped {
1633        #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
1634        fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
1635    }
1636    impl DayFlipped {
1637        #[unsafe(method(mouseDragged:))]
1638        fn transfer_dragged(&self, event: &NSEvent) {
1639            if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
1640        }
1641        #[unsafe(method(draggingEntered:))]
1642        fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1643        #[unsafe(method(draggingUpdated:))]
1644        fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
1645        #[unsafe(method(performDragOperation:))]
1646        fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
1647    }
1648
1649);
1650
1651impl DayFlipped {
1652    fn new(mtm: MainThreadMarker) -> Retained<Self> {
1653        let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
1654        unsafe { msg_send![super(this), init] }
1655    }
1656
1657    /// Apply a `background`/`corner_radius` surface. The fill (rounded by `corner_radius`) is
1658    /// drawn in `drawRect` with NSColor, not via the layer's `backgroundColor`, whose CGColorRef
1659    /// argument objc2's `msg_send` cannot type-check. A rounded child clip does use the CALayer
1660    /// (`cornerRadius` + `masksToBounds` are a CGFloat + `BOOL`, which are fine).
1661    /// SurfaceRole::SectionCard: the fill resolves dynamically in drawRect (theme-adaptive).
1662    fn set_section_card(&self, corner_radius: f64) {
1663        self.ivars().section_card.set(Some(corner_radius));
1664        unsafe {
1665            let _: () = msg_send![self, setNeedsDisplay: true];
1666        }
1667    }
1668
1669    /// Opaque window-background backdrop (the inspector panel wrap; see `FlippedIvars`).
1670    fn set_pane_backdrop(&self) {
1671        self.ivars().pane_backdrop.set(true);
1672        unsafe {
1673            let _: () = msg_send![self, setNeedsDisplay: true];
1674        }
1675    }
1676
1677    fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
1678        self.ivars()
1679            .surface
1680            .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
1681        unsafe {
1682            let _: () = msg_send![self, setNeedsDisplay: true];
1683            if clips || corner_radius > 0.0 {
1684                let _: () = msg_send![self, setWantsLayer: true];
1685                let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
1686                if !layer.is_null() {
1687                    let _: () = msg_send![layer, setCornerRadius: corner_radius];
1688                    let _: () = msg_send![layer, setMasksToBounds: true];
1689                }
1690            }
1691        }
1692    }
1693}
1694
1695// ---------------------------------------------------------------------------
1696// DayCanvas — a flipped view replaying the Day display list in drawRect (§11)
1697// ---------------------------------------------------------------------------
1698
1699struct CanvasIvars;
1700
1701define_class!(
1702    #[unsafe(super(NSView))]
1703    #[thread_kind = MainThreadOnly]
1704    #[name = "DayCanvas"]
1705    #[ivars = CanvasIvars]
1706    struct DayCanvas;
1707
1708    impl DayCanvas {
1709        #[unsafe(method(isFlipped))]
1710        fn is_flipped(&self) -> bool {
1711            true
1712        }
1713
1714        /// A summon-time context menu (docs/menus.md): built when the right-click lands,
1715        /// from the provider `set_context_menu_fn` registered — so a canvas can select what
1716        /// is under the pointer and offer commands for that selection.
1717        #[unsafe(method_id(menuForEvent:))]
1718        fn menu_for_event(
1719            &self,
1720            event: &objc2_app_kit::NSEvent,
1721        ) -> Option<Retained<NSMenu>> {
1722            let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
1723            let Some(f) = f else {
1724                return unsafe { msg_send![super(self), menuForEvent: event] };
1725            };
1726            // Guarded: the provider is app code (it usually re-selects, then builds).
1727            ffi_guard::contain(None, || {
1728                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1729                let items = f(day_spec::Point::new(p.x, p.y));
1730                if items.is_empty() {
1731                    return None;
1732                }
1733                Some(build_ns_menu(self.mtm(), "", &items))
1734            })
1735        }
1736
1737        // Focus, and with it the keyboard (docs/focus.md, docs/menus.md). A canvas is the one
1738        // built-in piece with no native control under it, so nothing else would ever make it
1739        // the first responder — and without that, arrow keys aimed at what it draws could only
1740        // be caught by watching the whole app.
1741        #[unsafe(method(acceptsFirstResponder))]
1742        fn accepts_first_responder(&self) -> bool {
1743            true
1744        }
1745
1746        // Clicking a canvas focuses it, the way clicking a table or a text field does. The
1747        // gesture recognizers (tap/drag) still see the press — this runs before `super`, which
1748        // is what forwards it to them.
1749        #[unsafe(method(mouseDown:))]
1750        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
1751            if let Some(window) = self.window() {
1752                window.makeFirstResponder(Some(self));
1753            }
1754            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
1755        }
1756
1757        // Report focus both ways, so `.focused(signal)` binds two-way and dayscript's
1758        // `assert_focused` can see it.
1759        #[unsafe(method(becomeFirstResponder))]
1760        fn become_first_responder(&self) -> bool {
1761            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1762            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1763                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1764            }
1765            true
1766        }
1767
1768        #[unsafe(method(resignFirstResponder))]
1769        fn resign_first_responder(&self) -> bool {
1770            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1771            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
1772                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
1773            }
1774            true
1775        }
1776
1777        /// The arrows, delivered to this canvas because it is the first responder. Anything
1778        /// else — and every arrow when the app registered no handler for this node — goes to
1779        /// `super`, which walks the responder chain exactly as it would have without us.
1780        #[unsafe(method(keyDown:))]
1781        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
1782            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1783            let handled = ffi_guard::contain(false, || {
1784                let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
1785                    return false;
1786                };
1787                let Some(key) = key_name(event) else {
1788                    return false;
1789                };
1790                // A canvas nobody asked keys from does not get to keep them: an enclosing
1791                // scroll view still scrolls, and an unclaimed key still beeps the way the
1792                // platform means it to.
1793                if !day_spec::keys::handled(node) {
1794                    return false;
1795                }
1796                emit(
1797                    node,
1798                    Event::Key(day_spec::KeyEvent {
1799                        key: key.to_string(),
1800                        modifiers: key_modifiers(event.modifierFlags()),
1801                    }),
1802                );
1803                true
1804            });
1805            if !handled {
1806                let _: () = unsafe { msg_send![super(self), keyDown: event] };
1807            }
1808        }
1809
1810        #[unsafe(method(drawRect:))]
1811        fn draw_rect(&self, _dirty: NSRect) {
1812            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1813            let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
1814            paint_ops(&ops);
1815        }
1816
1817        /// Hover entry/motion/exit (docs/canvas.md "Interaction"). The tracking area is installed
1818        /// by `enable_gesture`; `updateTrackingAreas` below keeps it the size of the view.
1819        #[unsafe(method(mouseEntered:))]
1820        fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
1821            self.report_hover(event, day_spec::DragPhase::Began);
1822        }
1823
1824        #[unsafe(method(mouseMoved:))]
1825        fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
1826            self.report_hover(event, day_spec::DragPhase::Changed);
1827        }
1828
1829        #[unsafe(method(mouseExited:))]
1830        fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
1831            self.report_hover(event, day_spec::DragPhase::Ended);
1832        }
1833
1834        #[unsafe(method(scrollWheel:))]
1835        fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
1836            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1837            let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
1838                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
1839                return;
1840            };
1841            ffi_guard::contain((), || {
1842                // Trackpads bracket a pan with phases; a discrete wheel tick has none and
1843                // arrives as a lone Changed — exactly the Event::Pan contract.
1844                let raw = unsafe { event.phase() };
1845                let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
1846                    day_spec::DragPhase::Began
1847                } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
1848                    || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
1849                {
1850                    day_spec::DragPhase::Ended
1851                } else {
1852                    day_spec::DragPhase::Changed
1853                };
1854                let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
1855                    event.scrollingDeltaY()
1856                });
1857                let win = unsafe { event.locationInWindow() };
1858                let loc = self.convertPoint_fromView(win, None);
1859                emit(
1860                    node,
1861                    Event::Pan {
1862                        phase,
1863                        delta,
1864                        location: Point::new(loc.x, loc.y),
1865                    },
1866                );
1867            })
1868        }
1869    }
1870);
1871
1872impl DayCanvas {
1873    fn new(mtm: MainThreadMarker) -> Retained<Self> {
1874        let this = Self::alloc(mtm).set_ivars(CanvasIvars);
1875        unsafe { msg_send![super(this), init] }
1876    }
1877
1878    /// One hover phase, reported to whichever node asked for it (docs/canvas.md "Interaction").
1879    ///
1880    /// `mouseEntered:`/`mouseExited:` are scoped by the tracking area, but **`mouseMoved:` is
1881    /// not**: it walks the responder chain, so a focused canvas hears about motion anywhere in
1882    /// its window — including outside itself. Hence the bounds test, without which a canvas
1883    /// reports a hover for a pointer that is nowhere near it (measured: a pointer parked outside
1884    /// the window entirely still produced hover positions).
1885    fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
1886        let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
1887        let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
1888            return;
1889        };
1890        ffi_guard::contain((), || {
1891            let win = unsafe { event.locationInWindow() };
1892            let loc = self.convertPoint_fromView(win, None);
1893            let b = self.bounds();
1894            let inside = loc.x >= b.origin.x
1895                && loc.x <= b.origin.x + b.size.width
1896                && loc.y >= b.origin.y
1897                && loc.y <= b.origin.y + b.size.height;
1898            // An exit is reported wherever it happens — that is the point of it — but a move
1899            // outside the view is not this view's hover.
1900            if !inside && phase != day_spec::DragPhase::Ended {
1901                return;
1902            }
1903            emit(
1904                node,
1905                Event::Hover {
1906                    phase,
1907                    location: Point::new(loc.x, loc.y),
1908                },
1909            );
1910        });
1911    }
1912}
1913
1914/// The tracking area a hovering canvas needs. `InVisibleRect` makes it follow the view's bounds,
1915/// so there is no rect to keep in step with layout; `ActiveInKeyWindow` matches the cursor areas
1916/// already installed here — a background window does not report hovers.
1917fn install_tracking_area(h: &NSView) {
1918    let opts = NSTrackingAreaOptions::MouseEnteredAndExited
1919        | NSTrackingAreaOptions::MouseMoved
1920        | NSTrackingAreaOptions::ActiveInKeyWindow
1921        | NSTrackingAreaOptions::InVisibleRect;
1922    let any: &objc2::runtime::AnyObject = h;
1923    let area = unsafe {
1924        NSTrackingArea::initWithRect_options_owner_userInfo(
1925            NSTrackingArea::alloc(),
1926            NSRect::ZERO,
1927            opts,
1928            Some(any),
1929            None,
1930        )
1931    };
1932    unsafe { h.addTrackingArea(&area) };
1933}
1934
1935// ---------------------------------------------------------------------------
1936// DayGesture — tap/drag recognizer target, node-id keyed (docs/shapes.md)
1937// ---------------------------------------------------------------------------
1938
1939struct GestureIvars {
1940    node: NodeId,
1941    kind: day_spec::GestureKind,
1942}
1943
1944define_class!(
1945    #[unsafe(super(NSObject))]
1946    #[thread_kind = MainThreadOnly]
1947    #[name = "DayGesture"]
1948    #[ivars = GestureIvars]
1949    struct DayGesture;
1950
1951    unsafe impl NSObjectProtocol for DayGesture {}
1952
1953    impl DayGesture {
1954        #[unsafe(method(fire:))]
1955        fn fire(&self, g: &NSGestureRecognizer) {
1956            ffi_guard::contain((), || {
1957                let node = self.ivars().node;
1958                let view = g.view();
1959                let loc = g.locationInView(view.as_deref());
1960                let at = Point::new(loc.x, loc.y);
1961                let phase = match g.state() {
1962                    NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
1963                    NSGestureRecognizerState::Ended
1964                    | NSGestureRecognizerState::Cancelled
1965                    | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
1966                    _ => day_spec::DragPhase::Changed,
1967                };
1968                let obj: &objc2::runtime::AnyObject = g.as_ref();
1969                match self.ivars().kind {
1970                    day_spec::GestureKind::Drag => {
1971                        let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
1972                            let t = unsafe { pan.translationInView(view.as_deref()) };
1973                            Point::new(t.x, t.y)
1974                        } else {
1975                            Point::ZERO
1976                        };
1977                        emit(node, Event::Drag { phase, location: at, translation });
1978                    }
1979                    day_spec::GestureKind::Pinch => {
1980                        // Cumulative since Began: `magnification` is the total delta (0 =
1981                        // unchanged), and Day's contract wants a factor.
1982                        let scale = if let Some(m) =
1983                            obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
1984                        {
1985                            1.0 + unsafe { m.magnification() }
1986                        } else {
1987                            1.0
1988                        };
1989                        emit(node, Event::Pinch { phase, scale, location: at });
1990                    }
1991                    _ => emit(node, Event::Tap(at)),
1992                }
1993            })
1994        }
1995    }
1996);
1997
1998impl DayGesture {
1999    fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2000        let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2001        unsafe { msg_send![super(this), init] }
2002    }
2003}
2004
2005// ---------------------------------------------------------------------------
2006// Navigation (docs/navigation.md): NSSplitView host, sidebar + detail panes.
2007// Page FRAMES are pane-owned (autoresized); Day lays content inside the size each
2008// page reports from setFrameSize:. Day's set_frame on pages is skipped.
2009// ---------------------------------------------------------------------------
2010
2011/// The stack presentation's back header (desktop has no system back affordance — this bar
2012/// gives a pushed page its way out, like AdwNavigationView's header on GTK). Hidden at root.
2013struct NavHeader {
2014    bar: Retained<NSView>,
2015    title: Retained<NSTextField>,
2016    /// Title per stack level (index 0 = root); the field shows the last.
2017    titles: Vec<String>,
2018    _target: Retained<DayTarget>,
2019}
2020
2021/// Height of the stack-nav back header while a pushed page is showing.
2022const NAV_HEADER_H: f64 = 34.0;
2023
2024// Drag limits for both draggable panes come from day-spec (`NAV_SIDEBAR_MIN_W` and friends): a
2025// sidebar NSSplitViewItem enforces them itself, which is why the divider no longer needs
2026// restoring by hand after every window resize.
2027use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2028
2029/// The content-list width to place divider 1 at, once, the first time the pane is showing —
2030/// `None` when the pane is collapsed or has already been placed. Latches on the way out, so the
2031/// two callers (the first frame pass, and the patch that reveals the pane) cannot both spend it.
2032fn take_list_placement(state: &mut NavState) -> Option<f64> {
2033    if !state.list_visible || state.list_positioned {
2034        return None;
2035    }
2036    state.list_positioned = true;
2037    state.list_width
2038}
2039
2040/// A tabs host's `NSTabView` margins inside its pane: the sides and the foot, and the top —
2041/// deeper, since the tabs themselves stand about a segment's height above the bezel.
2042const NAV_TABVIEW_INSET: f64 = 12.0;
2043const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2044
2045/// The `NavPresentation::Tabs` container: a real `NSTabView` — the Mac's own tab control, top
2046/// tabs on a bezel — whose items own the detail pages. The page frames stay native-owned
2047/// exactly as in a split: the tab view frames the selected item's view, and the page's
2048/// `setFrameSize:` reports it. The labels come from the NAV_MENU's rows, which arrive after
2049/// the pages' host (day-core mounts top-down: the rows page joins the host before its menu is
2050/// built), so `adopt_menu_for_tabs` runs when the menu is inserted and whenever its rows are
2051/// rebuilt.
2052///
2053/// Until 2026-09-12 this was an `NSSegmentedControl` docked at the foot, built from the rows
2054/// page's menu at the moment that page was inserted — before the menu existed — so no bar was
2055/// ever built and a tabs host showed its first page alone.
2056struct TabHost {
2057    view: Retained<objc2_app_kit::NSTabView>,
2058    /// The delegate reporting a native tab pick against the NAV_MENU's node; set once the menu
2059    /// is known.
2060    target: Option<Retained<DayTarget>>,
2061}
2062
2063thread_local! {
2064    /// A Day-driven tab selection in flight (`NavPatch::Select`, a label sync): the tab view's
2065    /// delegate must not echo it back as `SelectionChanged`.
2066    static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2067}
2068
2069/// Give the tab view its labels from the rows, and its selection. Rows and items are
2070/// index-aligned (destination `i` is item `i`); a count mismatch mid-rebuild labels what both
2071/// have.
2072fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2073    unsafe {
2074        let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2075        for (i, title) in titles.iter().enumerate().take(n) {
2076            tabs.view
2077                .tabViewItemAtIndex(i as isize)
2078                .setLabel(&NSString::from_str(title));
2079        }
2080        if n > 0 {
2081            TAB_PICK_SUPPRESS.with(|s| s.set(true));
2082            tabs.view
2083                .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2084            TAB_PICK_SUPPRESS.with(|s| s.set(false));
2085        }
2086    }
2087}
2088
2089/// A NAV_MENU reached a tabs host (its rows page sits in the host's collapsed sidebar pane):
2090/// the menu's rows become the tab labels and its node the delegate's target. Walks up from the
2091/// menu, so the innermost host — the one whose rows these are — is the one that takes them.
2092fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2093    let Some((titles, node)) = NAV_MENUS.with(|m| {
2094        m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2095            let ivars = d.ivars();
2096            (
2097                ivars
2098                    .items
2099                    .borrow()
2100                    .iter()
2101                    .map(|s| s.to_string())
2102                    .collect::<Vec<String>>(),
2103                ivars.node,
2104            )
2105        })
2106    }) else {
2107        return;
2108    };
2109    let mut up = unsafe { menu.superview() };
2110    while let Some(v) = up {
2111        let reached = NAV_STATE.with(|m| {
2112            let mut m = m.borrow_mut();
2113            let Some(s) = m.get_mut(&ptr_of(&v)) else {
2114                return false;
2115            };
2116            let selected = s.selected;
2117            if let Some(tabs) = s.tabs.as_mut() {
2118                if tabs.target.is_none() {
2119                    let target = DayTarget::new(mtm, node);
2120                    unsafe {
2121                        tabs.view
2122                            .setDelegate(Some(ProtocolObject::from_ref(&*target)))
2123                    };
2124                    tabs.target = Some(target);
2125                }
2126                sync_tab_labels(tabs, &titles, selected);
2127            }
2128            true
2129        });
2130        if reached {
2131            return;
2132        }
2133        up = unsafe { v.superview() };
2134    }
2135}
2136
2137struct NavState {
2138    sidebar_wrap: Retained<NSView>,
2139    detail_wrap: Retained<NSView>,
2140    /// The container behind the host view. A view holds NO strong reference to its controller,
2141    /// and the split view controller is what owns the items, their holding priorities, the
2142    /// sidebar's material and the split's delegate duties — so it has to be retained here or
2143    /// the sidebar loses its treatment the moment this realize returns.
2144    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2145    /// The sidebar item, for the `SidebarToggle` duty (docs/toolbars.md). AppKit's own
2146    /// `NSToolbarToggleSidebarItem` reaches the controller through the responder chain; this is
2147    /// the path dayscript and any non-toolbar caller take.
2148    sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2149    /// The content-list pane (docs/navigation.md), `Some` only on a host whose
2150    /// `NavProps::list_width` was set: the wrap its `Pane::List` page fills, and the
2151    /// `contentList` split item `NavPatch::ListVisible` collapses. The pane PERSISTS through
2152    /// every presentation (`Cap::NavContentList` = Native) — a narrow window collapses the
2153    /// sidebar and keeps the list, exactly as a narrow Mail.app does.
2154    list_wrap: Option<Retained<NSView>>,
2155    list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2156    /// The app's requested content-list width (`NavProps::list_width`) — applied once, at the
2157    /// first frame pass, by placing divider 1 (see `set_frame`).
2158    list_width: Option<f64>,
2159    /// Whether the content-list pane is showing (`NavProps::list_visible`, then
2160    /// `NavPatch::ListVisible`). Placing divider 1 for a pane that is collapsed is what re-opens
2161    /// it, so both placement paths ask first.
2162    list_visible: bool,
2163    /// Whether divider 1 has been placed at the app's requested width yet. Separate from
2164    /// `positioned` because the pane may not exist on screen when the first frame pass runs: an
2165    /// app opening on a full-width destination has nothing to size then, and spending the
2166    /// one-time placement there is what left the list at the solver's own width when it did
2167    /// appear.
2168    list_positioned: bool,
2169    /// Detail pages in stack order (the sidebar page is not in here in split mode; in stack
2170    /// mode `split == false`, the root page is here too, so push/pop visibility covers it).
2171    pages: Vec<Retained<NSView>>,
2172    /// The host's sidebar page, once it has one — what a re-present moves between the sidebar
2173    /// pane and the head of `pages` (docs/size-classes.md).
2174    sidebar_page: Option<Retained<NSView>>,
2175    /// The content-list pane's page, re-framed when the pane is first revealed: it was inserted
2176    /// into a collapsed wrap, where autoresizing can only keep it at zero.
2177    list_page: Option<Retained<NSView>>,
2178    positioned: bool,
2179    /// Which of the four presentations is drawn right now (docs/size-classes.md). All of them are
2180    /// the same `NSSplitViewController`: a stack is that split with its sidebar collapsed, a rail
2181    /// is it with a narrow one, and a tab bar is a collapsed sidebar plus the bottom bar below.
2182    presentation: NavPresentation,
2183    /// The detail page on screen, as an index into `pages`. Maintained by every patch that
2184    /// changes it — push, pop and select alike — so a re-present can carry it across.
2185    selected: usize,
2186    /// The tab view (`NavPresentation::Tabs` only), holding the detail pages as its items and
2187    /// labeled from the same rows the sidebar's outline view shows; a pick emits
2188    /// `SelectionChanged` against the same NAV_MENU node.
2189    tabs: Option<TabHost>,
2190    /// Back header (stack presentation only).
2191    header: Option<NavHeader>,
2192    /// The host's own title, kept so a re-present into a stack can seed a fresh back header
2193    /// with the same root title the initial build would have used.
2194    root_title: String,
2195    /// The host's node, for the same reason — a back header's button targets it.
2196    node: NodeId,
2197    /// How far the host reaches up under the window's title bar (see `pane_under_title_bar`):
2198    /// the strip each pane's wrap is kept below. Zero for a host that does not start at the top
2199    /// of a pinned window.
2200    title_strip: f64,
2201}
2202
2203/// A split item's view: a transparent pane that runs the item's full height, with `wrap` (the
2204/// view Day's pages and the rest of this backend frame themselves against) inside it.
2205///
2206/// `NSSplitViewController` expects its split view to reach the top of a full-size-content window
2207/// and lays its title-bar treatment over the top of every item: a title-bar background, and on
2208/// macOS 26 and later the frosted scroll pocket. Day pins its content below the title bar
2209/// (`pin_below_title_bar`), so a split framed where Day lays it out put that treatment over the
2210/// first strip of every page instead, blurring a detail page's heading. The host is framed up
2211/// under the bar instead (`set_frame`), and each wrap is held below the strip inside its pane, so
2212/// the treatment lands on the bar, the sidebar's material runs to the top of the window as
2213/// `allowsFullHeightLayout` intends, and every page still starts where Day laid it out.
2214fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2215    let pane = view_of(DayFlipped::new(mtm));
2216    unsafe {
2217        wrap.setFrame(pane.bounds());
2218        wrap.setAutoresizingMask(
2219            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2220                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2221        );
2222        pane.addSubview(wrap);
2223    }
2224    pane
2225}
2226
2227/// Hold `wrap` `strip` points below the top of the pane that holds it.
2228fn place_below_strip(wrap: &NSView, strip: f64) {
2229    let Some(pane) = (unsafe { wrap.superview() }) else {
2230        return;
2231    };
2232    let b = pane.bounds();
2233    unsafe {
2234        wrap.setFrame(NSRect::new(
2235            NSPoint::new(0.0, strip),
2236            NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2237        ))
2238    };
2239}
2240
2241/// The stack presentation's back header: a chevron + centered title docked above the pages,
2242/// hidden at the root. Desktop has no system back affordance, so a pushed page carries its own
2243/// way out (docs/navigation.md).
2244///
2245/// Built here rather than inline because a host that RE-PRESENTS into a stack needs one at that
2246/// moment (docs/size-classes.md), and a header that differed from the one a stack-at-launch host
2247/// gets would be a second shape to keep in step.
2248fn build_nav_header(
2249    mtm: MainThreadMarker,
2250    id: NodeId,
2251    detail_wrap: &NSView,
2252    root_title: &str,
2253) -> NavHeader {
2254    let bar = view_of(DayFlipped::new(mtm));
2255    let target = DayTarget::new(mtm, id);
2256    let back = unsafe {
2257        // Invariant: NSImageNameGoBackTemplate is one of AppKit's own named images, present
2258        // on every macOS release this backend builds for.
2259        let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2260            .expect("NSGoBackTemplate");
2261        let tobj: &objc2::runtime::AnyObject = target.as_ref();
2262        objc2_app_kit::NSButton::buttonWithImage_target_action(
2263            &img,
2264            Some(tobj),
2265            Some(sel!(navBack:)),
2266            mtm,
2267        )
2268    };
2269    let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2270    unsafe {
2271        back.setFrame(NSRect::new(
2272            NSPoint::new(6.0, 4.0),
2273            NSSize::new(30.0, NAV_HEADER_H - 8.0),
2274        ));
2275        title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2276        title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2277        title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2278        title.setFrame(NSRect::new(
2279            NSPoint::new(44.0, 9.0),
2280            NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2281        ));
2282        title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2283        bar.setFrame(NSRect::new(
2284            NSPoint::new(0.0, 0.0),
2285            NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2286        ));
2287        bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2288        bar.addSubview(&back);
2289        bar.addSubview(&title);
2290        bar.setHidden(true);
2291        detail_wrap.addSubview(&bar);
2292    }
2293    NavHeader {
2294        bar,
2295        title,
2296        titles: vec![root_title.to_string()],
2297        _target: target,
2298    }
2299}
2300
2301/// The frame a stack page occupies inside the detail wrap: full bounds at the root, inset below
2302/// the back header while a pushed page is showing. (A tabs host's pages are framed by its
2303/// `NSTabView`, never through here.)
2304fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
2305    let b = wrap.bounds();
2306    let top = if header_visible { NAV_HEADER_H } else { 0.0 };
2307    NSRect::new(
2308        NSPoint::new(0.0, top),
2309        NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
2310    )
2311}
2312
2313/// The row titles and the NAV_MENU node of the menu inside `page`, if it has one.
2314///
2315/// The tab bar needs the same rows the sidebar shows, and they arrive at the NAV_MENU rather
2316/// than at the host. Rather than plumb a second copy through the props, this walks down to the
2317/// menu that is already there — the sidebar page is Day-built and shallow, so the search is a
2318/// handful of views — and reads the titles it has stored for its own outline view.
2319fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
2320    fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
2321        if out.is_some() {
2322            return;
2323        }
2324        let found = NAV_MENUS.with(|m| {
2325            m.borrow()
2326                .get(&(v as *const NSView as usize))
2327                .map(|(_, d)| {
2328                    let ivars = d.ivars();
2329                    (
2330                        ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
2331                        ivars.node,
2332                    )
2333                })
2334        });
2335        if found.is_some() {
2336            *out = found;
2337            return;
2338        }
2339        for sub in unsafe { v.subviews() }.iter() {
2340            walk(&sub, out);
2341        }
2342    }
2343    let mut out = None;
2344    walk(page, &mut out);
2345    out
2346}
2347
2348/// Apply a presentation to the sidebar split item. All four are the same item at a different
2349/// thickness or collapsed outright, which is why a morph never rebuilds the split.
2350fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
2351    let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
2352    unsafe {
2353        item.setCanCollapse(shown);
2354        item.setCollapsed(!shown);
2355        match pres {
2356            NavPresentation::Split => {
2357                item.setAllowsFullHeightLayout(true);
2358                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2359                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2360            }
2361            // macOS has no rail: nothing in AppKit is a vertical strip of icon-only
2362            // destinations, and a source list pinned to icon width just truncates every row to an
2363            // ellipsis. `NavPresentation::Rail` is explicitly ROUNDABLE for exactly this case, so
2364            // it lands on the neighbor a Mac does have — an ordinary sidebar. Windows rounds the
2365            // other way (`PaneDisplayMode = LeftCompact` is a real rail there).
2366            NavPresentation::Rail => {
2367                item.setAllowsFullHeightLayout(true);
2368                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
2369                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
2370            }
2371            // Zero the thickness bounds before collapsing takes effect, or the pane keeps a
2372            // minimum width and the detail never reaches the window edge.
2373            NavPresentation::Stack | NavPresentation::Tabs => {
2374                item.setMinimumThickness(0.0);
2375                item.setMaximumThickness(0.0);
2376            }
2377        }
2378    }
2379}
2380
2381/// Show/hide the stack-nav back header for the given page stack and re-frame the pages under
2382/// it. The header shows exactly while a pushed page (depth ≥ 1 above the root) is on top; each
2383/// page's `DayNavPage::setFrameSize` reports the new size so Day re-lays its content.
2384/// The split view of the navigation host in `window` that has a content-list pane, for the
2385/// tracking separator pinned to its second divider (docs/toolbars.md).
2386pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
2387    NAV_STATE.with(|m| {
2388        m.borrow()
2389            .values()
2390            .find(|st| {
2391                st.list_item.is_some()
2392                    && st
2393                        .sidebar_wrap
2394                        .window()
2395                        .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
2396            })
2397            .map(|st| unsafe { st._split_vc.splitView() })
2398    })
2399}
2400
2401fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
2402    let visible = pages.len() >= 2;
2403    hdr.bar.setHidden(!visible);
2404    unsafe {
2405        hdr.title.setStringValue(&NSString::from_str(
2406            hdr.titles.last().map(String::as_str).unwrap_or(""),
2407        ));
2408    }
2409    let frame = nav_page_frame(wrap, visible);
2410    for page in pages {
2411        unsafe { page.setFrame(frame) };
2412    }
2413}
2414
2415/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
2416/// chrome changes but the pages do not.
2417///
2418/// Both presentations already share one `NSSplitViewController` — a stack is the same split with
2419/// its sidebar item collapsed to zero thickness — so the morph is three moves, and none of them
2420/// touches a page's CONTENT:
2421///
2422/// 1. the sidebar item collapses or expands (AppKit animates it and re-runs the titlebar
2423///    separator on its own),
2424/// 2. the sidebar PAGE moves between the sidebar wrap and the head of the detail stack,
2425/// 3. the back header appears or hides, since only a stack has one.
2426///
2427/// `addSubview` re-parents a view rather than rebuilding it, so every page keeps its subtree,
2428/// its scroll position, and its first responder across the move.
2429fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
2430    let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
2431        NAV_STATE.with(|m| {
2432            let st = m.borrow();
2433            let s = st.get(&ptr_of(host))?;
2434            Some((
2435                s.sidebar_page.clone(),
2436                s.detail_wrap.clone(),
2437                s.sidebar_wrap.clone(),
2438                s.sidebar_item.clone(),
2439                s.presentation,
2440                s.root_title.clone(),
2441                s.node,
2442                s.selected,
2443            ))
2444        })
2445    else {
2446        return;
2447    };
2448    if was == next {
2449        return;
2450    }
2451    apply_sidebar_item(&sidebar_item, next);
2452    // Settle the split now rather than at the next natural layout pass. `setCollapsed` marks the
2453    // split view as needing layout; without this the pane keeps its old width for one more frame,
2454    // which the dayscript screenshot seam captures (it renders the window offscreen the instant
2455    // the patch returns) and which a user crossing a breakpoint sees as a stutter.
2456    NAV_STATE.with(|m| {
2457        if let Some(s) = m.borrow().get(&ptr_of(host)) {
2458            unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
2459        }
2460    });
2461    // A stack needs a back header; nothing else may show one. Built on demand and kept
2462    // afterwards — rebuilding it on every morph would leak a target per crossing.
2463    let stacked = next == NavPresentation::Stack;
2464    let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
2465    if stacked && header.is_none() {
2466        header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
2467    }
2468    if let Some(hdr) = header.as_ref() {
2469        hdr.bar.setHidden(true);
2470    }
2471    // No tab view here: `Tabs` is a PINNED style on this backend (`Cap::NavTabsAdaptive` is
2472    // off), resolved the same at every width, so a host never morphs into or out of it — its
2473    // `NSTabView` is built at realize and lives for the host.
2474    // Which page is on screen, by IDENTITY: moving the sidebar page in or out of the detail list
2475    // shifts every index past it, so an index captured now would name the wrong page after.
2476    let mut pages = NAV_STATE.with(|m| {
2477        m.borrow()
2478            .get(&ptr_of(host))
2479            .map(|s| s.pages.clone())
2480            .unwrap_or_default()
2481    });
2482    let shown_page = pages.get(sel).cloned();
2483    // The sidebar page is a stack ROOT only while stacked; otherwise it lives in its own pane,
2484    // which is the sidebar in `Split`/`Rail` and a collapsed one behind a tab bar in `Tabs`.
2485    if let Some(page) = sidebar_page {
2486        pages.retain(|p| ptr_of(p) != ptr_of(&page));
2487        unsafe {
2488            if stacked {
2489                detail_wrap.addSubview(&page);
2490                pages.insert(0, page.clone());
2491            } else {
2492                page.setFrame(sidebar_wrap.bounds());
2493                sidebar_wrap.addSubview(&page);
2494            }
2495        }
2496        // A pane always shows its page; as a stack root it may have been hidden under a push.
2497        page.setHidden(false);
2498    }
2499    let shown = shown_page
2500        .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
2501        .unwrap_or_else(|| pages.len().saturating_sub(1));
2502    for (i, page) in pages.iter().enumerate() {
2503        page.setHidden(i != shown);
2504    }
2505    NAV_STATE.with(|m| {
2506        let mut m = m.borrow_mut();
2507        if let Some(s) = m.get_mut(&ptr_of(host)) {
2508            s.presentation = next;
2509            s.pages = pages;
2510            s.selected = shown;
2511            s.header = header;
2512            if let Some(hdr) = s.header.as_ref() {
2513                // Depth drives visibility, and the header is meaningless anywhere but a stack.
2514                if stacked {
2515                    sync_nav_header(hdr, &s.detail_wrap, &s.pages);
2516                } else {
2517                    hdr.bar.setHidden(true);
2518                }
2519            }
2520            if !stacked {
2521                // Leaving the stack: the pages were inset below the header, so give them the
2522                // pane back.
2523                let frame = nav_page_frame(&s.detail_wrap, false);
2524                for page in &s.pages {
2525                    unsafe { page.setFrame(frame) };
2526                }
2527            }
2528        }
2529    });
2530}
2531
2532// ---------------------------------------------------------------------------
2533// The sidebar pane holds its width through NSSplitViewController's own holding priorities
2534// (docs/navigation.md) — a sidebar NSSplitViewItem pins its thickness and lets the detail
2535// absorb a window resize, which is exactly the Finder/Mail behavior the hand-rolled
2536// `splitView:shouldAdjustSizeOfSubview:` delegate used to approximate. The controller IS the
2537// split's delegate, so Day must not install one of its own.
2538// ---------------------------------------------------------------------------
2539
2540struct CoverSheet(Retained<NSWindow>);
2541impl Drop for CoverSheet {
2542    fn drop(&mut self) {
2543        // Sheet transitions may run a nested AppKit update cycle. Defer them until the
2544        // core's tree borrow has ended; this retained pointer travels only to the main queue.
2545        let raw = Retained::into_raw(self.0.clone()) as usize;
2546        dispatch2::DispatchQueue::main().exec_async(move || {
2547            ffi_guard::contain((), || unsafe {
2548                let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
2549                if let Some(parent) = window.sheetParent() {
2550                    parent.endSheet(&window);
2551                }
2552                window.orderOut(None);
2553                window.setContentView(None);
2554            });
2555        });
2556    }
2557}
2558struct NavPageIvars {
2559    node: NodeId,
2560    /// A presented cover's strip under the window's title bar: the page paints it (its frame
2561    /// starts above the layout area) but lays its content out below it, and reports the
2562    /// remaining height (see `pin_below_title_bar`).
2563    top_inset: Cell<f64>,
2564    sheet: Cell<bool>,
2565    /// A half sheet (docs/cover.md): the window sheet stands half the parent's height.
2566    half: Cell<bool>,
2567}
2568
2569define_class!(
2570    #[unsafe(super(NSView))]
2571    #[thread_kind = MainThreadOnly]
2572    #[name = "DayNavPage"]
2573    #[ivars = NavPageIvars]
2574    struct DayNavPage;
2575
2576    impl DayNavPage {
2577        #[unsafe(method(isFlipped))]
2578        fn is_flipped(&self) -> bool {
2579            true
2580        }
2581
2582        #[unsafe(method(setFrameSize:))]
2583        fn set_frame_size(&self, size: NSSize) {
2584            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
2585            // Pane-driven resize (splitter drag, window resize): report the usable size
2586            // so NavLayout re-lays this page's content (enqueue-only, §8.3).
2587            ffi_guard::contain((), || {
2588                let inset = self.ivars().top_inset.get();
2589                emit(
2590                    self.ivars().node,
2591                    Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
2592                );
2593            })
2594        }
2595    }
2596);
2597
2598impl DayNavPage {
2599    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
2600        let this = Self::alloc(mtm).set_ivars(NavPageIvars {
2601            node,
2602            top_inset: Cell::new(0.0),
2603            sheet: Cell::new(false),
2604            half: Cell::new(false),
2605        });
2606        unsafe { msg_send![super(this), init] }
2607    }
2608}
2609
2610// ---------------------------------------------------------------------------
2611// Inspector (docs/inspector.md): an NSSplitViewController whose trailing pane is a REAL
2612// inspector item (`inspectorWithViewController:`) — the system treatment for exactly this
2613// surface: its own backing material, the standard thickness handling, full-height layout
2614// under the titlebar. Day's bound signal is the only visibility driver (the item cannot be
2615// user-collapsed), so this backend never emits `Event::InspectorChanged`.
2616// ---------------------------------------------------------------------------
2617
2618struct InspectorState {
2619    content_wrap: Handle,
2620    panel_wrap: Handle,
2621    /// Retained so the controller (the split's delegate) lives as long as its split.
2622    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2623    panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
2624}
2625
2626// ---------------------------------------------------------------------------
2627// Split (docs/split.md): a plain `NSSplitView` inside a flipped wrap (the wrap is the handle,
2628// so `set_frame`'s nav-host treatment of split views never sees it), two arranged flipped
2629// subviews as the panes, and a delegate that places the divider by the bound share, keeps
2630// both panes above the minimum, and reports a drag back as the new share.
2631// ---------------------------------------------------------------------------
2632
2633struct SplitState {
2634    split: Retained<objc2_app_kit::NSSplitView>,
2635    first_wrap: Handle,
2636    second_wrap: Handle,
2637    delegate: Retained<DaySplitDelegate>,
2638}
2639
2640struct SplitDelegateIvars {
2641    node: NodeId,
2642    min_pane: f64,
2643    /// The share as last patched or reported: what a report is compared against, and where
2644    /// the divider goes when the split first has a size or turns.
2645    share: Cell<f64>,
2646    /// The divider has been placed once; before that the split has no size to place it in.
2647    positioned: Cell<bool>,
2648    /// Day is moving the divider itself: the resize that follows is not a report.
2649    suppress: Cell<bool>,
2650}
2651
2652define_class!(
2653    #[unsafe(super(NSObject))]
2654    #[thread_kind = MainThreadOnly]
2655    #[name = "DaySplitDelegate"]
2656    #[ivars = SplitDelegateIvars]
2657    struct DaySplitDelegate;
2658
2659    unsafe impl NSObjectProtocol for DaySplitDelegate {}
2660
2661    unsafe impl NSSplitViewDelegate for DaySplitDelegate {
2662        #[unsafe(method(splitViewDidResizeSubviews:))]
2663        fn did_resize(&self, notification: &NSNotification) {
2664            ffi_guard::contain((), || {
2665                let Some(obj) = notification.object() else {
2666                    return;
2667                };
2668                let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
2669                    return;
2670                };
2671                let iv = self.ivars();
2672                let usable = split_usable(&sv);
2673                if usable <= 0.0 {
2674                    return;
2675                }
2676                // The first resize with a size: place the divider by the share, once.
2677                if !iv.positioned.replace(true) {
2678                    split_place(&sv, iv);
2679                    return;
2680                }
2681                if iv.suppress.get() {
2682                    return;
2683                }
2684                let Some(first) = sv.subviews().iter().next() else {
2685                    return;
2686                };
2687                let f = first.frame();
2688                let a = if sv.isVertical() {
2689                    f.size.width
2690                } else {
2691                    f.size.height
2692                };
2693                let share = (a / usable).clamp(0.0, 1.0);
2694                if (share - iv.share.get()).abs() > 1e-4 {
2695                    iv.share.set(share);
2696                    emit(iv.node, Event::ValueChanged(share));
2697                }
2698            })
2699        }
2700
2701        #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
2702        fn constrain_min(
2703            &self,
2704            _sv: &objc2_app_kit::NSSplitView,
2705            proposed: f64,
2706            _index: isize,
2707        ) -> f64 {
2708            proposed.max(self.ivars().min_pane)
2709        }
2710
2711        #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
2712        fn constrain_max(
2713            &self,
2714            sv: &objc2_app_kit::NSSplitView,
2715            proposed: f64,
2716            _index: isize,
2717        ) -> f64 {
2718            proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
2719        }
2720    }
2721);
2722
2723impl DaySplitDelegate {
2724    fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
2725        let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
2726            node,
2727            min_pane,
2728            share: Cell::new(share.clamp(0.0, 1.0)),
2729            positioned: Cell::new(false),
2730            suppress: Cell::new(false),
2731        });
2732        unsafe { msg_send![super(this), init] }
2733    }
2734}
2735
2736/// The length the two panes share along the split's axis: the frame minus the divider.
2737fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
2738    let frame = sv.frame();
2739    let len = if sv.isVertical() {
2740        frame.size.width
2741    } else {
2742        frame.size.height
2743    };
2744    (len - sv.dividerThickness()).max(0.0)
2745}
2746
2747/// Move the divider so the first pane takes the share, silently (Day's own write, not a drag).
2748fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
2749    let usable = split_usable(sv);
2750    if usable <= 0.0 {
2751        return;
2752    }
2753    iv.suppress.set(true);
2754    unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
2755    iv.suppress.set(false);
2756}
2757
2758// ---------------------------------------------------------------------------
2759
2760// ---------------------------------------------------------------------------
2761// DayNavMenuData — flat NSOutlineView source list for nav_menu() (docs/navigation.md)
2762// ---------------------------------------------------------------------------
2763
2764struct NavMenuIvars {
2765    node: NodeId,
2766    items: RefCell<Vec<Retained<NSString>>>,
2767    /// Pre-resolved template icons per row (docs/navigation.md), `None` where a row has no icon.
2768    /// Template images tint with the source-list's selection/appearance, so they read in light,
2769    /// dark, and while selected — the macOS-idiomatic sidebar look (Finder/Mail).
2770    icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2771    /// How much of each icon's box its drawing spans (`nav_icon_fill`), index-aligned with
2772    /// `icons`: the cell sizes the icon so the drawing matches a system sidebar glyph.
2773    icon_fills: RefCell<Vec<f64>>,
2774    /// Per-row icon tint (docs/vectors.md): recolors the template glyph via contentTintColor;
2775    /// `None` keeps the source-list's neutral template tint.
2776    tints: RefCell<Vec<Option<day_spec::Color>>>,
2777    /// Trailing accessory per item row (an unread count), `None` where a row has none.
2778    badges: RefCell<Vec<Option<Retained<NSString>>>>,
2779    /// Trailing accessory GLYPH per row, in the same slot as `badges` and drawn after it —
2780    /// a starred page's star. Resolved to images once per rebuild, like `icons`.
2781    icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
2782    badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
2783    /// Tint for `badge_icons`; `None` keeps the neutral template tint.
2784    badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
2785    /// Per-row context menu (docs/menus.md), empty = none. Built into an NSMenu and attached
2786    /// to the row's cell view, so a secondary click pops it like any native sidebar menu.
2787    menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
2788    /// Which items drag to reorder (`NavMenuProps::movable`); empty when none do.
2789    movable: RefCell<Vec<bool>>,
2790    /// Movable rows may cross section headers (`NavMenuProps::regroup`); set at creation.
2791    regroup: std::cell::Cell<bool>,
2792    /// Which movable items keep their section's sorted order (`NavMenuProps::sorted`).
2793    sorted: RefCell<Vec<bool>>,
2794    /// The outline's rows, in display order: `Some(i)` is item `i`, `None` is a section
2795    /// header. Day addresses rows by ITEM index, so every selection crossing the boundary
2796    /// goes through this map — a header must never shift what index 3 means.
2797    rows: RefCell<Vec<Option<usize>>>,
2798    /// One retained NSString per outline row: the row's text (a header's or an item's).
2799    row_objects: RefCell<Vec<Retained<NSString>>>,
2800    /// One NSNumber per outline row, holding the row's index: the outline's item IDENTITY.
2801    /// NSOutlineView matches items with `isEqual:`, so an NSString cannot be the identity —
2802    /// a section header titled "Controls" and an item titled "Controls" would collapse into one
2803    /// row, and the header would wear the item's icon. Row indexes are unique by construction.
2804    row_ids: RefCell<Vec<Retained<NSNumber>>>,
2805    /// Programmatic selection in flight: don't re-emit SelectionChanged.
2806    suppress: std::cell::Cell<bool>,
2807}
2808
2809struct NavCellIvars {
2810    /// The trailing accessories (an unread count, a status glyph), when the row has any: the
2811    /// label ends before them.
2812    accessory: RefCell<Option<Retained<NSView>>>,
2813    /// The unread count among them, sized to follow the row's text.
2814    count: RefCell<Option<Retained<NSTextField>>>,
2815    /// How much of the icon's box its drawing spans (`nav_icon_fill`).
2816    icon_fill: std::cell::Cell<f64>,
2817}
2818
2819define_class!(
2820    /// A sidebar row's cell. `NSTableCellView` lays out its icon and label itself, at the
2821    /// size the outline's row size style gives them: the system's Sidebar icon size setting,
2822    /// followed live (docs/navigation.md). This only makes room for the trailing accessories,
2823    /// which AppKit knows nothing about.
2824    #[unsafe(super(objc2_app_kit::NSTableCellView))]
2825    #[thread_kind = MainThreadOnly]
2826    #[name = "DayNavCell"]
2827    #[ivars = NavCellIvars]
2828    struct DayNavCell;
2829
2830    unsafe impl NSObjectProtocol for DayNavCell {}
2831
2832    impl DayNavCell {
2833        #[unsafe(method(layout))]
2834        fn layout(&self) {
2835            let _: () = unsafe { msg_send![super(self), layout] };
2836            ffi_guard::contain((), || self.fit_accessories());
2837        }
2838    }
2839);
2840
2841impl DayNavCell {
2842    fn new(mtm: MainThreadMarker) -> Retained<Self> {
2843        let this = Self::alloc(mtm).set_ivars(NavCellIvars {
2844            accessory: RefCell::new(None),
2845            count: RefCell::new(None),
2846            icon_fill: std::cell::Cell::new(1.0),
2847        });
2848        unsafe { msg_send![super(this), init] }
2849    }
2850
2851    /// After AppKit's layout: the count takes a size two points under the label's, and the
2852    /// label, which AppKit stretches to the cell's trailing edge, ends 6pt before the
2853    /// accessories so a long title truncates instead of running under its count. A showing
2854    /// progress ring re-fits the icon AppKit just sized.
2855    fn fit_accessories(&self) {
2856        let label = unsafe { self.textField() };
2857        if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
2858            let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
2859                (f.pointSize() - 2.0).max(9.0)
2860            });
2861            if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
2862                unsafe {
2863                    count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
2864                        size,
2865                        objc2_app_kit::NSFontWeightRegular,
2866                    )));
2867                }
2868                self.layoutSubtreeIfNeeded();
2869            }
2870        }
2871        if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
2872            let mut frame = label.frame();
2873            let end = accessory.frame().origin.x - 6.0;
2874            if frame.origin.x + frame.size.width > end {
2875                frame.size.width = (end - frame.origin.x).max(0.0);
2876                label.setFrame(frame);
2877            }
2878        }
2879        if let Some(icon) = unsafe { self.imageView() } {
2880            fit_nav_icon(&icon, self.ivars().icon_fill.get());
2881            nav_progress::fit(&icon);
2882        }
2883    }
2884}
2885
2886thread_local! {
2887    /// The side of a system sidebar glyph per symbol configuration (see `fit_nav_icon`).
2888    static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
2889}
2890
2891/// Draw a sidebar row's icon so its drawing is the size a system sidebar draws its SF Symbol,
2892/// centered in the slot AppKit lays out for it; `fill` is how much of the image's box the
2893/// drawing spans (`nav_icon_fill`). The slot is wider than the glyph AppKit puts there (22pt for a
2894/// 16pt glyph at Medium), and Day's icons are artwork that fills whatever frame it gets, so
2895/// left at the slot's size they read a third larger and heavier than Finder's or Mail's.
2896/// The side is measured, not tabled: a square symbol (`gearshape`) drawn with the symbol
2897/// configuration the row size style gave this image view, so it tracks the Sidebar icon size
2898/// setting and whatever a later macOS draws.
2899fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
2900    let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
2901        return;
2902    };
2903    let slot = icon.frame();
2904    // Configurations compare by value, and AppKit gives every cell of a row size style an
2905    // equal one, so the hash names the style.
2906    let key = config.hash() as u64;
2907    let side = NAV_GLYPH_SIDES
2908        .with(|m| m.borrow().get(&key).copied())
2909        .or_else(|| {
2910            let symbol =
2911                objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
2912                    &NSString::from_str("gearshape"),
2913                    None,
2914                )?;
2915            let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
2916            NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
2917            Some(side)
2918        });
2919    // The box that puts the drawing itself at the glyph's size: a Material Symbols icon keeps
2920    // the margin of its grid inside the box, so its box is that much larger.
2921    let Some(side) = side
2922        .filter(|s| *s > 0.0)
2923        .map(|s| (s / fill.clamp(0.25, 1.0)).round())
2924    else {
2925        return;
2926    };
2927    if slot.size.width <= side && slot.size.height <= side {
2928        return;
2929    }
2930    icon.setFrame(NSRect::new(
2931        NSPoint::new(
2932            (slot.origin.x + (slot.size.width - side) / 2.0).round(),
2933            (slot.origin.y + (slot.size.height - side) / 2.0).round(),
2934        ),
2935        NSSize::new(side, side),
2936    ));
2937}
2938
2939define_class!(
2940    #[unsafe(super(objc2_app_kit::NSTableRowView))]
2941    #[thread_kind = MainThreadOnly]
2942    #[name = "DayNavRowView"]
2943    struct DayNavRowView;
2944
2945    unsafe impl NSObjectProtocol for DayNavRowView {}
2946
2947    impl DayNavRowView {
2948        /// Always report the emphasized (key-window) state, so the selected sidebar row draws
2949        /// the accent pill with auto-whitened label/icon in both themes. Without this, a run
2950        /// whose window never becomes key (scripted screenshot captures) falls back to the
2951        /// unemphasized selection fill, which under a forced appearance rendered as a
2952        /// near-black pill that swallowed the row's label.
2953        #[unsafe(method(isEmphasized))]
2954        fn is_emphasized(&self) -> bool {
2955            true
2956        }
2957    }
2958);
2959
2960define_class!(
2961    #[unsafe(super(objc2_app_kit::NSOutlineView))]
2962    #[thread_kind = MainThreadOnly]
2963    #[name = "DayNavOutlineView"]
2964    struct DayNavOutlineView;
2965
2966    unsafe impl NSObjectProtocol for DayNavOutlineView {}
2967
2968    impl DayNavOutlineView {
2969        /// The clicked row's context menu (docs/menus.md): NSTableView-family views consume
2970        /// right-clicks themselves, so per-row menus are served here — resolve the row under
2971        /// the click, then build the same NSMenu the piece decorator would.
2972        #[unsafe(method_id(menuForEvent:))]
2973        fn menu_for_event(
2974            &self,
2975            event: &objc2_app_kit::NSEvent,
2976        ) -> Option<Retained<NSMenu>> {
2977            ffi_guard::contain(None, || {
2978                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2979                let row = unsafe { self.rowAtPoint(point) };
2980                let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
2981                // `define_class!` rewrites the return, so no early `return` — one expression.
2982                match data {
2983                    None => None,
2984                    Some(d) => {
2985                        let items = d
2986                            .item_of_row(row)
2987                            .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
2988                            .unwrap_or_default();
2989                        if items.is_empty() {
2990                            None
2991                        } else {
2992                            Some(build_ns_menu(d.mtm(), "", &items))
2993                        }
2994                    }
2995                }
2996            })
2997        }
2998    }
2999);
3000
3001define_class!(
3002    #[unsafe(super(NSObject))]
3003    #[thread_kind = MainThreadOnly]
3004    #[name = "DayNavMenuData"]
3005    #[ivars = NavMenuIvars]
3006    struct DayNavMenuData;
3007
3008    unsafe impl NSObjectProtocol for DayNavMenuData {}
3009
3010    unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3011        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3012        fn number_of_children(
3013            &self,
3014            _ov: &objc2_app_kit::NSOutlineView,
3015            item: Option<&objc2::runtime::AnyObject>,
3016        ) -> isize {
3017            if item.is_none() {
3018                self.ivars().row_objects.borrow().len() as isize
3019            } else {
3020                0
3021            }
3022        }
3023
3024        #[unsafe(method_id(outlineView:child:ofItem:))]
3025        fn child_of_item(
3026            &self,
3027            _ov: &objc2_app_kit::NSOutlineView,
3028            index: isize,
3029            _item: Option<&objc2::runtime::AnyObject>,
3030        ) -> Retained<objc2::runtime::AnyObject> {
3031            let ids = self.ivars().row_ids.borrow();
3032            // AppKit only asks for children it was told exist, but a stale query racing a
3033            // reload must degrade (an unmatched identity) rather than index out of bounds —
3034            // a panic here unwinds into an ObjC frame and aborts.
3035            let id = ids
3036                .get(index as usize)
3037                .cloned()
3038                .unwrap_or_else(|| NSNumber::new_isize(-1));
3039            unsafe { objc2::rc::Retained::cast_unchecked(id) }
3040        }
3041
3042        #[unsafe(method(outlineView:isItemExpandable:))]
3043        fn is_expandable(
3044            &self,
3045            _ov: &objc2_app_kit::NSOutlineView,
3046            _item: &objc2::runtime::AnyObject,
3047        ) -> bool {
3048            false
3049        }
3050
3051        // --- drag-to-reorder (docs/navigation.md "Reordering sidebar destinations"): the
3052        // outline's own drag pipeline, with the Gap placeholder Finder's sidebar shows. A row
3053        // moves within the run of movable rows around it, or, regrouping, into any section of
3054        // movable rows (`regroup_gap`); the app's data change brings the new order back as
3055        // `NavMenuPatch::Items`.
3056
3057        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3058        fn pasteboard_writer_for_item(
3059            &self,
3060            _ov: &objc2_app_kit::NSOutlineView,
3061            item: &objc2::runtime::AnyObject,
3062        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3063            let make = || {
3064                let row = Self::outline_row(item);
3065                let index = self.item_of_row(row)?;
3066                if !self.is_movable(index) {
3067                    return None;
3068                }
3069                let pbitem = objc2_app_kit::NSPasteboardItem::new();
3070                unsafe {
3071                    pbitem.setString_forType(
3072                        &NSString::from_str(&row.to_string()),
3073                        &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3074                    );
3075                }
3076                Some(ProtocolObject::from_retained(pbitem))
3077            };
3078            ffi_guard::contain(None, make)
3079        }
3080
3081        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3082        fn validate_drop(
3083            &self,
3084            ov: &objc2_app_kit::NSOutlineView,
3085            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3086            item: Option<&objc2::runtime::AnyObject>,
3087            child_index: isize,
3088        ) -> objc2_app_kit::NSDragOperation {
3089            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3090                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3091                    return objc2_app_kit::NSDragOperation::None;
3092                };
3093                // A drop past the run's end lands at that end: move the gap there.
3094                if drop.retarget {
3095                    unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3096                }
3097                objc2_app_kit::NSDragOperation::Move
3098            })
3099        }
3100
3101        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3102        fn accept_drop(
3103            &self,
3104            ov: &objc2_app_kit::NSOutlineView,
3105            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3106            item: Option<&objc2::runtime::AnyObject>,
3107            child_index: isize,
3108        ) -> bool {
3109            ffi_guard::contain(false, || {
3110                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3111                    return false;
3112                };
3113                // Deferred through the event queue: the app's callback never runs inside
3114                // AppKit's drop, and its data change reloads the rows in the new order.
3115                match drop.moves {
3116                    Some(NavMove::Reorder { from, to }) => {
3117                        emit(self.ivars().node, Event::ListReorder { from, to });
3118                    }
3119                    Some(NavMove::Regroup {
3120                        from,
3121                        section,
3122                        before,
3123                    }) => emit(
3124                        self.ivars().node,
3125                        Event::NavRegroup {
3126                            from,
3127                            section,
3128                            before,
3129                        },
3130                    ),
3131                    None => {}
3132                }
3133                true
3134            })
3135        }
3136    }
3137
3138    unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3139
3140    unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3141        /// Section headers are AppKit group rows: the source-list treatment (small, bold,
3142        /// secondary) comes free, and they are excluded from selection below.
3143        #[unsafe(method(outlineView:isGroupItem:))]
3144        fn is_group_item(
3145            &self,
3146            _ov: &objc2_app_kit::NSOutlineView,
3147            item: &objc2::runtime::AnyObject,
3148        ) -> bool {
3149            let row = Self::outline_row(item);
3150            row >= 0 && self.item_of_row(row).is_none()
3151        }
3152
3153        #[unsafe(method(outlineView:shouldSelectItem:))]
3154        fn should_select(
3155            &self,
3156            _ov: &objc2_app_kit::NSOutlineView,
3157            item: &objc2::runtime::AnyObject,
3158        ) -> bool {
3159            self.item_of_row(Self::outline_row(item)).is_some()
3160        }
3161
3162        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3163        fn view_for(
3164            &self,
3165            ov: &objc2_app_kit::NSOutlineView,
3166            _col: Option<&objc2_app_kit::NSTableColumn>,
3167            item: &objc2::runtime::AnyObject,
3168        ) -> Option<Retained<NSView>> {
3169            let mtm = self.mtm();
3170            let row = Self::outline_row(item);
3171            let text = self
3172                .ivars()
3173                .row_objects
3174                .borrow()
3175                .get(usize::try_from(row).unwrap_or(usize::MAX))
3176                .cloned();
3177            // No early returns: the method_id macro owns the return conversion.
3178            text.map(|text| {
3179                let text: &NSString = &text;
3180                let Some(index) = self.item_of_row(row) else {
3181                    // A section header: a plain label. AppKit gives group rows their own
3182                    // typography and places the text, so this only supplies it.
3183                    let cell = DayNavCell::new(mtm);
3184                    let label = unsafe { NSTextField::labelWithString(text, mtm) };
3185                    unsafe {
3186                        label.cell().inspect(|c| {
3187                            c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3188                        });
3189                        cell.addSubview(&label);
3190                        cell.setTextField(Some(&label));
3191                    }
3192                    return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3193                };
3194                let icon = self
3195                    .ivars()
3196                    .icons
3197                    .borrow()
3198                    .get(index)
3199                    .and_then(|o| o.clone());
3200                let badge = self
3201                    .ivars()
3202                    .badges
3203                    .borrow()
3204                    .get(index)
3205                    .and_then(|o| o.clone());
3206                let badge_icon = self
3207                    .ivars()
3208                    .badge_icons
3209                    .borrow()
3210                    .get(index)
3211                    .and_then(|o| o.clone());
3212                let badge_tint = self
3213                    .ivars()
3214                    .badge_tints
3215                    .borrow()
3216                    .get(index)
3217                    .copied()
3218                    .flatten();
3219                // The cell places the icon and the label itself, at the row size style's size
3220                // (the system's Sidebar icon size); `DayNavCell` keeps the label clear of the
3221                // trailing accessories.
3222                let cell = DayNavCell::new(mtm);
3223                let label = unsafe { NSTextField::labelWithString(text, mtm) };
3224                unsafe {
3225                    // Feed titles are arbitrarily long, so the label truncates with an
3226                    // ellipsis within the frame the cell gives it.
3227                    label.cell().inspect(|c| {
3228                        c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3229                    });
3230                    cell.addSubview(&label);
3231                    cell.setTextField(Some(&label));
3232                    // The badge sits at the trailing edge and keeps its intrinsic width; the
3233                    // label truncates into whatever is left, so a long feed name never pushes
3234                    // its own unread count off the pane.
3235                    // Both accessories share the trailing slot: the count (if any) and then
3236                    // the status glyph (if any), in a stack so a row can carry either or both
3237                    // without the constraints below caring which it got.
3238                    let accessory = objc2_app_kit::NSStackView::new(mtm);
3239                    accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3240                    accessory.setOrientation(
3241                        objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3242                    );
3243                    accessory.setSpacing(4.0);
3244                    let mut has_accessory = false;
3245                    let trailing: Retained<NSView> = match &badge {
3246                        Some(text) => {
3247                            let b = NSTextField::labelWithString(text, mtm);
3248                            b.setTranslatesAutoresizingMaskIntoConstraints(false);
3249                            b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3250                            b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3251                            b.setFont(Some(
3252                                &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3253                                    objc2_app_kit::NSFont::smallSystemFontSize(),
3254                                    objc2_app_kit::NSFontWeightRegular,
3255                                ),
3256                            ));
3257                            b.setContentCompressionResistancePriority_forOrientation(
3258                                objc2_app_kit::NSLayoutPriorityRequired,
3259                                objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3260                            );
3261                            *cell.ivars().count.borrow_mut() = Some(b.clone());
3262                            accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3263                                objc2::rc::Retained::into_super(b),
3264                            ));
3265                            has_accessory = true;
3266                            let v: Retained<NSView> =
3267                                objc2::rc::Retained::into_super(accessory.clone());
3268                            v
3269                        }
3270                        None => objc2::rc::Retained::into_super(accessory.clone()),
3271                    };
3272                    // The status glyph, tinted where the app gave it a meaning-bearing color
3273                    // (a star is yellow because that is what a star IS, not because the theme
3274                    // says so). Template images take contentTintColor exactly as the row's
3275                    // leading icon does.
3276                    if let Some(img) = &badge_icon {
3277                        let iv = objc2_app_kit::NSImageView::new(mtm);
3278                        iv.setImage(Some(img));
3279                        iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3280                        if let Some(c) = badge_tint {
3281                            iv.setContentTintColor(Some(&nscolor(c)));
3282                        }
3283                        iv.setContentCompressionResistancePriority_forOrientation(
3284                            objc2_app_kit::NSLayoutPriorityRequired,
3285                            objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3286                        );
3287                        accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
3288                        has_accessory = true;
3289                    }
3290                    cell.addSubview(&trailing);
3291                    if has_accessory {
3292                        *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
3293                    }
3294                    objc2_app_kit::NSLayoutConstraint::activateConstraints(
3295                        &objc2_foundation::NSArray::from_retained_slice(&[
3296                            trailing
3297                                .trailingAnchor()
3298                                .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
3299                            trailing
3300                                .centerYAnchor()
3301                                .constraintEqualToAnchor(&cell.centerYAnchor()),
3302                        ]),
3303                    );
3304                }
3305                if let Some(img) = icon {
3306                    let fill = self.ivars().icon_fills.borrow().get(index).copied();
3307                    cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
3308                    let tint = self.ivars().tints.borrow().get(index).copied().flatten();
3309                    let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
3310                    unsafe {
3311                        iv.setImage(Some(&img));
3312                        // Per-row tint (docs/vectors.md): the icons are template images, so
3313                        // contentTintColor recolors the alpha mask; None keeps the neutral look.
3314                        if let Some(t) = tint {
3315                            iv.setContentTintColor(Some(&nscolor(t)));
3316                        }
3317                        iv.setImageScaling(
3318                            objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
3319                        );
3320                        cell.addSubview(&iv);
3321                        cell.setImageView(Some(&iv));
3322                        let progress = self
3323                            .ivars()
3324                            .icon_progress
3325                            .borrow()
3326                            .iter()
3327                            .find(|(row, _)| *row == index)
3328                            .map(|(_, f)| *f);
3329                        nav_progress::update(&iv, progress);
3330                    }
3331                }
3332                objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
3333            })
3334        }
3335
3336        #[unsafe(method_id(outlineView:rowViewForItem:))]
3337        fn row_view_for(
3338            &self,
3339            _ov: &objc2_app_kit::NSOutlineView,
3340            _item: &objc2::runtime::AnyObject,
3341        ) -> Retained<objc2_app_kit::NSTableRowView> {
3342            let row: Retained<DayNavRowView> =
3343                unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
3344            objc2::rc::Retained::into_super(row)
3345        }
3346
3347        #[unsafe(method(outlineViewSelectionDidChange:))]
3348        fn selection_did_change(&self, notification: &NSNotification) {
3349            ffi_guard::contain((), || {
3350                if self.ivars().suppress.get() {
3351                    return;
3352                }
3353                let Some(obj) = (unsafe { notification.object() }) else {
3354                    return;
3355                };
3356                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
3357                    return;
3358                };
3359                let row = unsafe { ov.selectedRow() };
3360                if let Some(item) = self.item_of_row(row) {
3361                    emit(self.ivars().node, Event::SelectionChanged(item as i64));
3362                }
3363            })
3364        }
3365    }
3366);
3367
3368thread_local! {
3369    /// `nav_icon_fill` per icon name: a sidebar rebuilds its rows on every count change, and an
3370    /// icon's drawing does not change with them.
3371    static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
3372}
3373
3374/// `nav_icon_fill` for each resolved icon, by name; 1 where a row has none.
3375fn nav_icon_fills(
3376    names: &[Option<String>],
3377    images: &[Option<Retained<objc2_app_kit::NSImage>>],
3378) -> Vec<f64> {
3379    names
3380        .iter()
3381        .zip(images)
3382        .map(|(name, image)| match (name, image) {
3383            (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
3384                *m.borrow_mut()
3385                    .entry(name.clone())
3386                    .or_insert_with(|| nav_icon_fill(image))
3387            }),
3388            _ => 1.0,
3389        })
3390        .collect()
3391}
3392
3393/// How much of an icon's box its drawing spans along its longer side, in (0, 1]: a Material
3394/// Symbols glyph keeps the 80-unit margin of its 960-unit grid (about 0.83), an SF Symbol export
3395/// is boxed to its content (1), and artwork usually fills its square. Measured from the alpha of
3396/// one small render, since a plain SVG says nothing about where its drawing sits.
3397fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
3398    const PX: f64 = 64.0;
3399    let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
3400        return 1.0;
3401    };
3402    let (w, h) = (
3403        rep.pixelsWide().max(0) as usize,
3404        rep.pixelsHigh().max(0) as usize,
3405    );
3406    let stride = rep.bytesPerRow().max(0) as usize;
3407    let data = unsafe { rep.bitmapData() };
3408    if data.is_null() || stride < w * 4 {
3409        return 1.0;
3410    }
3411    // SAFETY: `scaled_rep` made a meshed 8-bit RGBA bitmap of `h` rows of `stride` bytes, which
3412    // `rep` owns and keeps alive for this borrow.
3413    let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
3414    let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
3415    for y in 0..h {
3416        for x in 0..w {
3417            if bytes[y * stride + x * 4 + 3] > 24 {
3418                (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
3419            }
3420        }
3421    }
3422    if x1 <= x0 || y1 <= y0 {
3423        return 1.0;
3424    }
3425    // The render stretched the image to a square; back in the image's own proportions, the
3426    // drawing's longer extent over the image's longer side is what proportional scaling keeps.
3427    let size = image.size();
3428    let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
3429    let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
3430    ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
3431}
3432
3433fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
3434    // A bundled icon name → a template NSImage (tinted by the source list); `None` per iconless row.
3435    icons
3436        .iter()
3437        .map(|ic| {
3438            let name = ic.as_deref()?;
3439            // Prefer the glyph SVG (docs/vectors.md): NSImage renders it at display size.
3440            let path = day_spec::resource::resolve_vector_svg(name)
3441                .or_else(|| day_spec::resource::resolve_image_file(name))?;
3442            use objc2::AllocAnyThread as _;
3443            let img = unsafe {
3444                objc2_app_kit::NSImage::initWithContentsOfFile(
3445                    objc2_app_kit::NSImage::alloc(),
3446                    &NSString::from_str(&path.to_string_lossy()),
3447                )
3448            }?;
3449            // Downloaded/user-file icons are artwork; bundled glyphs remain templates.
3450            unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
3451            Some(img)
3452        })
3453        .collect()
3454}
3455
3456impl DayNavMenuData {
3457    #[allow(clippy::too_many_arguments)]
3458    fn new(
3459        mtm: MainThreadMarker,
3460        node: NodeId,
3461        items: &[String],
3462        icons: &[Option<String>],
3463        badges: &[Option<String>],
3464        badge_icons: &[Option<String>],
3465        badge_tints: &[Option<day_spec::Color>],
3466        sections: &[Option<String>],
3467        tints: &[Option<day_spec::Color>],
3468        menus: &[Vec<day_spec::MenuItem>],
3469    ) -> Retained<Self> {
3470        let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
3471            node,
3472            items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
3473            icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
3474            icons: RefCell::new(resolve_nav_icons(icons)),
3475            tints: RefCell::new(tints.to_vec()),
3476            menus: RefCell::new(menus.to_vec()),
3477            movable: RefCell::new(Vec::new()),
3478            regroup: std::cell::Cell::new(false),
3479            sorted: RefCell::new(Vec::new()),
3480            badges: RefCell::new(ns_badges(badges)),
3481            icon_progress: RefCell::new(Vec::new()),
3482            badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
3483            badge_tints: RefCell::new(badge_tints.to_vec()),
3484            rows: RefCell::new(Vec::new()),
3485            row_objects: RefCell::new(Vec::new()),
3486            row_ids: RefCell::new(Vec::new()),
3487            suppress: std::cell::Cell::new(false),
3488        });
3489        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
3490        this.rebuild_rows(items, sections);
3491        this
3492    }
3493
3494    /// Data-driven rows changed (`NavMenuPatch::Items`): swap the stored decorations in place.
3495    // The parameters are the patch's payload: index-aligned per-row decoration arrays, each
3496    // landing in its own ivar. Bundling them would just move the same eight fields.
3497    #[allow(clippy::too_many_arguments)]
3498    fn set_items(
3499        &self,
3500        items: &[String],
3501        icons: &[Option<String>],
3502        badges: &[Option<String>],
3503        badge_icons: &[Option<String>],
3504        badge_tints: &[Option<day_spec::Color>],
3505        sections: &[Option<String>],
3506        tints: &[Option<day_spec::Color>],
3507        menus: &[Vec<day_spec::MenuItem>],
3508    ) {
3509        *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
3510        let resolved = resolve_nav_icons(icons);
3511        *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
3512        *self.ivars().icons.borrow_mut() = resolved;
3513        *self.ivars().tints.borrow_mut() = tints.to_vec();
3514        *self.ivars().menus.borrow_mut() = menus.to_vec();
3515        *self.ivars().badges.borrow_mut() = ns_badges(badges);
3516        self.ivars().icon_progress.borrow_mut().clear();
3517        *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
3518        *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
3519        self.rebuild_rows(items, sections);
3520    }
3521
3522    /// Flatten items + section headers into the outline's display rows. Each row gets its own
3523    /// retained NSString so the outline can tell two rows apart by identity even when their
3524    /// labels match (two feeds legitimately share a title).
3525    fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
3526        let mut rows = Vec::with_capacity(items.len());
3527        let mut objects = Vec::with_capacity(items.len());
3528        for (i, label) in items.iter().enumerate() {
3529            if let Some(Some(header)) = sections.get(i) {
3530                rows.push(None);
3531                objects.push(NSString::from_str(header));
3532            }
3533            rows.push(Some(i));
3534            objects.push(NSString::from_str(label));
3535        }
3536        let ids = (0..objects.len())
3537            .map(|i| NSNumber::new_isize(i as isize))
3538            .collect();
3539        *self.ivars().rows.borrow_mut() = rows;
3540        *self.ivars().row_objects.borrow_mut() = objects;
3541        *self.ivars().row_ids.borrow_mut() = ids;
3542    }
3543
3544    /// The outline row an item object names — the index its NSNumber identity carries — or
3545    /// `-1` for anything that is not one of ours (a stale query racing a reload).
3546    fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
3547        item.downcast_ref::<NSNumber>()
3548            .map(|n| n.integerValue())
3549            .unwrap_or(-1)
3550    }
3551
3552    /// Outline row → day item index.
3553    fn item_of_row(&self, row: isize) -> Option<usize> {
3554        if row < 0 {
3555            return None;
3556        }
3557        self.ivars()
3558            .rows
3559            .borrow()
3560            .get(row as usize)
3561            .copied()
3562            .flatten()
3563    }
3564
3565    /// Day item index → outline row.
3566    fn row_of_item(&self, item: usize) -> Option<usize> {
3567        self.ivars()
3568            .rows
3569            .borrow()
3570            .iter()
3571            .position(|r| *r == Some(item))
3572    }
3573
3574    fn is_movable(&self, item: usize) -> bool {
3575        self.ivars()
3576            .movable
3577            .borrow()
3578            .get(item)
3579            .copied()
3580            .unwrap_or(false)
3581    }
3582
3583    /// What a drop proposal means for a reorder, or `None` when it is no drop of ours: a drag
3584    /// from another view, of a row that cannot move, or (regrouping) to a gap no rule allows.
3585    /// Reordering, the gap clamps to the run of movable rows around the dragged one, which
3586    /// section headers and fixed rows end ([`reorder_gap`]); regrouping, see [`regroup_gap`].
3587    fn nav_drop(
3588        &self,
3589        ov: &objc2_app_kit::NSOutlineView,
3590        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3591        item: Option<&objc2::runtime::AnyObject>,
3592        child_index: isize,
3593    ) -> Option<NavDrop> {
3594        let src = unsafe { info.draggingSource() }?;
3595        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
3596            != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
3597        {
3598            return None;
3599        }
3600        let pb = unsafe { info.draggingPasteboard() };
3601        let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
3602            .to_string()
3603            .parse::<usize>()
3604            .ok()?;
3605        let rows = self.ivars().rows.borrow();
3606        // The flat outline proposes a gap among the root's children, or a row itself (a drop
3607        // ONTO it, index -1).
3608        let proposed = match item {
3609            Some(item) => Self::outline_row(item),
3610            None => child_index,
3611        };
3612        let proposed = usize::try_from(proposed).unwrap_or(rows.len());
3613        if self.ivars().regroup.get() {
3614            regroup_gap(
3615                &rows,
3616                &self.ivars().movable.borrow(),
3617                &self.ivars().sorted.borrow(),
3618                from_row,
3619                proposed,
3620                item.is_some(),
3621            )
3622        } else {
3623            reorder_gap(
3624                &rows,
3625                &self.ivars().movable.borrow(),
3626                from_row,
3627                proposed,
3628                item.is_some(),
3629            )
3630        }
3631    }
3632}
3633
3634/// A drop in a sidebar outline (`DayNavMenuData::nav_drop`).
3635#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3636struct NavDrop {
3637    /// The gap the row drops into, among the outline's rows.
3638    gap: usize,
3639    /// The proposal named some other place, and the gap moves here.
3640    retarget: bool,
3641    /// What the drop reports, or `None` for a drop back in place.
3642    moves: Option<NavMove>,
3643}
3644
3645/// What a sidebar drop reports, in item indices (the rows before the move).
3646#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3647enum NavMove {
3648    /// `Event::ListReorder`: `from` takes `to`'s place.
3649    Reorder { from: usize, to: usize },
3650    /// `Event::NavRegroup`: `from` joins the section whose first row is `section`, before
3651    /// `before` or at the section's end.
3652    Regroup {
3653        from: usize,
3654        section: usize,
3655        before: Option<usize>,
3656    },
3657}
3658
3659/// A reorder drop at `proposed`, a gap among the outline's `rows` (`None` a header, `Some(i)`
3660/// item `i`), for the row at `from_row`; `onto` when the proposal named a row itself, which
3661/// reads as the gap above it. The gap clamps to the run of movable rows around the dragged
3662/// one, which section headers and fixed rows end. `None` when that row cannot move.
3663fn reorder_gap(
3664    rows: &[Option<usize>],
3665    movable: &[bool],
3666    from_row: usize,
3667    proposed: usize,
3668    onto: bool,
3669) -> Option<NavDrop> {
3670    let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
3671    let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
3672    let in_run = |r: usize| rows[r].is_some_and(is_movable);
3673    let first = (0..from_row)
3674        .rev()
3675        .take_while(|r| in_run(*r))
3676        .last()
3677        .unwrap_or(from_row);
3678    let last = (from_row + 1..rows.len())
3679        .take_while(|r| in_run(*r))
3680        .last()
3681        .unwrap_or(from_row);
3682    let gap = proposed.clamp(first, last + 1);
3683    // The row's place once it has left its own: the row whose position it takes.
3684    let target_row = if gap > from_row { gap - 1 } else { gap };
3685    let moves = (target_row != from_row)
3686        .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
3687        .flatten();
3688    Some(NavDrop {
3689        gap,
3690        retarget: gap != proposed || onto,
3691        moves,
3692    })
3693}
3694
3695/// A regroup drop at `proposed`, a gap among the outline's `rows` (as [`reorder_gap`]'s), for
3696/// the row at `from_row` (docs/navigation.md "Moving rows between sections"). The gap's section
3697/// is the nearest header above it, or the rows above the first header; `before` is the item
3698/// right below the gap when that row is in the same section. A drop ONTO a header reads as
3699/// that section's first gap, onto an item as the gap above it. `None` when the row cannot
3700/// move, the gap is above the first header with no rows there, the section holds a fixed row,
3701/// or the gap is in the row's own section and the row is sorted. Gaps are never clamped.
3702fn regroup_gap(
3703    rows: &[Option<usize>],
3704    movable: &[bool],
3705    sorted: &[bool],
3706    from_row: usize,
3707    proposed: usize,
3708    onto: bool,
3709) -> Option<NavDrop> {
3710    let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
3711    let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
3712    let gap = match rows.get(proposed) {
3713        Some(None) if onto => proposed + 1,
3714        _ => proposed.min(rows.len()),
3715    };
3716    // The first outline row of the section a gap (or a row, as the gap above it) sits in.
3717    let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
3718        Some(header) => Some(header + 1),
3719        None => rows.first().copied().flatten().map(|_| 0),
3720    };
3721    let first = section_start(gap)?;
3722    let end = (first..rows.len())
3723        .find(|r| rows[*r].is_none())
3724        .unwrap_or(rows.len());
3725    let section = rows.get(first).copied().flatten()?;
3726    if !rows[first..end]
3727        .iter()
3728        .all(|r| r.is_some_and(|i| flag(movable, i)))
3729    {
3730        return None;
3731    }
3732    let own = section_start(from_row) == Some(first);
3733    if own && flag(sorted, from) {
3734        return None;
3735    }
3736    let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
3737        from,
3738        section,
3739        before: rows.get(gap).copied().flatten(),
3740    });
3741    Some(NavDrop {
3742        gap,
3743        retarget: gap != proposed || onto,
3744        moves,
3745    })
3746}
3747
3748#[cfg(test)]
3749mod nav_gap_tests {
3750    use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
3751
3752    /// 0 today, 1 [news], 2 a, 3 b, 4 e, 5 [tech], 6 c, 7 d, 8 [smart], 9 starred: items 0..=6.
3753    const ROWS: [Option<usize>; 10] = [
3754        Some(0),
3755        None,
3756        Some(1),
3757        Some(2),
3758        Some(3),
3759        None,
3760        Some(4),
3761        Some(5),
3762        None,
3763        Some(6),
3764    ];
3765    /// The feeds move; today and starred are fixed.
3766    const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
3767    const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
3768    const UNSORTED: [bool; 7] = [false; 7];
3769
3770    fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
3771        Some(NavMove::Regroup {
3772            from,
3773            section,
3774            before,
3775        })
3776    }
3777
3778    #[test]
3779    fn regroup_gaps_name_the_section_above_and_the_row_below() {
3780        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3781        // a, into tech's first gap: before c.
3782        assert_eq!(
3783            at(2, 6),
3784            Some(NavDrop {
3785                gap: 6,
3786                retarget: false,
3787                moves: regroup(1, 4, Some(4)),
3788            })
3789        );
3790        // c, into the gap above tech's header: the end of news.
3791        assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
3792        // a, between c and d, and at tech's end above smart's header.
3793        assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
3794        assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
3795    }
3796
3797    #[test]
3798    fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
3799        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
3800        // Smart holds starred, and the rows above the first header hold today.
3801        for gap in [0, 1, 9, 10] {
3802            assert_eq!(at(2, gap), None, "gap {gap}");
3803        }
3804        // A sorted row's own section offers no gap, its own place included.
3805        for gap in [2, 3, 4, 5] {
3806            assert_eq!(at(2, gap), None, "gap {gap}");
3807        }
3808        // Fixed rows and headers never drag.
3809        assert_eq!(at(0, 6), None);
3810        assert_eq!(at(1, 6), None);
3811        assert_eq!(at(9, 6), None);
3812    }
3813
3814    #[test]
3815    fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
3816        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
3817        // a, between b and e.
3818        assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
3819        // a, at news's end above tech's header.
3820        assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
3821        // Back in place, either side of itself: a drop that reports nothing.
3822        for gap in [2, 3] {
3823            let drop = at(2, gap).expect("offered");
3824            assert_eq!(drop.moves, None, "gap {gap}");
3825        }
3826    }
3827
3828    #[test]
3829    fn regroup_drops_onto_a_row_move_to_a_gap() {
3830        // Onto tech's header: its first gap. Onto d: the gap above d.
3831        assert_eq!(
3832            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
3833            Some(NavDrop {
3834                gap: 6,
3835                retarget: true,
3836                moves: regroup(1, 4, Some(4)),
3837            })
3838        );
3839        assert_eq!(
3840            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
3841            Some(NavDrop {
3842                gap: 7,
3843                retarget: true,
3844                moves: regroup(1, 4, Some(5)),
3845            })
3846        );
3847    }
3848
3849    #[test]
3850    fn regroup_offers_nothing_above_a_leading_header() {
3851        // 0 [news], 1 a, 2 [tech], 3 b.
3852        let rows = [None, Some(0), None, Some(1)];
3853        let movable = [true, true];
3854        let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
3855        assert_eq!(at(0), None);
3856        assert_eq!(at(1).map(|d| d.moves), Some(None));
3857        assert_eq!(at(2).map(|d| d.moves), Some(None));
3858        assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
3859        assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
3860    }
3861
3862    #[test]
3863    fn reorder_gaps_clamp_to_the_run() {
3864        // a past the run's end lands at its end: e's place.
3865        assert_eq!(
3866            reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
3867            Some(NavDrop {
3868                gap: 5,
3869                retarget: true,
3870                moves: Some(NavMove::Reorder { from: 1, to: 3 }),
3871            })
3872        );
3873        // Back in place.
3874        assert_eq!(
3875            reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
3876            Some(None)
3877        );
3878        // b above the run's start lands at a's place; a fixed row offers nothing.
3879        assert_eq!(
3880            reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
3881            Some(NavMove::Reorder { from: 2, to: 1 })
3882        );
3883        assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
3884    }
3885}
3886
3887/// The private pasteboard type carrying a dragged sidebar row (local reorder only).
3888const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
3889
3890/// Badge strings, retained once per rebuild rather than per cell.
3891fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
3892    badges
3893        .iter()
3894        .map(|b| b.as_deref().map(NSString::from_str))
3895        .collect()
3896}
3897
3898// ---------------------------------------------------------------------------
3899/// Force the table's visible rows to exist on the next main-loop turn — outside any `with_tree`
3900/// borrow, so `bind_row` may build them. `layoutSubtreeIfNeeded` is not enough: an occluded
3901/// window's table skips row tiling entirely, so `viewAtColumn:row:makeIfNecessary:` is the only
3902/// reliable way to realize rows without a draw pass (§10; see the Reload patch for why).
3903fn post_realize_visible_rows(key: usize) {
3904    <AppKit as Platform>::post(Box::new(move || {
3905        if let Some((table, data)) = list_entry(key) {
3906            unsafe { table.layoutSubtreeIfNeeded() };
3907            let range = unsafe { table.rowsInRect(table.visibleRect()) };
3908            if let Some(source) = data.ivars().source.borrow().clone()
3909                && let Some(report) = &source.first_visible
3910            {
3911                report(range.location.min((source.len)().saturating_sub(1)));
3912            }
3913            for row in range.location..range.location + range.length {
3914                let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
3915                // A snapshot/layout can have requested this cell while day-core held its
3916                // tree borrow. The delegate then returned an empty container; AppKit caches
3917                // it and will not ask viewForRow again. Complete that skipped bind here.
3918                if let Some(cell) = cell
3919                    && cell.subviews().is_empty()
3920                {
3921                    let source = data.ivars().source.borrow().clone();
3922                    if let Some(source) = source {
3923                        (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
3924                    }
3925                }
3926            }
3927        }
3928        // The builds above queued their styling effects; drain them now — outside the pump, no
3929        // event may arrive for a while (idle app), and a snapshot would capture bare rows.
3930        day_core::pump_events();
3931    }));
3932}
3933
3934/// A native drop changes the snapshot synchronously and suppresses the app's echo Reload.
3935/// Once AppKit has unwound its drop/gap tracking, reconcile the table with that snapshot:
3936/// the incremental move alone can leave its row tiling and scroll extent out of sync.
3937/// Preserve the user's viewport and selection; never force a jump to the moved row.
3938fn post_settle_list_drop(key: usize) {
3939    <AppKit as Platform>::post(Box::new(move || {
3940        // Publish the deferred on_reorder before reading the final row set. App code may
3941        // remove rows or close the list, so resolve the native handles only after the drain.
3942        day_core::pump_events();
3943        let Some((table, data)) = list_entry(key) else {
3944            return;
3945        };
3946        let Some(scroll) = table.enclosingScrollView() else {
3947            return;
3948        };
3949        let clip = scroll.contentView();
3950        let origin = clip.bounds().origin;
3951        let selected = table.selectedRowIndexes();
3952        let suppressed = data.ivars().suppress.replace(true);
3953        table.reloadData();
3954        // Outside with_tree: tiling is allowed to bind/rebind Day's cell contents here.
3955        table.layoutSubtreeIfNeeded();
3956        let restored = objc2_foundation::NSMutableIndexSet::new();
3957        for row in 0..table.numberOfRows().max(0) as usize {
3958            if selected.containsIndex(row) {
3959                restored.addIndex(row);
3960            }
3961        }
3962        table.selectRowIndexes_byExtendingSelection(&restored, false);
3963        let mut bounds = clip.bounds();
3964        bounds.origin = origin;
3965        clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
3966        scroll.reflectScrolledClipView(&clip);
3967        data.ivars().suppress.set(suppressed);
3968        post_realize_visible_rows(key);
3969    }));
3970}
3971
3972// DayListData — NSTableView data-source + delegate for the recycling list (docs/list.md, §10)
3973//
3974// No custom NSTableRowView: the table runs the PLAIN style, whose standard row view lays cell
3975// views out at the full row bounds — no inset to pin away — and whose cell-frame slide is what
3976// animates a row-action swipe. (A `layout`-override pin lived here under FullWidth until
3977// 2026-08; it also froze row content mid-swipe, revealing actions behind a motionless row.)
3978// ---------------------------------------------------------------------------
3979
3980define_class!(
3981    #[unsafe(super(NSTableView))]
3982    #[thread_kind = MainThreadOnly]
3983    #[name = "DayListView"]
3984    struct DayListView;
3985    unsafe impl NSObjectProtocol for DayListView {}
3986    impl DayListView {
3987        /// NSTableView consumes right-clicks before the row's container sees them. Resolve
3988        /// its summon-time provider from the visible cell, never from the selected row.
3989        #[unsafe(method_id(menuForEvent:))]
3990        fn menu_for_event(
3991            &self,
3992            event: &objc2_app_kit::NSEvent,
3993        ) -> Option<Retained<NSMenu>> {
3994            ffi_guard::contain(None, || {
3995                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3996                let row = unsafe { self.rowAtPoint(point) };
3997                let provider = if row >= 0 {
3998                    unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
3999                        .and_then(|cell| list_row_menu_provider(&cell))
4000                } else {
4001                    None
4002                };
4003                match provider {
4004                    Some((view, provider)) => {
4005                        let point = view.convertPoint_fromView(
4006                            unsafe { event.locationInWindow() }, None,
4007                        );
4008                        let items = provider(day_spec::Point::new(point.x, point.y));
4009                        if items.is_empty() {
4010                            None
4011                        } else {
4012                            Some(build_ns_menu(self.mtm(), "", &items))
4013                        }
4014                    }
4015                    None => unsafe { msg_send![super(self), menuForEvent: event] },
4016                }
4017            })
4018        }
4019
4020        #[unsafe(method(becomeFirstResponder))]
4021        fn become_first_responder(&self) -> bool {
4022            let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4023            if accepted {
4024                self.report_focus(true);
4025            }
4026            accepted
4027        }
4028
4029        #[unsafe(method(resignFirstResponder))]
4030        fn resign_first_responder(&self) -> bool {
4031            let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4032            if accepted {
4033                self.report_focus(false);
4034            }
4035            accepted
4036        }
4037
4038        #[unsafe(method(keyDown:))]
4039        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4040            ffi_guard::contain((), || {
4041                let key = unsafe { event.keyCode() };
4042                if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4043                    let row = unsafe { self.selectedRow() };
4044                    if row >= 0 && let Some(target) = unsafe { self.target() } {
4045                        let _: () = unsafe { msg_send![&*target, activateRow: self] };
4046                        return;
4047                    }
4048                }
4049                let _: () = unsafe { msg_send![super(self), keyDown: event] };
4050            });
4051        }
4052    }
4053);
4054
4055/// The cell can wrap its decorated row in layout containers. Search only this visible
4056/// cell, not other rows; cloning the provider releases the registry borrow before app code.
4057fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4058    if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
4059        return Some((view.retain(), provider));
4060    }
4061    view.subviews()
4062        .iter()
4063        .find_map(|view| list_row_menu_provider(&view))
4064}
4065
4066/// Plain labels receive the mouse event before their row does. Resolve the nearest dynamic
4067/// owner without copying providers onto descendants (which would go stale on recycling).
4068/// `Some(None)` means an owner deliberately returned no menu; do not fall through to a parent.
4069fn inherited_context_menu(
4070    view: &NSView,
4071    event: &objc2_app_kit::NSEvent,
4072) -> Option<Option<Retained<NSMenu>>> {
4073    let mut current = Some(view.retain());
4074    while let Some(view) = current {
4075        if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4076            let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4077            let items = provider(day_spec::Point::new(point.x, point.y));
4078            return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4079        }
4080        current = unsafe { view.superview() };
4081    }
4082    None
4083}
4084
4085impl DayListView {
4086    fn report_focus(&self, focused: bool) {
4087        ffi_guard::contain((), || {
4088            if let Some(target) = unsafe { self.target() }
4089                && let Some(data) = target.downcast_ref::<DayListData>()
4090            {
4091                emit(data.ivars().node, Event::FocusChanged(focused));
4092            }
4093        });
4094    }
4095}
4096
4097struct ListIvars {
4098    node: NodeId,
4099    /// Injected by `attach_list` once day-core wires the driver.
4100    source: RefCell<Option<ListSource>>,
4101    selectable: std::cell::Cell<bool>,
4102    /// Multi-select mode (docs/list.md): every change reports the FULL selected set.
4103    multi: std::cell::Cell<bool>,
4104    /// Programmatic selection in flight: don't re-emit SelectionChanged.
4105    suppress: std::cell::Cell<bool>,
4106    /// The row-token order this table currently displays — the baseline `permutation_moves`
4107    /// diffs a Reload against (docs/list.md: a same-set reorder animates as row moves).
4108    tokens: RefCell<Vec<u64>>,
4109    /// `RowHeight::Automatic` (docs/list.md "Row heights"): each row is as tall as Day laid
4110    /// it, through `tableView:heightOfRow:`. A uniform list never answers that selector, so
4111    /// NSTableView keeps its fixed-pitch fast path.
4112    automatic: bool,
4113    /// The list has section headers (docs/list.md "Sections"): AppKit group rows, which float
4114    /// at the top as their section scrolls under them. A header sizes to its content in any
4115    /// list, so a sectioned list answers `tableView:heightOfRow:` even when it is uniform.
4116    sections: bool,
4117    /// The height a header nobody has bound yet is given, like `estimate` for rows.
4118    header_estimate: std::cell::Cell<f64>,
4119    /// Each self-sizing row's height by row token, as Day last laid it. By token, not row: a
4120    /// splice or a drag moves rows without rebinding them.
4121    heights: RefCell<std::collections::HashMap<u64, f64>>,
4122    /// The row token each bound cell shows, so `RowSizeInvalidated` (which names the cell)
4123    /// finds the height it corrects.
4124    cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4125    /// The height a row nobody has bound yet is given: the last one Day measured, so a list
4126    /// of like rows scrolls without its rows jumping as they arrive.
4127    estimate: std::cell::Cell<f64>,
4128    /// A height pass is posted and not yet run (`post_row_heights` coalesces).
4129    heights_pending: std::cell::Cell<bool>,
4130}
4131
4132define_class!(
4133    #[unsafe(super(NSObject))]
4134    #[thread_kind = MainThreadOnly]
4135    #[name = "DayListData"]
4136    #[ivars = ListIvars]
4137    struct DayListData;
4138
4139    unsafe impl NSObjectProtocol for DayListData {}
4140    unsafe impl NSControlTextEditingDelegate for DayListData {}
4141
4142    impl DayListData {
4143        /// Only a self-sizing list answers `tableView:heightOfRow:`: NSTableView asks that
4144        /// of every row on each reload, and a uniform list's fixed `rowHeight` is the fast
4145        /// path. NSTableView reads this once, at `setDelegate:`, after `automatic` is set.
4146        #[unsafe(method(respondsToSelector:))]
4147        fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4148            if selector == objc2::sel!(tableView:heightOfRow:)
4149                && !self.ivars().automatic
4150                && !self.ivars().sections
4151            {
4152                false
4153            } else {
4154                unsafe { msg_send![super(self), respondsToSelector: selector] }
4155            }
4156        }
4157
4158        #[unsafe(method(listViewportChanged:))]
4159        fn list_viewport_changed(&self, notification: &NSNotification) {
4160            ffi_guard::contain((), || {
4161                let source = self.ivars().source.borrow().clone();
4162                if let Some(source) = source && let Some(report) = &source.first_visible
4163                    && let Some(object) = notification.object()
4164                    && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4165                    && let Some(document) = clip.documentView()
4166                    && let Some(table) = document.downcast_ref::<NSTableView>() {
4167                    let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4168                    report(visible.location.min((source.len)().saturating_sub(1)));
4169                }
4170            });
4171        }
4172
4173        #[unsafe(method(activateRow:))]
4174        fn activate_row(&self, table: &NSTableView) {
4175            ffi_guard::contain((), || {
4176                let row = unsafe { table.selectedRow() };
4177                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4178            });
4179        }
4180        #[unsafe(method(doubleClickRow:))]
4181        fn double_click_row(&self, table: &NSTableView) {
4182            ffi_guard::contain((), || {
4183                let row = unsafe { table.clickedRow() };
4184                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4185            });
4186        }
4187    }
4188
4189    unsafe impl NSTableViewDataSource for DayListData {
4190        #[unsafe(method(numberOfRowsInTableView:))]
4191        fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4192            // Reads the piece's snapshot only (no tree access) — safe even when called
4193            // synchronously from reloadData inside a with_tree borrow. Guarded because
4194            // `len` is a day-core closure.
4195            ffi_guard::contain(0, || {
4196                self.ivars()
4197                    .source
4198                    .borrow()
4199                    .as_ref()
4200                    .map(|s| (s.len)() as isize)
4201                    .unwrap_or(0)
4202            })
4203        }
4204
4205        // --- drag-to-reorder (docs/list.md): NSTableView's native drag pipeline. The dragged
4206        // row rides the pasteboard as a private-typed string; `validateDrop` consults the app's
4207        // guard live (the `.gap` feedback style opens the placeholder gap only where the guard
4208        // allows), and `acceptDrop` commits through the sync seam, then animates the native move.
4209
4210        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4211        fn pasteboard_writer_for_row(
4212            &self,
4213            _tv: &NSTableView,
4214            row: isize,
4215        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4216            // (Closure body: define_class converts only the TAIL expression, so early `return`s
4217            // must not escape the method itself.)
4218            let make = || {
4219                // Only reorderable lists write drag items — no seam, no drag.
4220                let reorderable = self
4221                    .ivars()
4222                    .source
4223                    .borrow()
4224                    .as_ref()
4225                    .is_some_and(|s| s.reorder.is_some());
4226                // A group row (a section header) never lifts (docs/list.md "Sections").
4227                if !reorderable || row < 0 || self.is_header(row) {
4228                    return None;
4229                }
4230                let item = objc2_app_kit::NSPasteboardItem::new();
4231                unsafe {
4232                    item.setString_forType(
4233                        &NSString::from_str(&row.to_string()),
4234                        &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4235                    );
4236                }
4237                Some(ProtocolObject::from_retained(item))
4238            };
4239            ffi_guard::contain(None, make)
4240        }
4241
4242        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4243        fn validate_drop(
4244            &self,
4245            tv: &NSTableView,
4246            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4247            row: isize,
4248            _op: objc2_app_kit::NSTableViewDropOperation,
4249        ) -> objc2_app_kit::NSDragOperation {
4250            // Guarded: `can_move` consults the app's reorder guard closure.
4251            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4252                let Some((from, len)) = self.drag_context(tv, info) else {
4253                    return objc2_app_kit::NSDragOperation::None;
4254                };
4255                // Normalize to an above insertion point (the gap style's semantics), convert to
4256                // the post-removal target index, and ask the guard.
4257                let ins = row.clamp(0, len as isize) as usize;
4258                let to = insertion_to_target(from, ins, len);
4259                let accepted = self.can_move(from, to);
4260                if accepted < 0 {
4261                    return objc2_app_kit::NSDragOperation::None;
4262                }
4263                let accepted = (accepted as usize).min(len.saturating_sub(1));
4264                if accepted != to {
4265                    // The guard retargeted: move the gap to where the drop would actually land.
4266                    unsafe {
4267                        tv.setDropRow_dropOperation(
4268                            target_to_insertion(from, accepted) as isize,
4269                            objc2_app_kit::NSTableViewDropOperation::Above,
4270                        );
4271                    }
4272                }
4273                objc2_app_kit::NSDragOperation::Move
4274            })
4275        }
4276
4277        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4278        fn accept_drop(
4279            &self,
4280            tv: &NSTableView,
4281            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4282            row: isize,
4283            _op: objc2_app_kit::NSTableViewDropOperation,
4284        ) -> bool {
4285            // (Closure body: early `return`s must not escape the define_class method itself.)
4286            let drop = || {
4287                let Some((from, len)) = self.drag_context(tv, info) else {
4288                    return false;
4289                };
4290                let ins = row.clamp(0, len as isize) as usize;
4291                let to = insertion_to_target(from, ins, len);
4292                let accepted = self.can_move(from, to);
4293                if accepted < 0 {
4294                    return false;
4295                }
4296                let accepted = (accepted as usize).min(len.saturating_sub(1));
4297                if accepted == from {
4298                    return true; // dropped back home — nothing to commit
4299                }
4300                // Commit through the sync seam (rotates Day's snapshot, defers the app
4301                // callback), THEN animate the native move — the data source already answers in
4302                // the new order.
4303                let mv = self
4304                    .ivars()
4305                    .source
4306                    .borrow()
4307                    .as_ref()
4308                    .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
4309                let Some(mv) = mv else { return false };
4310                mv(from, accepted);
4311                // Keep the displayed-order cache in step (the commit's echo skips the Reload
4312                // that would otherwise refresh it — see `permutation_moves`).
4313                {
4314                    let mut toks = self.ivars().tokens.borrow_mut();
4315                    if from < toks.len() && accepted < toks.len() {
4316                        let t = toks.remove(from);
4317                        toks.insert(accepted, t);
4318                    }
4319                }
4320                unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
4321                if let Some(scroll) = tv.enclosingScrollView() {
4322                    post_settle_list_drop(ptr_of(&scroll));
4323                }
4324                true
4325            };
4326            // Guarded: the commit runs the seam's move closure into day-core and the app.
4327            ffi_guard::contain(false, drop)
4328        }
4329    }
4330
4331    unsafe impl NSTableViewDelegate for DayListData {
4332        /// A self-sizing row's height (docs/list.md "Row heights"): the height Day laid it at
4333        /// once it has been bound, the running estimate until then. Asked before the row's view
4334        /// exists, often from inside `reloadData` under a day-core borrow, so it reads only this
4335        /// table's own record and the source's token snapshot.
4336        #[unsafe(method(tableView:heightOfRow:))]
4337        fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
4338            ffi_guard::contain(44.0, || {
4339                let ivars = self.ivars();
4340                let header = self.is_header(row);
4341                // A uniform sectioned list: rows keep the fixed pitch, headers size themselves.
4342                if !header && !ivars.automatic {
4343                    return unsafe { tv.rowHeight() };
4344                }
4345                let token = ivars
4346                    .source
4347                    .borrow()
4348                    .as_ref()
4349                    .filter(|s| row >= 0 && (row as usize) < (s.len)())
4350                    .map(|s| (s.token_at)(row as usize));
4351                token
4352                    .and_then(|t| ivars.heights.borrow().get(&t).copied())
4353                    .unwrap_or_else(|| {
4354                        if header {
4355                            ivars.header_estimate.get()
4356                        } else {
4357                            ivars.estimate.get()
4358                        }
4359                    })
4360            })
4361        }
4362
4363        /// Section headers are AppKit group rows (docs/list.md "Sections"): drawn in the
4364        /// group style, spanning the row, and floated over their section by
4365        /// `floatsGroupRows`.
4366        #[unsafe(method(tableView:isGroupRow:))]
4367        fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
4368            ffi_guard::contain(false, || self.is_header(row))
4369        }
4370
4371        /// A header is not an item: clicks and arrow keys pass over it.
4372        #[unsafe(method(tableView:shouldSelectRow:))]
4373        fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
4374            ffi_guard::contain(true, || !self.is_header(row))
4375        }
4376
4377        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
4378        fn view_for_row(
4379            &self,
4380            tv: &NSTableView,
4381            _col: Option<&NSTableColumn>,
4382            row: isize,
4383        ) -> Option<Retained<NSView>> {
4384            // Guarded: `bind_row` builds the app's row content.
4385            ffi_guard::contain(None, || {
4386                let mtm = self.mtm();
4387                // Headers pool apart from rows, so a recycled cell keeps its kind and rebinds.
4388                let header = self.is_header(row);
4389                let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
4390                // Recycle a cell view if one is free; else make a fresh flipped container.
4391                let cell: Retained<NSView> =
4392                    unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
4393                        let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
4394                        unsafe { v.setIdentifier(Some(&ident)) };
4395                        v
4396                    });
4397                // Day builds row content the first time it sees this cell, and rebinds
4398                // (slot-write) when the cell is recycled. NSTableView calls this outside
4399                // reloadData's stack, so the re-entry into with_tree is safe.
4400                let source = self.ivars().source.borrow().clone();
4401                if let Some(source) = source {
4402                    let raw = Retained::as_ptr(&cell) as RawHandle;
4403                    (source.bind_row)(row as usize, raw);
4404                    if self.ivars().automatic || header {
4405                        self.note_row_height(tv, &source, row, raw, header);
4406                    }
4407                }
4408                Some(cell)
4409            })
4410        }
4411
4412        #[unsafe(method(tableView:didRemoveRowView:forRow:))]
4413        fn did_remove_row_view(
4414            &self,
4415            _tv: &NSTableView,
4416            row_view: &objc2_app_kit::NSTableRowView,
4417            _row: isize,
4418        ) {
4419            // The row went back to the reuse pool (a reload dropping it past a shrunk source, a
4420            // scroll): clear its day element ids so it stops answering lookups, as the tree's
4421            // `outlineView:didRemoveRowView:forRow:` does. Deferred, since this fires inside
4422            // reload stacks that hold the day-core borrow, and re-checked: a cell the same
4423            // turn's reload already reused has a window again, and its fresh ids must survive.
4424            ffi_guard::contain((), || {
4425                let Some(cell) = row_view.subviews().iter().find(|sub| {
4426                    sub.identifier()
4427                        .map(|i| {
4428                            let i = i.to_string();
4429                            i == DAY_ROW_CELL || i == DAY_HEADER_CELL
4430                        })
4431                        .unwrap_or(false)
4432                }) else {
4433                    return;
4434                };
4435                // Raw +1 pointers across the post (the closure must be Send, which Retained is
4436                // not; everything stays on the main thread). AppKit may free a removed row view.
4437                let cell = Retained::into_raw(cell) as usize;
4438                let Some(this) = (unsafe {
4439                    Retained::retain(self as *const DayListData as *mut DayListData)
4440                }) else {
4441                    return;
4442                };
4443                let this = Retained::into_raw(this) as usize;
4444                <AppKit as Platform>::post(Box::new(move || {
4445                    // Reclaim both +1s first, so every early return balances them.
4446                    let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4447                    let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
4448                    let (Some(this), Some(cell)) = (this, cell) else {
4449                        return;
4450                    };
4451                    if cell.window().is_some() {
4452                        return; // reused already: its ids are the live row's
4453                    }
4454                    let recycle = this
4455                        .ivars()
4456                        .source
4457                        .borrow()
4458                        .as_ref()
4459                        .map(|s| s.recycle.clone());
4460                    if let Some(recycle) = recycle {
4461                        recycle(Retained::as_ptr(&cell) as RawHandle);
4462                    }
4463                }));
4464            })
4465        }
4466
4467        #[unsafe(method(tableViewSelectionDidChange:))]
4468        fn selection_did_change(&self, notification: &NSNotification) {
4469            ffi_guard::contain((), || {
4470                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
4471                    return;
4472                }
4473                let Some(obj) = (unsafe { notification.object() }) else {
4474                    return;
4475                };
4476                let Ok(tv) = obj.downcast::<NSTableView>() else {
4477                    return;
4478                };
4479                if self.ivars().multi.get() {
4480                    // Multi-select: report the FULL set (ascending; empty = cleared).
4481                    let idx = unsafe { tv.selectedRowIndexes() };
4482                    let mut rows = Vec::with_capacity(idx.count());
4483                    let mut i = idx.firstIndex();
4484                    while i != objc2_foundation::NSNotFound as usize {
4485                        rows.push(i as i64);
4486                        i = unsafe { idx.indexGreaterThanIndex(i) };
4487                    }
4488                    emit(self.ivars().node, Event::SelectionSet(rows));
4489                } else {
4490                    let row = unsafe { tv.selectedRow() };
4491                    if row >= 0 {
4492                        emit(self.ivars().node, Event::SelectionChanged(row as i64));
4493                    } else {
4494                        // CLEARED. `selectedRow()` answers -1, which is not a row, so there is
4495                        // nothing for `SelectionChanged` to carry and nothing for `on_select` to
4496                        // be called with — but the app still has to hear about it, or a detail
4497                        // pane goes on showing the row the user just deselected. The empty set is
4498                        // how that is said (`on_selection`, docs/list.md); reporting nothing was
4499                        // a silent contract break, since single-selection backends are documented
4500                        // as firing it with a one-element OR EMPTY set.
4501                        emit(self.ivars().node, Event::SelectionSet(Vec::new()));
4502                    }
4503                }
4504            })
4505        }
4506
4507        // --- swipe actions (docs/list.md): NSTableView's row-action pipeline. AppKit calls
4508        // this as the two-finger swipe starts, so the offer reflects the row's state at
4509        // GESTURE time; a full swipe across activates the first action (AppKit's own
4510        // full-slide behavior). The handler commits through the seam, which defers the app's
4511        // callback to the event drain.
4512        #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
4513        fn row_actions_for_row(
4514            &self,
4515            tv: &NSTableView,
4516            row: isize,
4517            edge: objc2_app_kit::NSTableRowActionEdge,
4518        ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
4519            // Guarded: `actions_at` runs the app's provider closure.
4520            ffi_guard::contain(NSArray::new(), || {
4521                let sw = self
4522                    .ivars()
4523                    .source
4524                    .borrow()
4525                    .as_ref()
4526                    .and_then(|s| s.swipe.clone());
4527                let Some(sw) = sw else {
4528                    return NSArray::new();
4529                };
4530                if row < 0 {
4531                    return NSArray::new();
4532                }
4533                // AppKit's Leading/Trailing already speak reading direction, same as ours.
4534                let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
4535                    day_spec::SwipeEdge::Leading
4536                } else {
4537                    day_spec::SwipeEdge::Trailing
4538                };
4539                let offer = (sw.actions_at)(row as usize, day_edge);
4540                let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
4541                    .iter()
4542                    .enumerate()
4543                    .map(|(i, a)| {
4544                        let style = if a.destructive {
4545                            objc2_app_kit::NSTableViewRowActionStyle::Destructive
4546                        } else {
4547                            objc2_app_kit::NSTableViewRowActionStyle::Regular
4548                        };
4549                        let perform = sw.perform.clone();
4550                        // Retained only for the swipe session: AppKit releases the actions
4551                        // (and this block) when the revealed buttons close.
4552                        let table = tv.retain();
4553                        let handler = block2::RcBlock::new(
4554                            move |_action: std::ptr::NonNull<
4555                                objc2_app_kit::NSTableViewRowAction,
4556                            >,
4557                                  row: isize| {
4558                                ffi_guard::contain((), || {
4559                                    perform(row as usize, day_edge, i);
4560                                    // A button press leaves the buttons revealed; close
4561                                    // them (a full slide already closed itself).
4562                                    unsafe { table.setRowActionsVisible(false) };
4563                                })
4564                            },
4565                        );
4566                        let action =
4567                            objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
4568                                style,
4569                                &NSString::from_str(&a.label),
4570                                &handler,
4571                            );
4572                        if let Some(t) = a.tint {
4573                            unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
4574                        }
4575                        // Glyph above the label — the Mail row-action look. The SF symbol
4576                        // resolves per OS release; an unknown name yields no image and the
4577                        // button keeps its label alone.
4578                        if let Some(sym) = a.symbol {
4579                            let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
4580                                &NSString::from_str(day_spec::sf_symbol_name(sym)),
4581                                None,
4582                            );
4583                            if let Some(img) = img {
4584                                unsafe { action.setImage(Some(&img)) };
4585                            }
4586                        }
4587                        action
4588                    })
4589                    .collect();
4590                NSArray::from_retained_slice(&actions)
4591            })
4592        }
4593    }
4594);
4595
4596impl DayListData {
4597    fn new(
4598        mtm: MainThreadMarker,
4599        node: NodeId,
4600        selectable: bool,
4601        multi: bool,
4602        automatic: bool,
4603        sections: bool,
4604    ) -> Retained<Self> {
4605        let this = Self::alloc(mtm).set_ivars(ListIvars {
4606            node,
4607            source: RefCell::new(None),
4608            selectable: std::cell::Cell::new(selectable),
4609            multi: std::cell::Cell::new(multi),
4610            suppress: std::cell::Cell::new(false),
4611            tokens: RefCell::new(Vec::new()),
4612            automatic,
4613            sections,
4614            header_estimate: std::cell::Cell::new(28.0),
4615            heights: RefCell::new(std::collections::HashMap::new()),
4616            cell_tokens: RefCell::new(std::collections::HashMap::new()),
4617            estimate: std::cell::Cell::new(44.0),
4618            heights_pending: std::cell::Cell::new(false),
4619        });
4620        unsafe { msg_send![super(this), init] }
4621    }
4622
4623    /// A self-sizing row was just bound to `cell`: record the height Day laid it at, and if
4624    /// the table drew the row at another height (the estimate, or the row's old content),
4625    /// correct it on the next turn. Not here: this runs inside NSTableView's own tiling.
4626    fn note_row_height(
4627        &self,
4628        table: &NSTableView,
4629        source: &ListSource,
4630        row: isize,
4631        cell: RawHandle,
4632        header: bool,
4633    ) {
4634        let height = (source.cell_height)(cell);
4635        if height <= 0.0 || row < 0 {
4636            return;
4637        }
4638        let token = (source.token_at)(row as usize);
4639        self.ivars()
4640            .cell_tokens
4641            .borrow_mut()
4642            .insert(cell as usize, token);
4643        self.ivars().heights.borrow_mut().insert(token, height);
4644        if header {
4645            self.ivars().header_estimate.set(height);
4646        } else {
4647            self.ivars().estimate.set(height);
4648        }
4649        let drawn = unsafe { table.rectOfRow(row) }.size.height;
4650        if (drawn - height).abs() > 0.5 {
4651            self.post_row_heights(table);
4652        }
4653    }
4654
4655    /// Whether display row `row` is a section header (docs/list.md "Sections").
4656    fn is_header(&self, row: isize) -> bool {
4657        row >= 0
4658            && self
4659                .ivars()
4660                .source
4661                .borrow()
4662                .as_ref()
4663                .and_then(|s| s.is_header.clone())
4664                .is_some_and(|is_header| is_header(row as usize))
4665    }
4666
4667    /// `ListPatch::RowSizeInvalidated`: the row in `cell` was re-laid at `height`. Arrives under
4668    /// the day-core borrow, so it only records the height; the table is told after the pass.
4669    fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
4670        let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
4671        if let Some(token) = token {
4672            self.ivars().heights.borrow_mut().insert(token, height);
4673            self.post_row_heights(table);
4674        }
4675    }
4676
4677    /// Tell the table, on the next main-loop turn, about every row near the viewport whose drawn
4678    /// height differs from the one Day laid it at. Coalesced: a pass that re-lays many rows
4679    /// posts one correction.
4680    fn post_row_heights(&self, table: &NSTableView) {
4681        if self.ivars().heights_pending.replace(true) {
4682            return;
4683        }
4684        // Raw +1 pointers across the post (the closure must be Send, which Retained is not;
4685        // everything stays on the main thread).
4686        let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
4687            return;
4688        };
4689        let this = Retained::into_raw(this) as usize;
4690        let table = Retained::into_raw(table.retain()) as usize;
4691        <AppKit as Platform>::post(Box::new(move || {
4692            // Reclaim both +1s first, so every early return balances them.
4693            let this = unsafe { Retained::from_raw(this as *mut DayListData) };
4694            let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
4695            let (Some(this), Some(table)) = (this, table) else {
4696                return;
4697            };
4698            this.ivars().heights_pending.set(false);
4699            ffi_guard::contain((), || this.apply_row_heights(&table));
4700        }));
4701    }
4702
4703    fn apply_row_heights(&self, table: &NSTableView) {
4704        let Some(source) = self.ivars().source.borrow().clone() else {
4705            return;
4706        };
4707        let count = unsafe { table.numberOfRows() }.max(0) as usize;
4708        let shown = unsafe { table.rowsInRect(table.visibleRect()) };
4709        // The viewport and the rows AppKit prepares around it.
4710        let first = shown.location.saturating_sub(8);
4711        let last = (shown.location + shown.length + 8)
4712            .min(count)
4713            .min((source.len)());
4714        let changed = objc2_foundation::NSMutableIndexSet::new();
4715        {
4716            let heights = self.ivars().heights.borrow();
4717            for row in first..last {
4718                if let Some(&height) = heights.get(&(source.token_at)(row)) {
4719                    let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
4720                    if (drawn - height).abs() > 0.5 {
4721                        unsafe { changed.addIndex(row) };
4722                    }
4723                }
4724            }
4725        }
4726        if changed.count() == 0 {
4727            return;
4728        }
4729        // Unanimated: the row takes its content's height, it does not grow into it.
4730        NSAnimationContext::beginGrouping();
4731        NSAnimationContext::currentContext().setDuration(0.0);
4732        unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
4733        NSAnimationContext::endGrouping();
4734    }
4735
4736    /// If this Reload is the same row set in a new order, the incremental `moveRowAtIndex`
4737    /// steps (each `(from, to)` interpreted against the already-moved rows, NSTableView's
4738    /// semantics) that transform the displayed order into the new one — and `None` for
4739    /// anything else (insert/remove/content change/no change), which reloads flat. Always
4740    /// refreshes the displayed-order cache.
4741    ///
4742    /// Every row that changes position must have a REALIZED row view (`table`): moving a
4743    /// viewless row (its old position sat outside the viewport, so it was never bound)
4744    /// animates nothing and leaves the row unbound at its new position — its content, and any
4745    /// element ids inside it, would simply not exist. Such a reorder returns `None` and
4746    /// reloads flat, which realizes and binds the row at its new position.
4747    fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
4748        let source = self.ivars().source.borrow();
4749        let source = source.as_ref()?;
4750        let n = (source.len)();
4751        let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
4752        let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
4753        if old.len() != n || n == 0 || old == new {
4754            return None;
4755        }
4756        let (mut so, mut sn) = (old.clone(), new.clone());
4757        so.sort_unstable();
4758        sn.sort_unstable();
4759        if so != sn {
4760            return None;
4761        }
4762        for i in 0..n {
4763            if old[i] != new[i]
4764                && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
4765            {
4766                return None;
4767            }
4768        }
4769        let mut work = old;
4770        let mut moves = Vec::new();
4771        for i in 0..n {
4772            if work[i] == new[i] {
4773                continue;
4774            }
4775            let j = (i + 1..n).find(|&j| work[j] == new[i])?;
4776            let t = work.remove(j);
4777            work.insert(i, t);
4778            moves.push((j, i));
4779        }
4780        Some(moves)
4781    }
4782
4783    /// The dragged row + current row count for an in-flight LOCAL reorder drag — `None` when the
4784    /// drag came from anywhere but this table (day never accepts foreign drops into a list) or
4785    /// the pasteboard doesn't carry the day row type.
4786    fn drag_context(
4787        &self,
4788        tv: &NSTableView,
4789        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4790    ) -> Option<(usize, usize)> {
4791        let src = unsafe { info.draggingSource() }?;
4792        if Retained::as_ptr(&src) as *const std::ffi::c_void
4793            != tv as *const NSTableView as *const std::ffi::c_void
4794        {
4795            return None;
4796        }
4797        let pb = unsafe { info.draggingPasteboard() };
4798        let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
4799            .to_string()
4800            .parse::<usize>()
4801            .ok()?;
4802        let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
4803        (from < len).then_some((from, len))
4804    }
4805
4806    /// The guard's verdict for `from -> to` (accepted index, or -1), through the sync seam.
4807    fn can_move(&self, from: usize, to: usize) -> i64 {
4808        self.ivars()
4809            .source
4810            .borrow()
4811            .as_ref()
4812            .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
4813            .unwrap_or(-1)
4814    }
4815}
4816
4817/// The reuse identifiers of a list's row cells and its section-header cells.
4818const DAY_ROW_CELL: &str = "day.cell";
4819const DAY_HEADER_CELL: &str = "day.header";
4820
4821/// The private pasteboard type carrying a dragged day list row's index (local reorder only).
4822const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
4823
4824/// An NSTableView drop lands at an INSERTION point (`row` with `.Above` semantics, 0..=len);
4825/// day's seam speaks post-removal target indices. Dropping `from` at insertion `ins`:
4826fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
4827    let to = if ins > from { ins - 1 } else { ins };
4828    to.min(len.saturating_sub(1))
4829}
4830
4831/// The inverse, for retargeting the drop gap: where the gap sits for a post-removal target.
4832fn target_to_insertion(from: usize, to: usize) -> usize {
4833    if to > from { to + 1 } else { to }
4834}
4835
4836/// A realized LIST's scroll view ptr → (table, data source) for attach_list / update / measure.
4837type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
4838
4839/// Clone a list's (table, data) out of `LIST_STATE` under a SHORT borrow. Every caller then
4840/// talks to AppKit with the map free: table calls that look innocuous (`endUpdates`, a scroll's
4841/// tiling, `viewAtColumn:row:makeIfNecessary:`, even `layoutSubtreeIfNeeded`) can synchronously
4842/// re-enter `viewForRow` → `bind_row` → a flush that tears nodes down — and `release` must be
4843/// able to take its own borrow at that depth. Holding the map across any of them was the
4844/// "RefCell already borrowed" contained panic every list walkthrough used to log, 24 a run.
4845fn list_entry(key: usize) -> Option<ListEntry> {
4846    LIST_STATE.with(|m| m.borrow().get(&key).cloned())
4847}
4848
4849// ---------------------------------------------------------------------------
4850// DayTreeData — NSOutlineView data-source + delegate for the hierarchical tree (docs/tree.md)
4851// ---------------------------------------------------------------------------
4852
4853struct TreeIvars {
4854    node: NodeId,
4855    /// Injected by `attach_tree` once day-core wires the driver.
4856    source: RefCell<Option<TreeSource>>,
4857    selectable: std::cell::Cell<bool>,
4858    /// Programmatic selection/disclosure in flight: don't re-emit the event (echo rule).
4859    suppress: std::cell::Cell<bool>,
4860    /// token → its interned NSNumber. NSOutlineView tracks items (selection, expansion,
4861    /// rowForItem) by object identity/equality, so every query for a token must answer with
4862    /// the same object — which is also what preserves expansion across reloadData.
4863    items: RefCell<HashMap<u64, Retained<NSNumber>>>,
4864}
4865
4866define_class!(
4867    #[unsafe(super(NSObject))]
4868    #[thread_kind = MainThreadOnly]
4869    #[name = "DayTreeData"]
4870    #[ivars = TreeIvars]
4871    struct DayTreeData;
4872
4873    unsafe impl NSObjectProtocol for DayTreeData {}
4874
4875    unsafe impl NSOutlineViewDataSource for DayTreeData {
4876        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
4877        fn number_of_children(
4878            &self,
4879            _ov: &objc2_app_kit::NSOutlineView,
4880            item: Option<&objc2::runtime::AnyObject>,
4881        ) -> isize {
4882            // Reads the piece's snapshot only (no tree access) — safe even when called
4883            // synchronously from reloadData inside a with_tree borrow. Guarded because
4884            // the closures are day-core's.
4885            ffi_guard::contain(0, || {
4886                let parent = item.and_then(Self::token_of_item);
4887                if item.is_some() && parent.is_none() {
4888                    return 0; // not one of ours (stale query racing a reload)
4889                }
4890                self.ivars()
4891                    .source
4892                    .borrow()
4893                    .as_ref()
4894                    .map(|s| (s.children_len)(parent) as isize)
4895                    .unwrap_or(0)
4896            })
4897        }
4898
4899        #[unsafe(method_id(outlineView:child:ofItem:))]
4900        fn child_of_item(
4901            &self,
4902            _ov: &objc2_app_kit::NSOutlineView,
4903            index: isize,
4904            item: Option<&objc2::runtime::AnyObject>,
4905        ) -> Retained<objc2::runtime::AnyObject> {
4906            // AppKit only asks for children it was told exist, but a stale query racing a
4907            // reload must degrade (token 0, an unmatched identity) rather than panic — an
4908            // unwind here crosses an ObjC frame and aborts.
4909            let token = ffi_guard::contain(0, || {
4910                let parent = item.and_then(Self::token_of_item);
4911                self.ivars()
4912                    .source
4913                    .borrow()
4914                    .as_ref()
4915                    .map(|s| (s.child_token)(parent, index.max(0) as usize))
4916                    .unwrap_or(0)
4917            });
4918            let ns = self.intern(token);
4919            unsafe { objc2::rc::Retained::cast_unchecked(ns) }
4920        }
4921
4922        #[unsafe(method(outlineView:isItemExpandable:))]
4923        fn is_expandable(
4924            &self,
4925            _ov: &objc2_app_kit::NSOutlineView,
4926            item: &objc2::runtime::AnyObject,
4927        ) -> bool {
4928            ffi_guard::contain(false, || {
4929                let Some(token) = Self::token_of_item(item) else {
4930                    return false;
4931                };
4932                self.ivars()
4933                    .source
4934                    .borrow()
4935                    .as_ref()
4936                    .map(|s| (s.expandable)(token))
4937                    .unwrap_or(false)
4938            })
4939        }
4940
4941        // --- drag-to-move (docs/tree.md): the dragged node rides the pasteboard as a
4942        // private-typed token string; `validateDrop` consults the guard live (forbidden
4943        // cursor where it denies, including ONTO-a-row drops via childIndex -1), and
4944        // `acceptDrop` commits through the sync seam — the app's own data write reloads.
4945
4946        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
4947        fn pasteboard_writer_for_item(
4948            &self,
4949            _ov: &objc2_app_kit::NSOutlineView,
4950            item: &objc2::runtime::AnyObject,
4951        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4952            let make = || {
4953                let movable = self
4954                    .ivars()
4955                    .source
4956                    .borrow()
4957                    .as_ref()
4958                    .is_some_and(|s| s.moves.is_some());
4959                let token = Self::token_of_item(item)?;
4960                if !movable {
4961                    return None;
4962                }
4963                let pbitem = objc2_app_kit::NSPasteboardItem::new();
4964                unsafe {
4965                    pbitem.setString_forType(
4966                        &NSString::from_str(&token.to_string()),
4967                        &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
4968                    );
4969                }
4970                Some(ProtocolObject::from_retained(pbitem))
4971            };
4972            ffi_guard::contain(None, make)
4973        }
4974
4975        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
4976        fn validate_drop(
4977            &self,
4978            ov: &objc2_app_kit::NSOutlineView,
4979            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4980            item: Option<&objc2::runtime::AnyObject>,
4981            child_index: isize,
4982        ) -> objc2_app_kit::NSDragOperation {
4983            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4984                match self.drop_proposal(ov, info, item, child_index) {
4985                    Some((token, parent, index)) if self.can_move(token, parent, index) => {
4986                        objc2_app_kit::NSDragOperation::Move
4987                    }
4988                    _ => objc2_app_kit::NSDragOperation::None,
4989                }
4990            })
4991        }
4992
4993        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
4994        fn accept_drop(
4995            &self,
4996            ov: &objc2_app_kit::NSOutlineView,
4997            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4998            item: Option<&objc2::runtime::AnyObject>,
4999            child_index: isize,
5000        ) -> bool {
5001            let drop = || {
5002                let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
5003                else {
5004                    return false;
5005                };
5006                if !self.can_move(token, parent, index) {
5007                    return false;
5008                }
5009                // Commit through the sync seam: defers the app's `on_move`; the app's own
5010                // data write drives the Reload (no native row animation on this path).
5011                let mv = self
5012                    .ivars()
5013                    .source
5014                    .borrow()
5015                    .as_ref()
5016                    .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5017                let Some(mv) = mv else { return false };
5018                mv(token, parent, index);
5019                true
5020            };
5021            ffi_guard::contain(false, drop)
5022        }
5023    }
5024
5025    unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5026
5027    unsafe impl NSOutlineViewDelegate for DayTreeData {
5028        #[unsafe(method(outlineView:isGroupItem:))]
5029        fn is_group_item(
5030            &self,
5031            _ov: &objc2_app_kit::NSOutlineView,
5032            item: &objc2::runtime::AnyObject,
5033        ) -> bool {
5034            Self::token_of_item(item).is_some_and(|t| {
5035                self.ivars()
5036                    .source
5037                    .borrow()
5038                    .as_ref()
5039                    .is_some_and(|s| (s.section_header)(t))
5040            })
5041        }
5042        #[unsafe(method(outlineView:shouldSelectItem:))]
5043        fn should_select_item(
5044            &self,
5045            _ov: &objc2_app_kit::NSOutlineView,
5046            item: &objc2::runtime::AnyObject,
5047        ) -> bool {
5048            Self::token_of_item(item).is_some_and(|t| {
5049                self.ivars()
5050                    .source
5051                    .borrow()
5052                    .as_ref()
5053                    .is_some_and(|s| !(s.section_header)(t))
5054            })
5055        }
5056
5057        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5058        fn view_for_item(
5059            &self,
5060            ov: &objc2_app_kit::NSOutlineView,
5061            _col: Option<&NSTableColumn>,
5062            item: &objc2::runtime::AnyObject,
5063        ) -> Option<Retained<NSView>> {
5064            // Guarded: `bind_row` builds the app's row content.
5065            ffi_guard::contain(None, || {
5066                let mtm = self.mtm();
5067                let token = Self::token_of_item(item)?;
5068                let ident = NSString::from_str("day.tree.cell");
5069                // Recycle a cell view if one is free; else make a fresh flipped container
5070                // (DayTreeCell re-lays its Day row at its own width — indentation makes
5071                // every tree cell's width per-row).
5072                let cell: Retained<NSView> =
5073                    unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5074                        let v: Retained<NSView> =
5075                            Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5076                        unsafe { v.setIdentifier(Some(&ident)) };
5077                        v
5078                    });
5079                if let Some(source) = self.ivars().source.borrow().as_ref() {
5080                    let raw = Retained::as_ptr(&cell) as RawHandle;
5081                    if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5082                        unsafe {
5083                            cell.setTextField(None);
5084                        }
5085                    }
5086                    (source.bind_row)(token, raw);
5087                    // Associate the actual Day label with NSTableCellView so AppKit can
5088                    // apply group typography and source-list background styles normally.
5089                    if (source.section_header)(token) {
5090                        fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5091                            for child in unsafe { view.subviews() }.iter() {
5092                                if let Ok(label) = child.clone().downcast::<NSTextField>() {
5093                                    return Some(label);
5094                                }
5095                                if let Some(label) = label_in(&child) {
5096                                    return Some(label);
5097                                }
5098                            }
5099                            None
5100                        }
5101                        if let Some(label) = label_in(&cell) {
5102                            let cell = cell.downcast_ref::<DayTreeCell>()?;
5103                            unsafe {
5104                                cell.setTextField(Some(&label));
5105                            }
5106                        }
5107                    }
5108                }
5109                Some(cell)
5110            })
5111        }
5112
5113        #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5114        fn type_select_string(
5115            &self,
5116            _ov: &objc2_app_kit::NSOutlineView,
5117            _col: Option<&NSTableColumn>,
5118            item: &objc2::runtime::AnyObject,
5119        ) -> Option<Retained<NSString>> {
5120            ffi_guard::contain(None, || {
5121                let token = Self::token_of_item(item)?;
5122                let text = self
5123                    .ivars()
5124                    .source
5125                    .borrow()
5126                    .as_ref()
5127                    .map(|s| (s.type_select_text)(token))
5128                    .unwrap_or_default();
5129                // Empty = this row doesn't participate in type-select.
5130                (!text.is_empty()).then(|| NSString::from_str(&text))
5131            })
5132        }
5133
5134        #[unsafe(method_id(outlineView:rowViewForItem:))]
5135        fn row_view_for_item(
5136            &self,
5137            ov: &objc2_app_kit::NSOutlineView,
5138            _item: &objc2::runtime::AnyObject,
5139        ) -> Retained<objc2_app_kit::NSTableRowView> {
5140            if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5141                // AppKit owns source-list group backgrounds, floating headers and selection.
5142                unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5143            } else {
5144                // The rounded-selection row (see DayTreeRowView).
5145                let rv: Retained<DayTreeRowView> =
5146                    unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5147                Retained::into_super(rv)
5148            }
5149        }
5150
5151        #[unsafe(method(outlineViewSelectionDidChange:))]
5152        fn selection_did_change(&self, notification: &NSNotification) {
5153            ffi_guard::contain((), || {
5154                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5155                    return;
5156                }
5157                let Some(obj) = (unsafe { notification.object() }) else {
5158                    return;
5159                };
5160                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5161                    return;
5162                };
5163                // Always the FULL token set (docs/tree.md): a tree cannot speak row indices.
5164                let idx = unsafe { ov.selectedRowIndexes() };
5165                let mut tokens = Vec::with_capacity(idx.count());
5166                let mut i = idx.firstIndex();
5167                while i != objc2_foundation::NSNotFound as usize {
5168                    if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5169                        && let Some(tok) = Self::token_of_item(&item)
5170                    {
5171                        tokens.push(tok);
5172                    }
5173                    i = unsafe { idx.indexGreaterThanIndex(i) };
5174                }
5175                emit(self.ivars().node, Event::TreeSelection(tokens));
5176            })
5177        }
5178
5179        #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5180        fn did_remove_row_view(
5181            &self,
5182            ov: &objc2_app_kit::NSOutlineView,
5183            row_view: &objc2_app_kit::NSTableRowView,
5184            _row: isize,
5185        ) {
5186            // The row went back to the reuse pool (a collapse, a reload dropping it): clear
5187            // its day element ids so it stops answering `find_by_id`. DEFERRED — this fires
5188            // inside collapse/reload stacks that hold the day-core borrow — and re-checked:
5189            // a cell already reused by the same turn's reload has a window again, and its
5190            // fresh ids must survive.
5191            ffi_guard::contain((), || {
5192                let mut cell_ptr: Option<usize> = None;
5193                for sub in row_view.subviews().iter() {
5194                    let is_cell = sub
5195                        .identifier()
5196                        .map(|i| i.to_string() == "day.tree.cell")
5197                        .unwrap_or(false);
5198                    if is_cell {
5199                        cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5200                    }
5201                }
5202                let Some(cell) = cell_ptr else { return };
5203                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5204                    return;
5205                };
5206                let key = Retained::as_ptr(&scroll) as usize;
5207                // Carry a RETAIN across the post as a raw +1 pointer (the boxed closure must
5208                // be Send, which Retained is not; we stay on the main thread throughout).
5209                // AppKit is free to dealloc removed row views — a bare pointer died here once.
5210                let retained =
5211                    unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5212                        as usize;
5213                <AppKit as Platform>::post(Box::new(move || {
5214                    // Reclaim the +1 first, unconditionally — every early return below must
5215                    // still balance the retain.
5216                    let cell_view: Retained<NSView> =
5217                        match unsafe { Retained::from_raw(retained as *mut NSView) } {
5218                            Some(v) => v,
5219                            None => return,
5220                        };
5221                    let recycle = tree_entry(key).and_then(|(_, data)| {
5222                        data.ivars()
5223                            .source
5224                            .borrow()
5225                            .as_ref()
5226                            .map(|s| s.recycle.clone())
5227                    });
5228                    let Some(recycle) = recycle else { return };
5229                    if cell_view.window().is_some() {
5230                        return; // reused already — its ids are the live row's
5231                    }
5232                    recycle(cell as RawHandle);
5233                }));
5234            })
5235        }
5236
5237        #[unsafe(method(outlineViewItemDidExpand:))]
5238        fn item_did_expand(&self, notification: &NSNotification) {
5239            self.report_disclosure(notification, true);
5240        }
5241
5242        #[unsafe(method(outlineViewItemDidCollapse:))]
5243        fn item_did_collapse(&self, notification: &NSNotification) {
5244            self.report_disclosure(notification, false);
5245        }
5246    }
5247);
5248
5249impl DayTreeData {
5250    fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5251        let this = Self::alloc(mtm).set_ivars(TreeIvars {
5252            node,
5253            source: RefCell::new(None),
5254            selectable: std::cell::Cell::new(selectable),
5255            suppress: std::cell::Cell::new(false),
5256            items: RefCell::new(HashMap::new()),
5257        });
5258        unsafe { msg_send![super(this), init] }
5259    }
5260
5261    /// The same NSNumber for a token, every time — NSOutlineView's item identity.
5262    fn intern(&self, token: u64) -> Retained<NSNumber> {
5263        self.ivars()
5264            .items
5265            .borrow_mut()
5266            .entry(token)
5267            .or_insert_with(|| NSNumber::new_u64(token))
5268            .clone()
5269    }
5270
5271    fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5272        item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
5273    }
5274
5275    /// A native disclosure (user click, keyboard left/right) → `Event::TreeExpanded`.
5276    /// Programmatic `TreePatch::Expand` applications are suppressed (the echo rule).
5277    fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5278        ffi_guard::contain((), || {
5279            if self.ivars().suppress.get() {
5280                return;
5281            }
5282            let token = unsafe { notification.userInfo() }
5283                .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
5284                .and_then(|item| Self::token_of_item(&item));
5285            if let Some(token) = token {
5286                emit(self.ivars().node, Event::TreeExpanded { token, expanded });
5287            }
5288        })
5289    }
5290
5291    /// The full drop proposal — `(dragged token, parent token, index)` — for a LOCAL drag
5292    /// from this outline; `None` for a foreign drag or an unparseable one. `index: None`
5293    /// means "ONTO the parent" (NSOutlineView's childIndex -1, `NSOutlineViewDropOnItemIndex`).
5294    fn drop_proposal(
5295        &self,
5296        ov: &objc2_app_kit::NSOutlineView,
5297        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5298        item: Option<&objc2::runtime::AnyObject>,
5299        child_index: isize,
5300    ) -> Option<(u64, Option<u64>, Option<usize>)> {
5301        let src = unsafe { info.draggingSource() }?;
5302        if Retained::as_ptr(&src) as *const std::ffi::c_void
5303            != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
5304        {
5305            return None;
5306        }
5307        let pb = unsafe { info.draggingPasteboard() };
5308        let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
5309            .to_string()
5310            .parse::<u64>()
5311            .ok()?;
5312        let parent = match item {
5313            Some(i) => Some(Self::token_of_item(i)?), // a non-token item is not ours
5314            None => None,
5315        };
5316        let index = (child_index >= 0).then_some(child_index as usize);
5317        Some((token, parent, index))
5318    }
5319
5320    /// The guard's live verdict through the sync seam.
5321    fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
5322        self.ivars()
5323            .source
5324            .borrow()
5325            .as_ref()
5326            .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
5327            .map(|v| v == MoveVerdict::Allow)
5328            .unwrap_or(false)
5329    }
5330}
5331
5332// DayOutlineView — an NSOutlineView that PINS its width to its clip on every layout pass.
5333// A table sizes itself from its COLUMNS, and the autoresizing mask only tracks deltas, so
5334// any early pass at a different pane width leaves a permanent offset (a 233pt table in a
5335// 220pt pane, whose selection pill then clips mid-corner). Enforcing it in `layout` — not
5336// in occasional deferred posts — closes every window where a stale width could draw.
5337define_class!(
5338    #[unsafe(super(objc2_app_kit::NSOutlineView))]
5339    #[thread_kind = MainThreadOnly]
5340    #[name = "DayOutlineView"]
5341    struct DayOutlineView;
5342
5343    impl DayOutlineView {
5344        #[unsafe(method(layout))]
5345        fn layout(&self) {
5346            sync_tree_width(self);
5347            let _: () = unsafe { msg_send![super(self), layout] };
5348        }
5349
5350        /// A summon-time ROW context menu (docs/menus.md, docs/tree.md): right-click asks
5351        /// the tree's `row_menu` provider for the row under the pointer.
5352        #[unsafe(method_id(menuForEvent:))]
5353        fn menu_for_event(
5354            &self,
5355            event: &objc2_app_kit::NSEvent,
5356        ) -> Option<Retained<NSMenu>> {
5357            ffi_guard::contain(None, || {
5358                let scroll = unsafe { self.enclosingScrollView() }?;
5359                let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
5360                let row_menu = data
5361                    .ivars()
5362                    .source
5363                    .borrow()
5364                    .as_ref()
5365                    .and_then(|s| s.row_menu.clone())?;
5366                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
5367                let row = unsafe { self.rowAtPoint(p) };
5368                if row < 0 {
5369                    return None;
5370                }
5371                let token =
5372                    unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
5373                let items = row_menu(token);
5374                if items.is_empty() {
5375                    return None;
5376                }
5377                Some(build_ns_menu(self.mtm(), "", &items))
5378            })
5379        }
5380    }
5381);
5382
5383// DayTreeRowView — a tree row with the MODERN selection: a rounded pill, inset from the
5384// pane's edges, in the system's semantic selection colors (accent when the tree has focus,
5385// the quiet gray otherwise). Drawn by hand rather than through `NSTableViewStyle::Inset`,
5386// whose machinery pads the table wider than its clip and fights day's fixed-frame layout —
5387// and a hand-drawn plain color also captures correctly offscreen, where materials go black
5388// (docs/navigation.md's sidebar-screenshot rule).
5389define_class!(
5390    #[unsafe(super(objc2_app_kit::NSTableRowView))]
5391    #[thread_kind = MainThreadOnly]
5392    #[name = "DayTreeRowView"]
5393    struct DayTreeRowView;
5394
5395    impl DayTreeRowView {
5396        #[unsafe(method(drawSelectionInRect:))]
5397        fn draw_selection_in_rect(&self, _dirty: NSRect) {
5398            if !unsafe { self.isSelected() } {
5399                return;
5400            }
5401            let color = if unsafe { self.isEmphasized() } {
5402                unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
5403            } else {
5404                unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
5405            };
5406            let b = self.bounds();
5407            let pill = NSRect::new(
5408                NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
5409                NSSize::new(
5410                    (b.size.width - 10.0).max(0.0),
5411                    (b.size.height - 2.0).max(0.0),
5412                ),
5413            );
5414            unsafe {
5415                color.setFill();
5416                objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
5417                    pill, 5.0, 5.0,
5418                )
5419                .fill();
5420            }
5421        }
5422    }
5423);
5424
5425// DayTreeCell — a tree row's flipped cell container. NSOutlineView frames it at the row's
5426// INDENTED position, so its width is per-row; every native layout pass re-lays the Day row
5427// content inside it at that width through the seam's `layout_cell`.
5428define_class!(
5429    #[unsafe(super(objc2_app_kit::NSTableCellView))]
5430    #[thread_kind = MainThreadOnly]
5431    #[name = "DayTreeCell"]
5432    struct DayTreeCell;
5433
5434    impl DayTreeCell {
5435        #[unsafe(method(isFlipped))]
5436        fn is_flipped(&self) -> bool {
5437            true
5438        }
5439
5440        #[unsafe(method(layout))]
5441        fn layout(&self) {
5442            let _: () = unsafe { msg_send![super(self), layout] };
5443            ffi_guard::contain((), || {
5444                let width = self.bounds().size.width;
5445                if width <= 0.0 {
5446                    return;
5447                }
5448                // This cell's tree: walk up to the outline, then to its scroll host, which
5449                // keys TREE_STATE. (The cell may be in the reuse pool — no outline — or the
5450                // tree may be mid-teardown; both just skip.)
5451                let mut cur = unsafe { self.superview() };
5452                let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
5453                while let Some(v) = cur {
5454                    cur = unsafe { v.superview() };
5455                    if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
5456                        outline = Some(ov);
5457                        break;
5458                    }
5459                }
5460                let Some(ov) = outline else { return };
5461                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5462                    return;
5463                };
5464                let f = tree_entry(Retained::as_ptr(&scroll) as usize)
5465                    .and_then(|(_, data)| {
5466                        data.ivars()
5467                            .source
5468                            .borrow()
5469                            .as_ref()
5470                            .map(|s| s.layout_cell_size.clone())
5471                    });
5472                if let Some(f) = f {
5473                    f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
5474                }
5475            })
5476        }
5477    }
5478);
5479
5480impl DayTreeCell {
5481    fn new(mtm: MainThreadMarker) -> Retained<Self> {
5482        unsafe { msg_send![Self::alloc(mtm), init] }
5483    }
5484}
5485
5486/// The private pasteboard type carrying a dragged day tree node's token (local moves only).
5487const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
5488
5489/// A realized TREE's scroll view ptr → (outline, data source).
5490type TreeEntry = (
5491    Retained<objc2_app_kit::NSOutlineView>,
5492    Retained<DayTreeData>,
5493);
5494
5495/// Clone a tree's (outline, data) out of `TREE_STATE` under a SHORT borrow — the same
5496/// re-entrancy rule as `list_entry` (its comment has the war story).
5497fn tree_entry(key: usize) -> Option<TreeEntry> {
5498    TREE_STATE.with(|m| m.borrow().get(&key).cloned())
5499}
5500
5501/// Keep the outline exactly as wide as its clip — DayOutlineView calls this on every layout
5502/// pass (its comment has the why). The list never noticed the width drift because it lays
5503/// row content at the HOST's width; tree rows lay out at the CELL's, which exposes it.
5504fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
5505    let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
5506        return;
5507    };
5508    let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
5509    let f = outline.frame();
5510    if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
5511        unsafe {
5512            outline.setFrameSize(NSSize::new(clip_w, f.size.height));
5513            outline.sizeLastColumnToFit();
5514        }
5515    }
5516}
5517
5518/// Realize the tree's visible rows on the next main-loop turn, outside any borrow — the
5519/// tree twin of `post_realize_visible_rows` (its comment explains the occluded-window trap).
5520fn post_realize_visible_tree_rows(key: usize) {
5521    <AppKit as Platform>::post(Box::new(move || {
5522        if let Some((outline, _)) = tree_entry(key) {
5523            let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
5524            for row in range.location..range.location + range.length {
5525                let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
5526            }
5527        }
5528        day_core::pump_events();
5529    }));
5530}
5531
5532/// A realized NAV_MENU's native outline view paired with its data-source object.
5533type NavMenuEntry = (
5534    Retained<objc2_app_kit::NSOutlineView>,
5535    Retained<DayNavMenuData>,
5536);
5537
5538fn ns_rect(r: day_spec::Rect) -> NSRect {
5539    NSRect::new(
5540        NSPoint::new(r.origin.x, r.origin.y),
5541        NSSize::new(r.size.width, r.size.height),
5542    )
5543}
5544
5545fn draw_op(op: &DrawOp) {
5546    unsafe {
5547        match op {
5548            // One path for the whole batch, then one fill or stroke: the template is appended
5549            // once per position, so the rasterizer is entered once however many copies there are
5550            // (docs/canvas.md "Stamping"). A gradient resolves against the batch's own bounds,
5551            // which is what makes a stamped scatter shade across the group rather than repeating
5552            // the ramp inside every dot.
5553            DrawOp::Stamp(st) => {
5554                let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
5555                for p in &st.at {
5556                    if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
5557                        unsafe { batch.appendBezierPath(&copy) };
5558                    }
5559                }
5560                let color = match &st.paint {
5561                    day_spec::Paint::Solid(c) => *c,
5562                    // A gradient over a stamped batch clips to the whole batch path; the solid
5563                    // fallback below keeps the marks visible on a backend path that cannot.
5564                    _ => day_spec::Color::WHITE,
5565                };
5566                match &st.stroke {
5567                    None => {
5568                        nscolor(color).setFill();
5569                        unsafe { batch.fill() };
5570                    }
5571                    Some(style) => {
5572                        nscolor(color).setStroke();
5573                        apply_stroke_style(&batch, style);
5574                        unsafe { batch.stroke() };
5575                    }
5576                }
5577            }
5578            DrawOp::Fill(shape, paint) => match paint {
5579                day_spec::Paint::Solid(color) => {
5580                    nscolor(*color).setFill();
5581                    if let Some(p) = bezier(shape) {
5582                        p.fill();
5583                    }
5584                }
5585                day_spec::Paint::Linear(g) => {
5586                    // Native linear gradient: clip to the shape's path, then NSGradient along
5587                    // the line resolved from the gradient's unit points in the shape's bounds.
5588                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5589                        let b = shape.bounds();
5590                        let (s, e) = (g.start.resolve(b), g.end.resolve(b));
5591                        NSGraphicsContext::saveGraphicsState_class();
5592                        p.addClip();
5593                        grad.drawFromPoint_toPoint_options(
5594                            NSPoint::new(s.x, s.y),
5595                            NSPoint::new(e.x, e.y),
5596                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5597                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5598                        );
5599                        NSGraphicsContext::restoreGraphicsState_class();
5600                    }
5601                }
5602                day_spec::Paint::Radial(g) => {
5603                    // Native radial gradient: clip to the path, map unit space onto the bounds
5604                    // (elliptical in non-square bounds), draw circular in unit coordinates.
5605                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
5606                        let b = shape.bounds();
5607                        NSGraphicsContext::saveGraphicsState_class();
5608                        p.addClip();
5609                        concat_unit_to_bounds(b);
5610                        let c = NSPoint::new(g.center.x, g.center.y);
5611                        grad.drawFromCenter_radius_toCenter_radius_options(
5612                            c,
5613                            0.0,
5614                            c,
5615                            g.radius,
5616                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5617                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
5618                        );
5619                        NSGraphicsContext::restoreGraphicsState_class();
5620                    }
5621                }
5622            },
5623            DrawOp::Stroke(shape, paint, style) => {
5624                if let Some(p) = bezier(shape) {
5625                    apply_stroke_style(&p, style);
5626                    match paint {
5627                        day_spec::Paint::Solid(color) => {
5628                            nscolor(*color).setStroke();
5629                            p.stroke();
5630                        }
5631                        // No gradient-stroke primitive here either: turn the stroke into the
5632                        // region it covers and draw the gradient through that clip.
5633                        // No gradient-stroke primitive: convert the stroke into the REGION it
5634                        // covers (CoreGraphics can, and NSGraphicsContext hands us its context),
5635                        // clip to that, then draw the gradient through it.
5636                        _ => {
5637                            let Some(ctx) = NSGraphicsContext::currentContext() else {
5638                                return;
5639                            };
5640                            let cg = ctx.CGContext();
5641                            NSGraphicsContext::saveGraphicsState_class();
5642                            objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
5643                            objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
5644                                &cg,
5645                            ));
5646                            objc2_core_graphics::CGContext::clip(Some(&cg));
5647                            draw_gradient_in(paint, shape.bounds());
5648                            NSGraphicsContext::restoreGraphicsState_class();
5649                        }
5650                    }
5651                }
5652            }
5653            DrawOp::Clip(shape) => {
5654                // `addClip` intersects with the current clip and honors the path's winding rule.
5655                if let Some(p) = bezier(shape) {
5656                    p.addClip();
5657                }
5658            }
5659            DrawOp::Text {
5660                text,
5661                at,
5662                size,
5663                color,
5664                anchor,
5665                font,
5666            } => {
5667                let font = canvas_nsfont(*size, font);
5668                let attrs = canvas_text_attrs(&font, *color);
5669                let ns = NSString::from_str(text);
5670                let mut origin = NSPoint::new(at.x, at.y);
5671                // `drawAtPoint:` takes the top-leading corner of the line box, so any other
5672                // anchor is an offset from it. The size comes from the attributes the draw is
5673                // about to use, which is why the alignment belongs here and not in the app: the
5674                // caller would have to ask for these same metrics through `measure_text` first.
5675                if *anchor != day_spec::TextAnchor::LEADING {
5676                    let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
5677                    let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
5678                    origin.x += dx;
5679                    origin.y += dy;
5680                }
5681                let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
5682            }
5683            // A released bitmap draws nothing rather than a placeholder: the canvas re-records
5684            // on every tracked read, so a handle can be dropped between the record and the
5685            // replay, and a frame that flashes a grey box is worse than one that omits the image.
5686            DrawOp::Image {
5687                image,
5688                rect,
5689                opacity,
5690            } => {
5691                let img = BITMAPS.with(|m| m.borrow().get(&image.0).map(|b| b.image.clone()));
5692                if let Some(img) = img {
5693                    let dest = NSRect::new(
5694                        NSPoint::new(rect.origin.x, rect.origin.y),
5695                        NSSize::new(rect.size.width, rect.size.height),
5696                    );
5697                    // DayCanvas is flipped (top-left origin). Respect that context so image
5698                    // rows stay upright, including under the canvas's rotation/zoom transforms.
5699                    // A zero `fromRect` means the whole image; `fraction` multiplies its alpha.
5700                    img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
5701                        dest,
5702                        NSRect::ZERO,
5703                        objc2_app_kit::NSCompositingOperation::SourceOver,
5704                        *opacity,
5705                        true,
5706                        None,
5707                    );
5708                }
5709            }
5710            DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
5711            DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
5712            DrawOp::Concat(m) => {
5713                let t = NSAffineTransform::new();
5714                t.setTransformStruct(NSAffineTransformStruct {
5715                    m11: m.a,
5716                    m12: m.b,
5717                    m21: m.c,
5718                    m22: m.d,
5719                    tX: m.tx,
5720                    tY: m.ty,
5721                });
5722                t.concat();
5723            }
5724        }
5725    }
5726}
5727
5728/// An `NSGradient` from a display-list gradient's stops (sRGB, like every canvas color).
5729fn nsgradient(
5730    stops: &[(f64, day_spec::Color)],
5731) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
5732    if stops.is_empty() {
5733        return None;
5734    }
5735    let colors = objc2_foundation::NSArray::from_retained_slice(
5736        &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
5737    );
5738    let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
5739    unsafe {
5740        objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
5741            objc2_app_kit::NSGradient::alloc(),
5742            &colors,
5743            locations.as_ptr(),
5744            &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
5745        )
5746    }
5747}
5748
5749/// Concat a bounds-mapping transform (unit gradient space → `b`) onto the current context, so a
5750/// circular gradient drawn in unit coordinates renders elliptically stretched to the bounds.
5751fn concat_unit_to_bounds(b: day_spec::Rect) {
5752    let t = NSAffineTransform::new();
5753    t.setTransformStruct(NSAffineTransformStruct {
5754        m11: b.size.width,
5755        m12: 0.0,
5756        m21: 0.0,
5757        m22: b.size.height,
5758        tX: b.origin.x,
5759        tY: b.origin.y,
5760    });
5761    unsafe { t.concat() };
5762}
5763
5764/// Put a [`day_spec::StrokeStyle`] onto a path.
5765///
5766/// NOTE: this backend used to force ROUND caps on every stroke. It now honors the style, whose
5767/// default is BUTT — the same default the spec and every other backend use. A line that wants
5768/// round ends asks for `StrokeStyle::round`.
5769fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
5770    use day_spec::{LineCap, LineJoin};
5771    unsafe {
5772        p.setLineWidth(style.width);
5773        p.setLineCapStyle(match style.cap {
5774            LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
5775            LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
5776            LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
5777        });
5778        if style.is_plain() {
5779            return;
5780        }
5781        p.setLineJoinStyle(match style.join {
5782            LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
5783            LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
5784            LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
5785        });
5786        p.setMiterLimit(style.miter_limit);
5787        if !style.dash.is_empty() {
5788            let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
5789            p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
5790        }
5791    }
5792}
5793
5794/// Draw a gradient through whatever clip is installed, in AppKit's own NSGradient terms.
5795/// Shared by the gradient FILL arms and the gradient STROKE arm, which differ only in what they
5796/// clipped to first.
5797fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
5798    let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
5799        | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
5800    match paint {
5801        day_spec::Paint::Linear(g) => {
5802            if let Some(grad) = nsgradient(&g.stops) {
5803                let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
5804                unsafe {
5805                    grad.drawFromPoint_toPoint_options(
5806                        NSPoint::new(s.x, s.y),
5807                        NSPoint::new(e.x, e.y),
5808                        opts,
5809                    )
5810                };
5811            }
5812        }
5813        day_spec::Paint::Radial(g) => {
5814            if let Some(grad) = nsgradient(&g.stops) {
5815                NSGraphicsContext::saveGraphicsState_class();
5816                concat_unit_to_bounds(bounds);
5817                let c = NSPoint::new(g.center.x, g.center.y);
5818                unsafe {
5819                    grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
5820                };
5821                NSGraphicsContext::restoreGraphicsState_class();
5822            }
5823        }
5824        day_spec::Paint::Solid(_) => {}
5825    }
5826}
5827
5828fn apply_button_content(
5829    btn: &NSButton,
5830    title: &str,
5831    icon: Option<&day_spec::Icon>,
5832    icon_only: bool,
5833) {
5834    let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
5835    if let Some(image) = &image {
5836        let size = image.size();
5837        let longest = size.width.max(size.height);
5838        if longest > 0.0 {
5839            image.setSize(objc2_foundation::NSSize::new(
5840                size.width * 20.0 / longest,
5841                size.height * 20.0 / longest,
5842            ));
5843        }
5844    }
5845    let style = BUTTON_STYLES
5846        .with(|m| m.borrow().get(&ptr_of(btn)).copied())
5847        .unwrap_or_default();
5848    BUTTON_IMAGES.with(|images| {
5849        images.remove(ptr_of(btn));
5850        if let Some(image) = &image {
5851            images.insert(ptr_of(btn), image.clone());
5852        }
5853    });
5854    set_button_title(btn, title, style);
5855    // The position first: the image setter pads a glyph that sits beside a title, and leaves
5856    // an icon-only one alone, by reading it.
5857    unsafe {
5858        btn.setImagePosition(if image.is_none() {
5859            objc2_app_kit::NSCellImagePosition::NoImage
5860        } else if icon_only {
5861            objc2_app_kit::NSCellImagePosition::ImageOnly
5862        } else {
5863            objc2_app_kit::NSCellImagePosition::ImageLeading
5864        });
5865    }
5866    set_button_image(btn, style);
5867    unsafe {
5868        // The title is the spoken name (an icon-only button shows none), unless the app named
5869        // the button itself; overwriting that here replaced app labels on every title change.
5870        if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
5871            btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
5872        }
5873        let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
5874        btn.setToolTip(tooltip.as_deref());
5875    }
5876}
5877
5878/// Bordered buttons do not reliably apply contentTintColor to template images. Keep
5879/// the native button, but supply an image that draws the original vector's alpha in
5880/// the requested contrast color at the destination resolution.
5881fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
5882    use day_spec::props::ButtonStyleSpec as S;
5883    let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
5884    let image = image.map(|source| {
5885        let S::Tinted(fill) = style else {
5886            return source;
5887        };
5888        let size = source.size();
5889        let ink = nscolor(S::on_tint(fill));
5890        let draw = block2::RcBlock::new(move |rect: NSRect| {
5891            source.drawInRect_fromRect_operation_fraction(
5892                rect,
5893                NSRect::ZERO,
5894                objc2_app_kit::NSCompositingOperation::SourceOver,
5895                1.0,
5896            );
5897            unsafe {
5898                ink.setFill();
5899                objc2_app_kit::NSRectFillUsingOperation(
5900                    rect,
5901                    objc2_app_kit::NSCompositingOperation::SourceIn,
5902                );
5903            }
5904            objc2::runtime::Bool::YES
5905        });
5906        objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
5907    });
5908    unsafe {
5909        let position = btn.imagePosition();
5910        // Beside a title, the glyph gets a clear gap: AppKit draws a leading image flush
5911        // against the text, so the image carries the space itself (a template stays one, so
5912        // the label color still tints it). The cell centers the image in its slot, so half
5913        // the extra width lands on each side.
5914        let image = image.map(|source| {
5915            // The position is set after this on a fresh button, so an unset one counts as
5916            // "beside a title"; only an icon-only button keeps the glyph as drawn.
5917            if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
5918                return source;
5919            }
5920            let size = source.size();
5921            let template = source.isTemplate();
5922            let padded = NSSize::new(size.width + 8.0, size.height);
5923            let draw = block2::RcBlock::new(move |_rect: NSRect| {
5924                source.drawInRect_fromRect_operation_fraction(
5925                    NSRect::new(NSPoint::new(0.0, 0.0), size),
5926                    NSRect::ZERO,
5927                    objc2_app_kit::NSCompositingOperation::SourceOver,
5928                    1.0,
5929                );
5930                objc2::runtime::Bool::YES
5931            });
5932            let out =
5933                objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
5934            out.setTemplate(template);
5935            out
5936        });
5937        btn.setImage(image.as_deref());
5938        btn.setImagePosition(position);
5939        btn.setImageHugsTitle(true);
5940    }
5941}
5942
5943/// Put `ButtonProps::selected` on an `NSButton`, keeping it an NSButton. A momentary button
5944/// shows no state, so the first `true` makes it push-on/push-off, whose on state AppKit draws
5945/// as the bezel's highlighted fill and VoiceOver reads as selected; a button that never
5946/// selects keeps its momentary type. A click toggles the state natively before the action
5947/// runs, so the `action:` handler restores the value recorded here.
5948fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
5949    BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
5950    unsafe {
5951        if on {
5952            btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
5953        }
5954        btn.setState(if on {
5955            NSControlStateValueOn
5956        } else {
5957            NSControlStateValueOff
5958        });
5959    }
5960}
5961
5962/// The corner radius of the tint painted behind a tinted button's bezel: the rounded push
5963/// bezel's own, so the fill reads as the bezel rather than as a box around it.
5964const TINT_CORNER_RADIUS: f64 = 6.0;
5965
5966/// Put a [`day_spec::props::ButtonStyleSpec`] on an `NSButton`, keeping it an NSButton.
5967///
5968/// Prominent = the return-key default button. Tinted = `bezelColor`, which AppKit composites
5969/// through the button's own bezel — so the pressed darkening, the focus ring and the disabled
5970/// look all still come from the control rather than from us painting a rectangle. macOS 26
5971/// composites the push bezel as a system material that ignores `bezelColor` on screen (an
5972/// offscreen `cacheDisplay` still honors it), so the tint is also painted on the control's
5973/// backing layer, where the translucent material lets it through; on older systems the opaque
5974/// tinted bezel covers that layer, so nothing changes there.
5975fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
5976    use day_spec::props::ButtonStyleSpec as S;
5977    let title = unsafe { btn.title() }.to_string();
5978    unsafe {
5979        // Reset first, so a patch from one style to another leaves nothing of the old one.
5980        btn.setKeyEquivalent(&NSString::from_str(""));
5981        btn.setBezelColor(None);
5982        btn.setBordered(!matches!(style, S::Plain));
5983        match style {
5984            S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
5985            S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
5986            // Bordered is the stock NSButton look already; Automatic asks for nothing, and an
5987            // NSButton hugs a one-glyph title already, so Compact asks for nothing either.
5988            S::Bordered | S::Automatic | S::Compact | S::Plain => {}
5989        }
5990        btn.setWantsLayer(true);
5991        if let Some(layer) = btn.layer() {
5992            match style {
5993                S::Tinted(c) => {
5994                    layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
5995                    layer.setCornerRadius(TINT_CORNER_RADIUS);
5996                }
5997                _ => layer.setBackgroundColor(None),
5998            }
5999        }
6000    }
6001    BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6002    let ink = match style {
6003        S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6004        _ => None,
6005    };
6006    unsafe {
6007        btn.setContentTintColor(ink.as_deref());
6008    }
6009    set_button_title(btn, &title, style);
6010    set_button_image(btn, style);
6011}
6012
6013/// Set a button's title, coloring it for the tint where there is one.
6014///
6015/// `contentTintColor` is NOT the seam for this: on a bordered `NSButton`,
6016/// AppKit keeps drawing the title in its own control text color — which is how a
6017/// white-on-rust button came out black-on-rust. An ATTRIBUTED title is the documented way to
6018/// control the text color, so that is what a tinted button gets.
6019///
6020/// The button's own font is carried into the attributes: an attributed title supplies the whole
6021/// run, so leaving the font out would drop the control font and render at the system default.
6022fn set_button_title(
6023    btn: &objc2_app_kit::NSButton,
6024    title: &str,
6025    style: day_spec::props::ButtonStyleSpec,
6026) {
6027    use day_spec::props::ButtonStyleSpec as S;
6028    // Changing an attributed title can reset NSButton's image placement. A reactive
6029    // tint must keep an icon-only button icon-only, including its native template tint.
6030    let position = unsafe { btn.imagePosition() };
6031    let S::Tinted(fill) = style else {
6032        // Plain title: AppKit picks the label color that suits the bezel it is drawing.
6033        unsafe {
6034            btn.setTitle(&NSString::from_str(title));
6035            btn.setImagePosition(position);
6036        }
6037        return;
6038    };
6039    unsafe {
6040        let col = nscolor(S::on_tint(fill));
6041        let font = btn
6042            .font()
6043            .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6044        // Centered, matching a plain NSButton title: an attributed title carries its own
6045        // paragraph style, and the default is left-aligned.
6046        let para = objc2_app_kit::NSMutableParagraphStyle::new();
6047        para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6048        let keys: [&NSString; 3] = [
6049            objc2_app_kit::NSFontAttributeName,
6050            objc2_app_kit::NSForegroundColorAttributeName,
6051            objc2_app_kit::NSParagraphStyleAttributeName,
6052        ];
6053        let objs: [&objc2::runtime::AnyObject; 3] = [
6054            font.as_ref() as &objc2::runtime::AnyObject,
6055            col.as_ref() as &objc2::runtime::AnyObject,
6056            para.as_ref() as &objc2::runtime::AnyObject,
6057        ];
6058        let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6059        let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6060            objc2_foundation::NSAttributedString::alloc(),
6061            &NSString::from_str(title),
6062            Some(&attrs),
6063        );
6064        btn.setAttributedTitle(&s);
6065        btn.setImagePosition(position);
6066    }
6067}
6068
6069// NSImageView supports aspect-fit but not aspect-fill. Expand its native drawing about
6070// the center and clip to the view; this retains vector rendering and template tinting.
6071define_class!(
6072    #[unsafe(super(objc2_app_kit::NSImageView))]
6073    #[thread_kind = MainThreadOnly]
6074    #[name = "DayFillImageView"]
6075    struct FillImageView;
6076
6077    impl FillImageView {
6078        #[unsafe(method(drawRect:))]
6079        fn draw_rect(&self, dirty: NSRect) {
6080            let bounds = self.bounds();
6081            let image = unsafe { self.image() };
6082            let Some(size) = image.map(|image| image.size()).filter(|size| {
6083                size.width > 0.0 && size.height > 0.0
6084                    && bounds.size.width > 0.0 && bounds.size.height > 0.0
6085            }) else {
6086                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6087                return;
6088            };
6089            let x = bounds.size.width / size.width;
6090            let y = bounds.size.height / size.height;
6091            let scale = x.max(y) / x.min(y);
6092            let cx = bounds.origin.x + bounds.size.width / 2.0;
6093            let cy = bounds.origin.y + bounds.size.height / 2.0;
6094            NSGraphicsContext::saveGraphicsState_class();
6095            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6096            let transform = NSAffineTransform::transform();
6097            transform.translateXBy_yBy(cx, cy);
6098            transform.scaleBy(scale);
6099            transform.translateXBy_yBy(-cx, -cy);
6100            transform.concat();
6101            let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6102            NSGraphicsContext::restoreGraphicsState_class();
6103        }
6104
6105        #[unsafe(method(setFrameSize:))]
6106        fn set_frame_size(&self, size: NSSize) {
6107            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6108            NSView::setNeedsDisplay(self, true);
6109        }
6110    }
6111);
6112
6113fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6114    use day_spec::Shape;
6115    use objc2_app_kit::NSBezierPath;
6116    unsafe {
6117        Some(match shape {
6118            Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6119            Shape::RoundedRect(r, rad) => {
6120                NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6121            }
6122            Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6123            Shape::Arc {
6124                rect,
6125                start_deg,
6126                sweep_deg,
6127            } => {
6128                let p = NSBezierPath::new();
6129                let center = NSPoint::new(
6130                    rect.origin.x + rect.size.width / 2.0,
6131                    rect.origin.y + rect.size.height / 2.0,
6132                );
6133                let radius = rect.size.width.min(rect.size.height) / 2.0;
6134                // Flipped view: increasing angle is visually clockwise, matching the spec.
6135                p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6136                    center,
6137                    radius,
6138                    *start_deg,
6139                    *start_deg + *sweep_deg,
6140                );
6141                p
6142            }
6143            Shape::Line(a, b) => {
6144                let p = NSBezierPath::new();
6145                p.moveToPoint(NSPoint::new(a.x, a.y));
6146                p.lineToPoint(NSPoint::new(b.x, b.y));
6147                p
6148            }
6149            Shape::Polygon(pts) => {
6150                if pts.len() < 2 {
6151                    return None;
6152                }
6153                let p = NSBezierPath::new();
6154                p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6155                for pt in &pts[1..] {
6156                    p.lineToPoint(NSPoint::new(pt.x, pt.y));
6157                }
6158                p.closePath();
6159                p
6160            }
6161            Shape::Path(path) => {
6162                use day_spec::PathSeg;
6163                if path.segs.is_empty() {
6164                    return None;
6165                }
6166                let p = NSBezierPath::new();
6167                // NSBezierPath's own quadratic API is macOS 14+, so quads are ELEVATED to
6168                // cubics with the standard formula (c1 = p0 + 2/3(c - p0), c2 = p1 + 2/3(c -
6169                // p1)), which is exact rather than an approximation.
6170                let mut cur = NSPoint::new(0.0, 0.0);
6171                for seg in &path.segs {
6172                    match seg {
6173                        PathSeg::Move(a) => {
6174                            cur = NSPoint::new(a.x, a.y);
6175                            p.moveToPoint(cur);
6176                        }
6177                        PathSeg::Line(a) => {
6178                            cur = NSPoint::new(a.x, a.y);
6179                            p.lineToPoint(cur);
6180                        }
6181                        PathSeg::Quad(c, a) => {
6182                            let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6183                            let c1 = NSPoint::new(
6184                                cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6185                                cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6186                            );
6187                            let c2 = NSPoint::new(
6188                                end.x + 2.0 / 3.0 * (ctl.x - end.x),
6189                                end.y + 2.0 / 3.0 * (ctl.y - end.y),
6190                            );
6191                            p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6192                            cur = end;
6193                        }
6194                        PathSeg::Cubic(c1, c2, a) => {
6195                            cur = NSPoint::new(a.x, a.y);
6196                            p.curveToPoint_controlPoint1_controlPoint2(
6197                                cur,
6198                                NSPoint::new(c1.x, c1.y),
6199                                NSPoint::new(c2.x, c2.y),
6200                            );
6201                        }
6202                        PathSeg::Close => p.closePath(),
6203                    }
6204                }
6205                p.setWindingRule(match path.rule {
6206                    day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6207                    day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6208                });
6209                p
6210            }
6211        })
6212    }
6213}
6214
6215// ---------------------------------------------------------------------------
6216// DayUndoManager — the native FRONT of the app's one undo stack (docs/model.md)
6217// ---------------------------------------------------------------------------
6218
6219/// The mirrored [`day_spec::UndoState`]: what the stock Edit menu reads through the standard
6220/// `undo:`/`redo:` validation. The stack itself lives in day-model; this object only answers
6221/// questions and forwards invocations — two histories can never fork.
6222struct UndoIvars {
6223    state: std::cell::RefCell<day_spec::UndoState>,
6224}
6225
6226define_class!(
6227    #[unsafe(super(objc2_foundation::NSUndoManager))]
6228    #[thread_kind = MainThreadOnly]
6229    #[name = "DayUndoManager"]
6230    #[ivars = UndoIvars]
6231    struct DayUndoManager;
6232
6233    /// Overrides of the questions AppKit's menu validation asks, answered from the mirrored
6234    /// state — and of the two verbs, forwarded as `Event::Undo` (enqueue-only, like every
6235    /// other event). Registration/grouping machinery of the superclass is never used.
6236    impl DayUndoManager {
6237        #[unsafe(method(canUndo))]
6238        fn can_undo(&self) -> bool {
6239            self.ivars().state.borrow().can_undo
6240        }
6241
6242        #[unsafe(method(canRedo))]
6243        fn can_redo(&self) -> bool {
6244            self.ivars().state.borrow().can_redo
6245        }
6246
6247        #[unsafe(method(undo))]
6248        fn do_undo(&self) {
6249            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
6250        }
6251
6252        #[unsafe(method(redo))]
6253        fn do_redo(&self) {
6254            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
6255        }
6256
6257        #[unsafe(method_id(undoMenuItemTitle))]
6258        fn undo_menu_item_title(&self) -> Retained<NSString> {
6259            // Route through the superclass's own title former, so "Undo" itself comes out in
6260            // the system language; the action label arrived already localized from the app.
6261            let label = self.ivars().state.borrow().undo_label.clone();
6262            unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6263        }
6264
6265        #[unsafe(method_id(redoMenuItemTitle))]
6266        fn redo_menu_item_title(&self) -> Retained<NSString> {
6267            let label = self.ivars().state.borrow().redo_label.clone();
6268            unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
6269        }
6270    }
6271);
6272
6273fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
6274    UNDO_FRONT.with(|u| {
6275        u.borrow_mut()
6276            .get_or_insert_with(|| {
6277                let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
6278                    state: std::cell::RefCell::new(day_spec::UndoState::default()),
6279                });
6280                unsafe { msg_send![super(this), init] }
6281            })
6282            .clone()
6283    })
6284}
6285
6286// ---------------------------------------------------------------------------
6287// DayWinDelegate — resize + close + key tracking, per window
6288// ---------------------------------------------------------------------------
6289
6290/// `node`: the day window-root id this delegate's window reports to. `None` = the PRIMARY
6291/// window — resize goes to `WINDOW_NODE` and close terminates the app; a secondary window
6292/// (docs/windows.md) reports to its own root and close tears down just that window.
6293struct WinIvars {
6294    node: Option<NodeId>,
6295    /// The tab group this window was opened in (`WindowTabbing::Group`/`Preferred`): the
6296    /// tab bar's "+" opens another window of the same group.
6297    group: Option<String>,
6298    /// The last display state reported (`WindowState::code`), so a resize that does not change
6299    /// the zoom state reports nothing.
6300    last_state: Cell<i32>,
6301}
6302
6303define_class!(
6304    #[unsafe(super(NSObject))]
6305    #[thread_kind = MainThreadOnly]
6306    #[name = "DayWinDelegate"]
6307    #[ivars = WinIvars]
6308    struct DayWinDelegate;
6309
6310    unsafe impl NSObjectProtocol for DayWinDelegate {}
6311
6312    /// The responder chain's last stop for the standard edit nav hosts: a focused text view
6313    /// answered `cut:`/`copy:`/`paste:` long before the window asked its delegate, so what
6314    /// arrives here is the app's to handle — the same precedence the undo manager route uses.
6315    impl DayWinDelegate {
6316        /// Edit ▸ Undo. The stock item's nil-target `undo:` finds no implementor among Day's
6317        /// plain views, so the delegate is where the chain lands — resolving through the
6318        /// acting manager keeps a focused field's typing undo ahead of the document stack.
6319        #[unsafe(method(undo:))]
6320        fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6321            ffi_guard::contain((), || {
6322                if let Some(m) = self.acting_undo_manager() {
6323                    unsafe { m.undo() };
6324                }
6325            });
6326        }
6327
6328        /// Edit ▸ Redo.
6329        #[unsafe(method(redo:))]
6330        fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6331            ffi_guard::contain((), || {
6332                if let Some(m) = self.acting_undo_manager() {
6333                    unsafe { m.redo() };
6334                }
6335            });
6336        }
6337
6338        #[unsafe(method(cut:))]
6339        fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6340            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
6341        }
6342
6343        #[unsafe(method(copy:))]
6344        fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6345            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
6346        }
6347
6348        #[unsafe(method(paste:))]
6349        fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6350            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
6351        }
6352
6353        #[unsafe(method(selectAll:))]
6354        fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
6355            ffi_guard::contain((), || {
6356                emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
6357            });
6358        }
6359
6360        /// AppKit's menu validation, the same machinery that greys Edit items for text views:
6361        /// the bridge state answers for cut/copy, and paste additionally requires the
6362        /// pasteboard to actually hold text.
6363        #[unsafe(method(validateMenuItem:))]
6364        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
6365            ffi_guard::contain(false, || {
6366                let state = EDIT_STATE.with(|s| s.get());
6367                match unsafe { item.action() } {
6368                    // The undo pair enables from the acting manager and takes its titles
6369                    // ("Undo Move Shape"), exactly as AppKit's own windows do.
6370                    Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
6371                        Some(m) => {
6372                            item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
6373                            unsafe { m.canUndo() }
6374                        }
6375                        None => false,
6376                    },
6377                    Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
6378                        Some(m) => {
6379                            item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
6380                            unsafe { m.canRedo() }
6381                        }
6382                        None => false,
6383                    },
6384                    Some(a) if a == sel!(selectAll:) => state.can_select_all,
6385                    Some(a) if a == sel!(cut:) => state.can_cut,
6386                    Some(a) if a == sel!(copy:) => state.can_copy,
6387                    Some(a) if a == sel!(paste:) => {
6388                        state.can_paste && {
6389                            let pb = unsafe { NSPasteboard::generalPasteboard() };
6390                            pb.types().is_some_and(|types| !types.is_empty())
6391                        }
6392                    }
6393                    _ => true,
6394                }
6395            })
6396        }
6397    }
6398
6399    unsafe impl NSWindowDelegate for DayWinDelegate {
6400        #[unsafe(method(windowDidResize:))]
6401        fn window_did_resize(&self, notification: &NSNotification) {
6402            ffi_guard::contain((), || {
6403                if let Some(obj) = unsafe { notification.object() }
6404                    && let Ok(win) = obj.downcast::<NSWindow>()
6405                    && let Some(size) = pin_below_title_bar(&win)
6406                {
6407                    let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6408                    emit(target, Event::WindowResized(size));
6409                }
6410                // Zooming is a resize with no notification of its own.
6411                self.report_state_of(notification);
6412            })
6413        }
6414
6415        #[unsafe(method(windowShouldClose:))]
6416        fn window_should_close(&self, _window: &NSWindow) -> bool {
6417            ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
6418        }
6419
6420        #[unsafe(method(windowWillClose:))]
6421        fn window_will_close(&self, _notification: &NSNotification) {
6422            ffi_guard::contain((), || {
6423                match self.ivars().node {
6424                    // Secondary window: confirm the close to day-core, which tears the
6425                    // subtree down on a DEFERRED hop (never inside this AppKit close frame).
6426                    Some(node) => emit(node, Event::WindowClosed),
6427                    // Primary window: closing it quits, taking secondaries with it
6428                    // (docs/windows.md close policy), unless the app keeps running without a
6429                    // window (a status item, `KeepRunning::Always`): then it closes like any
6430                    // other window and day-core decides.
6431                    None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
6432                    None => {
6433                        let app = NSApplication::sharedApplication(self.mtm());
6434                        unsafe { app.terminate(None) };
6435                    }
6436                }
6437            })
6438        }
6439
6440        #[unsafe(method_id(windowWillReturnUndoManager:))]
6441        fn window_will_return_undo_manager(
6442            &self,
6443            _window: &NSWindow,
6444        ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6445            // The responder chain already gave a focused text field its OWN manager before
6446            // asking the window — typing undo stays the field's, the model stack gets the
6447            // rest, exactly the precedence the plan's typing rule wants.
6448            ffi_guard::contain(None, || {
6449                UNDO_FRONT.with(|u| {
6450                    u.borrow()
6451                        .as_ref()
6452                        .map(|m| Retained::into_super(m.clone()))
6453                })
6454            })
6455        }
6456
6457        #[unsafe(method(windowDidBecomeKey:))]
6458        fn window_did_become_key(&self, _notification: &NSNotification) {
6459            ffi_guard::contain((), || {
6460                if let Some(node) = self.ivars().node {
6461                    emit(node, Event::WindowFocused(true));
6462                }
6463            })
6464        }
6465
6466        #[unsafe(method(windowDidResignKey:))]
6467        fn window_did_resign_key(&self, _notification: &NSNotification) {
6468            ffi_guard::contain((), || {
6469                if let Some(node) = self.ivars().node {
6470                    emit(node, Event::WindowFocused(false));
6471                }
6472            })
6473        }
6474
6475        #[unsafe(method(windowDidMiniaturize:))]
6476        fn window_did_miniaturize(&self, notification: &NSNotification) {
6477            ffi_guard::contain((), || self.report_state_of(notification))
6478        }
6479
6480        #[unsafe(method(windowDidDeminiaturize:))]
6481        fn window_did_deminiaturize(&self, notification: &NSNotification) {
6482            ffi_guard::contain((), || self.report_state_of(notification))
6483        }
6484
6485        #[unsafe(method(windowDidEnterFullScreen:))]
6486        fn window_did_enter_full_screen(&self, notification: &NSNotification) {
6487            ffi_guard::contain((), || self.report_state_of(notification))
6488        }
6489
6490        #[unsafe(method(windowDidExitFullScreen:))]
6491        fn window_did_exit_full_screen(&self, notification: &NSNotification) {
6492            ffi_guard::contain((), || self.report_state_of(notification))
6493        }
6494    }
6495
6496    // The tab bar's "+" button walks the responder chain (window → delegate) for
6497    // `newWindowForTab:` — present only when the app registered a new-window builder
6498    // (otherwise automatic tabbing is off and no "+" exists).
6499    impl DayWinDelegate {
6500        #[unsafe(method(newWindowForTab:))]
6501        fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
6502            ffi_guard::contain((), || {
6503                // A window in a tab group of its own gets another window of that group
6504                // (`register_new_window_for`); everything else gets File ▸ New Window's.
6505                let _ = match self.ivars().group.as_deref() {
6506                    Some(group) => day_core::windows::open_new_window_for_group(group),
6507                    None => day_core::windows::open_new_window(),
6508                };
6509            })
6510        }
6511    }
6512);
6513
6514impl DayWinDelegate {
6515    fn report_state_of(&self, notification: &NSNotification) {
6516        if let Some(obj) = unsafe { notification.object() }
6517            && let Ok(win) = obj.downcast::<NSWindow>()
6518        {
6519            self.report_state(&win);
6520        }
6521    }
6522}
6523
6524/// The day name for a key press, or `None` for every key the route does not carry — the
6525/// [`day_spec::KeyEvent`] names (docs/menus.md).
6526fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
6527    match unsafe { event.keyCode() } {
6528        123 => Some("ArrowLeft"),
6529        124 => Some("ArrowRight"),
6530        125 => Some("ArrowDown"),
6531        126 => Some("ArrowUp"),
6532        // Not the delete keys. This backend draws a menu bar, so a Delete accelerator on a
6533        // menu item owns them (docs/menus.md) — and a focused piece that CLAIMS a key stops
6534        // that accelerator from ever seeing it, which is how a canvas ends up swallowing the
6535        // Delete its own Edit menu was going to act on.
6536        //
6537        // A digit, main row or keypad, named by what it types. Never under ⌘, ⌥ or ⌃: those
6538        // combinations are accelerators, and claiming one would starve the menu the same way.
6539        _ => {
6540            let held = NSEventModifierFlags::Command
6541                | NSEventModifierFlags::Option
6542                | NSEventModifierFlags::Control;
6543            if event.modifierFlags().intersects(held) {
6544                return None;
6545            }
6546            let typed = event.characters()?.to_string();
6547            let mut chars = typed.chars();
6548            match (chars.next(), chars.next()) {
6549                (Some(c), None) => day_spec::KeyEvent::digit_name(c),
6550                _ => None,
6551            }
6552        }
6553    }
6554}
6555
6556/// AppKit's modifier flags as day's mask.
6557fn key_modifiers(f: NSEventModifierFlags) -> u8 {
6558    let mut modifiers = 0u8;
6559    if f.contains(NSEventModifierFlags::Shift) {
6560        modifiers |= day_spec::KeyEvent::SHIFT;
6561    }
6562    if f.contains(NSEventModifierFlags::Command) {
6563        modifiers |= day_spec::KeyEvent::PRIMARY;
6564    }
6565    if f.contains(NSEventModifierFlags::Option) {
6566        modifiers |= day_spec::KeyEvent::ALT;
6567    }
6568    modifiers
6569}
6570
6571impl DayWinDelegate {
6572    /// The manager AppKit's own undo mechanics act on: ask the FIRST RESPONDER, whose
6573    /// `undoManager` walks the chain itself — a field editor answers with its typing
6574    /// history, everything else falls through to `windowWillReturnUndoManager` and lands on
6575    /// the app's front. Falls back to the front when no window is key yet.
6576    fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
6577        let responder = NSApplication::sharedApplication(self.mtm())
6578            .keyWindow()
6579            .and_then(|w| w.firstResponder());
6580        responder
6581            .and_then(|r| unsafe { r.undoManager() })
6582            .or_else(|| {
6583                UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
6584            })
6585    }
6586}
6587
6588impl DayWinDelegate {
6589    fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
6590        let this = Self::alloc(mtm).set_ivars(WinIvars {
6591            node,
6592            group,
6593            last_state: Cell::new(day_spec::WindowState::Normal.code()),
6594        });
6595        unsafe { msg_send![super(this), init] }
6596    }
6597
6598    /// Report the window's display state if it changed since the last report
6599    /// (docs/windows.md "Window properties"): to the window's root node, or `WINDOW_NODE` for the
6600    /// primary, the same routing as `WindowResized`.
6601    fn report_state(&self, window: &NSWindow) {
6602        let state = ns_window_state(window);
6603        if self.ivars().last_state.replace(state.code()) != state.code() {
6604            log::debug!("appkit: window state now {state:?}");
6605            let target = self.ivars().node.unwrap_or(WINDOW_NODE);
6606            emit(target, Event::WindowStateChanged(state));
6607        }
6608    }
6609}
6610
6611/// What AppKit says a window is showing as: miniaturized wins (a fullscreen window can be
6612/// neither), then fullscreen (whose frame also reads as zoomed), then zoomed.
6613fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
6614    if window.isMiniaturized() {
6615        day_spec::WindowState::Minimized
6616    } else if window
6617        .styleMask()
6618        .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
6619    {
6620        day_spec::WindowState::Fullscreen
6621    } else if window.isZoomed() {
6622        day_spec::WindowState::Maximized
6623    } else {
6624        day_spec::WindowState::Normal
6625    }
6626}
6627
6628/// Ask AppKit for `state`, undoing whatever the window is in first: fullscreen and miniaturized
6629/// have to be left before a window can zoom, and each is its own toggle.
6630fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
6631    use day_spec::WindowState as S;
6632    let current = ns_window_state(window);
6633    if current == state {
6634        return;
6635    }
6636    unsafe {
6637        match current {
6638            S::Minimized => window.deminiaturize(None),
6639            // Leaving fullscreen animates; asking for another state in the same turn would be
6640            // dropped by AppKit mid-transition, so the request stops at leaving it. The state
6641            // signal reads back `Normal`, and a second request takes it from there.
6642            S::Fullscreen => {
6643                window.toggleFullScreen(None);
6644                return;
6645            }
6646            S::Maximized if state != S::Minimized => window.zoom(None),
6647            _ => {}
6648        }
6649        match state {
6650            S::Normal => {}
6651            S::Minimized => window.miniaturize(None),
6652            S::Maximized => {
6653                if !window.isZoomed() {
6654                    window.zoom(None)
6655                }
6656            }
6657            S::Fullscreen => window.toggleFullScreen(None),
6658        }
6659    }
6660}
6661
6662// ---------------------------------------------------------------------------
6663// The backend
6664// ---------------------------------------------------------------------------
6665
6666/// Renderers registered by external Day Piece crates (§8.2 layer 3 — linkme convenience).
6667#[distributed_slice]
6668pub static RENDERERS: [fn() -> Renderer<AppKit>];
6669
6670/// A live secondary window (docs/windows.md). The delegate is RETAINED here —
6671/// `setDelegate:` holds it weakly, and unlike the primary's (kept alive because `run`
6672/// never returns) a secondary's delegate would die at the end of `open_window` otherwise.
6673struct SecondaryWin {
6674    window: Retained<NSWindow>,
6675    #[allow(dead_code)] // held for lifetime only; AppKit talks to it via the weak delegate ref
6676    delegate: Retained<DayWinDelegate>,
6677    content: Handle,
6678}
6679
6680/// Deliver an explicitly registered Escape accelerator before a field editor swallows it.
6681/// The monitor is local to this process and removed with the backend.
6682struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
6683impl Drop for MenuEscapeMonitor {
6684    fn drop(&mut self) {
6685        unsafe { NSEvent::removeMonitor(&self.0) };
6686    }
6687}
6688
6689pub struct AppKit {
6690    menu_escape_monitor: Option<MenuEscapeMonitor>,
6691    sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
6692
6693    mtm: MainThreadMarker,
6694    registry: Registry<AppKit>,
6695    window: Option<Retained<NSWindow>>,
6696    content: Option<Handle>,
6697    secondary: Vec<SecondaryWin>,
6698    app_name: String,
6699    /// Where the next secondary window's top-left goes (docs/windows.md). macOS staggers new
6700    /// windows rather than stacking them: `cascadeTopLeftFromPoint:` places the window and
6701    /// answers the point after it, so threading that answer through here is the whole
6702    /// mechanism. `None` until the primary exists — the cascade starts from its corner.
6703    cascade: Option<NSPoint>,
6704    /// One tracking-area owner per view carrying a `.cursor()` (docs/cursor.md), keyed by the
6705    /// view pointer. Removed when the cursor goes back to `Default`.
6706    cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
6707}
6708
6709impl AppKit {
6710    /// Rebuild a `text_field` as the other class (plain ⇄ secure) and put the replacement
6711    /// where the old view was: same text, look and place among its siblings, same focus and
6712    /// selection, and every view-keyed entry moved to it. day-core drops the old handle
6713    /// without a `release`, so nothing keyed by it may stay behind.
6714    fn swap_text_field(
6715        &mut self,
6716        h: &Handle,
6717        old: &NSTextField,
6718        node: NodeId,
6719        secure: bool,
6720    ) -> Retained<NSTextField> {
6721        let new = new_text_field(self.mtm, node, secure);
6722        let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
6723        // Focus and selection first: reading them is only meaningful while the old field
6724        // still edits. `stringValue` below answers the field editor's live text.
6725        let window = h.window();
6726        let focused = window
6727            .as_deref()
6728            .is_some_and(|w| owns_first_responder(w, h));
6729        let selection = old.currentEditor().map(|e| e.selectedRange());
6730        unsafe {
6731            new.setStringValue(&old.stringValue());
6732            new.setPlaceholderString(old.placeholderString().as_deref());
6733            new.setEnabled(old.isEnabled());
6734            new.setFont(old.font().as_deref());
6735            new.setFrame(h.frame());
6736            new.setHidden(h.isHidden());
6737            new.setMenu(h.menu().as_deref());
6738            new.setToolTip(h.toolTip().as_deref());
6739            // Opacity and transform ride the layer (`set_opacity` / `set_transform`).
6740            if h.wantsLayer() {
6741                new.setWantsLayer(true);
6742                new.setAlphaValue(h.alphaValue());
6743                let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
6744                let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
6745                if !from.is_null() && !to.is_null() {
6746                    let t: CGAffineTransform = msg_send![from, affineTransform];
6747                    let _: () = msg_send![to, setAffineTransform: t];
6748                }
6749            }
6750            // Accessibility (`set_a11y`): only what was set explicitly, so the new class
6751            // keeps its own defaults (a secure field's role and hidden value) for the rest.
6752            if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
6753                new.setAccessibilityIdentifier(Some(&id));
6754            }
6755            if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
6756                new.setAccessibilityLabel(Some(&label));
6757            }
6758            if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
6759                new.setAccessibilityHelp(Some(&help));
6760            }
6761            if !h.isAccessibilityElement() {
6762                new.setAccessibilityElement(false);
6763            }
6764        }
6765        // Recognizers and the cursor's tracking area move as objects, keeping their targets.
6766        for r in unsafe { h.gestureRecognizers() }.iter() {
6767            unsafe {
6768                h.removeGestureRecognizer(&r);
6769                new.addGestureRecognizer(&r);
6770            }
6771        }
6772        GESTURES.with(|m| {
6773            let mut m = m.borrow_mut();
6774            if let Some(targets) = m.remove(&old_key) {
6775                m.insert(new_key, targets);
6776            }
6777        });
6778        if let Some((owner, area)) = self.cursors.remove(&old_key) {
6779            unsafe {
6780                h.removeTrackingArea(&area);
6781                new.addTrackingArea(&area);
6782            }
6783            self.cursors.insert(new_key, (owner, area));
6784        }
6785        PAN_NODES.with(|t| rekey(t, old_key, new_key));
6786        HOVER_NODES.with(|t| rekey(t, old_key, new_key));
6787        KEY_NODES.with(|t| rekey(t, old_key, new_key));
6788        FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
6789        CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
6790        transfer::moved(h, &new);
6791        // The old field goes silent before it leaves: ending its editing session would
6792        // otherwise report a focus loss for a node that keeps its focus.
6793        unsafe { old.setDelegate(None) };
6794        TARGETS.with(|m| {
6795            m.borrow_mut().remove(&old_key);
6796        });
6797        if let Some(parent) = unsafe { h.superview() } {
6798            unsafe {
6799                parent.addSubview_positioned_relativeTo(
6800                    &new,
6801                    objc2_app_kit::NSWindowOrderingMode::Above,
6802                    Some(h),
6803                );
6804                h.removeFromSuperview();
6805            }
6806        }
6807        if focused && let Some(window) = window {
6808            FIELD_SWAP.with(|s| s.set(true));
6809            let taken = window.makeFirstResponder(Some(&new));
6810            FIELD_SWAP.with(|s| s.set(false));
6811            // Taking focus selects the whole text; put back what was selected (the caret,
6812            // usually). Both classes count in UTF-16 units, so the range carries over.
6813            if taken && let Some(editor) = new.currentEditor() {
6814                let len = unsafe { new.stringValue() }.length();
6815                let range = selection
6816                    .filter(|r| r.location.saturating_add(r.length) <= len)
6817                    .unwrap_or(objc2_foundation::NSRange::new(len, 0));
6818                editor.setSelectedRange(range);
6819            }
6820        }
6821        // Whatever else was keyed by the old view goes with it.
6822        day_spec::sidetable::sweep(old_key);
6823        new
6824    }
6825
6826    pub fn new() -> Self {
6827        let mtm =
6828            MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
6829        let mut registry = Registry::default();
6830        for f in RENDERERS {
6831            registry.register(f());
6832        }
6833        AppKit {
6834            menu_escape_monitor: None,
6835            mtm,
6836            registry,
6837            window: None,
6838            sharing: None,
6839            content: None,
6840            secondary: Vec::new(),
6841            app_name: "Day".into(),
6842            cascade: None,
6843            cursors: HashMap::new(),
6844        }
6845    }
6846
6847    /// Public helper for external renderers.
6848    pub fn mtm(&self) -> MainThreadMarker {
6849        self.mtm
6850    }
6851
6852    /// The `NSWindow` whose content container is `host`: a secondary window, or the primary.
6853    fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
6854        if let Some(w) = self
6855            .secondary
6856            .iter()
6857            .find(|w| ptr_of(&w.content) == ptr_of(host))
6858        {
6859            return Some(w.window.clone());
6860        }
6861        self.content
6862            .as_ref()
6863            .filter(|c| ptr_of(c) == ptr_of(host))
6864            .and(self.window.clone())
6865    }
6866
6867    /// Build a Day window: titled + closable (Preferences kind drops resize/minimize and
6868    /// disallows tabbing per macOS convention; Normal windows share the `day.normal`
6869    /// tabbing group), a flipped content view, and a per-window delegate (`node`: `None` =
6870    /// primary). The window is NOT released-when-closed — Rust's `Retained` owns it, and
6871    /// the AppKit default would double-release under us on close.
6872    fn make_window(
6873        &self,
6874        options: &WindowOptions,
6875        prefs_style: bool,
6876        node: Option<NodeId>,
6877    ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
6878        let mtm = self.mtm;
6879        let (title, size, min_size, tabbing) = (
6880            options.title.as_str(),
6881            options.size,
6882            options.min_size,
6883            &options.tabbing,
6884        );
6885        let content_rect =
6886            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
6887        // The kind decides the controls, the chrome decides the frame (docs/window-chrome.md).
6888        let style = window_chrome::style_mask(options, prefs_style);
6889        let window = window_chrome::alloc_window(
6890            mtm,
6891            content_rect,
6892            style,
6893            options.chrome == day_spec::WindowChrome::Frameless,
6894        );
6895        unsafe { window.setReleasedWhenClosed(false) };
6896        window.setTitle(&NSString::from_str(title));
6897        if let Some(min) = min_size {
6898            unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
6899        }
6900        if let Some(max) = options.max_size {
6901            unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
6902        }
6903        use day_spec::WindowTabbing as T;
6904        use objc2_app_kit::NSWindowTabbingMode as M;
6905        let group = match tabbing {
6906            T::Group(g) | T::Preferred(g) => Some(g.clone()),
6907            T::Automatic | T::Disallowed => None,
6908        };
6909        match tabbing {
6910            _ if prefs_style => window.setTabbingMode(M::Disallowed),
6911            T::Disallowed => window.setTabbingMode(M::Disallowed),
6912            // Same-kind Day windows group as native tabs (System Settings "prefer tabs",
6913            // View ▸ Show Tab Bar, Merge All Windows) — meaningful once a second Normal
6914            // window can exist; inert while automatic tabbing is globally off (see `run`).
6915            T::Automatic => unsafe {
6916                window.setTabbingIdentifier(&NSString::from_str("day.normal"))
6917            },
6918            T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
6919            T::Preferred(g) => {
6920                unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
6921                window.setTabbingMode(M::Preferred);
6922            }
6923        }
6924        if group.is_some() {
6925            // A named group is the app asking for tabs, so the class-wide switch `run` may have
6926            // turned off (no New Window builder) goes back on for it.
6927            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
6928        }
6929        let delegate = DayWinDelegate::new(mtm, node, group);
6930        window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
6931        let content = view_of(DayFlipped::new(mtm));
6932        window.setContentView(Some(&content));
6933        window_chrome::apply(&window, &content, options);
6934        // Tab / Shift-Tab (docs/focus.md). AppKit does NOT derive the key view loop from the view
6935        // hierarchy: `nextKeyView` is nil on a programmatically built window and the loop stays
6936        // empty, so Tab moves focus OUT of a text field and onto nothing — measured on the
6937        // showcase's Focus page, where three Tabs in a row left every field unfocused. Every other
6938        // Day backend gets traversal from its widget order for free; this is the one that has to
6939        // ask. Autorecalculation rather than a call at the end of each layout because Day's tree
6940        // is reactive: fields appear, move, and vanish between passes, and AppKit rebuilding the
6941        // loop on hierarchy changes is the same rule expressed once.
6942        window.setAutorecalculatesKeyViewLoop(true);
6943        (window, delegate, content)
6944    }
6945}
6946
6947impl Default for AppKit {
6948    fn default() -> Self {
6949        Self::new()
6950    }
6951}
6952
6953fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
6954    Retained::from(x.as_ref())
6955}
6956
6957fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
6958    unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
6959}
6960
6961/// The macOS native semantic text style for a logical [`Font`] (`None` for a custom size).
6962/// `NSFont.preferredFont(forTextStyle:)` gives the OS's own typography, tracking the system settings.
6963fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
6964    use objc2_app_kit::*;
6965    unsafe {
6966        Some(match f {
6967            Font::LargeTitle => NSFontTextStyleLargeTitle,
6968            Font::Title => NSFontTextStyleTitle1,
6969            Font::Title2 => NSFontTextStyleTitle2,
6970            Font::Title3 => NSFontTextStyleTitle3,
6971            Font::Headline => NSFontTextStyleHeadline,
6972            Font::Subheadline => NSFontTextStyleSubheadline,
6973            Font::Body => NSFontTextStyleBody,
6974            Font::Callout => NSFontTextStyleCallout,
6975            Font::Footnote => NSFontTextStyleFootnote,
6976            Font::Caption => NSFontTextStyleCaption1,
6977            Font::Caption2 => NSFontTextStyleCaption2,
6978            Font::System(_) | Font::Custom(..) => return None,
6979        })
6980    }
6981}
6982
6983fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
6984    use day_spec::FontWeight as W;
6985    use objc2_app_kit::*;
6986    unsafe {
6987        match w {
6988            W::UltraLight => NSFontWeightUltraLight,
6989            W::Thin => NSFontWeightThin,
6990            W::Light => NSFontWeightLight,
6991            W::Regular => NSFontWeightRegular,
6992            W::Medium => NSFontWeightMedium,
6993            W::Semibold => NSFontWeightSemibold,
6994            W::Bold => NSFontWeightBold,
6995            W::Heavy => NSFontWeightHeavy,
6996            W::Black => NSFontWeightBlack,
6997        }
6998    }
6999}
7000
7001/// The `NSFontManager` weight rung (0 … 15) for a Day weight — the scale
7002/// `fontWithFamily:traits:weight:size:` matches faces on (5 = regular, 9 = bold).
7003fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7004    use day_spec::FontWeight as W;
7005    match w {
7006        W::UltraLight => 2,
7007        W::Thin => 3,
7008        W::Light => 4,
7009        W::Regular => 5,
7010        W::Medium => 6,
7011        W::Semibold => 8,
7012        W::Bold => 9,
7013        W::Heavy => 10,
7014        W::Black => 12,
7015    }
7016}
7017
7018/// Resolve a canvas font (docs/fonts.md) at an absolute size: the system face for `None`,
7019/// else the family's nearest member through `NSFontManager` (which also synthesizes a bold or
7020/// italic the family lacks), falling back to a PostScript/full-name lookup (a bundled font
7021/// registered in `run`) and then to the system font with one warning.
7022fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7023    use objc2_app_kit::*;
7024    let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7025    let mtm = objc2::MainThreadMarker::new().expect("canvas draws on the main thread");
7026    let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7027    let mut traits = NSFontTraitMask::empty();
7028    if weight >= day_spec::FontWeight::Semibold {
7029        traits |= NSFontTraitMask::BoldFontMask;
7030    }
7031    if font.italic {
7032        traits |= NSFontTraitMask::ItalicFontMask;
7033    }
7034    let Some(family) = font.family.as_deref() else {
7035        let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7036        return if font.italic {
7037            unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7038        } else {
7039            base
7040        };
7041    };
7042    let ns_family = NSString::from_str(family);
7043    if let Some(f) = unsafe {
7044        manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7045    } {
7046        return f;
7047    }
7048    if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7049        return if traits.is_empty() {
7050            f
7051        } else {
7052            unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7053        };
7054    }
7055    log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7056    unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7057}
7058
7059/// The attribute dictionary canvas text draws and measures with (the same one, so
7060/// `measure_text` and `replay` agree on the line box).
7061fn canvas_text_attrs(
7062    font: &NSFont,
7063    color: day_spec::Color,
7064) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7065    let col = nscolor(color);
7066    // SAFETY: both are AppKit's own attribute-name constants, valid for the process lifetime.
7067    let keys: [&NSString; 2] = unsafe {
7068        [
7069            objc2_app_kit::NSFontAttributeName,
7070            objc2_app_kit::NSForegroundColorAttributeName,
7071        ]
7072    };
7073    let objs: [&objc2::runtime::AnyObject; 2] = [
7074        font as &objc2::runtime::AnyObject,
7075        col.as_ref() as &objc2::runtime::AnyObject,
7076    ];
7077    objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7078}
7079
7080/// Resolve a [`FontSpec`] to a native `NSFont`: a semantic style via `preferredFont(forTextStyle:)`
7081/// (or a custom system size), then an optional weight override (at the same size) and italic trait.
7082fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7083    use objc2_app_kit::*;
7084    let base: Retained<NSFont> = match spec.style {
7085        Font::System(pt) => {
7086            let w = spec
7087                .weight
7088                .map(ns_weight)
7089                .unwrap_or(unsafe { NSFontWeightRegular });
7090            unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7091        }
7092        // A bundled family (§18.4), registered with CoreText in run(). fontWithName resolves
7093        // family, full, and PostScript names. A weight override maps to the bold trait (the
7094        // family decides what it can supply); unknown families fall back to the system font.
7095        Font::Custom(name, pt) => {
7096            match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7097                Some(f) => {
7098                    if spec
7099                        .weight
7100                        .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7101                    {
7102                        let mtm = objc2::MainThreadMarker::new()
7103                            .expect("labels realize on the main thread");
7104                        unsafe {
7105                            NSFontManager::sharedFontManager(mtm)
7106                                .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
7107                        }
7108                    } else {
7109                        f
7110                    }
7111                }
7112                None => {
7113                    log::warn!(
7114                        "unknown font family {name:?} — falling back to the system font \
7115                         (is the file in the project's fonts/ directory?)"
7116                    );
7117                    let w = spec
7118                        .weight
7119                        .map(ns_weight)
7120                        .unwrap_or(unsafe { NSFontWeightRegular });
7121                    unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7122                }
7123            }
7124        }
7125        style => {
7126            // Invariant: System/Custom matched above, so only the semantic styles — which
7127            // `ns_text_style` maps exhaustively — can reach this arm.
7128            let ts = ns_text_style(style).expect("semantic style");
7129            let opts = objc2_foundation::NSDictionary::new();
7130            let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
7131            match spec.weight {
7132                // A weight override keeps the style's (system-resolved) size but re-picks the weight.
7133                Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
7134                None => f,
7135            }
7136        }
7137    };
7138    // Tabular figures. Cocoa exposes them as a whole font, not a trait, so this re-picks the
7139    // system font at the resolved size/weight rather than converting — which is why it only
7140    // applies to the system styles: a bundled `Font::Custom` family keeps its own figures (asking
7141    // for the system's monospaced-digit face there would silently swap the typeface).
7142    let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
7143        let w = spec
7144            .weight
7145            .map(ns_weight)
7146            .unwrap_or(unsafe { NSFontWeightRegular });
7147        unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
7148    } else {
7149        base
7150    };
7151    // Monospace, by the same rule as tabular: Cocoa ships it as a whole font, so this re-picks
7152    // the system's monospaced face at the resolved size and weight. Skipped for a bundled family
7153    // — swapping a chosen typeface for the system mono would be a surprise, not a refinement.
7154    let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
7155        let w = spec
7156            .weight
7157            .map(ns_weight)
7158            .unwrap_or(unsafe { NSFontWeightRegular });
7159        unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
7160    } else {
7161        base
7162    };
7163    // Relative size (`FontSpec::scale`). Applied last, over whatever face the traits above
7164    // settled on, and through `convertFont_toSize` so a bundled family keeps its typeface —
7165    // re-picking the system font here would undo the Custom/monospace/tabular work above.
7166    let base = if spec.scale != 1.0 {
7167        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7168        let pts = spec.resolved_points(base.pointSize());
7169        unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
7170    } else {
7171        base
7172    };
7173    if spec.italic {
7174        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
7175        unsafe {
7176            NSFontManager::sharedFontManager(mtm)
7177                .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
7178        }
7179    } else {
7180        base
7181    }
7182}
7183
7184/// Build an `NSAttributedString` for a label's text + runs (docs/text-runs.md).
7185///
7186/// Ranges arrive as BYTE offsets into a Rust `str`; `NSAttributedString` indexes UTF-16. The
7187/// conversion is per-run rather than a blanket assumption: any text with an emoji or a CJK
7188/// character makes the two disagree, and an off-by-N range there styles the wrong words.
7189/// Stamp a paragraph alignment across a label's whole attributed string.
7190///
7191/// Separate from `setAlignment:` because the two live in different places: the cell has a
7192/// paragraph style, the attributed string carries its own, and the string's wins.
7193fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
7194    use objc2_foundation::{NSMutableAttributedString, NSRange};
7195    unsafe {
7196        let cur = tf.attributedStringValue();
7197        let m = NSMutableAttributedString::initWithAttributedString(
7198            NSMutableAttributedString::alloc(),
7199            &cur,
7200        );
7201        let style = objc2_app_kit::NSMutableParagraphStyle::new();
7202        style.setAlignment(align);
7203        // Wrapping is what makes alignment observable at all, and the default paragraph style a
7204        // fresh NSMutableParagraphStyle carries would otherwise reset it to clipping.
7205        style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
7206        m.addAttribute_value_range(
7207            objc2_app_kit::NSParagraphStyleAttributeName,
7208            &style,
7209            NSRange::new(0, cur.length()),
7210        );
7211        tf.setAttributedStringValue(&m);
7212    }
7213}
7214
7215fn attributed_label(
7216    text: &str,
7217    base_font: &NSFont,
7218    color: Option<day_spec::Color>,
7219    role: day_spec::props::TextRole,
7220    runs: &[day_spec::TextRun],
7221) -> Retained<objc2_foundation::NSAttributedString> {
7222    use objc2_foundation::{NSMutableAttributedString, NSRange};
7223    let ns = NSString::from_str(text);
7224    let s = unsafe {
7225        NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
7226    };
7227    let whole = NSRange::new(0, ns.length());
7228    unsafe {
7229        s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
7230        // Always a foreground: an attributed range with no color attribute draws in black,
7231        // which is unreadable in dark mode. `labelColor` is the adaptive default the field
7232        // would have used on its own.
7233        // An explicit color wins; otherwise the ROLE picks which adaptive system color to use.
7234        // Both are adaptive, which is the point of asking for a role instead of a grey: the
7235        // secondary label is legible against either appearance's background, and a literal one
7236        // cannot be.
7237        let fg = color.map(nscolor).unwrap_or_else(|| match role {
7238            day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
7239            day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
7240        });
7241        s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
7242    }
7243    for r in runs {
7244        let Some(range) = utf16_range(text, &r.range) else {
7245            continue;
7246        };
7247        unsafe {
7248            s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
7249            if let Some(c) = r.color {
7250                s.addAttribute_value_range(
7251                    objc2_app_kit::NSForegroundColorAttributeName,
7252                    &nscolor(c),
7253                    range,
7254                );
7255            }
7256            if let Some(c) = r.background {
7257                s.addAttribute_value_range(
7258                    objc2_app_kit::NSBackgroundColorAttributeName,
7259                    &nscolor(c),
7260                    range,
7261                );
7262            }
7263            if r.underline.is_on() {
7264                let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
7265                s.addAttribute_value_range(
7266                    objc2_app_kit::NSUnderlineStyleAttributeName,
7267                    &style,
7268                    range,
7269                );
7270            }
7271            if r.strikethrough {
7272                let one = objc2_foundation::NSNumber::new_i64(1);
7273                s.addAttribute_value_range(
7274                    objc2_app_kit::NSStrikethroughStyleAttributeName,
7275                    &one,
7276                    range,
7277                );
7278            }
7279            if let Some(url) = r.link.as_deref() {
7280                // The native field editor hit-tests this attribute; DayLabel handles its
7281                // delegate callback and reports LinkActivated without opening the URL itself.
7282                let value = NSString::from_str(url);
7283                s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
7284            }
7285        }
7286    }
7287    s.into_super()
7288}
7289
7290/// [`Underline`](day_spec::Underline) as an `NSUnderlineStyle` bitmask: the line style in the low
7291/// byte, the pattern in the second. `Dotted`/`Wavy` are patterns over a single line, which is
7292/// exactly how AppKit spells them.
7293fn ns_underline(u: day_spec::Underline) -> i64 {
7294    use day_spec::Underline as U;
7295    match u {
7296        U::None => 0,
7297        U::Single => 0x01,
7298        U::Double => 0x09,
7299        U::Dotted => 0x01 | 0x0100,
7300        U::Wavy => 0x01 | 0x0400,
7301    }
7302}
7303
7304/// A byte range in `text` as an `NSRange` in UTF-16 units, or `None` if it is out of bounds.
7305fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
7306    let start = text.get(..r.start)?.encode_utf16().count();
7307    let len = text.get(r.clone())?.encode_utf16().count();
7308    Some(objc2_foundation::NSRange::new(start, len))
7309}
7310
7311/// Register every bundled font file (the project's `fonts/`, staged per §18.4) with CoreText for
7312/// this process, so `Font::Custom` family names resolve through `NSFont::fontWithName`. Called
7313/// once from `run()`; a failure (already registered on a hot relaunch, or a broken file) only
7314/// means that family won't resolve, so it logs and moves on.
7315fn register_bundled_fonts() {
7316    // CFURLRef is toll-free bridged with NSURL, so the NSURL pointer passes straight through.
7317    #[link(name = "CoreText", kind = "framework")]
7318    unsafe extern "C" {
7319        fn CTFontManagerRegisterFontsForURL(
7320            font_url: *const std::ffi::c_void,
7321            scope: u32, // kCTFontManagerScopeProcess = 1
7322            error: *mut *const std::ffi::c_void,
7323        ) -> bool;
7324    }
7325    for path in day_spec::fonts::bundled_fonts() {
7326        let url = unsafe {
7327            objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
7328        };
7329        let ok = unsafe {
7330            CTFontManagerRegisterFontsForURL(
7331                Retained::as_ptr(&url) as *const std::ffi::c_void,
7332                1,
7333                std::ptr::null_mut(),
7334            )
7335        };
7336        if !ok {
7337            log::warn!("could not register bundled font {}", path.display());
7338        }
7339    }
7340}
7341
7342/// `TextAlign` → AppKit. `Natural` rather than `Left` for the leading case: it follows the
7343/// writing direction, so an RTL locale aligns right without the app asking (docs/localization.md).
7344fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
7345    match a {
7346        day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
7347        day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
7348        day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
7349    }
7350}
7351
7352fn configure_label_cell(tf: &NSTextField) {
7353    if let Some(cell) = unsafe { tf.cell() } {
7354        unsafe {
7355            cell.setWraps(true);
7356            cell.setUsesSingleLineMode(false);
7357            cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
7358        }
7359    }
7360}
7361
7362/// If `parent` is a scroll view, children go into its (flipped) document view.
7363fn content_of(parent: &Handle) -> Retained<NSView> {
7364    if let Some(sv) = parent.downcast_ref::<NSScrollView>()
7365        && let Some(doc) = unsafe { sv.documentView() }
7366    {
7367        return doc;
7368    }
7369    parent.clone()
7370}
7371
7372/// Run `body` (which sets animatable properties on a layer-backed view) inside an
7373/// `NSAnimationContext` group so AppKit interpolates the change on the render server with the
7374/// curve's timing function, or immediately when `anim` is `None` (§8.4). `allowsImplicitAnimation`
7375/// makes direct property changes on layer-backed views animate. A spring maps to an overshooting
7376/// cubic-bezier timing function (a visible bounce without an explicit `CASpringAnimation`).
7377fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
7378    let Some(a) = anim else {
7379        body();
7380        return;
7381    };
7382    let (dur, timing) = appkit_timing(a);
7383    unsafe {
7384        NSAnimationContext::beginGrouping();
7385        let ctx = NSAnimationContext::currentContext();
7386        ctx.setDuration(dur);
7387        ctx.setTimingFunction(Some(&timing));
7388        ctx.setAllowsImplicitAnimation(true);
7389        body();
7390        NSAnimationContext::endGrouping();
7391    }
7392}
7393
7394/// The `(duration_secs, timing function)` for a curve. Springs render as an overshooting bezier
7395/// (control point y > 1) whose overshoot grows as damping falls, over a response-derived duration.
7396fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
7397    unsafe {
7398        let named = |n| {
7399            (
7400                a.duration_secs().max(0.01),
7401                CAMediaTimingFunction::functionWithName(n),
7402            )
7403        };
7404        match a.curve {
7405            Curve::Linear => named(kCAMediaTimingFunctionLinear),
7406            Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
7407            Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
7408            Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
7409            Curve::Spring { damping, .. } => {
7410                // Overshoot bezier over exactly the specified duration (authoritative timing).
7411                let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
7412                (
7413                    a.duration_secs().max(0.05),
7414                    CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
7415                )
7416            }
7417        }
7418    }
7419}
7420
7421/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
7422/// a visible placeholder. A missing renderer usually means the piece's `appkit` feature wasn't enabled
7423/// (Tier A.2 derives it automatically under `day build`; a bare `cargo` build may miss it). Deduped
7424/// per kind so a placeholder rendered every frame doesn't spam the log.
7425fn warn_missing_renderer(kind: PieceKind) {
7426    day_spec::placeholder::report(kind, "appkit");
7427}
7428
7429/// The visible-but-harmless placeholder label the unregistered-kind arm renders. Shared with
7430/// the [`props_of`] mismatch fallback, so a wrong props payload degrades to the same surface
7431/// (the warning is already reported by `props_of` itself).
7432pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
7433    view_of(unsafe {
7434        NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
7435    })
7436}
7437
7438impl Toolkit for AppKit {
7439    /// Settled unless a toolbar edit is still painting (toolbar.rs `CHROME_SETTLE`); AppKit's
7440    /// own transitions (sheets, nav pushes) complete within the turn that starts them.
7441    fn ui_idle(&mut self) -> bool {
7442        toolbar::chrome_settled()
7443    }
7444
7445    type Handle = Handle;
7446
7447    fn dark_mode(&mut self) -> bool {
7448        // The app's EFFECTIVE appearance — one source for the system setting, the DAY_THEME
7449        // launch force (applied as an NSApp override at startup), and a set_appearance call.
7450        let app = NSApplication::sharedApplication(self.mtm());
7451        app.effectiveAppearance()
7452            .name()
7453            .to_string()
7454            .contains("Dark")
7455    }
7456
7457    /// System Settings › Accessibility › Display › "Reduce motion", as NSWorkspace reports it
7458    /// (docs/accessibility.md). `install_reduce_motion_observer` re-reads it on a flip.
7459    fn reduce_motion(&mut self) -> bool {
7460        objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
7461    }
7462
7463    /// macOS is the one platform whose badge takes arbitrary text: `NSDockTile.badgeLabel` is a
7464    /// `String`, so `Text` renders literally and a count is just its decimal form. A nil label
7465    /// clears it (docs/badge.md).
7466    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
7467        use day_spec::AppBadge;
7468        let label = match badge {
7469            AppBadge::None => None,
7470            // Zero clears, matching the platform convention the doc states.
7471            AppBadge::Count(0) => None,
7472            AppBadge::Count(n) => Some(n.to_string()),
7473            AppBadge::Text(t) if t.is_empty() => None,
7474            AppBadge::Text(t) => Some(t.clone()),
7475            // No dedicated dot on the Dock; the smallest honest mark is a single bullet.
7476            AppBadge::Dot => Some("\u{2022}".to_string()),
7477        };
7478        let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
7479        let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
7480        unsafe { tile.setBadgeLabel(ns.as_deref()) };
7481        tile.display();
7482    }
7483
7484    fn set_appearance(&mut self, dark: Option<bool>) {
7485        let app = NSApplication::sharedApplication(self.mtm());
7486        let appearance = dark.and_then(|d| {
7487            objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
7488                if d {
7489                    objc2_app_kit::NSAppearanceNameDarkAqua
7490                } else {
7491                    objc2_app_kit::NSAppearanceNameAqua
7492                }
7493            })
7494        });
7495        // `None` clears the override — back to the system appearance.
7496        unsafe { app.setAppearance(appearance.as_deref()) };
7497    }
7498
7499    fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
7500        controls::refresh_gesture::attach(handle, host);
7501    }
7502
7503    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
7504        unsafe {
7505            handle.setHidden(!visible);
7506        }
7507    }
7508
7509    fn capability(&self, cap: Cap) -> Support {
7510        match cap {
7511            Cap::SearchField => Support::Native,
7512            Cap::ComboBox => Support::Native,
7513            Cap::Stepper => Support::Native,
7514            Cap::DateTimePicker => Support::Native,
7515            Cap::ColorPicker => Support::Native,
7516            Cap::PullRefresh => Support::Emulated,
7517            Cap::Pager => Support::Emulated,
7518            Cap::PullRefreshGesture => Support::Emulated,
7519            // A tracking-area owner sets an `NSCursor` per view (docs/cursor.md). Wait, progress,
7520            // help, and move take the arrow — AppKit draws no such shapes — and the zoom and
7521            // diagonal-resize cursors need macOS 15.
7522            Cap::Cursor => Support::Native,
7523            // `NSFontManager` enumerates every family and member (docs/fonts.md).
7524            Cap::FontList => Support::Native,
7525            // An image-and-text table cell's content (docs/list.md "List items").
7526            Cap::ListItem => Support::Native,
7527            // ImageIO behind `NSBitmapImageRep` reads every container macOS knows and writes
7528            // back PNG/JPEG/TIFF/BMP/GIF, and carries the container's own metadata dictionary
7529            // (docs/images.md).
7530            Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
7531            // Canvas export (docs/canvas.md "Exporting"): the canvas painter replayed into a
7532            // CGBitmapContext, or a CGPDFContext that keeps shapes and text vector.
7533            Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
7534            // The announcement-requested notification, posted from the primary window
7535            // (docs/accessibility.md).
7536            Cap::Announce => Support::Native,
7537            // `NSWorkspace.accessibilityDisplayShouldReduceMotion`, re-read when the workspace
7538            // posts its display-options change (docs/accessibility.md).
7539            Cap::ReduceMotion => Support::Native,
7540            Cap::Snapshot
7541            | Cap::NativeSymbols
7542            // The rows as chrome: `Rail` is the same source list pinned narrow, `Tabs` an
7543            // NSSegmentedControl docked below the pages. AppKit has no app-level tab bar —
7544            // NSTabView owns its own page content, the opposite of Day's model — so the bar
7545            // is composed from the control a Mac uses for a one-of-N switch this size.
7546            //
7547            // `Cap::NavTabsAdaptive` is deliberately NOT here: a Mac app may PIN a tab bar, but
7548            // a narrow Mac window hides its sidebar and pushes rather than growing one. It falls
7549            // through to the `Unsupported` arm below.
7550            | Cap::NavTabs
7551            | Cap::NavSplit
7552            // Both presentations are the same NSSplitViewController — a stack is that split with
7553            // its sidebar item collapsed — so re-presenting is a collapse plus one `addSubview`
7554            // that re-parents the sidebar page (docs/size-classes.md).
7555            | Cap::NavRepresent
7556            // A REAL `contentList` NSSplitViewItem between sidebar and detail; the pane
7557            // persists through every presentation (docs/navigation.md).
7558            | Cap::NavContentList
7559            | Cap::Dialogs
7560            | Cap::FileDialogs
7561            // NSOpenPanel with `canChooseDirectories` (docs/files.md).
7562            | Cap::FolderDialog
7563            | Cap::Animation
7564            // NSTextView natively honors all three text-area attributes.
7565            | Cap::TextEditable
7566            | Cap::TextSelectable
7567            | Cap::TextSpellCheck
7568            // NSTableView's own drag pipeline, with the `.gap` placeholder (docs/list.md), in
7569            // lists and in the source-list sidebar itself (docs/navigation.md).
7570            | Cap::NavReorder | Cap::ListReorder
7571            // NSTableView's view-based reuse queue (`makeViewWithIdentifier`) hands Day's cells
7572            // back for new rows; `didRemoveRowView` recycles them (docs/list.md).
7573            | Cap::ListRecycling
7574            // NSTableView row actions: reveal-as-you-swipe buttons with the native full-slide
7575            // activation (docs/list.md).
7576            | Cap::ListSwipeActions
7577            // NSTableView group rows with `floatsGroupRows` (docs/list.md "Sections").
7578            | Cap::ListSections
7579            // NSOutlineView hosts Day-built rows natively, drag-reparent included
7580            // (docs/tree.md).
7581            | Cap::Tree
7582            | Cap::TreeSections
7583            | Cap::TreeMove
7584            // Real NSWindows with native tabbing + the Windows menu (docs/windows.md).
7585            | Cap::MultiWindow
7586            // `miniaturize:` / `zoom:` / `toggleFullScreen:`, reported back through the window
7587            // delegate's notifications (docs/windows.md "Window properties").
7588            | Cap::WindowStates
7589            | Cap::WindowFullscreen
7590            // `NSWindowSharingNone`: captures, recordings and screen sharing see an empty window.
7591            | Cap::ContentProtection
7592            // Per-window `tabbingIdentifier` / `tabbingMode`, with the "+" opening the group's
7593            // own builder.
7594            | Cap::WindowTabbing
7595            // `applicationDockMenu:` on the app delegate (docs/menus.md).
7596            | Cap::DockMenu
7597            // Borderless windows that still take key, a transparent title bar over the
7598            // content, a clear window background, and `NSVisualEffectView` materials behind the
7599            // content (docs/window-chrome.md).
7600            | Cap::FramelessWindow
7601            | Cap::OverlayTitleBar
7602            | Cap::TransparentWindow
7603            | Cap::WindowMaterial
7604            // `performWindowDragWithEvent:` from a press on the region's own background.
7605            | Cap::DragRegion
7606            // `NSStatusItem`s in the menu bar, a progress bar drawn on the Dock tile, and the
7607            // accessory activation policy (docs/status-item.md).
7608            | Cap::StatusItem
7609            | Cap::AppProgress
7610            | Cap::DockVisibility
7611            // Frame, limits, level, Spaces, style-mask controls, per-window appearance, Dock
7612            // bounces, and `NSScreen` (docs/windows.md "Window properties").
7613            | Cap::WindowGeometry
7614            | Cap::WindowPosition
7615            | Cap::WindowLevel
7616            | Cap::WindowAppearance
7617            | Cap::RequestAttention
7618            | Cap::Monitors
7619            // Run-time shortcuts appear in the Dock menu beside the declared ones.
7620            | Cap::DynamicShortcuts
7621            // A real NSToolbar in the title bar (docs/toolbars.md).
7622            | Cap::Toolbar
7623            // The bar holds a native search field (docs/search.md).
7624            | Cap::ToolbarSearch
7625            | Cap::AppMenu
7626            // NSDockTile.badgeLabel is an arbitrary String, so all three payloads render — the
7627            // only backend where Text is real (docs/badge.md).
7628            | Cap::AppBadgeCount
7629            | Cap::AppBadgeText
7630            // NSUndoManager fronted by DayUndoManager: the stock Edit menu retitles and
7631            // enables itself, ⌘Z/⇧⌘Z land through the responder chain (docs/model.md).
7632            | Cap::UndoBridge
7633            | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
7634            | Cap::AppBadgeDot
7635            | Cap::Appearance
7636            // firstBaselineOffsetFromTop — the platform's own answer (docs/baseline.md).
7637            | Cap::BaselineAlignment
7638            // A REAL inspector NSSplitViewItem (`inspectorWithViewController:`): the system
7639            // trailing-pane material and full-height layout (docs/inspector.md).
7640            | Cap::Inspector
7641            // A plain NSSplitView with two arranged panes (docs/split.md).
7642            | Cap::Split
7643            | Cap::TextRuns
7644            | Cap::TextLinks => Support::Native,
7645            // A topmost autoresizing child of the content view — not a system modal
7646            // (docs/cover.md's ArkUI tier).
7647            Cap::Cover => Support::Emulated,
7648            // `.sheet()` is a window sheet on the primary window (docs/cover.md "Modal sheet").
7649            Cap::CoverSheet => Support::Native,
7650            _ => Support::Unsupported,
7651        }
7652    }
7653
7654    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
7655        let mtm = self.mtm;
7656        match Builtin::from_key(kind) {
7657            Some(Builtin::Container) => {
7658                let v = DayFlipped::new(mtm);
7659                if let Some(p) = props.downcast_ref::<ContainerProps>() {
7660                    if p.role == Some(day_spec::SurfaceRole::SectionCard) {
7661                        v.set_section_card(p.corner_radius);
7662                    } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
7663                        v.set_surface(p.background, p.corner_radius, p.clips);
7664                    }
7665                }
7666                view_of(v)
7667            }
7668            Some(Builtin::Scroll) => {
7669                let horizontal = props
7670                    .downcast_ref::<day_spec::props::ScrollProps>()
7671                    .map(|p| p.horizontal)
7672                    .unwrap_or(false);
7673                let sv = unsafe { NSScrollView::new(mtm) };
7674                unsafe {
7675                    sv.setHasVerticalScroller(!horizontal);
7676                    sv.setHasHorizontalScroller(horizontal);
7677                    sv.setDrawsBackground(false);
7678                    // Overlay scrollers ALWAYS: day lays content out at the scroll's full frame
7679                    // width, and a legacy scroller (the "always show scroll bars" system
7680                    // setting, or a mouse attached) would reserve ~15pt and clip trailing
7681                    // content. Overlay floats above content instead — and matches the GTK/Qt
7682                    // backends.
7683                    sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
7684                }
7685                let doc = DayFlipped::new(mtm);
7686                unsafe { sv.setDocumentView(Some(doc.as_ref())) };
7687                view_of(sv)
7688            }
7689            Some(Builtin::Label) => {
7690                // `props_of`, not a panicking downcast, for every typed-props arm: a mismatch
7691                // (a piece registered under a builtin key, or a day-core regression) warns once
7692                // per kind and degrades to the placeholder — realize runs inside native
7693                // up-calls, where a panic is a process kill.
7694                let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
7695                    return placeholder_view(mtm, kind);
7696                };
7697                let tf = DayLabel::new(mtm, id, &p.text);
7698                configure_label_cell(&tf);
7699                if !p.wraps || p.max_lines > 0 {
7700                    unsafe {
7701                        tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
7702                        if !p.wraps || p.max_lines == 1 {
7703                            tf.setUsesSingleLineMode(true);
7704                            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
7705                        }
7706                    }
7707                }
7708                unsafe { tf.setFont(Some(&nsfont(p.font))) };
7709                // The PLAIN path needs the role as much as the attributed one below: a label
7710                // with no runs never reaches `attributed_label`, and reading the role only there
7711                // left every ordinary `.secondary()` label rendering in the primary color.
7712                match (p.color, p.role) {
7713                    (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
7714                    (None, day_spec::props::TextRole::Secondary) => unsafe {
7715                        tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
7716                    },
7717                    (None, day_spec::props::TextRole::Primary) => {}
7718                }
7719                if !p.runs.is_empty() {
7720                    let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
7721                    unsafe { tf.setAttributedStringValue(&s) };
7722                }
7723                tf.ivars().has_runs.set(!p.runs.is_empty());
7724                tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
7725                // Alignment goes on last and, for a runs label, has to reach inside the
7726                // attributed string. `setAlignment:` writes the cell's paragraph style, which an
7727                // attributed string then overrides wholesale with its own — so a markdown label
7728                // set only through the cell comes out leading-aligned no matter what was asked.
7729                if p.align != day_spec::props::TextAlign::Leading {
7730                    unsafe { tf.setAlignment(nstextalign(p.align)) };
7731                    if !p.runs.is_empty() {
7732                        set_paragraph_alignment(&tf, nstextalign(p.align));
7733                    }
7734                }
7735                view_of(Retained::into_super(tf))
7736            }
7737            Some(Builtin::Button) => {
7738                let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
7739                    return placeholder_view(mtm, kind);
7740                };
7741                let target = DayTarget::new(mtm, id);
7742                let btn = unsafe {
7743                    NSButton::buttonWithTitle_target_action(
7744                        &NSString::from_str(&p.title),
7745                        Some(&*target),
7746                        Some(sel!(action:)),
7747                        mtm,
7748                    )
7749                };
7750                apply_button_style(&btn, p.style);
7751                if p.icon.is_some() {
7752                    apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
7753                }
7754                unsafe { btn.setEnabled(p.enabled) };
7755                set_button_selected(&btn, p.selected);
7756                let view = view_of(btn);
7757                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7758                view
7759            }
7760            Some(Builtin::Toggle) => {
7761                let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
7762                    return placeholder_view(mtm, kind);
7763                };
7764                let target = DayTarget::new(mtm, id);
7765                let sw = unsafe { NSSwitch::new(mtm) };
7766                unsafe {
7767                    sw.setState(if p.on { 1 } else { 0 });
7768                    sw.setEnabled(p.enabled);
7769                    sw.setTarget(Some(&*target));
7770                    sw.setAction(Some(sel!(action:)));
7771                }
7772                let view = view_of(sw);
7773                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7774                view
7775            }
7776            Some(Builtin::Slider) => {
7777                let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
7778                    return placeholder_view(mtm, kind);
7779                };
7780                let target = DayTarget::new(mtm, id);
7781                let sl = unsafe {
7782                    NSSlider::sliderWithValue_minValue_maxValue_target_action(
7783                        p.value,
7784                        p.min,
7785                        p.max,
7786                        Some(&*target),
7787                        Some(sel!(action:)),
7788                        mtm,
7789                    )
7790                };
7791                unsafe { sl.setContinuous(true) };
7792                let view = view_of(sl);
7793                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
7794                view
7795            }
7796            Some(Builtin::Picker) => picker::realize_any(self, props, id),
7797            Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
7798            Some(Builtin::TextField) => {
7799                let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
7800                    return placeholder_view(mtm, kind);
7801                };
7802                let tf = new_text_field(mtm, id, false);
7803                unsafe {
7804                    tf.setStringValue(&NSString::from_str(&p.text));
7805                    tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
7806                }
7807                view_of(tf)
7808            }
7809            Some(Builtin::Divider) => {
7810                let b = unsafe { NSBox::new(mtm) };
7811                unsafe { b.setBoxType(NSBoxType::Separator) };
7812                view_of(b)
7813            }
7814            Some(Builtin::Progress) => {
7815                let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
7816                    return placeholder_view(mtm, kind);
7817                };
7818                if p.value.is_none() {
7819                    return crate::controls::spinner::make(self, p, id);
7820                }
7821                let pi = unsafe { NSProgressIndicator::new(mtm) };
7822                unsafe {
7823                    match p.value {
7824                        Some(v) => {
7825                            pi.setStyle(NSProgressIndicatorStyle::Bar);
7826                            pi.setIndeterminate(false);
7827                            pi.setMinValue(0.0);
7828                            pi.setMaxValue(1.0);
7829                            pi.setDoubleValue(v);
7830                        }
7831                        None => {
7832                            pi.setStyle(NSProgressIndicatorStyle::Spinning);
7833                            pi.setIndeterminate(true);
7834                            pi.startAnimation(None);
7835                        }
7836                    }
7837                }
7838                view_of(pi)
7839            }
7840            Some(Builtin::Canvas) => {
7841                let canvas = DayCanvas::new(mtm);
7842                KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
7843                view_of(canvas)
7844            }
7845            Some(Builtin::Inspector) => {
7846                let (visible, width, leading) = props
7847                    .downcast_ref::<InspectorProps>()
7848                    .map(|p| {
7849                        (
7850                            p.visible,
7851                            p.width,
7852                            p.edge == day_spec::props::PaneEdge::Leading,
7853                        )
7854                    })
7855                    .unwrap_or((false, 280.0, false));
7856                let content_wrap = view_of(DayFlipped::new(mtm));
7857                let panel_flipped = DayFlipped::new(mtm);
7858                // The panel draws an opaque window-background backdrop over the item's
7859                // vibrancy material — without it the section cards' thin quaternary fill
7860                // composites into near-black in dark mode (see `FlippedIvars`).
7861                panel_flipped.set_pane_backdrop();
7862                let panel_wrap = view_of(panel_flipped);
7863                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
7864                // Force loadView before the items go in — the same lifecycle rule the nav
7865                // host below documents.
7866                let _ = unsafe { split_vc.view() };
7867                let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
7868                let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
7869                unsafe {
7870                    content_vc.setView(&content_wrap);
7871                    panel_vc.setView(&panel_wrap);
7872                }
7873                let content_item = unsafe {
7874                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
7875                };
7876                // A TRAILING pane is a real inspector item (the system treatment). A LEADING
7877                // one is a plain item placed first: `sidebarWithViewController:` would bring
7878                // sidebar material, which captures black offscreen (docs/navigation.md), and
7879                // the panel wrap already paints its own backdrop.
7880                let panel_item = unsafe {
7881                    if leading {
7882                        objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
7883                    } else {
7884                        objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
7885                    }
7886                };
7887                unsafe {
7888                    // Day's signal is the only visibility driver: with the pinned width the
7889                    // divider has nothing to drag and the pane cannot be user-collapsed, so
7890                    // there is no native-initiated change to report back.
7891                    panel_item.setCanCollapse(false);
7892                    panel_item.setCollapsed(!visible);
7893                    panel_item.setMinimumThickness(width);
7894                    panel_item.setMaximumThickness(width);
7895                    panel_item.setAllowsFullHeightLayout(true);
7896                    if leading {
7897                        split_vc.addSplitViewItem(&panel_item);
7898                        split_vc.addSplitViewItem(&content_item);
7899                    } else {
7900                        split_vc.addSplitViewItem(&content_item);
7901                        split_vc.addSplitViewItem(&panel_item);
7902                    }
7903                }
7904                let split = unsafe { split_vc.splitView() };
7905                unsafe {
7906                    split.setVertical(true);
7907                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
7908                    // The same Auto Layout hand-back as the nav host below: Day owns this
7909                    // view's frame outside the split; the controller's own constraints keep
7910                    // doing the pane sizing inside it.
7911                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
7912                }
7913                let view = view_of(split);
7914                INSPECTOR_STATE.with(|m| {
7915                    m.borrow_mut().insert(
7916                        ptr_of(&view),
7917                        InspectorState {
7918                            content_wrap,
7919                            panel_wrap,
7920                            _split_vc: split_vc,
7921                            panel_item,
7922                        },
7923                    )
7924                });
7925                view
7926            }
7927            Some(Builtin::InspectorPane) => {
7928                // A DayNavPage for its `setFrameSize:` → `FrameChanged` report: the pane's
7929                // frame is native-owned (the split sizes it), exactly like a nav page —
7930                // NAV_PAGES membership is what makes `set_frame` skip it.
7931                let pane = view_of(DayNavPage::new(mtm, id));
7932                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
7933                let panel = props
7934                    .downcast_ref::<InspectorPaneProps>()
7935                    .map(|p| p.panel)
7936                    .unwrap_or(false);
7937                INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
7938                pane
7939            }
7940            Some(Builtin::Split) => {
7941                let (axis, fraction, min_pane) = props
7942                    .downcast_ref::<SplitProps>()
7943                    .map(|p| (p.axis, p.fraction, p.min_pane))
7944                    .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
7945                let wrap = view_of(DayFlipped::new(mtm));
7946                let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
7947                let first_wrap = view_of(DayFlipped::new(mtm));
7948                let second_wrap = view_of(DayFlipped::new(mtm));
7949                unsafe {
7950                    // AppKit's "vertical" is the divider's orientation: panes side by side.
7951                    split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
7952                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
7953                    split.addArrangedSubview(&first_wrap);
7954                    split.addArrangedSubview(&second_wrap);
7955                    split.setFrame(wrap.bounds());
7956                    split.setAutoresizingMask(
7957                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
7958                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
7959                    );
7960                    wrap.addSubview(&split);
7961                }
7962                let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
7963                split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7964                SPLIT_STATE.with(|m| {
7965                    m.borrow_mut().insert(
7966                        ptr_of(&wrap),
7967                        SplitState {
7968                            split,
7969                            first_wrap,
7970                            second_wrap,
7971                            delegate,
7972                        },
7973                    )
7974                });
7975                wrap
7976            }
7977            Some(Builtin::SplitPane) => {
7978                // A DayNavPage, as an inspector pane: the splitter owns its frame, and its
7979                // `setFrameSize:` reports `FrameChanged`.
7980                let pane = view_of(DayNavPage::new(mtm, id));
7981                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
7982                let second = props
7983                    .downcast_ref::<SplitPaneProps>()
7984                    .map(|p| p.second)
7985                    .unwrap_or(false);
7986                SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
7987                pane
7988            }
7989            Some(Builtin::Nav) => {
7990                let presentation = props
7991                    .downcast_ref::<NavProps>()
7992                    .map(|p| p.presentation)
7993                    .unwrap_or(NavPresentation::Split);
7994                let is_split = presentation.is_split();
7995                // The host is an NSSplitViewController, not a bare NSSplitView. Handing the
7996                // sidebar pane to `NSSplitViewItem::sidebarWithViewController:` is what buys
7997                // the system treatment: AppKit installs its own backing material and vibrancy
7998                // (so no hand-rolled NSVisualEffectView), pins the thickness with a sidebar
7999                // holding priority, animates collapse/expand, and drives the window's titlebar
8000                // separator. Day still owns the CONTENT of each pane — the two wraps below are
8001                // the item view controllers' views, so `insert`/`remove`/the NAV patches are
8002                // unchanged.
8003                let sidebar_wrap = view_of(DayFlipped::new(mtm));
8004                let detail_wrap = view_of(DayFlipped::new(mtm));
8005                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8006                // Force loadView/viewDidLoad before the items go in. NSSplitViewController
8007                // installs an item's view into the split as the item is added, which it can
8008                // only do once its own view exists — and reading `splitView` does not trigger
8009                // the lifecycle the way reading `view` does. Skipping this leaves a split view
8010                // with zero subviews: correct frame, nothing in it.
8011                let _ = unsafe { split_vc.view() };
8012                // Plain NSViewControllers with their view set explicitly: setting `view` up
8013                // front is what stops NSViewController looking for a nib named after itself.
8014                let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8015                let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8016                unsafe {
8017                    sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8018                    detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8019                }
8020                let sidebar_item = unsafe {
8021                    objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8022                };
8023                let detail_item = unsafe {
8024                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8025                };
8026                // The content-list pane (docs/navigation.md): a REAL `contentList`
8027                // NSSplitViewItem between the sidebar and the detail — Mail's own machinery,
8028                // holding priorities included. Its `Pane::List` page fills `list_wrap` exactly
8029                // as the sidebar page fills its own wrap, and the pane persists through every
8030                // presentation (only `NavPatch::ListVisible` collapses it).
8031                let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8032                // Set before the item joins the split, exactly as the sidebar's is below. A
8033                // collapsed state applied afterwards — by `NavPatch::ListVisible`, on a window
8034                // that has not been displayed — reports as collapsed and is then laid back out
8035                // from the item's holding priorities, which is how an app whose first
8036                // destination has no list opened with one beside it anyway.
8037                let list_visible = props
8038                    .downcast_ref::<NavProps>()
8039                    .is_none_or(|p| p.list_visible);
8040                let (list_wrap, list_item) = match list_width {
8041                    Some(w) => {
8042                        let wrap = view_of(DayFlipped::new(mtm));
8043                        let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8044                        unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8045                        let item = unsafe {
8046                            objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8047                        };
8048                        unsafe {
8049                            item.setCanCollapse(true);
8050                            item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8051                            item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8052                            item.setCollapsed(!list_visible);
8053                        }
8054                        (Some(wrap), Some(item))
8055                    }
8056                    None => (None, None),
8057                };
8058                unsafe {
8059                    // A stack presentation has no sidebar to show: collapse the (empty) pane
8060                    // and refuse the drag, so the detail owns the full width.
8061                    sidebar_item.setCanCollapse(is_split);
8062                    sidebar_item.setCollapsed(!is_split);
8063                    if is_split {
8064                        // Run the sidebar's material to the top of the window, under the
8065                        // titlebar, the way Mail and Finder do. Pairs with the unified toolbar
8066                        // style the window already uses (toolbar.rs).
8067                        sidebar_item.setAllowsFullHeightLayout(true);
8068                        sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8069                        sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8070                    } else {
8071                        sidebar_item.setMinimumThickness(0.0);
8072                        sidebar_item.setMaximumThickness(0.0);
8073                    }
8074                    split_vc.addSplitViewItem(&sidebar_item);
8075                    if let Some(item) = list_item.as_ref() {
8076                        split_vc.addSplitViewItem(item);
8077                    }
8078                    split_vc.addSplitViewItem(&detail_item);
8079                }
8080                let split = unsafe { split_vc.splitView() };
8081                // NSToolbarToggleSidebarItem sends `toggleSidebar:` down the RESPONDER chain,
8082                // and NSSplitViewController implements it — but a view controller only patches
8083                // itself into that chain when it is parented (a window's contentViewController
8084                // or another controller's child), and Day's tree is view-based all the way to
8085                // the window. Insert it by hand, directly after the split view, so a first
8086                // responder anywhere inside either pane walks up through it.
8087                unsafe {
8088                    let after = split.nextResponder();
8089                    split.setNextResponder(Some(&split_vc));
8090                    // The controller must never end up aiming at itself or at its OWN view,
8091                    // or its dealloc aborts the process: `-[NSViewController dealloc]`
8092                    // splices itself out with `view.nextResponder = self.nextResponder`, and
8093                    // if that lands the view on itself AppKit raises "The next responder
8094                    // should never be yourself!" — an NSException that unwinds into Rust and
8095                    // aborts. Both shapes occur here naturally: before macOS 15 the freshly
8096                    // loaded split view's next IS the controller, and on 15+ `view` is a
8097                    // WRAPPER above `splitView` whose auto-wiring makes the split's next
8098                    // that wrapper. Neither is a real upstream hop, so drop them.
8099                    let own_view = split_vc.view();
8100                    let vc_resp: *const objc2_app_kit::NSResponder = {
8101                        let r: &objc2_app_kit::NSResponder = &split_vc;
8102                        r
8103                    };
8104                    let view_resp: *const objc2_app_kit::NSResponder = {
8105                        let r: &objc2_app_kit::NSResponder = &own_view;
8106                        r
8107                    };
8108                    let upstream = after.filter(|a| {
8109                        let p: *const objc2_app_kit::NSResponder = &**a;
8110                        p != vc_resp && p != view_resp
8111                    });
8112                    split_vc.setNextResponder(upstream.as_deref());
8113                }
8114                unsafe {
8115                    split.setVertical(true);
8116                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8117                    // Day owns this view's frame (`set_frame`). A split view vended by
8118                    // NSSplitViewController arrives switched over to Auto Layout, which
8119                    // ignores that frame and lays the split out at zero — a window with
8120                    // chrome and nothing under it. Hand it back to autoresizing translation
8121                    // so Day stays the layout owner outside the split; the constraints the
8122                    // controller installs BETWEEN the split and its panes are untouched and
8123                    // keep doing the pane sizing.
8124                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
8125                }
8126                let root_title = props
8127                    .downcast_ref::<NavProps>()
8128                    .map(|p| p.title.clone())
8129                    .unwrap_or_default();
8130                // Stack presentation: a back header (hidden at root) — desktop has no system
8131                // back affordance, so a pushed page needs its own way out (docs/navigation.md).
8132                let header = if presentation == NavPresentation::Stack {
8133                    Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
8134                } else {
8135                    None
8136                };
8137                // A tabs host: the Mac's own tab control fills the detail pane and takes the
8138                // detail pages as its items (`TabHost`).
8139                let tabs = (presentation == NavPresentation::Tabs).then(|| {
8140                    let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
8141                    // Inset from the pane, the way a tab view sits in any Mac window: its
8142                    // tabs stand above the bezel, so flush to the top they run into the
8143                    // toolbar's edge, and flush to the sides the bezel hugs the sidebar. The
8144                    // autoresizing mask keeps the margins as the pane resizes.
8145                    let b = detail_wrap.bounds();
8146                    let frame = NSRect::new(
8147                        NSPoint::new(NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP),
8148                        NSSize::new(
8149                            (b.size.width - 2.0 * NAV_TABVIEW_INSET).max(0.0),
8150                            (b.size.height - NAV_TABVIEW_INSET_TOP - NAV_TABVIEW_INSET).max(0.0),
8151                        ),
8152                    );
8153                    unsafe {
8154                        tv.setTabViewType(
8155                            if props
8156                                .downcast_ref::<NavProps>()
8157                                .is_some_and(|p| p.documents.is_some())
8158                            {
8159                                objc2_app_kit::NSTabViewType::NoTabsNoBorder
8160                            } else {
8161                                objc2_app_kit::NSTabViewType::TopTabsBezelBorder
8162                            },
8163                        );
8164                        tv.setFrame(frame);
8165                        tv.setAutoresizingMask(
8166                            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8167                                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8168                        );
8169                        detail_wrap.addSubview(&tv);
8170                    }
8171                    TabHost {
8172                        view: tv,
8173                        target: None,
8174                    }
8175                });
8176                let view = view_of(split);
8177                NAV_STATE.with(|m| {
8178                    m.borrow_mut().insert(
8179                        ptr_of(&view),
8180                        NavState {
8181                            sidebar_wrap,
8182                            detail_wrap,
8183                            _split_vc: split_vc,
8184                            sidebar_item,
8185                            list_wrap,
8186                            list_item,
8187                            pages: Vec::new(),
8188                            list_page: None,
8189                            sidebar_page: None,
8190                            list_width,
8191                            list_visible,
8192                            list_positioned: false,
8193                            positioned: false,
8194                            presentation,
8195                            selected: 0,
8196                            tabs,
8197                            header,
8198                            root_title,
8199                            node: id,
8200                            title_strip: 0.0,
8201                        },
8202                    )
8203                });
8204                view
8205            }
8206            Some(Builtin::NavPage) => {
8207                let page = view_of(DayNavPage::new(mtm, id));
8208                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
8209                if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
8210                    PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
8211                }
8212                page
8213            }
8214            // Emulated fullscreen cover (docs/cover.md, the ArkUI tier): a DayNavPage — its
8215            // setFrameSize: override reports FrameChanged, so a window resize re-lays the cover
8216            // content for free — parked hidden until CoverPatch::Present re-homes it on top.
8217            Some(Builtin::Cover) => {
8218                let page = DayNavPage::new(mtm, id);
8219                let cover_props = props.downcast_ref::<CoverProps>();
8220                // A half sheet is a sheet here: macOS has no half-height presentation of its
8221                // own, so the window sheet stands in, at half the parent's height.
8222                page.ivars()
8223                    .sheet
8224                    .set(cover_props.is_some_and(|p| p.sheet || p.half));
8225                page.ivars().half.set(cover_props.is_some_and(|p| p.half));
8226                unsafe { page.setHidden(true) };
8227                view_of(page)
8228            }
8229            Some(Builtin::NavMenu) => {
8230                let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
8231                    return placeholder_view(mtm, kind);
8232                };
8233                let data = DayNavMenuData::new(
8234                    mtm,
8235                    id,
8236                    &p.items,
8237                    &p.icons,
8238                    &p.badges,
8239                    &p.badge_icons,
8240                    &p.badge_tints,
8241                    &p.sections,
8242                    &p.tints,
8243                    &p.menus,
8244                );
8245                *data.ivars().movable.borrow_mut() = p.movable.clone();
8246                data.ivars().regroup.set(p.regroup);
8247                *data.ivars().sorted.borrow_mut() = p.sorted.clone();
8248                // The Day subclass serves per-row context menus via menuForEvent:.
8249                let outline: Retained<objc2_app_kit::NSOutlineView> = {
8250                    let o: Retained<DayNavOutlineView> =
8251                        unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
8252                    NAV_OUTLINE_MENUS
8253                        .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
8254                    unsafe { msg_send![&*o, self] }
8255                };
8256                let col = unsafe {
8257                    objc2_app_kit::NSTableColumn::initWithIdentifier(
8258                        objc2_app_kit::NSTableColumn::alloc(mtm),
8259                        &NSString::from_str("item"),
8260                    )
8261                };
8262                unsafe {
8263                    outline.addTableColumn(&col);
8264                    outline.setOutlineTableColumn(Some(&col));
8265                    outline.setHeaderView(None);
8266                    // SourceList: the real sidebar treatment (Finder/Mail). The outline now
8267                    // lives inside a sidebar NSSplitViewItem, so AppKit supplies the backing
8268                    // material and the vibrancy the source-list selection composites through.
8269                    // This was Inset until 2026-08 because the earlier hand-rolled
8270                    // NSVisualEffectView blended behind the window, and an offscreen capture
8271                    // (`cacheDisplayInRect`) has no backdrop to sample — the selection came out
8272                    // a black pill that swallowed the row label. The material is AppKit's own
8273                    // now, and captures go through the window server (`snapshot_view`), which
8274                    // composites the material for real instead of guessing at it.
8275                    // `style = SourceList` is the whole switch: the matching
8276                    // `selectionHighlightStyle` constant is deprecated precisely because the
8277                    // style property now implies it.
8278                    outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8279                    // The default row size style follows the system's Sidebar icon size
8280                    // (Small, Medium, Large), live, as Finder's and Mail's sidebars do: AppKit
8281                    // sets the row height, the label's font and the icon's size. A table made
8282                    // in code starts at Custom, which ignores the setting.
8283                    outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
8284                    // Section headers pin to the top of the scroll as their group passes under
8285                    // it, the way Finder's sidebar groups do.
8286                    outline.setFloatsGroupRows(true);
8287                    outline.setIndentationPerLevel(0.0);
8288                    // Drag-to-reorder within this sidebar only (docs/navigation.md): rows that
8289                    // cannot move offer no drag, so registering costs a plain sidebar nothing.
8290                    outline.registerForDraggedTypes(
8291                        &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8292                            DAY_NAV_PASTEBOARD_TYPE,
8293                        )]),
8294                    );
8295                    outline.setDraggingSourceOperationMask_forLocal(
8296                        objc2_app_kit::NSDragOperation::Move,
8297                        true,
8298                    );
8299                    outline.setDraggingSourceOperationMask_forLocal(
8300                        objc2_app_kit::NSDragOperation::None,
8301                        false,
8302                    );
8303                    outline.setDraggingDestinationFeedbackStyle(
8304                        objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8305                    );
8306                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8307                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8308                    outline.reloadData();
8309                }
8310                let scroll = unsafe { NSScrollView::new(mtm) };
8311                unsafe {
8312                    scroll.setDrawsBackground(false);
8313                    scroll.setHasVerticalScroller(true);
8314                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
8315                    // clip the trailing edge of rows laid out at the full frame width (see
8316                    // the SCROLL realize).
8317                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8318                    // One column, sized to the pane: a sidebar never scrolls sideways.
8319                    scroll.setHasHorizontalScroller(false);
8320                    outline.setAutoresizingMask(
8321                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8322                    );
8323                    outline.setColumnAutoresizingStyle(
8324                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8325                    );
8326                    scroll.setDocumentView(Some(&outline));
8327                }
8328                let view = view_of(scroll);
8329                // Day selects by ITEM index; section headers make that differ from the
8330                // outline's row index, so every programmatic selection maps through `rows`.
8331                if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
8332                    data.ivars().suppress.set(true);
8333                    unsafe {
8334                        outline.selectRowIndexes_byExtendingSelection(
8335                            &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8336                            false,
8337                        )
8338                    };
8339                    data.ivars().suppress.set(false);
8340                }
8341                NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8342                view
8343            }
8344            Some(Builtin::List) => {
8345                let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
8346                    return placeholder_view(mtm, kind);
8347                };
8348                // Every list reports responder changes, even without an activation handler.
8349                let table: Retained<DayListView> =
8350                    unsafe { msg_send![DayListView::alloc(mtm), init] };
8351                let table = Retained::into_super(table);
8352                let col = unsafe {
8353                    NSTableColumn::initWithIdentifier(
8354                        NSTableColumn::alloc(mtm),
8355                        &NSString::from_str("day.list.col"),
8356                    )
8357                };
8358                let data = DayListData::new(
8359                    mtm,
8360                    id,
8361                    p.selectable,
8362                    p.multi_select,
8363                    p.row_height == RowHeight::Automatic,
8364                    p.sections,
8365                );
8366                unsafe {
8367                    if p.multi_select {
8368                        table.setAllowsMultipleSelection(true);
8369                    }
8370                    table.addTableColumn(&col);
8371                    table.setHeaderView(None);
8372                    // PLAIN, the classic edge-to-edge style: the macOS 11+ decorated styles
8373                    // (automatic ~14pt, FullWidth ~6pt) inset every cell view, clipping day
8374                    // row content laid out at the host's full frame width. This table ran
8375                    // FullWidth with a custom NSTableRowView pinning cells back to the row
8376                    // bounds until 2026-08 — and that pin also clobbered the cell-frame slide
8377                    // AppKit performs for row-action swipes, so the actions revealed behind a
8378                    // row whose CONTENT never moved. Plain has no inset to fight: standard
8379                    // row views, standard cell frames, and the swipe slide works untouched.
8380                    table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
8381                    // ...and the default intercell spacing (3pt × 2pt) shaves the column the
8382                    // same way — the last few points of a trailing control. Day rows own all
8383                    // of their spacing.
8384                    table.setIntercellSpacing(NSSize::new(0.0, 0.0));
8385                    // Host-drawn row separators (docs/list.md): the native horizontal grid
8386                    // line, which sits exactly at the row boundary — aligned with the
8387                    // selection, stationary under a row-action swipe, the Mail look.
8388                    if p.separators == Some(true) {
8389                        table.setGridStyleMask(
8390                            objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
8391                        );
8392                        table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
8393                    }
8394                    table.setColumnAutoresizingStyle(
8395                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8396                    );
8397                    // Section headers pin to the top while their section scrolls under them,
8398                    // the way Mail's and Finder's group rows do (docs/list.md "Sections").
8399                    table.setFloatsGroupRows(p.sections);
8400                    match p.row_height {
8401                        RowHeight::Uniform(h) => table.setRowHeight(h),
8402                        RowHeight::Automatic => table.setRowHeight(44.0),
8403                    }
8404                    if !p.selectable {
8405                        table.setSelectionHighlightStyle(
8406                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8407                        );
8408                    }
8409                    // Transparent: day panes own their backgrounds — the stock
8410                    // controlBackgroundColor would paint an appearance-colored slab that
8411                    // fights a themed app (visible whenever rows don't fill the viewport).
8412                    table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8413                    table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8414                    table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8415                    table.setTarget(Some(&*data));
8416                    if p.activatable {
8417                        table.setDoubleAction(Some(sel!(doubleClickRow:)));
8418                    }
8419                    if p.reorderable {
8420                        // Native drag-to-reorder (docs/list.md): rows drag within this table
8421                        // only (move locally, nothing leaves the app), and the drop target shows
8422                        // macOS's temporary placeholder GAP while the drag is over the table.
8423                        table.registerForDraggedTypes(
8424                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8425                                DAY_ROW_PASTEBOARD_TYPE,
8426                            )]),
8427                        );
8428                        table.setDraggingSourceOperationMask_forLocal(
8429                            objc2_app_kit::NSDragOperation::Move,
8430                            true,
8431                        );
8432                        table.setDraggingSourceOperationMask_forLocal(
8433                            objc2_app_kit::NSDragOperation::None,
8434                            false,
8435                        );
8436                        table.setDraggingDestinationFeedbackStyle(
8437                            objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
8438                        );
8439                    }
8440                }
8441                let scroll = unsafe { NSScrollView::new(mtm) };
8442                unsafe {
8443                    scroll.setDrawsBackground(false);
8444                    scroll.setHasVerticalScroller(true);
8445                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
8446                    // clip the trailing edge of rows laid out at the full frame width (see
8447                    // the SCROLL realize).
8448                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8449                    scroll.setDocumentView(Some(&table));
8450                    let clip = scroll.contentView();
8451                    clip.setPostsBoundsChangedNotifications(true);
8452                    objc2_foundation::NSNotificationCenter::defaultCenter()
8453                        .addObserver_selector_name_object(
8454                            &data,
8455                            sel!(listViewportChanged:),
8456                            Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
8457                            Some(&clip),
8458                        );
8459                }
8460                let view = view_of(scroll);
8461                LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
8462                view
8463            }
8464            Some(Builtin::Tree) => {
8465                let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
8466                    return placeholder_view(mtm, kind);
8467                };
8468                // The width-pinning subclass (see DayOutlineView).
8469                let outline: Retained<objc2_app_kit::NSOutlineView> = {
8470                    let o: Retained<DayOutlineView> =
8471                        unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
8472                    unsafe { msg_send![&*o, self] }
8473                };
8474                let col = unsafe {
8475                    NSTableColumn::initWithIdentifier(
8476                        NSTableColumn::alloc(mtm),
8477                        &NSString::from_str("day.tree.col"),
8478                    )
8479                };
8480                let data = DayTreeData::new(mtm, id, p.selectable);
8481                unsafe {
8482                    if p.multi_select {
8483                        outline.setAllowsMultipleSelection(true);
8484                    }
8485                    outline.addTableColumn(&col);
8486                    outline.setOutlineTableColumn(Some(&col));
8487                    outline.setHeaderView(None);
8488                    if p.section_headers {
8489                        // Real source-list groups use AppKit's trailing, hover-revealed
8490                        // show/hide button and float over their children while scrolling.
8491                        outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
8492                        outline.setFloatsGroupRows(true);
8493                    } else {
8494                        // Generic trees keep their existing full-width cells and rounded
8495                        // DayTreeRowView selection. Source lists use native row drawing.
8496                        outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
8497                        outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
8498                    }
8499                    outline.setColumnAutoresizingStyle(
8500                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
8501                    );
8502                    outline.setAutoresizesOutlineColumn(true);
8503                    if let Some(indent) = p.indent {
8504                        outline.setIndentationPerLevel(indent);
8505                    }
8506                    match p.row_height {
8507                        RowHeight::Uniform(h) => outline.setRowHeight(h),
8508                        RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
8509                        RowHeight::Automatic => {}
8510                    }
8511                    if !p.selectable {
8512                        outline.setSelectionHighlightStyle(
8513                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
8514                        );
8515                    }
8516                    outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
8517                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
8518                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
8519                    if p.movable {
8520                        // Native drag-to-move (docs/tree.md): nodes drag within this outline
8521                        // only. The REGULAR feedback style (not the list's Gap): a tree drop
8522                        // must distinguish "between rows" (insertion line) from "ONTO a row"
8523                        // (the highlighted-parent drop), and Gap has no onto affordance.
8524                        outline.registerForDraggedTypes(
8525                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
8526                                DAY_TREE_PASTEBOARD_TYPE,
8527                            )]),
8528                        );
8529                        outline.setDraggingSourceOperationMask_forLocal(
8530                            objc2_app_kit::NSDragOperation::Move,
8531                            true,
8532                        );
8533                        outline.setDraggingSourceOperationMask_forLocal(
8534                            objc2_app_kit::NSDragOperation::None,
8535                            false,
8536                        );
8537                    }
8538                }
8539                let scroll = unsafe { NSScrollView::new(mtm) };
8540                unsafe {
8541                    scroll.setDrawsBackground(false);
8542                    scroll.setHasVerticalScroller(true);
8543                    scroll.setHasHorizontalScroller(false);
8544                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8545                    outline.setAutoresizingMask(
8546                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
8547                    );
8548                    scroll.setDocumentView(Some(&outline));
8549                }
8550                let view = view_of(scroll);
8551                TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
8552                view
8553            }
8554            Some(Builtin::Image) => {
8555                let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
8556                    return placeholder_view(mtm, kind);
8557                };
8558                let iv: Retained<objc2_app_kit::NSImageView> =
8559                    if p.content_mode == ContentMode::Fill {
8560                        let view: Retained<FillImageView> =
8561                            unsafe { msg_send![FillImageView::alloc(mtm), init] };
8562                        Retained::from(
8563                            <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
8564                        )
8565                    } else {
8566                        unsafe { objc2_app_kit::NSImageView::new(mtm) }
8567                    };
8568                // Fill expands the native aspect-fit drawing in FillImageView; Stretch
8569                // scales each axis independently, and Fit keeps the stock image view.
8570                let scaling = match p.content_mode {
8571                    ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
8572                    _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
8573                };
8574                unsafe { iv.setImageScaling(scaling) };
8575                if let Some(img) = appkit_image_for(&p.source) {
8576                    // Vector-glyph tint (docs/vectors.md): template rendering + the view's
8577                    // content tint — AppKit recolors the alpha mask natively. A template with
8578                    // no tint keeps the view's nil tint: the neutral template color the nav
8579                    // menu's own rows draw with, light in dark mode, dark in light.
8580                    if p.tint.is_some() || p.template {
8581                        unsafe { img.setTemplate(true) };
8582                    }
8583                    unsafe { iv.setImage(Some(&img)) };
8584                }
8585                if let Some(t) = p.tint {
8586                    unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
8587                }
8588                IMAGE_MODES.with(|t| {
8589                    t.insert(
8590                        ptr_of(&iv),
8591                        ImageMode {
8592                            template: p.template,
8593                            tinted: p.tint.is_some(),
8594                        },
8595                    )
8596                });
8597                view_of(iv)
8598            }
8599            Some(Builtin::ListItem) => {
8600                let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
8601                else {
8602                    return placeholder_view(mtm, kind);
8603                };
8604                make_list_item(p, mtm)
8605            }
8606            // A recycled list cell is ADOPTED from the native list, never realized
8607            // through this path; anything else is an extension piece.
8608            Some(Builtin::ListCell) | None => {
8609                if let Some(make) = self.registry.get(kind).map(|r| r.make) {
8610                    return make(self, props, id);
8611                }
8612                // Unregistered kind: LOUD once-per-kind warning, then a visible-but-harmless
8613                // placeholder (§8.2's debug check will panic first in debug builds once the
8614                // required-kinds set lands).
8615                warn_missing_renderer(kind);
8616                placeholder_view(mtm, kind)
8617            }
8618        }
8619    }
8620
8621    fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
8622        match kind {
8623            kinds::LIST_ITEM => {
8624                let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
8625                    return;
8626                };
8627                let props = LIST_ITEMS.with(|m| {
8628                    let mut m = m.borrow_mut();
8629                    let props = m.get_mut(&ptr_of(h))?;
8630                    use day_spec::props::ListItemPatch as P;
8631                    match p {
8632                        P::Title(t) => props.title = t.clone(),
8633                        P::Subtitle(t) => props.subtitle = t.clone(),
8634                        P::Detail(t) => props.detail = t.clone(),
8635                        P::Icon(i) => props.icon = i.clone(),
8636                        P::IconTint(c) => props.icon_tint = *c,
8637                        P::Checked(on) => props.checked = *on,
8638                    }
8639                    Some(props.clone())
8640                });
8641                if let Some(props) = props {
8642                    dress_list_item(h, &props, self.mtm());
8643                }
8644            }
8645            kinds::IMAGE => {
8646                if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
8647                    match p {
8648                        day_spec::props::ImagePatch::Tint(c) => {
8649                            // Template rendering + the view's content tint, exactly as at realize
8650                            // — the glyph repaints in place rather than being rebuilt
8651                            // (docs/vectors.md). A template glyph stays one when the tint goes.
8652                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8653                                let key = ptr_of(&iv);
8654                                let template = IMAGE_MODES
8655                                    .with(|t| {
8656                                        t.with(key, |m| {
8657                                            m.tinted = c.is_some();
8658                                            m.renders_template()
8659                                        })
8660                                    })
8661                                    .unwrap_or(c.is_some());
8662                                if let Some(img) = unsafe { iv.image() } {
8663                                    unsafe { img.setTemplate(template) };
8664                                }
8665                                unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
8666                            }
8667                        }
8668                        // A source swap repaints the same view (docs/images.md), so an `image()`
8669                        // bound to a signal shows new pixels without rebuilding its subtree —
8670                        // which is what makes a decode-then-show flow a patch and not a rebuild.
8671                        day_spec::props::ImagePatch::Source(source) => {
8672                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
8673                                // A source that will not load leaves the view showing what it
8674                                // was — the patch's contract, and what GTK, Qt and Android do.
8675                                // The new image renders the way the view does: a tinted or
8676                                // template glyph stays one, so a recycled sidebar row shows the
8677                                // icon it was rebound to in the same color.
8678                                if let Some(img) = appkit_image_for(source) {
8679                                    let template = IMAGE_MODES
8680                                        .with(|t| t.get(ptr_of(&iv)))
8681                                        .is_some_and(|m| m.renders_template());
8682                                    unsafe {
8683                                        img.setTemplate(template);
8684                                        iv.setImage(Some(&img));
8685                                    }
8686                                }
8687                            }
8688                        }
8689                    }
8690                }
8691            }
8692            kinds::CONTAINER => {
8693                if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
8694                    patch.downcast_ref::<ContainerPatch>(),
8695                    h.clone().downcast::<DayFlipped>(),
8696                ) {
8697                    // A background patch only targets a background container (corner radius 0).
8698                    // The AnimSpec is not honored: the fill is drawRect content
8699                    // (rasterized by our own drawing code so dynamic system colors re-resolve
8700                    // per appearance), not a CALayer property, and Core Animation only
8701                    // interpolates layer properties, so there is nothing for the render server
8702                    // to tween. Day animates only what the toolkit's animator can execute
8703                    // (§8.4), so an animated background change applies at commit here.
8704                    v.set_surface(*c, 0.0, false);
8705                }
8706            }
8707            kinds::LABEL => {
8708                if let (Some(p), Ok(tf)) = (
8709                    patch.downcast_ref::<LabelPatch>(),
8710                    h.clone().downcast::<NSTextField>(),
8711                ) {
8712                    match p {
8713                        LabelPatch::Text(t) => {
8714                            unsafe { tf.setStringValue(&NSString::from_str(t)) };
8715                            if let Some(label) = h.downcast_ref::<DayLabel>() {
8716                                label.ivars().has_runs.set(false);
8717                                label.set_links(false);
8718                            }
8719                        }
8720                        LabelPatch::Color(c) => unsafe {
8721                            tf.setTextColor(c.map(nscolor).as_deref())
8722                        },
8723                        LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
8724                        LabelPatch::Runs(text, runs) => {
8725                            // The field's current font is the base the runs sit on, taken as the
8726                            // live object rather than rebuilt from a `FontSpec`, which would lose
8727                            // the semantic style behind the resolved size.
8728                            let base = unsafe { tf.font() };
8729                            let s = match base.as_deref() {
8730                                Some(f) => {
8731                                    attributed_label(text, f, None, Default::default(), runs)
8732                                }
8733                                None => attributed_label(
8734                                    text,
8735                                    &nsfont(day_spec::FontSpec::default()),
8736                                    None,
8737                                    Default::default(),
8738                                    runs,
8739                                ),
8740                            };
8741                            unsafe { tf.setAttributedStringValue(&s) };
8742                            // Preserve paragraph alignment and activate links introduced by a
8743                            // reactive markdown update without replacing the native label.
8744                            set_paragraph_alignment(&tf, unsafe { tf.alignment() });
8745                            if let Some(label) = h.downcast_ref::<DayLabel>() {
8746                                label.ivars().has_runs.set(!runs.is_empty());
8747                                label.set_links(runs.iter().any(|r| r.link.is_some()));
8748                            }
8749                        }
8750                    }
8751                }
8752            }
8753            kinds::BUTTON => {
8754                if let (Some(p), Ok(btn)) = (
8755                    patch.downcast_ref::<ButtonPatch>(),
8756                    h.clone().downcast::<NSButton>(),
8757                ) {
8758                    match p {
8759                        ButtonPatch::Content(c) => {
8760                            apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
8761                        }
8762                        ButtonPatch::Title(t) => {
8763                            let style = BUTTON_STYLES
8764                                .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
8765                                .unwrap_or_default();
8766                            set_button_title(&btn, t, style);
8767                        }
8768                        ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
8769                        ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
8770                        ButtonPatch::Style(s) => apply_button_style(&btn, *s),
8771                    }
8772                }
8773            }
8774            kinds::TOGGLE => {
8775                if let (Some(p), Ok(sw)) = (
8776                    patch.downcast_ref::<TogglePatch>(),
8777                    h.clone().downcast::<NSSwitch>(),
8778                ) {
8779                    match p {
8780                        TogglePatch::On(on) => {
8781                            let want = if *on { 1 } else { 0 };
8782                            if unsafe { sw.state() } != want {
8783                                unsafe { sw.setState(want) };
8784                            }
8785                        }
8786                        TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
8787                    }
8788                }
8789            }
8790            kinds::SLIDER => {
8791                if let (Some(p), Ok(sl)) = (
8792                    patch.downcast_ref::<SliderPatch>(),
8793                    h.clone().downcast::<NSSlider>(),
8794                ) {
8795                    match p {
8796                        SliderPatch::Value(v) => {
8797                            if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
8798                                unsafe { sl.setDoubleValue(*v) };
8799                            }
8800                        }
8801                        SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
8802                    }
8803                }
8804            }
8805            kinds::PROGRESS => {
8806                if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
8807                {
8808                    crate::controls::spinner::update(self, h, p);
8809                    return;
8810                }
8811
8812                if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
8813                    patch.downcast_ref::<ProgressPatch>(),
8814                    h.clone().downcast::<NSProgressIndicator>(),
8815                ) {
8816                    unsafe {
8817                        match v {
8818                            Some(val) => {
8819                                if pi.isIndeterminate() {
8820                                    pi.stopAnimation(None);
8821                                    pi.setIndeterminate(false);
8822                                    pi.setStyle(NSProgressIndicatorStyle::Bar);
8823                                    pi.setMinValue(0.0);
8824                                    pi.setMaxValue(1.0);
8825                                }
8826                                if (pi.doubleValue() - val).abs() > 0.0001 {
8827                                    pi.setDoubleValue(*val);
8828                                }
8829                            }
8830                            None => {
8831                                pi.setIndeterminate(true);
8832                                pi.setStyle(NSProgressIndicatorStyle::Spinning);
8833                                pi.startAnimation(None);
8834                            }
8835                        }
8836                    }
8837                }
8838            }
8839            kinds::NAV_MENU => {
8840                if let Some(NavMenuPatch::Items {
8841                    items,
8842                    icons,
8843                    badges,
8844                    badge_icons,
8845                    badge_tints,
8846                    sections,
8847                    tints,
8848                    menus,
8849                    movable,
8850                    sorted,
8851                    selected,
8852                    rows_changed,
8853                    ..
8854                }) = patch.downcast_ref::<NavMenuPatch>()
8855                {
8856                    NAV_MENUS.with(|m| {
8857                        let m = m.borrow();
8858                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
8859                            return;
8860                        };
8861                        *data.ivars().movable.borrow_mut() = movable.clone();
8862                        *data.ivars().sorted.borrow_mut() = sorted.clone();
8863                        data.set_items(
8864                            items,
8865                            icons,
8866                            badges,
8867                            badge_icons,
8868                            badge_tints,
8869                            sections,
8870                            tints,
8871                            menus,
8872                        );
8873                        data.ivars().suppress.set(true);
8874                        // The same rows with new words or counts: reload just those rows, which
8875                        // keeps the selection and every other row's view.
8876                        if let Some(rows) = rows_changed {
8877                            let set = objc2_foundation::NSMutableIndexSet::new();
8878                            for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
8879                                unsafe { set.addIndex(row) };
8880                            }
8881                            unsafe {
8882                                outline.reloadDataForRowIndexes_columnIndexes(
8883                                    &set,
8884                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
8885                                )
8886                            };
8887                            data.ivars().suppress.set(false);
8888                            return;
8889                        }
8890                        unsafe {
8891                            outline.reloadData();
8892                            match selected.and_then(|i| data.row_of_item(i)) {
8893                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
8894                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8895                                    false,
8896                                ),
8897                                None => outline.deselectAll(None),
8898                            }
8899                        }
8900                        data.ivars().suppress.set(false);
8901                    });
8902                    // The rows are a tabs host's labels where the menu sits in one.
8903                    adopt_menu_for_tabs(self.mtm(), h);
8904                } else if let Some(NavMenuPatch::IconProgress(progress)) =
8905                    patch.downcast_ref::<NavMenuPatch>()
8906                {
8907                    NAV_MENUS.with(|menus| {
8908                        let menus = menus.borrow();
8909                        let Some((outline, data)) = menus.get(&ptr_of(h)) else {
8910                            return;
8911                        };
8912                        let previous = data.ivars().icon_progress.replace(progress.clone());
8913                        for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
8914                            let Some(index) = item else {
8915                                continue;
8916                            };
8917                            let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
8918                            if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
8919                                continue;
8920                            }
8921                            if let Some(view) = unsafe {
8922                                outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
8923                            } && let Some(cell) =
8924                                view.downcast_ref::<objc2_app_kit::NSTableCellView>()
8925                                && let Some(icon) = unsafe { cell.imageView() }
8926                            {
8927                                nav_progress::update(&icon, value);
8928                            }
8929                        }
8930                    });
8931                } else if let Some(NavMenuPatch::Selected(sel)) =
8932                    patch.downcast_ref::<NavMenuPatch>()
8933                {
8934                    NAV_MENUS.with(|m| {
8935                        let m = m.borrow();
8936                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
8937                            return;
8938                        };
8939                        data.ivars().suppress.set(true);
8940                        unsafe {
8941                            match sel.and_then(|i| data.row_of_item(i)) {
8942                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
8943                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
8944                                    false,
8945                                ),
8946                                None => outline.deselectAll(None),
8947                            }
8948                        }
8949                        data.ivars().suppress.set(false);
8950                    });
8951                }
8952            }
8953            kinds::INSPECTOR => {
8954                if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
8955                    INSPECTOR_STATE.with(|m| {
8956                        if let Some(state) = m.borrow().get(&ptr_of(h)) {
8957                            // Directly, not through the animator proxy: a screenshot must not
8958                            // catch a mid-animation pane (the sidebar-toggle rule).
8959                            state.panel_item.setCollapsed(!*v);
8960                        }
8961                    });
8962                }
8963            }
8964            kinds::SPLIT => {
8965                if let Some(p) = patch.downcast_ref::<SplitPatch>() {
8966                    SPLIT_STATE.with(|m| {
8967                        let m = m.borrow();
8968                        let Some(state) = m.get(&ptr_of(h)) else {
8969                            return;
8970                        };
8971                        let iv = state.delegate.ivars();
8972                        match p {
8973                            SplitPatch::Fraction(f) => {
8974                                iv.share.set(f.clamp(0.0, 1.0));
8975                                if iv.positioned.get() {
8976                                    split_place(&state.split, iv);
8977                                }
8978                            }
8979                            SplitPatch::Axis(axis) => unsafe {
8980                                state
8981                                    .split
8982                                    .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
8983                                state.split.adjustSubviews();
8984                                if iv.positioned.get() {
8985                                    split_place(&state.split, iv);
8986                                }
8987                            },
8988                        }
8989                    });
8990                }
8991            }
8992            kinds::NAV => {
8993                if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
8994                    nav_present(self.mtm(), h, *next);
8995                    return;
8996                }
8997                if let Some(p) = patch.downcast_ref::<NavPatch>() {
8998                    NAV_STATE.with(|m| {
8999                        let mut m = m.borrow_mut();
9000                        let Some(state) = m.get_mut(&ptr_of(h)) else {
9001                            return;
9002                        };
9003                        match p {
9004                            NavPatch::Pushed { title, .. } => {
9005                                // Only the new top detail page stays visible.
9006                                let last = state.pages.len().saturating_sub(1);
9007                                state.selected = last;
9008                                for (i, page) in state.pages.iter().enumerate() {
9009                                    page.setHidden(i != last);
9010                                }
9011                                if let Some(hdr) = state.header.as_mut() {
9012                                    hdr.titles.push(title.clone());
9013                                    sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9014                                }
9015                            }
9016                            NavPatch::Popped => {
9017                                // Hide the outgoing top; reveal its predecessor (Day
9018                                // removes the popped page right after this patch).
9019                                let n = state.pages.len();
9020                                if let Some(top) = state.pages.last() {
9021                                    top.setHidden(true);
9022                                }
9023                                if n >= 2 {
9024                                    state.pages[n - 2].setHidden(false);
9025                                }
9026                                state.selected = n.saturating_sub(2);
9027                                if let Some(hdr) = state.header.as_mut() {
9028                                    if hdr.titles.len() > 1 {
9029                                        hdr.titles.pop();
9030                                    }
9031                                    // The popped page is still in `pages` here (Day removes
9032                                    // it right after this patch), so frame for depth-after-pop.
9033                                    let after: Vec<Retained<NSView>> = state
9034                                        .pages
9035                                        .iter()
9036                                        .take(n.saturating_sub(1))
9037                                        .cloned()
9038                                        .collect();
9039                                    sync_nav_header(hdr, &state.detail_wrap, &after);
9040                                }
9041                            }
9042                            NavPatch::Title(t) => {
9043                                if let Some(hdr) = state.header.as_mut() {
9044                                    if let Some(last) = hdr.titles.last_mut() {
9045                                        *last = t.clone();
9046                                    }
9047                                    unsafe {
9048                                        hdr.title.setStringValue(&NSString::from_str(t));
9049                                    }
9050                                }
9051                            }
9052                            // The custom back header always routes back through Day
9053                            // (NavBack{already_popped:false}), so there is no native auto-pop to
9054                            // suppress; the guard runs in the pieces layer (docs/navigation.md).
9055                            NavPatch::GuardTop(_) => {}
9056                            NavPatch::Reorder(order) => {
9057                                let old = state.pages.clone();
9058                                state.pages =
9059                                    order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9060                                if let Some(tabs) = &state.tabs {
9061                                    TAB_PICK_SUPPRESS.with(|s| s.set(true));
9062                                    unsafe {
9063                                        let items = tabs.view.tabViewItems();
9064                                        for item in items.iter() {
9065                                            tabs.view.removeTabViewItem(&item);
9066                                        }
9067                                        for i in order {
9068                                            if let Some(item) = items.iter().nth(*i) {
9069                                                tabs.view.addTabViewItem(&item);
9070                                            }
9071                                        }
9072                                    }
9073                                    TAB_PICK_SUPPRESS.with(|s| s.set(false));
9074                                }
9075                            }
9076                            // Handled outside this borrow (it re-homes views and builds chrome).
9077                            NavPatch::Presentation(_) => {}
9078                            // Resident-page switch (docs/navigation.md): every page stays in the
9079                            // view hierarchy and only one is unhidden, so switching tabs keeps
9080                            // each page's scroll position and first responder exactly as left.
9081                            NavPatch::Select(i) => {
9082                                state.selected = *i;
9083                                match state.tabs.as_ref() {
9084                                    // The tab view shows exactly its selected item's page.
9085                                    Some(tabs) => {
9086                                        let n = unsafe { tabs.view.numberOfTabViewItems() };
9087                                        if (*i as isize) < n {
9088                                            TAB_PICK_SUPPRESS.with(|s| s.set(true));
9089                                            unsafe {
9090                                                tabs.view.selectTabViewItemAtIndex(*i as isize)
9091                                            };
9092                                            TAB_PICK_SUPPRESS.with(|s| s.set(false));
9093                                        }
9094                                    }
9095                                    None => {
9096                                        for (n, page) in state.pages.iter().enumerate() {
9097                                            page.setHidden(n != *i);
9098                                        }
9099                                    }
9100                                }
9101                            }
9102                            // Per-destination pane visibility (docs/navigation.md). Directly,
9103                            // not through the animator proxy: a screenshot must not catch a
9104                            // mid-animation pane (the sidebar-toggle rule), and settled now,
9105                            // like a re-present, so the detail's frame is right the instant
9106                            // the patch returns rather than one layout pass later.
9107                            NavPatch::ListVisible(v) => {
9108                                state.list_visible = *v;
9109                                if let Some(item) = state.list_item.as_ref() {
9110                                    item.setCollapsed(!*v);
9111                                    let split = unsafe { state._split_vc.splitView() };
9112                                    unsafe { split.layoutSubtreeIfNeeded() };
9113                                    // First time this pane is actually on screen: give it the
9114                                    // width the app asked for. The frame pass that would
9115                                    // otherwise do it has already run, back when there was no
9116                                    // pane to size.
9117                                    if let Some(w) = take_list_placement(state) {
9118                                        unsafe {
9119                                            split.setPosition_ofDividerAtIndex(
9120                                                day_spec::NAV_SIDEBAR_WIDTH + w,
9121                                                1,
9122                                            );
9123                                        }
9124                                    }
9125                                    // Re-frame the pane's page to the wrap it fills. A page
9126                                    // inserted while the pane was collapsed got a zero-width
9127                                    // frame, and `ViewWidthSizable` scales zero to zero however
9128                                    // wide the wrap becomes, so the list stayed invisible while
9129                                    // its rows were still there to click. An app opening on a
9130                                    // full-page section hits this on the first reveal.
9131                                    if *v
9132                                        && let Some(wrap) = state.list_wrap.as_ref()
9133                                        && let Some(page) = state.list_page.as_ref()
9134                                    {
9135                                        unsafe {
9136                                            wrap.layoutSubtreeIfNeeded();
9137                                            page.setFrame(wrap.bounds());
9138                                        }
9139                                    }
9140                                }
9141                            }
9142                            // Never arrives here: the pane persists through every presentation
9143                            // (`Cap::NavContentList` = Native), so the pieces layer never asks
9144                            // for the merged-stack shape.
9145                            NavPatch::ListInStack(_) => {}
9146                        }
9147                    });
9148                }
9149            }
9150            // Emulated cover (docs/cover.md): present = re-home onto the window's content view
9151            // at full bounds, topmost, autoresized with the window (the DayNavPage handle
9152            // reports FrameChanged on every resize). Dismiss = hide + report `CoverHidden`
9153            // immediately (no transition on this tier). Interactive dismissal doesn't exist on
9154            // this backend, so DismissDisabled has nothing to disable.
9155            kinds::COVER => {
9156                if let (Some(p), Ok(page)) = (
9157                    patch.downcast_ref::<CoverPatch>(),
9158                    h.clone().downcast::<DayNavPage>(),
9159                ) {
9160                    let node = page.ivars().node;
9161                    match p {
9162                        CoverPatch::Present { background, .. } => {
9163                            if page.ivars().sheet.get() {
9164                                if let Some(parent) =
9165                                    primary_content().and_then(|v| unsafe { v.window() })
9166                                {
9167                                    let bounds = parent.frame().size;
9168                                    let height = if page.ivars().half.get() {
9169                                        (bounds.height * 0.5).clamp(160.0, 620.0)
9170                                    } else {
9171                                        (bounds.height - 80.0).clamp(300.0, 620.0)
9172                                    };
9173                                    let size = NSSize::new(
9174                                        (bounds.width - 40.0).clamp(320.0, 640.0),
9175                                        height,
9176                                    );
9177                                    let window = unsafe {
9178                                        NSWindow::initWithContentRect_styleMask_backing_defer(
9179                                            NSWindow::alloc(MainThreadMarker::new().unwrap()),
9180                                            NSRect::new(NSPoint::new(0.0, 0.0), size),
9181                                            NSWindowStyleMask::Titled,
9182                                            NSBackingStoreType::Buffered,
9183                                            false,
9184                                        )
9185                                    };
9186                                    unsafe {
9187                                        window.setReleasedWhenClosed(false);
9188                                        page.removeFromSuperview();
9189                                        page.setHidden(false);
9190                                        page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
9191                                        window.setContentView(Some(&page));
9192                                    }
9193                                    let key = ptr_of(h);
9194                                    COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
9195                                    dispatch2::DispatchQueue::main().exec_async(move || {
9196                                        ffi_guard::contain((), || {
9197                                            let window =
9198                                                COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
9199                                            if let (Some(window), Some(parent)) = (
9200                                                window,
9201                                                primary_content()
9202                                                    .and_then(|v| unsafe { v.window() }),
9203                                            ) {
9204                                                unsafe {
9205                                                    parent.beginSheet_completionHandler(
9206                                                        &window, None,
9207                                                    );
9208                                                }
9209                                            }
9210                                        });
9211                                    });
9212                                    emit(
9213                                        node,
9214                                        Event::FrameChanged(Size::new(size.width, size.height)),
9215                                    );
9216                                }
9217                                return;
9218                            }
9219                            // A cover must occlude the window (the native tiers' modal surfaces
9220                            // are opaque): default to the window background when the app sets
9221                            // no explicit color.
9222                            unsafe {
9223                                page.setWantsLayer(true);
9224                                if let Some(layer) = page.layer() {
9225                                    let color = match background {
9226                                        Some(bg) => nscolor(*bg),
9227                                        None => NSColor::windowBackgroundColor(),
9228                                    };
9229                                    layer.setBackgroundColor(Some(&color.CGColor()));
9230                                }
9231                            }
9232                            // The primary window's content, specifically: firstObject()
9233                            // is arbitrary once secondary windows exist (docs/windows.md).
9234                            if let Some(content) = primary_content() {
9235                                if let Some(window) = unsafe { content.window() } {
9236                                    toolbar::cover_presented(ptr_of(h), &window);
9237                                }
9238                                // Edge to edge like the root's own background, laid out below
9239                                // the title bar like the root's content: the page starts at the
9240                                // top of the window (above the pinned content origin) and
9241                                // keeps the same strip above its own layout origin.
9242                                let top = title_bar_inset(&content);
9243                                let full = content.frame().size;
9244                                page.ivars().top_inset.set(top);
9245                                unsafe {
9246                                    page.removeFromSuperview();
9247                                    content.addSubview(&page);
9248                                    page.setFrame(NSRect::new(
9249                                        NSPoint::new(0.0, -top),
9250                                        NSSize::new(full.width, full.height),
9251                                    ));
9252                                    page.setBoundsOrigin(NSPoint::new(0.0, -top));
9253                                    page.setAutoresizingMask(
9254                                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9255                                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9256                                    );
9257                                    page.setHidden(false);
9258                                }
9259                                emit(
9260                                    node,
9261                                    Event::FrameChanged(Size::new(
9262                                        full.width,
9263                                        (full.height - top).max(0.0),
9264                                    )),
9265                                );
9266                            }
9267                        }
9268                        CoverPatch::DismissDisabled(_) => {}
9269                        CoverPatch::Dismiss => {
9270                            COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
9271                            toolbar::cover_dismissed(ptr_of(h));
9272                            unsafe {
9273                                page.setHidden(true);
9274                                page.removeFromSuperview();
9275                            }
9276                            emit(node, Event::CoverHidden);
9277                        }
9278                    }
9279                }
9280            }
9281            kinds::PICKER => picker::update_any(self, h, patch),
9282            kinds::TEXT_AREA => textarea::update_any(self, h, patch),
9283            kinds::TEXT_FIELD => {
9284                if let (Some(p), Ok(tf)) = (
9285                    patch.downcast_ref::<TextFieldPatch>(),
9286                    h.clone().downcast::<NSTextField>(),
9287                ) {
9288                    match p {
9289                        TextFieldPatch::Text { text, from_native } => {
9290                            // Origin-tagged echo suppression (§4.4).
9291                            if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
9292                                unsafe { tf.setStringValue(&NSString::from_str(text)) };
9293                            }
9294                        }
9295                        TextFieldPatch::Placeholder(t) => unsafe {
9296                            tf.setPlaceholderString(Some(&NSString::from_str(t)))
9297                        },
9298                        TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
9299                    }
9300                }
9301            }
9302            kinds::LIST => match patch.downcast_ref::<ListPatch>() {
9303                Some(ListPatch::Splice(deltas)) => {
9304                    // The set changed by exactly these deltas: animate each row in, out, or
9305                    // across, the thing a reload cannot express. Indexes are sequential, so
9306                    // each delta gets its own begin/endUpdates batch (NSTableView's combined
9307                    // batch semantics re-interpret indexes; one-at-a-time stays literal).
9308                    // Row realization stays deferred, as with Reload.
9309                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9310                        use objc2_app_kit::NSTableViewAnimationOptions;
9311                        for d in deltas {
9312                            unsafe {
9313                                table.beginUpdates();
9314                                match d {
9315                                    day_spec::props::RowDelta::Insert(i) => table
9316                                        .insertRowsAtIndexes_withAnimation(
9317                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9318                                            NSTableViewAnimationOptions::SlideDown,
9319                                        ),
9320                                    day_spec::props::RowDelta::Remove(i) => table
9321                                        .removeRowsAtIndexes_withAnimation(
9322                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
9323                                            NSTableViewAnimationOptions::SlideUp,
9324                                        ),
9325                                    day_spec::props::RowDelta::Move(from, to) => {
9326                                        table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
9327                                    }
9328                                }
9329                                table.endUpdates();
9330                            }
9331                        }
9332                        // The displayed order matches the source again: refresh the cache a
9333                        // committed drag keeps in step and `permutation_moves` compares, or the
9334                        // next Reload finds a stale length and reloads flat instead of animating.
9335                        if let Some(source) = data.ivars().source.borrow().as_ref() {
9336                            let n = (source.len)();
9337                            *data.ivars().tokens.borrow_mut() =
9338                                (0..n).map(|i| (source.token_at)(i)).collect();
9339                        }
9340                    }
9341                    post_realize_visible_rows(ptr_of(h));
9342                }
9343                Some(ListPatch::Reload) => {
9344                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9345                        // NSTableView reloadData clears selection for this view-based source.
9346                        // Preserve identities, not indexes, across refreshes/reorders; removed
9347                        // items disappear from the selection without selecting their successor.
9348                        let selected = unsafe { table.selectedRowIndexes() };
9349                        let tokens: Vec<u64> = data
9350                            .ivars()
9351                            .tokens
9352                            .borrow()
9353                            .iter()
9354                            .enumerate()
9355                            .filter(|(row, _)| selected.containsIndex(*row))
9356                            .map(|(_, token)| *token)
9357                            .collect();
9358                        data.ivars().suppress.set(true);
9359                        // A reload whose rows are the same set in a new order (a shuffle,
9360                        // a programmatic sort) animates as native row moves instead of a
9361                        // blink: a `moveRowAtIndex` batch, the same animation a drag commit
9362                        // gets. Anything else (insert/remove/content change) reloads flat.
9363                        // reloadData queries numberOfRows synchronously (snapshot only, no
9364                        // tree) and defers viewForRow, so both paths are safe in with_tree.
9365                        if let Some(moves) = data.permutation_moves(&table) {
9366                            unsafe {
9367                                table.beginUpdates();
9368                                for (from, to) in moves {
9369                                    table.moveRowAtIndex_toIndex(from as isize, to as isize);
9370                                }
9371                                table.endUpdates();
9372                            }
9373                        } else {
9374                            unsafe { table.reloadData() };
9375                        }
9376                        let restored = objc2_foundation::NSMutableIndexSet::new();
9377                        for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
9378                            if tokens.contains(token) {
9379                                restored.addIndex(row);
9380                            }
9381                        }
9382                        unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
9383                        data.ivars().suppress.set(false);
9384                    }
9385                    // Realize the visible rows on the next main-loop turn, outside this borrow.
9386                    // An occluded window (locked screen, covered, headless CI) gets no normal
9387                    // draw pass; NSTableView would first realize these rows inside a snapshot's
9388                    // `cacheDisplayInRect`, where `bind_row` must skip the held borrow and the
9389                    // table would cache permanently blank cells.
9390                    post_realize_visible_rows(ptr_of(h));
9391                }
9392                Some(ListPatch::ScrollToRow(row)) => {
9393                    // Same deferral discipline as ScrollToEnd: the scroll tiles target rows
9394                    // synchronously, which must happen outside this `with_tree` borrow.
9395                    let (key, row) = (ptr_of(h), *row);
9396                    <AppKit as Platform>::post(Box::new(move || {
9397                        if let Some((table, _)) = list_entry(key) {
9398                            let rows = unsafe { table.numberOfRows() };
9399                            if rows > 0 {
9400                                unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
9401                            }
9402                        }
9403                    }));
9404                    post_realize_visible_rows(ptr_of(h));
9405                }
9406                Some(ListPatch::ScrollToEnd) => {
9407                    // Deferred to the next main-loop turn: an actual scroll forces NSTableView
9408                    // to tile (realize) the target rows synchronously, and this patch arrives
9409                    // inside a `with_tree` borrow where `bind_row` must skip; the table would
9410                    // cache blank cells for every newly exposed row (see Reload above).
9411                    let key = ptr_of(h);
9412                    <AppKit as Platform>::post(Box::new(move || {
9413                        if let Some((table, _)) = list_entry(key) {
9414                            let rows = unsafe { table.numberOfRows() };
9415                            if rows > 0 {
9416                                unsafe { table.scrollRowToVisible(rows - 1) };
9417                            }
9418                        }
9419                    }));
9420                    // ...and realize whatever the scroll exposed, still outside the borrow.
9421                    post_realize_visible_rows(ptr_of(h));
9422                }
9423                Some(ListPatch::Selected(rows)) => {
9424                    // Programmatic selection sync (empty = clear), suppressed so the
9425                    // delegate does not echo it back as a selection event.
9426                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9427                        data.ivars().suppress.set(true);
9428                        unsafe {
9429                            if rows.is_empty() {
9430                                table.deselectAll(None);
9431                            } else {
9432                                let set = objc2_foundation::NSMutableIndexSet::new();
9433                                let count = table.numberOfRows().max(0) as usize;
9434                                for r in rows.iter().copied().filter(|r| *r < count) {
9435                                    set.addIndex(r);
9436                                }
9437                                table.selectRowIndexes_byExtendingSelection(&set, false);
9438                            }
9439                        }
9440                        data.ivars().suppress.set(false);
9441                    }
9442                }
9443                Some(ListPatch::RowSizeInvalidated { cell, height }) => {
9444                    if let Some((table, data)) = list_entry(ptr_of(h)) {
9445                        data.row_resized(&table, *cell, *height);
9446                    }
9447                }
9448                // `None` = a patch for another kind's enum. A desktop table has no editing mode
9449                // (Cap::ListEditing is Unsupported).
9450                Some(ListPatch::Editing(_)) | None => {}
9451            },
9452            kinds::TREE => match patch.downcast_ref::<TreePatch>() {
9453                Some(TreePatch::Reload) => {
9454                    // Interned items keep their identity across reloadData, so NSOutlineView
9455                    // itself preserves expansion; the piece re-asserts it (and the selection)
9456                    // by token right after, belt and braces. reloadData queries the child
9457                    // counts synchronously (snapshot only, no tree) and defers viewForItem.
9458                    if let Some((outline, _)) = tree_entry(ptr_of(h)) {
9459                        unsafe { outline.reloadData() };
9460                    }
9461                    post_realize_visible_tree_rows(ptr_of(h));
9462                }
9463                Some(TreePatch::Expand(token, on)) => {
9464                    // Deferred: expandItem/collapseItem realize (or remove) the disclosed
9465                    // rows synchronously, and this patch arrives inside a `with_tree` borrow
9466                    // where `bind_row` must skip; the outline would cache permanently blank,
9467                    // id-less rows (the ScrollToEnd rule, one arm over).
9468                    let (key, token, on) = (ptr_of(h), *token, *on);
9469                    <AppKit as Platform>::post(Box::new(move || {
9470                        if let Some((outline, data)) = tree_entry(key) {
9471                            let item = data.intern(token);
9472                            // Suppressed: a programmatic disclosure must not echo back as
9473                            // `Event::TreeExpanded`. Redundant applications are AppKit no-ops.
9474                            data.ivars().suppress.set(true);
9475                            unsafe {
9476                                if on {
9477                                    outline.expandItem(Some(&item));
9478                                } else {
9479                                    outline.collapseItem(Some(&item));
9480                                }
9481                            }
9482                            data.ivars().suppress.set(false);
9483                        }
9484                        day_core::pump_events();
9485                    }));
9486                    post_realize_visible_tree_rows(ptr_of(h));
9487                }
9488                Some(TreePatch::Selected(tokens)) => {
9489                    if let Some((outline, data)) = tree_entry(ptr_of(h)) {
9490                        data.ivars().suppress.set(true);
9491                        unsafe {
9492                            if tokens.is_empty() {
9493                                outline.deselectAll(None);
9494                            } else {
9495                                let set = objc2_foundation::NSMutableIndexSet::new();
9496                                for t in tokens {
9497                                    // A token under a collapsed ancestor has no row, so it is
9498                                    // skipped; the piece re-applies after expansion changes.
9499                                    let row = outline.rowForItem(Some(&data.intern(*t)));
9500                                    if row >= 0 {
9501                                        set.addIndex(row as usize);
9502                                    }
9503                                }
9504                                outline.selectRowIndexes_byExtendingSelection(&set, false);
9505                            }
9506                        }
9507                        data.ivars().suppress.set(false);
9508                    }
9509                }
9510                Some(TreePatch::Reveal(token)) => {
9511                    // Deferred: the scroll tiles target rows synchronously, which must
9512                    // happen outside this `with_tree` borrow (the ScrollToRow rule).
9513                    let (key, token) = (ptr_of(h), *token);
9514                    <AppKit as Platform>::post(Box::new(move || {
9515                        if let Some((outline, data)) = tree_entry(key) {
9516                            let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
9517                            if row >= 0 {
9518                                unsafe { outline.scrollRowToVisible(row) };
9519                            }
9520                        }
9521                    }));
9522                    post_realize_visible_tree_rows(ptr_of(h));
9523                }
9524                None => {}
9525            },
9526            _ => {
9527                if let Some(update) = self.registry.get(kind).map(|r| r.update) {
9528                    update(self, h, patch);
9529                }
9530            }
9531        }
9532    }
9533
9534    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
9535    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
9536        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
9537        // the hook needs it mutably.
9538        let f = self.registry.get(kind).and_then(|r| r.release);
9539        if let Some(f) = f {
9540            f(self, h);
9541        }
9542    }
9543    fn release(&mut self, h: Handle) {
9544        LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
9545        // A released window content = that window is gone (docs/windows.md teardown):
9546        // drop the SecondaryWin (closing a straggler NSWindow) and its delegate with it.
9547        // (A re-fired windowWillClose emits to a torn-down node: dropped, harmless.)
9548        self.secondary.retain(|w| {
9549            if ptr_of(&w.content) == ptr_of(&h) {
9550                w.window.close();
9551                // The window's keyed state goes with it: its toolbar (toolbar.rs BARS,
9552                // keyed by the window pointer) used to survive a secondary close, and its
9553                // items, targets, retained NSToolbar and delegate all leaked.
9554                day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
9555                false
9556            } else {
9557                true
9558            }
9559        });
9560        TARGETS.with(|m| {
9561            m.borrow_mut().remove(&ptr_of(&h));
9562        });
9563        LIST_STATE.with(|m| {
9564            m.borrow_mut().remove(&ptr_of(&h));
9565        });
9566        TREE_STATE.with(|m| {
9567            m.borrow_mut().remove(&ptr_of(&h));
9568        });
9569        GESTURES.with(|m| {
9570            m.borrow_mut().remove(&ptr_of(&h));
9571        });
9572        NAV_STATE.with(|m| {
9573            if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
9574                // Unhook the split view controller from the responder chain before the drop
9575                // deallocs it. AppKit rewires these pointers behind day's back (mounting the
9576                // split resets its next to the superview; the controller's own view keeps
9577                // aiming at the controller), and a controller whose next responder is its own
9578                // view dies in dealloc's chain splice with the "next responder should never
9579                // be yourself" NSException, foreign to Rust, so it aborts the process
9580                // instead of unwinding (the Stack-page teardown crash, 2026-08).
9581                unsafe {
9582                    nav._split_vc.setNextResponder(None);
9583                    let split = nav._split_vc.splitView();
9584                    if split.nextResponder().is_some_and(|r| {
9585                        core::ptr::eq::<objc2::runtime::AnyObject>(
9586                            r.as_ref(),
9587                            nav._split_vc.as_ref(),
9588                        )
9589                    }) {
9590                        split.setNextResponder(None);
9591                    }
9592                }
9593            }
9594        });
9595        NAV_PAGES.with(|set| {
9596            set.borrow_mut().remove(&ptr_of(&h));
9597        });
9598        SPLIT_STATE.with(|m| {
9599            if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
9600                state.split.setDelegate(None);
9601            }
9602        });
9603        INSPECTOR_STATE.with(|m| {
9604            if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
9605                // The same dealloc-splice guard as the nav host above: never let the
9606                // controller (or its split) dealloc aiming at itself.
9607                unsafe {
9608                    insp._split_vc.setNextResponder(None);
9609                    let split = insp._split_vc.splitView();
9610                    if split.nextResponder().is_some_and(|r| {
9611                        core::ptr::eq::<objc2::runtime::AnyObject>(
9612                            r.as_ref(),
9613                            insp._split_vc.as_ref(),
9614                        )
9615                    }) {
9616                        split.setNextResponder(None);
9617                    }
9618                }
9619            }
9620        });
9621        NAV_MENUS.with(|m| {
9622            if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
9623                // The outline registers under its pointer (`menuForEvent:` resolves by
9624                // outline, not by this scroll handle): sweep that auxiliary key too, so
9625                // NAV_OUTLINE_MENUS, and any future outline-keyed table, drops it. A
9626                // surviving entry served the dead menu's rows once the address was recycled.
9627                day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
9628            }
9629        });
9630        // One call reclaims this handle's entry from every SideTable on this thread (canvas
9631        // OPS, PAGE_PANE, the picker/textarea state, and whatever lands later), running each
9632        // table's teardown hook (day-spec sidetable). The explicit removals above are the
9633        // older per-map checklist; new per-view maps should be SideTables so this sweep covers
9634        // them without another line here.
9635        day_spec::sidetable::sweep(ptr_of(&h));
9636        unsafe { h.removeFromSuperview() };
9637    }
9638
9639    fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
9640        // A nav menu that has just gained ancestors: if one of them is a tabs host, its rows
9641        // Are that host's tab labels (`adopt_menu_for_tabs`). The menu is built after its rows
9642        // page joined the host, so this is the first moment the host can see its rows.
9643        if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
9644            unsafe { content_of(parent).addSubview(child) };
9645            adopt_menu_for_tabs(self.mtm(), child);
9646            return;
9647        }
9648        // Nav host: pages land by their pane, not their position (docs/size-classes.md). Pages
9649        // fill their pane via autoresizing; the pane, not Day, owns their frames.
9650        let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
9651        let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
9652        let handled = NAV_STATE.with(|m| {
9653            let mut m = m.borrow_mut();
9654            let Some(state) = m.get_mut(&ptr_of(parent)) else {
9655                return false;
9656            };
9657            // The content-list page fills its pane at every presentation
9658            // (docs/navigation.md), never a member of the detail stack.
9659            if page_pane == Some(day_spec::props::Pane::List)
9660                && let Some(wrap) = state.list_wrap.as_ref()
9661            {
9662                state.list_page = Some(child.clone());
9663                unsafe {
9664                    child.setFrame(wrap.bounds());
9665                    child.setAutoresizingMask(
9666                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9667                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9668                    );
9669                    wrap.addSubview(child);
9670                }
9671                return true;
9672            }
9673            if is_sidebar_page {
9674                state.sidebar_page = Some(child.clone());
9675            }
9676            // Split (nav host Sidebar): the sidebar pane's page goes in the sidebar; the rest are
9677            // detail pages. Stack: every page, including the sidebar's, which is the stack's
9678            // root, lives in the detail pane so push/pop visibility covers them all.
9679            // The rows page goes to the sidebar pane in every presentation but `Stack`, where
9680            // it is the stack root and joins the detail pages instead.
9681            let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
9682            // A tabs host's detail page becomes an item of its tab view, which frames it (the
9683            // page's `setFrameSize:` reports the size to Day). Its label comes with the
9684            // menu's rows: already here when a page joins a live host, otherwise when the
9685            // menu is inserted (`adopt_menu_for_tabs`).
9686            if !to_pane && let Some(tabs) = state.tabs.as_ref() {
9687                state.pages.push(child.clone());
9688                let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
9689                unsafe {
9690                    child.setAutoresizingMask(
9691                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9692                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9693                    );
9694                    item.setView(Some(child));
9695                    tabs.view.addTabViewItem(&item);
9696                }
9697                if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
9698                    sync_tab_labels(tabs, &titles, state.selected);
9699                }
9700                return true;
9701            }
9702            let (wrap, frame) = if to_pane {
9703                (&state.sidebar_wrap, state.sidebar_wrap.bounds())
9704            } else {
9705                state.pages.push(child.clone());
9706                let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
9707                (
9708                    &state.detail_wrap,
9709                    nav_page_frame(&state.detail_wrap, visible),
9710                )
9711            };
9712            unsafe {
9713                child.setFrame(frame);
9714                child.setAutoresizingMask(
9715                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9716                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9717                );
9718                wrap.addSubview(child);
9719            }
9720            true
9721        });
9722        if handled {
9723            return;
9724        }
9725        // Split host (docs/split.md): each pane fills its wrap, an arranged subview the
9726        // splitter sizes; the pane's own `setFrameSize:` reports the size to Day.
9727        let split_pane = SPLIT_STATE.with(|m| {
9728            let m = m.borrow();
9729            let Some(state) = m.get(&ptr_of(parent)) else {
9730                return false;
9731            };
9732            let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
9733            let wrap = if second {
9734                &state.second_wrap
9735            } else {
9736                &state.first_wrap
9737            };
9738            unsafe {
9739                child.setFrame(wrap.bounds());
9740                child.setAutoresizingMask(
9741                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9742                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9743                );
9744                wrap.addSubview(child);
9745            }
9746            true
9747        });
9748        if split_pane {
9749            return;
9750        }
9751        // Inspector host: each pane fills its wrap via autoresizing, the nav-page contract;
9752        // the split, not Day, owns the pane frames (docs/inspector.md).
9753        let inspected = INSPECTOR_STATE.with(|m| {
9754            let m = m.borrow();
9755            let Some(state) = m.get(&ptr_of(parent)) else {
9756                return false;
9757            };
9758            let panel = INSPECTOR_PANES
9759                .with(|t| t.get(ptr_of(child)))
9760                .unwrap_or(false);
9761            let wrap = if panel {
9762                &state.panel_wrap
9763            } else {
9764                &state.content_wrap
9765            };
9766            unsafe {
9767                child.setFrame(wrap.bounds());
9768                child.setAutoresizingMask(
9769                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9770                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9771                );
9772                wrap.addSubview(child);
9773            }
9774            true
9775        });
9776        if !inspected {
9777            // Absolute positioning: z-order is build order; index is irrelevant for
9778            // non-overlapping frames (stack_z will need ordered insertion later).
9779            unsafe { content_of(parent).addSubview(child) };
9780        }
9781    }
9782
9783    fn remove(&mut self, parent: &Handle, child: &Handle) {
9784        PAGE_PANE.with(|t| t.remove(ptr_of(child)));
9785        let mtm = self.mtm();
9786        NAV_STATE.with(|m| {
9787            if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
9788                // A tabs host: the page leaves with its tab item.
9789                if let Some(tabs) = state.tabs.as_ref() {
9790                    unsafe {
9791                        let n = tabs.view.numberOfTabViewItems();
9792                        for i in 0..n {
9793                            let item = tabs.view.tabViewItemAtIndex(i);
9794                            if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
9795                                tabs.view.removeTabViewItem(&item);
9796                                break;
9797                            }
9798                        }
9799                    }
9800                }
9801                state.pages.retain(|p| ptr_of(p) != ptr_of(child));
9802                if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
9803                    state.sidebar_page = None;
9804                }
9805            }
9806        });
9807        unsafe { child.removeFromSuperview() };
9808    }
9809
9810    fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
9811        unsafe { content_of(parent).addSubview(child) };
9812    }
9813
9814    fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
9815        match kind {
9816            kinds::LABEL => {
9817                if let Some(tf) = h.downcast_ref::<NSTextField>() {
9818                    let w = p.width.unwrap_or(1.0e6);
9819                    // The field owns maximumNumberOfLines; measuring its cell bypasses it.
9820                    let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
9821                    let mut height = s.height.ceil();
9822                    // AppKit's truncating single-line mode still measures explicit newlines
9823                    // as multiple lines. Bound that case using AppKit's own font metrics.
9824                    if tf.maximumNumberOfLines() == 1 {
9825                        thread_local! {
9826                            static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
9827                        }
9828                        if let Some(font) = unsafe { tf.font() } {
9829                            height = height.min(
9830                                METRICS
9831                                    .with(|metrics| metrics.defaultLineHeightForFont(&font))
9832                                    .ceil(),
9833                            );
9834                        }
9835                    }
9836                    return Size::new(s.width.ceil().min(w), height);
9837                }
9838                Size::ZERO
9839            }
9840            kinds::BUTTON | kinds::TOGGLE => {
9841                let s = unsafe { h.fittingSize() };
9842                Size::new(s.width.ceil(), s.height.ceil())
9843            }
9844            kinds::SLIDER => {
9845                let s = unsafe { h.fittingSize() };
9846                Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
9847            }
9848            kinds::PICKER => picker::measure_any(self, h, p),
9849            kinds::TEXT_AREA => textarea::measure_any(self, h, p),
9850            kinds::TEXT_FIELD => {
9851                let s = unsafe { h.fittingSize() };
9852                Size::new(
9853                    p.width.unwrap_or(s.width.max(160.0)),
9854                    s.height.max(22.0).ceil(),
9855                )
9856            }
9857            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
9858            // The stack's own fitting size, at least a table row's 28pt; the words truncate to
9859            // the row's width.
9860            kinds::LIST_ITEM => {
9861                let s = h.fittingSize();
9862                Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
9863            }
9864            kinds::PROGRESS => {
9865                // Indeterminate spinner is a fixed square; determinate bar fills width.
9866                let indeterminate = h
9867                    .clone()
9868                    .downcast::<NSProgressIndicator>()
9869                    .map(|pi| unsafe { pi.isIndeterminate() })
9870                    .unwrap_or(false);
9871                if indeterminate {
9872                    let large = h
9873                        .downcast_ref::<NSProgressIndicator>()
9874                        .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
9875                    let side = if large { 32.0 } else { 20.0 };
9876                    Size::new(side, side)
9877                } else {
9878                    Size::new(p.width.unwrap_or(180.0), 20.0)
9879                }
9880            }
9881            kinds::NAV_MENU => {
9882                let rows = NAV_MENUS.with(|m| {
9883                    m.borrow()
9884                        .get(&ptr_of(h))
9885                        .map(|(_, d)| d.ivars().items.borrow().len())
9886                        .unwrap_or(0)
9887                });
9888                Size::new(
9889                    p.width.unwrap_or(220.0),
9890                    p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
9891                )
9892            }
9893            // The recycling list fills the space it is offered (its native scroll owns overflow).
9894            kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
9895            _ => {
9896                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
9897                    measure(self, h, p)
9898                } else {
9899                    let s = unsafe { h.fittingSize() };
9900                    Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
9901                }
9902            }
9903        }
9904    }
9905
9906    fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
9907        unsafe {
9908            h.setWantsLayer(true);
9909        }
9910        let v = h.clone();
9911        with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
9912    }
9913
9914    fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
9915        // Expressed in the view's own geometry (see `TRANSFORMS`), so hit-testing follows the
9916        // drawing, as UIKit's does. Without a laid-out frame yet, `set_frame` applies it.
9917        TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
9918        let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
9919        let v = h.clone();
9920        with_appkit_anim(anim, move || {
9921            if let Some(base) = base {
9922                apply_geometry(&v, base, t);
9923            }
9924        });
9925    }
9926
9927    fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
9928        if let Some(label) = h.downcast_ref::<DayLabel>() {
9929            label.ivars().selectable.set(selectable);
9930            label.set_links(label.ivars().has_links.get());
9931        } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
9932            unsafe { tf.setSelectable(selectable) };
9933        }
9934        None
9935    }
9936
9937    fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
9938        let node = text_field_node(h)?;
9939        let old = h.downcast_ref::<NSTextField>()?;
9940        // Hidden characters are a class on AppKit. A field already of the right class is
9941        // dressed in place; otherwise its replacement is, and the node moves to it.
9942        let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
9943            .then(|| self.swap_text_field(h, old, node, traits.secure));
9944        let tf = swapped.as_deref().unwrap_or(old);
9945        unsafe {
9946            // Read-only keeps the bezel and the ordinary text color; the text stays
9947            // selectable, so it can still be copied.
9948            tf.setEditable(!traits.read_only);
9949            tf.setSelectable(true);
9950        }
9951        // The purpose is AutoFill's hint on the desktop: which saved credential or contact
9952        // detail the system offers. `Number` and `Decimal` have no content type. A constant
9953        // newer than the running system leaves the field untyped.
9954        let content_type = match traits.purpose {
9955            InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
9956            InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
9957            InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
9958            InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
9959            InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
9960            InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
9961            InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
9962            InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
9963            InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
9964        };
9965        unsafe {
9966            tf.setContentType(content_type);
9967            // Only free text wants the system finishing words; a name, an address or a code
9968            // is typed exactly.
9969            tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
9970        }
9971        // No on-screen keyboard, so no action key to label; and no native length limit:
9972        // day-pieces holds `max_length`.
9973        swapped.map(view_of)
9974    }
9975
9976    fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
9977        let key = Retained::as_ptr(h) as usize;
9978        if cursor == Cursor::Default {
9979            // Release: drop the tracking area, and the hide if this owner holds one.
9980            if let Some((owner, area)) = self.cursors.remove(&key) {
9981                unsafe { h.removeTrackingArea(&area) };
9982                if owner.ivars().hiding.replace(false) {
9983                    NSCursor::unhide();
9984                }
9985            }
9986            return;
9987        }
9988        let hidden = cursor == Cursor::None;
9989        let shape = if hidden { None } else { ns_cursor(&cursor) };
9990        let mtm = self.mtm;
9991        let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
9992            let owner = DayCursorOwner::new(mtm);
9993            // InVisibleRect: the area follows the view's bounds, so no rect to keep in step
9994            // with layout. ActiveInKeyWindow: the shape belongs to the window taking input.
9995            let opts = NSTrackingAreaOptions::CursorUpdate
9996                | NSTrackingAreaOptions::MouseEnteredAndExited
9997                | NSTrackingAreaOptions::ActiveInKeyWindow
9998                | NSTrackingAreaOptions::InVisibleRect;
9999            let any: &objc2::runtime::AnyObject = &owner;
10000            let area = unsafe {
10001                NSTrackingArea::initWithRect_options_owner_userInfo(
10002                    NSTrackingArea::alloc(),
10003                    NSRect::ZERO,
10004                    opts,
10005                    Some(any),
10006                    None,
10007                )
10008            };
10009            unsafe { h.addTrackingArea(&area) };
10010            (owner, area)
10011        });
10012        let changed = {
10013            let iv = owner.ivars();
10014            let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10015                (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10016                (None, None) => true,
10017                _ => false,
10018            };
10019            *iv.cursor.borrow_mut() = shape;
10020            let was_hidden = iv.hidden.replace(hidden);
10021            !same || was_hidden != hidden
10022        };
10023        // A reactive change while the pointer is already inside: AppKit only asks on entry,
10024        // so ask it to re-evaluate now.
10025        if changed && let Some(w) = h.window() {
10026            unsafe { w.invalidateCursorRectsForView(h) };
10027        }
10028    }
10029
10030    /// Where the control actually draws its first line of text (docs/baseline.md).
10031    ///
10032    /// AppKit publishes `firstBaselineOffsetFromTop`, but it is measured from the top of the
10033    /// view's alignment rect and it is rounded to whole points, and that rounding is visible.
10034    /// An `NSDatePicker` in a 26pt frame insets its alignment rect 4pt and answers 15, i.e. 19
10035    /// in frame terms, while it paints at 19.9; a label beside it then sits a point high, which
10036    /// is exactly the drift baseline alignment exists to remove.
10037    ///
10038    /// So derive it from the metrics AppKit rounded: a single line of the control's own font,
10039    /// centered in its alignment rect, with the baseline an ascender below the line's top. That
10040    /// reproduces AppKit's own numbers for a plain label and a bezeled field (12.91 → its 13,
10041    /// 19.91 → its 20) while keeping the fractional part that makes a picker land on the line.
10042    /// Controls with no font of their own keep AppKit's answer.
10043    fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
10044        if !day_spec::kind_has_baseline(kind) {
10045            return None;
10046        }
10047        // The view has to be at the height the row settled on before it answers: a control
10048        // that centers its text vertically moves its baseline with its box.
10049        let current = unsafe { h.frame() };
10050        if (current.size.height - size.height).abs() > 0.5 {
10051            unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
10052        }
10053        let insets = unsafe { h.alignmentRectInsets() };
10054        let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
10055        let font = h
10056            .downcast_ref::<NSControl>()
10057            .and_then(|c| unsafe { c.font() });
10058        let offset = match font {
10059            // A multi-line editor's first line sits at the top of its text container, not
10060            // centered in it, so the centering model would put its baseline half a box too low.
10061            Some(_) if kind == kinds::TEXT_AREA => reported,
10062            Some(f) => {
10063                let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
10064                let line = ascender - descender;
10065                let align_h = (size.height - insets.top - insets.bottom).max(0.0);
10066                insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
10067            }
10068            None => reported,
10069        };
10070        // AppKit's documented "no baseline" answer is the view's own height.
10071        (offset > 0.0 && offset < size.height).then_some(offset)
10072    }
10073
10074    fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
10075        // Nav pages: the splitter pane / nav container owns the frame (autoresized).
10076        if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
10077            return;
10078        }
10079        // Every Day parent is flipped (DayFlipped containers, flipped scroll document views),
10080        // so top-left frames apply directly.
10081        let r = NSRect::new(
10082            NSPoint::new(frame.origin.x, frame.origin.y),
10083            NSSize::new(frame.size.width, frame.size.height),
10084        );
10085        // Nav host: the sidebar holds its width when the window resizes and the detail pane
10086        // absorbs the change. That is now the sidebar NSSplitViewItem's behavior, so the
10087        // only thing left to do here is give the split its frame and place the divider once;
10088        // re-placing it on every resize would fight the item and undo a user's drag.
10089        if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
10090            // A host at the top of a window's pinned content reaches up under the title bar,
10091            // where its controller expects to be (see `pane_under_title_bar`); its panes keep
10092            // their content below the strip, so nothing Day laid out moves.
10093            let strip = unsafe { split.superview() }
10094                .and_then(|sup| {
10095                    let content = unsafe { sup.window() }?.contentView()?;
10096                    // Layout wrappers (for example zstack with a reader cover) may sit
10097                    // between the window root and its navigation host. A direct-parent
10098                    // check misses them and puts AppKit's frosted pocket over page text.
10099                    let mut ancestor = Some(sup.clone());
10100                    while let Some(view) = ancestor {
10101                        if std::ptr::eq(&*view, &*content) {
10102                            break;
10103                        }
10104                        if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
10105                            return None; // nested navigation belongs to the outer pane
10106                        }
10107                        ancestor = unsafe { view.superview() };
10108                    }
10109                    let point = unsafe {
10110                        sup.convertPoint_toView(
10111                            NSPoint::new(frame.origin.x, frame.origin.y),
10112                            Some(&content),
10113                        )
10114                    };
10115                    (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
10116                })
10117                .unwrap_or(0.0);
10118            let r = NSRect::new(
10119                NSPoint::new(r.origin.x, r.origin.y - strip),
10120                NSSize::new(r.size.width, r.size.height + strip),
10121            );
10122            let wraps = NAV_STATE.with(|m| {
10123                m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
10124                    (s.title_strip != strip).then(|| {
10125                        s.title_strip = strip;
10126                        let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
10127                        w.extend(s.list_wrap.clone());
10128                        w
10129                    })
10130                })
10131            });
10132            let first = NAV_STATE.with(|m| {
10133                m.borrow_mut()
10134                    .get_mut(&ptr_of(h))
10135                    .map(|s| {
10136                        if !s.presentation.is_split() {
10137                            return (false, None);
10138                        }
10139                        let sidebar = !std::mem::replace(&mut s.positioned, true);
10140                        // The list's divider waits for the pane to be showing. Placing it while
10141                        // the pane is collapsed re-opens it (which is how an app whose first
10142                        // destination has no list opened with one beside it) and spends the one
10143                        // placement the pane gets, leaving it at the solver's width later on.
10144                        (sidebar, take_list_placement(s))
10145                    })
10146                    .unwrap_or((false, None))
10147            });
10148            unsafe {
10149                split.setFrame(r);
10150                split.layoutSubtreeIfNeeded();
10151            }
10152            // After the panes have their new size, so each wrap is placed in the final pane;
10153            // autoresizing keeps the strip from then on.
10154            for wrap in wraps.iter().flatten() {
10155                place_below_strip(wrap, strip);
10156            }
10157            unsafe {
10158                if first.0 {
10159                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
10160                }
10161                // A triple split has a second divider, and nothing else places it: left alone,
10162                // the controller's initial constraint pass lands it wherever the solver liked, so
10163                // the content list opens at an arbitrary width and the detail pane gets the
10164                // leftovers until the first manual drag re-settles them.
10165                if let Some(w) = first.1 {
10166                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
10167                }
10168            }
10169        } else {
10170            BASE_FRAMES.with(|m| {
10171                m.insert(
10172                    ptr_of(h),
10173                    [
10174                        frame.origin.x,
10175                        frame.origin.y,
10176                        frame.size.width,
10177                        frame.size.height,
10178                    ],
10179                )
10180            });
10181            // A transform (`set_transform`) is applied to the frame Day laid out.
10182            match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
10183                Some(t) => apply_geometry(
10184                    h,
10185                    [
10186                        frame.origin.x,
10187                        frame.origin.y,
10188                        frame.size.width,
10189                        frame.size.height,
10190                    ],
10191                    t,
10192                ),
10193                None => unsafe { h.setFrame(r) },
10194            }
10195        }
10196    }
10197
10198    fn set_scroll_content(&mut self, h: &Handle, content: Size) {
10199        if let Some(sv) = h.downcast_ref::<NSScrollView>()
10200            && let Some(doc) = unsafe { sv.documentView() }
10201        {
10202            unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
10203        }
10204    }
10205
10206    /// A macOS table row: the dense rows of a Finder or Mail list, 28pt for an icon and a line of body text.
10207    fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
10208        day_spec::RowMetrics {
10209            insets: day_spec::Insets {
10210                top: 4.0,
10211                leading: 8.0,
10212                bottom: 4.0,
10213                trailing: 8.0,
10214            },
10215            min_height: 28.0,
10216        }
10217    }
10218
10219    fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
10220        if let Some(sv) = h.downcast_ref::<NSScrollView>()
10221            && let Some(doc) = unsafe { sv.documentView() }
10222        {
10223            unsafe {
10224                doc.scrollRectToVisible(NSRect::new(
10225                    NSPoint::new(target.origin.x, target.origin.y),
10226                    NSSize::new(target.size.width, target.size.height),
10227                ))
10228            };
10229        }
10230    }
10231
10232    fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
10233        let Some(window) = h.window() else { return };
10234        // A list's public handle is its scroll view; keyboard focus belongs to the table.
10235        let list = list_entry(ptr_of(h));
10236        let responder: &NSResponder = match &list {
10237            Some((table, _)) => table,
10238            None => h,
10239        };
10240        let responder_ptr = responder as *const NSResponder as usize;
10241        if focused {
10242            window.makeFirstResponder(Some(responder));
10243            return;
10244        }
10245        // Resign only while this view still owns focus, so a stale release can't blur a
10246        // sibling.
10247        let owns = window
10248            .firstResponder()
10249            .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
10250            || owns_first_responder(&window, h);
10251        if owns {
10252            window.makeFirstResponder(None);
10253        }
10254    }
10255
10256    fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
10257        // The overrides live on `DayFlipped` (the container view); registering any other
10258        // view is harmless but inert, the graceful silence the duty documents.
10259        if focusable {
10260            FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
10261        } else {
10262            FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
10263        }
10264    }
10265
10266    fn set_event_sink(&mut self, sink: EventSink) {
10267        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
10268    }
10269
10270    fn set_edit_state(&mut self, state: &day_spec::EditState) {
10271        EDIT_STATE.with(|s| s.set(*state));
10272    }
10273
10274    fn modifiers(&mut self) -> day_spec::Modifiers {
10275        let f = NSEvent::modifierFlags_class();
10276        day_spec::Modifiers {
10277            shift: f.contains(NSEventModifierFlags::Shift),
10278            primary: f.contains(NSEventModifierFlags::Command),
10279            alt: f.contains(NSEventModifierFlags::Option),
10280        }
10281    }
10282
10283    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
10284        let front = undo_front(self.mtm);
10285        *front.ivars().state.borrow_mut() = state.clone();
10286    }
10287
10288    fn attach_list(&mut self, host: &Handle, source: ListSource) {
10289        let key = ptr_of(host);
10290        if let Some((table, data)) = list_entry(key) {
10291            data.ivars().source.replace(Some(source));
10292            // Initial fill: numberOfRows reads the snapshot only; viewForRow is deferred.
10293            unsafe { table.reloadData() };
10294        }
10295        // Force the table to realize its visible row views on the next main-loop turn, outside
10296        // any `with_tree` borrow, so `viewForRow`/`bind_row` build the cells then. Otherwise a
10297        // headless CI window never lays the table out until a snapshot's `cacheDisplayInRect`
10298        // forces it *inside* the snapshot borrow, where `bind_row` must skip (blank rows).
10299        post_realize_visible_rows(key);
10300    }
10301
10302    fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
10303        let key = ptr_of(host);
10304        if let Some((outline, data)) = tree_entry(key) {
10305            data.ivars().source.replace(Some(source));
10306            // Initial fill: child counts read the snapshot only; viewForItem is deferred.
10307            unsafe { outline.reloadData() };
10308        }
10309        // Realize visible rows on the next main-loop turn, outside any borrow (the
10310        // attach_list comment has the occluded-window story).
10311        <AppKit as Platform>::post(Box::new(move || {
10312            if let Some((outline, _)) = tree_entry(key) {
10313                unsafe { outline.layoutSubtreeIfNeeded() };
10314            }
10315        }));
10316    }
10317
10318    fn adopt(&mut self, raw: RawHandle) -> Handle {
10319        // A recycling NSTableView cell view; Day builds/rebinds its row content in place.
10320        // Invariant, not app input: day-core only passes back the cell pointer this backend
10321        // itself vended through `bind_row`, so a null here is a framework bug worth stopping on.
10322        let ptr = raw as *mut NSView;
10323        unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
10324    }
10325
10326    fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
10327        self.edit_toolbar(h, ops)
10328    }
10329
10330    fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
10331        self.patch_toolbar(h, patch);
10332    }
10333
10334    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
10335        let mtm = self.mtm;
10336        if self.menu_escape_monitor.is_none() {
10337            let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
10338                ffi_guard::contain(event.as_ptr(), || {
10339                    let event_ref = unsafe { event.as_ref() };
10340                    let app = NSApplication::sharedApplication(mtm);
10341                    // Native dialogs retain their cancellation behavior. Only an enabled
10342                    // menu key equivalent can consume Escape, never the general key stream.
10343                    if app.modalWindow().is_none()
10344                        && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
10345                        && unsafe { event_ref.charactersIgnoringModifiers() }
10346                            .is_some_and(|s| s.to_string() == "\u{1b}")
10347                        && app
10348                            .mainMenu()
10349                            .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
10350                    {
10351                        std::ptr::null_mut()
10352                    } else {
10353                        event.as_ptr()
10354                    }
10355                })
10356            });
10357            self.menu_escape_monitor = unsafe {
10358                NSEvent::addLocalMonitorForEventsMatchingMask_handler(
10359                    objc2_app_kit::NSEventMask::KeyDown,
10360                    &block,
10361                )
10362            }
10363            .map(MenuEscapeMonitor);
10364        }
10365        let app = NSApplication::sharedApplication(mtm);
10366        let menubar = NSMenu::new(mtm);
10367        // macOS owns the application menu; relocate app-level roles while preserving
10368        // their callbacks, shortcuts, and enabled state.
10369        let mut items = items.to_vec();
10370        let about = extract_app_role(&mut items, day_spec::MenuRole::About);
10371        let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
10372        let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
10373        let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
10374        let services =
10375            install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
10376        // Fill the standard slots the app did not claim, in the platform's bar order
10377        // (day-core owns that policy so every backend arranges its bar the same way).
10378        // Fill the standard slots the app left open, in macOS's bar order. The Window menu is
10379        // installed natively below, so the style deliberately supplies none.
10380        let items =
10381            day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
10382        let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
10383        // Each top-level entry becomes a menu-bar menu.
10384        for item in &items {
10385            match item {
10386                day_spec::MenuItem::Submenu { label, items, role } => {
10387                    let sub = build_ns_menu(mtm, label, items);
10388                    let it = NSMenuItem::new(mtm);
10389                    // Help is held back: the Window menu is installed natively after this loop
10390                    // (AppKit owns it so it can append the live window list), and Help sits
10391                    // last on every Mac menu bar.
10392                    if *role == Some(day_spec::MenuBarRole::Help)
10393                        || *label == day_localization::t(day_localization::key::day_help)
10394                    {
10395                        help_menu = Some((label.clone(), sub));
10396                        continue;
10397                    }
10398                    it.setTitle(&NSString::from_str(label));
10399                    it.setSubmenu(Some(&sub));
10400                    menubar.addItem(&it);
10401                }
10402                other => {
10403                    // A bare top-level action → wrap in a one-item menu so it has a submenu.
10404                    let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
10405                    let it = NSMenuItem::new(mtm);
10406                    it.setSubmenu(Some(&sub));
10407                    menubar.addItem(&it);
10408                }
10409            }
10410        }
10411        // The Window menu (docs/windows.md): auto-installed unless the app's model owns
10412        // `MenuRole::Minimize` (then the app is composing its own window management).
10413        if !model_has_role(&items, day_spec::MenuRole::Minimize) {
10414            install_windows_menu(mtm, &app, &menubar);
10415        }
10416        if let Some((label, help)) = help_menu {
10417            let it = NSMenuItem::new(mtm);
10418            it.setTitle(&NSString::from_str(&label));
10419            it.setSubmenu(Some(&help));
10420            menubar.addItem(&it);
10421            // Registering it makes AppKit add the Help search field and index the help book —
10422            // behavior no hand-built menu reproduces.
10423            unsafe { app.setHelpMenu(Some(&help)) };
10424        }
10425        app.setMainMenu(Some(&menubar));
10426        unsafe { app.setServicesMenu(Some(&services)) };
10427    }
10428
10429    fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
10430        let Some(view) = h.downcast_ref::<NSView>() else {
10431            return;
10432        };
10433        if items.is_empty() {
10434            unsafe { view.setMenu(None) };
10435            return;
10436        }
10437        let menu = build_ns_menu(self.mtm, "", items);
10438        // Attach to the view AND its current subviews: a right-click that hit-tests a child
10439        // control (the label inside a padded target) must find the menu on the view it hit —
10440        // AppKit does not walk ancestors for `.menu`, and controls swallow the event.
10441        // DayFlipped's `rightMouseDown:` pops the menu explicitly; native controls (labels)
10442        // show their `.menu` through their own default path.
10443        unsafe { view.setMenu(Some(&menu)) };
10444        fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
10445            for sub in v.subviews() {
10446                unsafe { sub.setMenu(Some(menu)) };
10447                apply_to_subviews(&sub, menu);
10448            }
10449        }
10450        apply_to_subviews(view, &menu);
10451    }
10452
10453    fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
10454        transfer::source(h, source);
10455    }
10456    fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
10457        transfer::target(h, target);
10458    }
10459    fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
10460        // Consulted by the classes that override `menuForEvent:` (the canvas; docs/menus.md
10461        // "Dynamic context menus" lists the covered surfaces per backend).
10462        CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
10463    }
10464
10465    fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
10466        let key = ptr_of(h);
10467        // Pan is not a recognizer on macOS: the two-finger idiom is the trackpad SCROLL, so
10468        // the canvas view's own `scrollWheel:` override reports it for registered nodes.
10469        // Containers use a horizontal-only monitor so nested vertical scrolling still works.
10470        if kind == day_spec::GestureKind::Pan {
10471            PAN_NODES.with(|t| t.insert(key, node));
10472            install_container_pan_monitor();
10473            return;
10474        }
10475        // Nor is hover: it is a tracking area plus `mouseEntered:`/`mouseMoved:`/`mouseExited:`,
10476        // which only `DayCanvas` overrides — a hover enabled on another view emits nothing, the
10477        // same limitation Pan has.
10478        if kind == day_spec::GestureKind::Hover {
10479            // Idempotent, and it has to be checked here rather than falling through to the
10480            // recognizer guard below: day-core re-enables a gesture on rebuild, and a second
10481            // tracking area on the same view means a second copy of every hover event.
10482            let first = HOVER_NODES.with(|t| t.get(key)).is_none();
10483            HOVER_NODES.with(|t| t.insert(key, node));
10484            if first {
10485                install_tracking_area(h);
10486            }
10487            return;
10488        }
10489        // Idempotent: attach each kind at most once per view.
10490        let already = GESTURES.with(|m| {
10491            m.borrow()
10492                .get(&key)
10493                .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
10494        });
10495        if already {
10496            return;
10497        }
10498        let mtm = self.mtm;
10499        let target = DayGesture::new(mtm, node, kind);
10500        let recognizer: Retained<NSGestureRecognizer> = unsafe {
10501            match kind {
10502                day_spec::GestureKind::Drag => {
10503                    Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
10504                        NSPanGestureRecognizer::alloc(mtm),
10505                        Some(&target),
10506                        Some(sel!(fire:)),
10507                    ))
10508                }
10509                day_spec::GestureKind::Pinch => Retained::into_super(
10510                    objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
10511                        objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
10512                        Some(&target),
10513                        Some(sel!(fire:)),
10514                    ),
10515                ),
10516                _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
10517                    NSClickGestureRecognizer::alloc(mtm),
10518                    Some(&target),
10519                    Some(sel!(fire:)),
10520                )),
10521            }
10522        };
10523        unsafe { h.addGestureRecognizer(&recognizer) };
10524        GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
10525    }
10526
10527    fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
10528        unsafe {
10529            if let Some(id) = &a11y.identifier {
10530                h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
10531            }
10532            if let Some(label) = &a11y.label {
10533                h.setAccessibilityLabel(Some(&NSString::from_str(label)));
10534                APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
10535            } else {
10536                APP_LABELED.with(|t| t.remove(ptr_of(h)));
10537            }
10538            if let Some(hint) = &a11y.hint {
10539                h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
10540            }
10541            if let Some(value) = &a11y.value {
10542                let ns = NSString::from_str(value);
10543                h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
10544            }
10545            // Only apply an EXPLICIT role (canvas/custom pieces, e.g. a Meter): native controls
10546            // already report the right role, so Day records but doesn't override theirs (§13).
10547            if let Some(role) = ns_role(a11y.role) {
10548                h.setAccessibilityRole(Some(role));
10549            }
10550            if a11y.role == day_spec::Role::Tab {
10551                h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
10552            }
10553            if let Some(on) = a11y.selected {
10554                h.setAccessibilitySelected(on);
10555            }
10556            // Decorative / hidden: drop from the AX tree entirely. An ignored view alone is
10557            // not enough — AppKit promotes an ignored element's children into its parent's
10558            // list — so the subtree is cut off too, which also covers subviews added later
10559            // (list rows, re-created children). Hidden never flips back, so the override is
10560            // never lifted.
10561            if a11y.hidden {
10562                h.setAccessibilityElement(false);
10563                h.setAccessibilityChildren(Some(&NSArray::new()));
10564            }
10565        }
10566    }
10567
10568    /// The announcement request goes out from the primary window (any live element will
10569    /// do; the app object stands in before the window exists). Without VoiceOver nothing
10570    /// observes the notification, so posting is free.
10571    fn announce(&mut self, text: &str, urgent: bool) {
10572        use objc2_app_kit::{
10573            NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
10574            NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
10575            NSAccessibilityPriorityLevel,
10576        };
10577        let app = NSApplication::sharedApplication(self.mtm());
10578        let window = primary_content().and_then(|content| content.window());
10579        let element: &objc2::runtime::AnyObject = match &window {
10580            Some(window) => window,
10581            None => &app,
10582        };
10583        // High priority interrupts the current sentence; medium waits its turn.
10584        let priority = if urgent {
10585            NSAccessibilityPriorityLevel::High
10586        } else {
10587            NSAccessibilityPriorityLevel::Medium
10588        };
10589        let announcement = NSString::from_str(text);
10590        let priority = NSNumber::new_isize(priority.0);
10591        let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
10592        // SAFETY: the keys are AppKit's constants and both values are the types the
10593        // announcement notification documents (an NSString and an NSNumber).
10594        unsafe {
10595            let user_info = NSDictionary::from_slices::<NSString>(
10596                &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
10597                &values,
10598            );
10599            NSAccessibilityPostNotificationWithUserInfo(
10600                element,
10601                NSAccessibilityAnnouncementRequestedNotification,
10602                Some(&user_info),
10603            );
10604        }
10605    }
10606
10607    fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
10608        unsafe {
10609            let role = h
10610                .accessibilityRole()
10611                .map(|r| day_role_from_ns(&r.to_string()))
10612                .unwrap_or(day_spec::Role::None);
10613            // A picker answers its displayed selection and its enabled state itself: the
10614            // inline style is a stack of radios, not one control.
10615            let picker = picker::read_native(h);
10616            day_spec::NativeSnapshot {
10617                found: true,
10618                role,
10619                label: h.accessibilityLabel().map(|s| s.to_string()),
10620                value: h
10621                    .accessibilityValue()
10622                    .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
10623                identifier: h
10624                    .accessibilityIdentifier()
10625                    .map(|s| s.to_string())
10626                    .filter(|s| !s.is_empty()),
10627                text: match &picker {
10628                    Some((text, _)) => text.clone(),
10629                    None => native_text(h),
10630                },
10631                number: native_number(h),
10632                checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
10633                    match sw.state() {
10634                        s if s == NSControlStateValueOn => Some(true),
10635                        s if s == NSControlStateValueOff => Some(false),
10636                        // Mixed is neither on nor off.
10637                        _ => None,
10638                    }
10639                } else if let Some(btn) = h.downcast_ref::<NSButton>() {
10640                    // A Day button's selected state (`ButtonProps::selected`): its own
10641                    // `state`, which a momentary button holds off at rest.
10642                    BUTTON_SELECTED
10643                        .with(|m| m.borrow().contains_key(&ptr_of(h)))
10644                        .then(|| btn.state() == NSControlStateValueOn)
10645                } else {
10646                    None
10647                },
10648                // A label is a non-editable NSTextField whose `isEnabled` says nothing about
10649                // input; every other control answers for itself.
10650                enabled: match (&picker, h.downcast_ref::<NSControl>()) {
10651                    (Some((_, on)), _) => *on,
10652                    (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
10653                    (None, Some(c)) => Some(c.isEnabled()),
10654                    (None, None) => None,
10655                },
10656                // Off-window counts as not shown: nothing of it reaches the screen.
10657                visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
10658                frame: native_frame(h),
10659            }
10660        }
10661    }
10662
10663    fn request_frame(
10664        &mut self,
10665        host: &Handle,
10666        cb: day_spec::FrameCallback,
10667    ) -> day_spec::CancelFrame {
10668        frame::request(host, cb)
10669    }
10670
10671    fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
10672        OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
10673        unsafe { h.setNeedsDisplay(true) };
10674    }
10675    fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
10676        NAV_STATE.with(|m| {
10677            let m = m.borrow();
10678            let Some(st) = m.get(&ptr_of(host)) else {
10679                return false;
10680            };
10681            // A pane to toggle exists in `Split` and `Rail`; a stack has none and a tab bar
10682            // keeps its rows in the chrome, where hiding them would strand the user.
10683            if !matches!(
10684                st.presentation,
10685                NavPresentation::Split | NavPresentation::Rail
10686            ) {
10687                return false;
10688            }
10689            let item = &st.sidebar_item;
10690            // Set directly, not through the `animator` proxy. The proxy defers the change to
10691            // an animation the dayscript screenshot step does not wait on, so a scripted
10692            // toggle captured a sidebar that had not moved yet. AppKit's own
10693            // NSToolbarToggleSidebarItem still animates — it runs `toggleSidebar:` on the
10694            // controller and never comes through here.
10695            let collapsed = unsafe { item.isCollapsed() };
10696            unsafe { item.setCollapsed(!collapsed) };
10697            true
10698        })
10699    }
10700
10701    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
10702        let content = self.content.as_ref().ok_or("no window content")?;
10703        snapshot_view(content)
10704    }
10705
10706    /// Decode bytes into an `NSImage` (docs/images.md).
10707    ///
10708    /// `NSBitmapImageRep` is asked first and kept: it is what actually reads the container, it
10709    /// answers in PIXELS (`NSImage.size` is in points and reports a 144-DPI photo at
10710    /// two-thirds its real width), and it is the only thing here that can re-encode later.
10711    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
10712        use objc2::AllocAnyThread as _;
10713        let data = NSData::with_bytes(bytes);
10714        let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
10715        else {
10716            emit(
10717                WINDOW_NODE,
10718                Event::ImageDecoded {
10719                    req,
10720                    result: Err(day_spec::ImageError::Decode),
10721                },
10722            );
10723            return;
10724        };
10725        let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
10726        let info = day_spec::BitmapInfo {
10727            pixels: Size::new(w, h),
10728            // Decoded bytes carry no density — a PNG is simply its pixels. Only a staged @2x
10729            // asset has a scale, and that arrives through the named path instead.
10730            scale: 1.0,
10731            format: day_spec::ImageFormat::sniff(bytes),
10732            has_alpha: unsafe { rep.hasAlpha() },
10733        };
10734        // Built AT the rep's pixel size so it draws 1:1 by default: an NSImage otherwise adopts
10735        // the rep's own `size`, which ImageIO derives from the file's DPI — that is what shrinks
10736        // a 144-DPI photo for no reason the app asked for.
10737        let image = unsafe {
10738            objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
10739        };
10740        unsafe { image.addRepresentation(&rep) };
10741        BITMAPS.with(|m| {
10742            m.borrow_mut().insert(
10743                id.0,
10744                AppKitBitmap {
10745                    image,
10746                    rep: Some(rep),
10747                    info,
10748                },
10749            )
10750        });
10751        emit(
10752            WINDOW_NODE,
10753            Event::ImageDecoded {
10754                req,
10755                result: Ok(info),
10756            },
10757        );
10758    }
10759
10760    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
10761        BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
10762    }
10763
10764    /// The container's own metadata (docs/images.md).
10765    ///
10766    /// DPI is DERIVED rather than read from a tag: AppKit has already resolved the file's
10767    /// resolution into the rep's point size, so pixels-per-point × 72 is the number the platform
10768    /// itself believes — and it is right for containers that record resolution in ways EXIF
10769    /// does not.
10770    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
10771        let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
10772        let mut out = day_spec::ImageProperties::default();
10773        let size = unsafe { rep.size() };
10774        if size.width > 0.0 {
10775            let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
10776            // 72 is "no resolution recorded" wearing a number; reporting it would read as a fact
10777            // the file never stated.
10778            if (dpi - 72.0).abs() > 0.5 {
10779                out.dpi = Some(dpi);
10780            }
10781        }
10782        // EXIF arrives as a dictionary of the format's own keys. It is walked through
10783        // `msg_send!` rather than a downcast because a generic `NSDictionary` is not a
10784        // `DowncastTarget`.
10785        if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
10786            let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
10787            for key in keys.iter() {
10788                let value: Option<Retained<objc2::runtime::AnyObject>> =
10789                    unsafe { msg_send![&*exif, objectForKey: &*key] };
10790                let Some(value) = value else { continue };
10791                let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
10792                let (k, v) = (key.to_string(), text.to_string());
10793                match k.as_str() {
10794                    "Orientation" => out.orientation = v.parse().ok(),
10795                    "DateTimeOriginal" => out.created = Some(v.clone()),
10796                    _ => {}
10797                }
10798                // Keys stay in EXIF's own vocabulary, passed through rather than translated —
10799                // the doc for `extra` promises exactly that.
10800                out.extra.push((k, v));
10801            }
10802        }
10803        Some(out)
10804    }
10805
10806    /// What `NSBitmapImageRep` WRITES. It reads more than this — WebP and HEIF among them — and
10807    /// the asymmetry is the platform's own, which is exactly why this duty exists instead of
10808    /// letting `Cap::ImageEncode` imply every format round-trips.
10809    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
10810        use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
10811        vec![Png, Jpeg, Tiff, Bmp, Gif]
10812    }
10813
10814    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
10815        let result = encode_bitmap(id, spec);
10816        emit(WINDOW_NODE, Event::ImageEncoded { req, result });
10817    }
10818
10819    fn release_image(&mut self, id: day_spec::BitmapId) {
10820        release_bitmap(id);
10821    }
10822
10823    /// Replay `ops` offscreen through the canvas's own painter (docs/canvas.md "Exporting") and
10824    /// keep the result in the decode table, so `image`, `encode_image` and `DrawOp::Image` take
10825    /// it like any decoded bitmap.
10826    fn render_bitmap(
10827        &mut self,
10828        req: u64,
10829        id: day_spec::BitmapId,
10830        ops: &[DrawOp],
10831        size: Size,
10832        scale: f64,
10833    ) {
10834        let result = render_bitmap_image(ops, size, scale).map(|bitmap| {
10835            let info = bitmap.info;
10836            BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
10837            info
10838        });
10839        emit(WINDOW_NODE, Event::BitmapRendered { req, result });
10840    }
10841
10842    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
10843        let result = render_pdf_bytes(pages, info);
10844        emit(WINDOW_NODE, Event::PdfRendered { req, result });
10845    }
10846
10847    /// `NSFontManager.availableFontFamilies` + `availableMembersOfFontFamily:`, whose members
10848    /// are `[postscriptName, styleName, weight 0 … 15, traits]` (docs/fonts.md). The `.`-prefixed
10849    /// families are the system's private UI faces and are skipped, as Font Book skips them.
10850    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
10851        use day_spec::FontWeight as W;
10852        let mtm =
10853            objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
10854        let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
10855        let mut out = Vec::new();
10856        for family in unsafe { manager.availableFontFamilies() }.iter() {
10857            let name = family.to_string();
10858            if name.starts_with('.') {
10859                continue;
10860            }
10861            let mut faces = Vec::new();
10862            if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
10863                for member in members.iter() {
10864                    if member.count() < 4 {
10865                        continue;
10866                    }
10867                    let style = member
10868                        .objectAtIndex(1)
10869                        .downcast_ref::<NSString>()
10870                        .map(|s| s.to_string())
10871                        .unwrap_or_default();
10872                    let weight = member
10873                        .objectAtIndex(2)
10874                        .downcast_ref::<objc2_foundation::NSNumber>()
10875                        .map(|n| n.integerValue())
10876                        .unwrap_or(5);
10877                    let traits = member
10878                        .objectAtIndex(3)
10879                        .downcast_ref::<objc2_foundation::NSNumber>()
10880                        .map(|n| n.integerValue())
10881                        .unwrap_or(0);
10882                    let weight = match weight {
10883                        ..=2 => W::UltraLight,
10884                        3 => W::Thin,
10885                        4 => W::Light,
10886                        5 => W::Regular,
10887                        6 => W::Medium,
10888                        7 | 8 => W::Semibold,
10889                        9 => W::Bold,
10890                        10 | 11 => W::Heavy,
10891                        _ => W::Black,
10892                    };
10893                    let italic = traits & 0x1 != 0; // NSItalicFontMask
10894                    faces.push(day_spec::FontFace {
10895                        name: if style.is_empty() {
10896                            day_spec::FontFace::synthesized_name(weight, italic)
10897                        } else {
10898                            style
10899                        },
10900                        weight,
10901                        italic,
10902                    });
10903                }
10904            }
10905            out.push(day_spec::FontFamilyInfo {
10906                family: name,
10907                faces,
10908            });
10909        }
10910        out
10911    }
10912
10913    /// `sizeWithAttributes:` with the attributes `replay` draws with; the ascent is the
10914    /// font's own, so `at.y + ascent` is where the glyphs' baseline lands.
10915    fn measure_text(
10916        &mut self,
10917        text: &str,
10918        size: f64,
10919        font: &day_spec::CanvasFont,
10920    ) -> Option<day_spec::TextMetrics> {
10921        let nsfont = canvas_nsfont(size, font);
10922        let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
10923        let ns = NSString::from_str(text);
10924        let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
10925        // The INK box: `NSStringDrawingUsesDeviceMetrics` is what turns `boundingRectWithSize:`
10926        // from the layout box into the glyphs' own bounds, and it comes back baseline-relative
10927        // with y up — hence the flip. An unbounded size so nothing wraps: this measures one line.
10928        let unbounded = NSSize::new(f64::MAX, f64::MAX);
10929        let ink: NSRect = unsafe {
10930            msg_send![
10931                &ns,
10932                boundingRectWithSize: unbounded,
10933                options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
10934                attributes: &*attrs,
10935            ]
10936        };
10937        Some(day_spec::TextMetrics::from_baseline(
10938            sz.width,
10939            nsfont.ascender(),
10940            sz.height - nsfont.ascender(),
10941            nsfont.capHeight(),
10942            day_spec::Rect::new(
10943                ink.origin.x,
10944                -(ink.origin.y + ink.size.height),
10945                ink.size.width,
10946                ink.size.height,
10947            ),
10948        ))
10949    }
10950
10951    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
10952        let content = self.content.as_ref().ok_or("no window content")?;
10953        snapshot_view_chrome(content)
10954    }
10955
10956    fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
10957        snapshot_view(host)
10958    }
10959
10960    fn open_window(
10961        &mut self,
10962        id: NodeId,
10963        options: &WindowOptions,
10964        kind: day_spec::WindowKind,
10965    ) -> day_spec::WindowOpenReply<Handle> {
10966        let prefs = kind.is_panel();
10967        let (window, delegate, content) = self.make_window(options, prefs, Some(id));
10968        if prefs {
10969            // A settings panel is one-of-a-kind and centered, and it stays OUT of the Window
10970            // menu — the macOS convention every stock app follows (docs/windows.md).
10971            window.center();
10972            unsafe { window.setExcludedFromWindowsMenu(true) };
10973        } else {
10974            // Stagger, don't stack. Without this every window opens at the same centered frame
10975            // and the one underneath is invisible — which is exactly what two Day windows did.
10976            //
10977            // `cascadeTopLeftFromPoint:` puts the window AT the point it is given and answers
10978            // the point for the one after, so the series has to be primed from the primary
10979            // rather than seeded with its corner — seeding lands the first new window exactly
10980            // on top of the primary, which is the bug this replaces.
10981            let from = match self.cascade {
10982                Some(p) => p,
10983                None => self
10984                    .window
10985                    .as_ref()
10986                    .map(|w| {
10987                        let f = w.frame();
10988                        let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
10989                        // Asking the primary to cascade from where it already is leaves it
10990                        // there and answers the next slot — the offset the first new window wants.
10991                        unsafe { w.cascadeTopLeftFromPoint(top_left) }
10992                    })
10993                    .unwrap_or(NSPoint::new(0.0, 0.0)),
10994            };
10995            self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
10996        }
10997        window_chrome::place(&window, options.placement);
10998        // `center` (a settings panel's, or a `Centered` placement's) uses the main screen, the
10999        // one with the keyboard focus, which on a Mac with several displays need not be the
11000        // app's: such a window goes to the primary's screen instead. A scripted run on the
11001        // capture display relies on this to keep the window in its captures.
11002        if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
11003            center_on_screen_of(&window, self.window.as_deref());
11004        }
11005        // Secondary windows need the same initial client-coordinate pinning as the
11006        // primary. Native document pages may move here before any resize notification.
11007        let _ = pin_below_title_bar(&window);
11008        if !options.start_hidden {
11009            window.makeKeyAndOrderFront(None);
11010        }
11011        // Same macOS 26 quirk as the primary (`run`): a window ordered front before its
11012        // first turn drops pre-run layer displays — nudge every layer once.
11013        mark_tree_needs_display(&content);
11014        self.secondary.push(SecondaryWin {
11015            window,
11016            delegate,
11017            content: content.clone(),
11018        });
11019        day_spec::WindowOpenReply::Open(content)
11020    }
11021
11022    fn native_window_tabs(&self) -> bool {
11023        true
11024    }
11025    fn group_windows(&mut self, hosts: &[Handle]) {
11026        let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
11027        let Some(first) = windows.first() else {
11028            return;
11029        };
11030        unsafe {
11031            NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
11032        }
11033        // Explicit insertion respects the model even when system automatic tabbing is off.
11034        for window in windows.iter().skip(1) {
11035            unsafe {
11036                first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
11037            }
11038        }
11039        if let Some(group) = first.tabGroup() {
11040            if !group.isTabBarVisible() {
11041                unsafe {
11042                    first.toggleTabBar(None);
11043                }
11044            }
11045            for (i, window) in windows.iter().enumerate() {
11046                group.insertWindow_atIndex(window, i as isize);
11047            }
11048        }
11049        // Adding/showing a native tab strip changes contentLayoutRect without necessarily
11050        // resizing the window. Re-pin every member and tell the layout tree its usable size.
11051        for window in &windows {
11052            if let Some(size) = pin_below_title_bar(window) {
11053                let node = window
11054                    .delegate()
11055                    .and_then(|d| d.downcast::<DayWinDelegate>().ok())
11056                    .and_then(|d| d.ivars().node)
11057                    .unwrap_or(WINDOW_NODE);
11058                emit(node, Event::WindowResized(size));
11059            }
11060        }
11061    }
11062    fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
11063        let Some(window) = self.ns_window_for(host) else {
11064            return Vec::new();
11065        };
11066        let windows = window.tabGroup().map(|g| g.windows());
11067        let Some(windows) = windows else {
11068            return Vec::new();
11069        };
11070        windows
11071            .iter()
11072            .filter_map(|window| {
11073                self.secondary
11074                    .iter()
11075                    .find(|w| std::ptr::eq(&*w.window, &*window))
11076                    .and_then(|w| w.delegate.ivars().node)
11077            })
11078            .collect()
11079    }
11080
11081    fn close_window(&mut self, host: &Handle) {
11082        // `close()` runs the full native path — windowWillClose → `WindowClosed` →
11083        // day-core teardown — so programmatic and title-bar closes are one code path.
11084        if let Some(w) = self
11085            .secondary
11086            .iter()
11087            .find(|w| ptr_of(&w.content) == ptr_of(host))
11088        {
11089            w.window.close();
11090        }
11091    }
11092
11093    fn focus_window(&mut self, host: &Handle) {
11094        if let Some(w) = self
11095            .secondary
11096            .iter()
11097            .find(|w| ptr_of(&w.content) == ptr_of(host))
11098        {
11099            w.window.makeKeyAndOrderFront(None);
11100        }
11101    }
11102
11103    fn fit_window(&mut self, host: &Handle, size: Size) {
11104        let Some(w) = self
11105            .secondary
11106            .iter()
11107            .find(|w| ptr_of(&w.content) == ptr_of(host))
11108        else {
11109            return;
11110        };
11111        unsafe {
11112            // `setContentSize:` rather than `setFrame:`: Day measured the CONTENT, and AppKit
11113            // adds the title bar itself. Sizing the frame instead would eat the bar's height out
11114            // of the panel and clip the last row by exactly that much.
11115            w.window
11116                .setContentSize(NSSize::new(size.width, size.height));
11117            // A settings panel that fits its content has no reason to be resizable, and macOS
11118            // panels are not — dropping the mask also stops the user dragging it back to a size
11119            // the content does not fill.
11120            let mask = w.window.styleMask();
11121            w.window
11122                .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
11123            w.window.center();
11124        }
11125        center_on_screen_of(&w.window, self.window.as_deref());
11126    }
11127
11128    fn set_window_title(&mut self, host: &Handle, title: &str) {
11129        if let Some(w) = self
11130            .secondary
11131            .iter()
11132            .find(|w| ptr_of(&w.content) == ptr_of(host))
11133        {
11134            w.window.setTitle(&NSString::from_str(title));
11135            return;
11136        }
11137        // The PRIMARY window is retitlable too. It is an ordinary window (docs/windows.md), so
11138        // `window_title` in the first window's shell and `set_title` on `initial_window()` both
11139        // arrive here — and searching only the secondary list silently dropped them.
11140        if self
11141            .content
11142            .as_ref()
11143            .is_some_and(|c| ptr_of(c) == ptr_of(host))
11144            && let Some(w) = self.window.as_ref()
11145        {
11146            w.setTitle(&NSString::from_str(title));
11147        }
11148    }
11149
11150    fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
11151        use day_spec::WindowChange as C;
11152        let Some(window) = self.ns_window_for(host) else {
11153            return;
11154        };
11155        match change {
11156            C::State(state) => set_ns_window_state(&window, *state),
11157            // Screen capture, recording and sharing see an empty window; the user still does.
11158            C::ContentProtected(on) => window.setSharingType(if *on {
11159                objc2_app_kit::NSWindowSharingType::None
11160            } else {
11161                objc2_app_kit::NSWindowSharingType::ReadOnly
11162            }),
11163            other => window_chrome::apply_property(&window, other),
11164        }
11165    }
11166
11167    fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
11168        self.ns_window_for(host)
11169            .map(|w| window_chrome::frame_of(&w))
11170    }
11171
11172    fn monitors(&self) -> Vec<day_spec::Monitor> {
11173        window_chrome::monitors(self.mtm)
11174    }
11175
11176    /// The Dock menu lists them: day-core folds the run-time shortcuts into the model it sends
11177    /// through `set_dock_menu`, so there is nothing more to install here.
11178    fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
11179
11180    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
11181        dock::set_app_items(self.mtm, items);
11182    }
11183
11184    fn set_drag_region(&mut self, h: &Handle, drag: bool) {
11185        window_chrome::set_drag_region(h, drag);
11186    }
11187
11188    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
11189        status_item::set_items(self.mtm, items);
11190    }
11191
11192    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
11193        status_item::set_progress(self.mtm, progress);
11194    }
11195
11196    fn set_dock_visible(&mut self, visible: bool) {
11197        status_item::set_dock_visible(self.mtm, visible);
11198    }
11199
11200    fn set_keep_running(&mut self, keep: bool) {
11201        status_item::set_keep_running(keep);
11202    }
11203
11204    fn quit_app(&mut self) {
11205        let app = NSApplication::sharedApplication(self.mtm);
11206        unsafe { app.terminate(None) };
11207    }
11208
11209    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
11210        use present::PresentSpec;
11211        let mtm = self.mtm;
11212        // Sheets attach to the KEY window at present time (docs/windows.md) — a dialog
11213        // raised from a secondary/preferences window belongs on it; primary is the
11214        // fallback when no DAY window is key (a system panel may hold key status).
11215        let app = NSApplication::sharedApplication(mtm);
11216        let key = app.keyWindow().filter(|k| {
11217            let mut owner = k.clone();
11218            while let Some(parent) = owner.sheetParent() {
11219                owner = parent;
11220            }
11221            self.window
11222                .as_deref()
11223                .is_some_and(|w| std::ptr::eq(w, &*owner))
11224                || self
11225                    .secondary
11226                    .iter()
11227                    .any(|s| std::ptr::eq(&*s.window, &*owner))
11228        });
11229        let Some(mut window) = key.or_else(|| self.window.clone()) else {
11230            emit(
11231                WINDOW_NODE,
11232                Event::PresentResult {
11233                    req,
11234                    result: present::PresentResult::Dismissed,
11235                },
11236            );
11237            return;
11238        };
11239        // A dialog opened from a modal cover belongs on the active sheet, not behind it.
11240        while let Some(sheet) = window.attachedSheet() {
11241            window = sheet;
11242        }
11243        // File pickers use a different native object (NSOpen/NSSavePanel), not an NSAlert.
11244        match spec {
11245            PresentSpec::OpenFile {
11246                filters, multiple, ..
11247            } => {
11248                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11249                unsafe {
11250                    panel.setCanChooseFiles(true);
11251                    panel.setCanChooseDirectories(false);
11252                    panel.setAllowsMultipleSelection(*multiple);
11253                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11254                }
11255                apply_allowed_file_types(&panel, filters);
11256                let p = panel.clone();
11257                // Completion blocks run inside a C ABI frame, so their bodies are contained
11258                // like every other trampoline (§8.5) — this one and the four below.
11259                let handler: block2::RcBlock<dyn Fn(isize)> =
11260                    block2::RcBlock::new(move |resp: isize| {
11261                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11262                    });
11263                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11264                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11265                return;
11266            }
11267            // The folder chooser is the same NSOpenPanel with files and directories swapped.
11268            PresentSpec::OpenFolder { .. } => {
11269                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
11270                unsafe {
11271                    panel.setCanChooseFiles(false);
11272                    panel.setCanChooseDirectories(true);
11273                    panel.setCanCreateDirectories(true);
11274                    panel.setAllowsMultipleSelection(false);
11275                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11276                }
11277                let p = panel.clone();
11278                let handler: block2::RcBlock<dyn Fn(isize)> =
11279                    block2::RcBlock::new(move |resp: isize| {
11280                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
11281                    });
11282                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11283                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
11284                return;
11285            }
11286            PresentSpec::SaveFile { suggested_name, .. } => {
11287                let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
11288                unsafe {
11289                    panel.setMessage(Some(&NSString::from_str(spec.title())));
11290                    panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
11291                }
11292                apply_allowed_file_types(&panel, spec.filters());
11293                let p = panel.clone();
11294                let handler: block2::RcBlock<dyn Fn(isize)> =
11295                    block2::RcBlock::new(move |resp: isize| {
11296                        // The pieces layer copies the staged bytes to the chosen local path.
11297                        ffi_guard::contain((), || emit_panel_result(req, resp, &p));
11298                    });
11299                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
11300                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
11301                return;
11302            }
11303            _ => {}
11304        }
11305        let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
11306        unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
11307        if let Some(msg) = spec.message() {
11308            unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
11309        }
11310        // The completion handler must outlive this call, so it's a heap (Rc) block.
11311        let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
11312            PresentSpec::Dialog { buttons, .. } => {
11313                if buttons
11314                    .iter()
11315                    .any(|b| b.role == present::ButtonRole::Destructive)
11316                {
11317                    unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
11318                }
11319                for b in buttons {
11320                    unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
11321                }
11322                block2::RcBlock::new(move |resp: isize| {
11323                    ffi_guard::contain((), || {
11324                        // NSAlertFirstButtonReturn = 1000; add order == spec order.
11325                        let idx = resp - 1000;
11326                        emit(
11327                            WINDOW_NODE,
11328                            Event::PresentResult {
11329                                req,
11330                                result: present::PresentResult::Button(idx as i64),
11331                            },
11332                        );
11333                        PRESENT_ALERTS.with(|m| {
11334                            m.borrow_mut().remove(&req);
11335                        });
11336                    })
11337                })
11338            }
11339            PresentSpec::Prompt {
11340                placeholder,
11341                initial,
11342                ok,
11343                cancel,
11344                ..
11345            } => {
11346                let tf = unsafe { NSTextField::new(mtm) };
11347                unsafe {
11348                    tf.setFrame(NSRect::new(
11349                        NSPoint::new(0.0, 0.0),
11350                        NSSize::new(260.0, 24.0),
11351                    ));
11352                    tf.setEditable(true);
11353                    tf.setBezeled(true);
11354                    tf.setStringValue(&NSString::from_str(initial));
11355                    tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
11356                    alert.setAccessoryView(Some(&tf));
11357                    alert.addButtonWithTitle(&NSString::from_str(ok)); // resp 1000
11358                    alert.addButtonWithTitle(&NSString::from_str(cancel)); // resp 1001
11359                }
11360                block2::RcBlock::new(move |resp: isize| {
11361                    ffi_guard::contain((), || {
11362                        let result = if resp == 1000 {
11363                            present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
11364                        } else {
11365                            present::PresentResult::Dismissed
11366                        };
11367                        emit(WINDOW_NODE, Event::PresentResult { req, result });
11368                        PRESENT_ALERTS.with(|m| {
11369                            m.borrow_mut().remove(&req);
11370                        });
11371                    })
11372                })
11373            }
11374            // File pickers returned early above.
11375            PresentSpec::OpenFile { .. }
11376            | PresentSpec::OpenFolder { .. }
11377            | PresentSpec::SaveFile { .. } => unreachable!(),
11378        };
11379        unsafe {
11380            alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
11381        }
11382        PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
11383    }
11384
11385    fn dismiss(&mut self, req: u64) {
11386        // Close the sheet; its completion handler fires but its (native) result is dropped
11387        // because day-core already removed the pending request when it resolved.
11388        let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
11389        if let Some(alert) = alert {
11390            let sheet = alert.window();
11391            if let Some(parent) = sheet.sheetParent() {
11392                unsafe { parent.endSheet(&sheet) };
11393            }
11394        }
11395        // File-picker sheets are their own NSWindow.
11396        let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
11397        if let Some(panel) = panel
11398            && let Some(parent) = panel.sheetParent()
11399        {
11400            unsafe { parent.endSheet(&panel) };
11401        }
11402    }
11403
11404    fn application_handlers(
11405        &mut self,
11406        query: &day_spec::applications::HandlerQuery,
11407    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
11408    {
11409        applications::handlers(query)
11410    }
11411
11412    fn open_url_with_application(
11413        &mut self,
11414        url: &str,
11415        application: &str,
11416        completion: day_spec::applications::OpenApplicationCompletion,
11417    ) {
11418        applications::open(url, application, completion);
11419    }
11420
11421    fn share_support(&self) -> day_spec::Support {
11422        day_spec::Support::Native
11423    }
11424    fn share_url(&mut self, url: &str, _title: &str) -> bool {
11425        use objc2::{msg_send, runtime::AnyObject};
11426        use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
11427        let Some(mtm) = objc2::MainThreadMarker::new() else {
11428            return false;
11429        };
11430        let Some(url) = NSURL::URLWithString(&NSString::from_str(url)) else {
11431            return false;
11432        };
11433        let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
11434        let Some(view) = app.keyWindow().and_then(|w| w.contentView()) else {
11435            return false;
11436        };
11437        unsafe {
11438            let items = NSArray::from_retained_slice(&[url]);
11439            let picker: objc2::rc::Allocated<AnyObject> =
11440                msg_send![objc2::class!(NSSharingServicePicker), alloc];
11441            let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
11442            let bounds = view.bounds();
11443            let y = if view.isFlipped() {
11444                30.0
11445            } else {
11446                bounds.size.height - 30.0
11447            };
11448            let rect = NSRect::new(
11449                NSPoint::new(bounds.size.width - 30.0, y),
11450                NSSize::new(1.0, 1.0),
11451            );
11452            let _: () = msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: 3usize];
11453            self.sharing = Some(picker);
11454        }
11455        true
11456    }
11457    fn open_url(&mut self, url: &str) {
11458        // NSWorkspace opens the URL in the user's default handler (Safari for http(s), Mail for
11459        // mailto:, …). An unparseable string yields no NSURL and is silently ignored.
11460        let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
11461        if let Some(nsurl) = nsurl {
11462            unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
11463        }
11464    }
11465}
11466
11467/// Apply a file dialog's extension filters (`allowedFileTypes` — deprecated but still the simplest
11468/// extension-based API; `UTType` would pull in another framework crate for no benefit here).
11469#[allow(deprecated)]
11470fn apply_allowed_file_types(
11471    panel: &objc2_app_kit::NSSavePanel,
11472    filters: &[day_spec::present::FileFilter],
11473) {
11474    let exts: Vec<Retained<NSString>> = filters
11475        .iter()
11476        .flat_map(|f| f.extensions.iter())
11477        .map(|e| NSString::from_str(e))
11478        .collect();
11479    if !exts.is_empty() {
11480        let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
11481        let arr = objc2_foundation::NSArray::from_slice(&refs);
11482        unsafe { panel.setAllowedFileTypes(Some(&arr)) };
11483    }
11484}
11485
11486/// Turn an open panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1):
11487/// every chosen URL, so a multiple-selection pick reports all of its files (and a folder
11488/// chooser its one directory).
11489fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
11490    let mut paths = Vec::new();
11491    if resp == 1 {
11492        for url in unsafe { panel.URLs() }.iter() {
11493            if let Some(p) = unsafe { url.path() } {
11494                paths.push(p.to_string());
11495            }
11496        }
11497    }
11498    let result = if paths.is_empty() {
11499        present::PresentResult::Dismissed
11500    } else {
11501        present::PresentResult::Files(paths)
11502    };
11503    emit(WINDOW_NODE, Event::PresentResult { req, result });
11504    PRESENT_PANELS.with(|m| {
11505        m.borrow_mut().remove(&req);
11506    });
11507}
11508
11509/// Turn a save panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1).
11510fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
11511    let result = if resp == 1 {
11512        unsafe { panel.URL() }
11513            .and_then(|url| unsafe { url.path() })
11514            .map(|p| present::PresentResult::Files(vec![p.to_string()]))
11515            .unwrap_or(present::PresentResult::Dismissed)
11516    } else {
11517        present::PresentResult::Dismissed
11518    };
11519    emit(WINDOW_NODE, Event::PresentResult { req, result });
11520    PRESENT_PANELS.with(|m| {
11521        m.borrow_mut().remove(&req);
11522    });
11523}
11524
11525impl Platform for AppKit {
11526    const TARGET: &'static str = "macos-appkit";
11527    const TOOLKIT: &'static str = "appkit";
11528
11529    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
11530        let mtm = self.mtm;
11531        // The App menu / About use the app's display name. `app_name` overrides the (possibly
11532        // decorated) window title; setting the process name also makes the standard About panel and
11533        // the bold App-menu title show it (an unbundled binary otherwise shows the exe name).
11534        self.app_name = options
11535            .app_name
11536            .clone()
11537            .unwrap_or_else(|| options.title.clone());
11538        // The bold App-menu title, the About panel and Quit all show the app's NAME. Always set
11539        // it, not just when `app_name` was given explicitly — an app that only set `title` was
11540        // showing its kebab-case cargo target ("day-sheets") where its name belongs.
11541        //
11542        // Two sources, because AppKit consults them in order: the main bundle's CFBundleName
11543        // wins when there is one, and `day launch` runs the binary UNBUNDLED during development,
11544        // where the name falls back to the executable's file name. Writing the info dictionary
11545        // covers the bundled case; the process name covers the unbundled one.
11546        unsafe {
11547            objc2_foundation::NSProcessInfo::processInfo()
11548                .setProcessName(&NSString::from_str(&self.app_name));
11549            let bundle = objc2_foundation::NSBundle::mainBundle();
11550            let info: Option<Retained<objc2_foundation::NSDictionary>> =
11551                msg_send![&bundle, infoDictionary];
11552            if let Some(info) = info {
11553                let key = NSString::from_str("CFBundleName");
11554                let value = NSString::from_str(&self.app_name);
11555                // `infoDictionary` is documented immutable, but the instance backing an
11556                // unbundled process is a mutable dictionary; guard the send so a genuinely
11557                // immutable one is left alone instead of raising.
11558                if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
11559                    let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
11560                }
11561            }
11562        }
11563        // RTL locales (docs/localization): AppleTextDirection flips AppKit's app-wide
11564        // userInterfaceLayoutDirection (label alignment, slider fill, control mirroring) —
11565        // read at NSApplication init, so register before sharedApplication. Registration
11566        // domain only: volatile, never persisted to the app's defaults.
11567        if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
11568            unsafe {
11569                use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
11570                let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
11571                    .into_super()
11572                    .into_super()
11573                    .into_super();
11574                let dict = NSDictionary::from_retained_objects(
11575                    &[
11576                        &*NSString::from_str("AppleTextDirection"),
11577                        &*NSString::from_str("NSForceRightToLeftWritingDirection"),
11578                    ],
11579                    &[yes.clone(), yes],
11580                );
11581                NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
11582            }
11583        }
11584        let app = NSApplication::sharedApplication(mtm);
11585        // A menu-bar app keeps out of the Dock from the first frame (docs/status-item.md): its
11586        // bundle carries LSUIElement, and an unbundled `day launch` run hears DAY_MACOS_DOCK=0.
11587        let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
11588            || unsafe {
11589                let bundle = objc2_foundation::NSBundle::mainBundle();
11590                let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
11591                    &bundle,
11592                    objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
11593                ];
11594                value.is_some_and(|v| {
11595                    let on: bool = msg_send![&v, boolValue];
11596                    on
11597                })
11598            };
11599        app.setActivationPolicy(if menu_bar_app {
11600            NSApplicationActivationPolicy::Accessory
11601        } else {
11602            NSApplicationActivationPolicy::Regular
11603        });
11604        let document_delegate = documents::delegate(mtm);
11605        app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
11606        // DAY_THEME=light|dark forces the appearance app-wide (themed CI screenshot runs and
11607        // local theme checks); unset ⇒ follow the system.
11608        if let Ok(theme) = std::env::var("DAY_THEME") {
11609            let name = match theme.as_str() {
11610                "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11611                "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11612                _ => None,
11613            };
11614            if let Some(name) = name {
11615                let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
11616                unsafe { app.setAppearance(appearance.as_deref()) };
11617            }
11618        }
11619        // Bundled custom fonts (§18.4) must be registered before the first label realizes.
11620        register_bundled_fonts();
11621
11622        // Default menu bar (standard app menu + Edit) so ⌘Q / Cut-Copy-Paste work before the app
11623        // installs its own via `app_menu(...)`. Rebuilt after `ready` for the items that depend
11624        // on the app's registrations — see there.
11625        let app_name = self.app_name.clone();
11626        install_main_menu(mtm, &app, &app_name);
11627        // App activation / termination → day lifecycle events (docs/lifecycle.md).
11628        install_lifecycle_observers();
11629        install_appearance_observer();
11630        install_reduce_motion_observer();
11631
11632        let (window, delegate, content) = self.make_window(&options, false, None);
11633        // Optional window-appearance override (opt-in via env). An app with a fixed light/dark
11634        // palette sets `DAY_APPEARANCE=light|dark` so native controls (list, fields, editor) match
11635        // its own colors instead of following the system appearance. Unset = follow the system.
11636        let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
11637            Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
11638            Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
11639            _ => None,
11640        };
11641        if let Some(name) = appearance_name
11642            && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
11643        {
11644            window.setAppearance(Some(&appearance));
11645        }
11646        // The primary delegate lives for the process (this frame never returns); secondary
11647        // delegates are retained in `self.secondary`.
11648        std::mem::forget(delegate);
11649
11650        self.window = Some(window.clone());
11651        self.content = Some(content.clone());
11652        PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
11653
11654        // The root lays out below the title bar, not under it (§7.7).
11655        let layout = pin_below_title_bar(&window)
11656            .unwrap_or(Size::new(options.size.width, options.size.height));
11657        ready(self, content, layout);
11658
11659        // `ready` ran the app's root() — registrations are in. Without a new-window
11660        // builder only one Normal window can ever exist: turn automatic tabbing off so no
11661        // tab bar, "+" button, or dead tab menu items appear (docs/windows.md).
11662        if day_core::windows::new_window_action_id() == 0
11663            && options.tabbing == day_spec::WindowTabbing::Automatic
11664        {
11665            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
11666        }
11667        // The DEFAULT menu bar was built before `root()` ran, so its registration-dependent
11668        // items — Settings…/⌘, and File ▸ New Window — could not exist yet. Rebuild it now that
11669        // they can. An app with its own `app_menu` model already replaced the whole bar and
11670        // gets its items through the injection path instead.
11671        if !day_core::has_app_menu() {
11672            install_main_menu(mtm, &app, &app_name);
11673        }
11674
11675        // Reopen where the user left it (docs/windows.md). AppKit persists the frame under an
11676        // autosave name and hands it back on request; `setFrameUsingName` answers false the
11677        // first time, which is when centering is the right answer.
11678        //
11679        // NOT while a dayscript is driving or `DAY_WINDOW` has forced a size: a restored frame
11680        // would make every captured screenshot's dimensions depend on where the developer last
11681        // dragged the window, and the capture suites compare those across machines.
11682        let deterministic =
11683            std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
11684        let autosave = NSString::from_str("day.main");
11685        if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
11686            window.center();
11687            // An explicit placement wins over centering, but not over the frame the user left.
11688            window_chrome::place(&window, options.placement);
11689        }
11690        // A scripted run whose capture needs a display scale this host's displays lack opens on
11691        // the one `day launch` made for it (`DAY_WINDOW_SCREEN`, a CGDirectDisplayID): a
11692        // capture is the window server's pixels, so it has the scale of the display under it.
11693        if let Some(screen) = capture_screen(mtm) {
11694            let (visible, frame) = (screen.visibleFrame(), window.frame());
11695            window.setFrameOrigin(NSPoint::new(
11696                visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
11697                visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
11698            ));
11699        }
11700        if !deterministic {
11701            unsafe { window.setFrameAutosaveName(&autosave) };
11702        }
11703        if !options.start_hidden {
11704            window.makeKeyAndOrderFront(None);
11705            app.activate();
11706        }
11707        // The root was mounted before the window was shown (ready() runs first), and on
11708        // macOS 26 layer displays requested pre-run are dropped for a window ordered front
11709        // before the app finishes launching — the window stays blank until the next real
11710        // event. Re-mark the whole tree so the first run-loop turn commits a full frame.
11711        if let Some(content) = window.contentView() {
11712            mark_tree_needs_display(&content);
11713        }
11714        if std::env::var_os("DAY_DUMP").is_some() {
11715            std::thread::spawn(|| {
11716                std::thread::sleep(std::time::Duration::from_millis(2000));
11717                Self::post(Box::new(|| {
11718                    // The primary's content specifically (docs/windows.md).
11719                    if let Some(content) = primary_content() {
11720                        let desc: Retained<NSString> =
11721                            unsafe { msg_send![&*content, _subtreeDescription] };
11722                        log::warn!("{desc}");
11723                    }
11724                }));
11725            });
11726        }
11727        app.run();
11728    }
11729
11730    fn post(f: Box<dyn FnOnce() + Send>) {
11731        // Posted-closure trampoline (§8.5): the closure runs inside dispatch's C frame, so a
11732        // panic is contained here rather than unwinding into libdispatch.
11733        dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
11734    }
11735
11736    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
11737        // The timer door behind `day::sleep` (docs/async.md): `dispatch_after` on the main
11738        // queue, so a sleep is a dispatch timer rather than a parked helper thread. Contained
11739        // like `post`. A delay too large for dispatch's clock runs at the far horizon instead.
11740        let when =
11741            dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
11742                .unwrap_or(dispatch2::DispatchTime::FOREVER);
11743        if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
11744            ffi_guard::contain((), f);
11745        }) {
11746            log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
11747        }
11748    }
11749
11750    fn locale_hints(&self) -> Vec<String> {
11751        // The user's ordered language preference from Settings ("fr-FR", "en-US", …), which is
11752        // the ambient locale Day negotiates its catalogs against (§12.2, docs/localization.md).
11753        objc2_foundation::NSLocale::preferredLanguages()
11754            .iter()
11755            .map(|s| s.to_string())
11756            .collect()
11757    }
11758}
11759
11760// `CGWindowListCreateImage` is obsoleted as of the macOS 15 SDK (ScreenCaptureKit is the
11761// sanctioned replacement) but still resolves and answers on macOS 26. It is declared here rather
11762// than taken from a binding because the availability attribute would refuse the call outright,
11763// and every use below treats a NULL return as "ask the offscreen path instead".
11764unsafe extern "C" {
11765    fn CGWindowListCreateImage(
11766        bounds: objc2_core_foundation::CGRect,
11767        list_option: u32,
11768        window_id: u32,
11769        image_option: u32,
11770    ) -> *mut objc2_core_graphics::CGImage;
11771}
11772
11773/// kCGWindowListOptionIncludingWindow — composite only this window, so whatever is stacked over
11774/// it (another app, a CI runner's stray window) cannot appear in the capture.
11775const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
11776/// kCGWindowImageBoundsIgnoreFraming — the window's own frame, without its drop shadow, which
11777/// makes the returned image exactly `window.frame()` at the backing scale.
11778const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
11779
11780/// Encode a captured rep as PNG, in sRGB.
11781///
11782/// A capture arrives in the color space of the display it was composited for, and a PNG of it
11783/// embeds that display's ICC profile: the same color then has different sample values on every
11784/// machine, and on every other Day target, which all capture sRGB. Converting first makes a
11785/// macOS capture's samples comparable with theirs and independent of the capturing display.
11786fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
11787    let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
11788        &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
11789        objc2_app_kit::NSColorRenderingIntent::Default,
11790    );
11791    let rep = srgb.as_deref().unwrap_or(rep);
11792    let data = unsafe {
11793        rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
11794    }
11795    .ok_or("png encode failed")?;
11796    Ok(data.to_vec())
11797}
11798
11799/// Capture `content` by asking the WINDOW SERVER for the composited window and cropping to it.
11800///
11801/// This exists because an offscreen render cannot draw macOS's own materials. As of macOS 26 a
11802/// sidebar `NSSplitViewItem` is a Liquid Glass surface the window server composites from what is
11803/// behind it; `cacheDisplayInRect` has no backdrop to sample, so it renders the sidebar as an
11804/// opaque white slab with none of its rows in it — every macos-appkit gallery shot had a blank
11805/// sidebar. The window server has the real pixels, including the rows.
11806///
11807/// It answers only while the window is actually on screen. A hidden, minimized or
11808/// never-composited window has no image to hand back (verified: hiding the app makes this return
11809/// NULL while the offscreen path still produces a frame), so this returns `Err` and the caller
11810/// falls back rather than failing the capture.
11811fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
11812    let window = content.window().ok_or("view is not in a window")?;
11813    // An attached sheet is the active modal surface and has its own composited window.
11814    // Capturing only the parent's window would show dimmed content without the modal UI.
11815    if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
11816        return snapshot_via_window_server(&sheet, chrome);
11817    }
11818    let number = window.windowNumber();
11819    if number <= 0 {
11820        return Err(format!("window {number} is not on screen"));
11821    }
11822    // The server hands back the frame it last COMPOSITED, which is the previous one whenever the
11823    // app has changed the view tree since. A capture taken right after a state change then shows
11824    // the state before it — a `when` whose outgoing arm is already gone from the tree and from the
11825    // view hierarchy still appears in the image, so a walkthrough asserting on pixels reads a
11826    // stale frame as "the change did not happen". Push the pending work out first: lay out, draw,
11827    // then commit the layer tree to the render server.
11828    unsafe { content.layoutSubtreeIfNeeded() };
11829    window.displayIfNeeded();
11830    CATransaction::flush();
11831    // CGRectNull asks for the window's own bounds rather than a screen region.
11832    let null_rect = objc2_core_foundation::CGRect::new(
11833        objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
11834        objc2_core_foundation::CGSize::new(0.0, 0.0),
11835    );
11836    let shot = unsafe {
11837        CGWindowListCreateImage(
11838            null_rect,
11839            CG_WINDOW_LIST_INCLUDING_WINDOW,
11840            number as u32,
11841            CG_WINDOW_IMAGE_IGNORE_FRAMING,
11842        )
11843    };
11844    if shot.is_null() {
11845        return Err("the window server has no image for this window".into());
11846    }
11847    // SAFETY: non-NULL CGImageRef owned by this call (Create rule); CFRetained takes that
11848    // ownership over, so it is released exactly once.
11849    let shot = unsafe {
11850        objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
11851    };
11852
11853    // A chrome capture is the window image as the server composited it — titlebar, toolbar and
11854    // rounded corners included — so it is done here, before the crop.
11855    if chrome {
11856        let rep = unsafe {
11857            objc2_app_kit::NSBitmapImageRep::initWithCGImage(
11858                objc2_app_kit::NSBitmapImageRep::alloc(),
11859                &shot,
11860            )
11861        };
11862        return png_of_rep(&rep);
11863    }
11864
11865    // Crop the window frame down to the content view. Keeping the framing identical to the
11866    // offscreen path is the point: the titlebar has never been part of a Day capture, and every
11867    // published gallery shot would otherwise change size.
11868    let frame = window.frame();
11869    if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
11870        return Err("zero-size window".into());
11871    }
11872    let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
11873    // Cocoa rects are bottom-left origin; a CGImage's are top-left, so the content's distance
11874    // from the window top is what the crop needs.
11875    let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
11876    let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
11877    let crop = objc2_core_foundation::CGRect::new(
11878        objc2_core_foundation::CGPoint::new(
11879            (in_window.origin.x * scale).round(),
11880            (from_top * scale).round(),
11881        ),
11882        objc2_core_foundation::CGSize::new(
11883            (in_window.size.width * scale).round(),
11884            (in_window.size.height * scale).round(),
11885        ),
11886    );
11887    let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
11888        .ok_or("crop to the content view failed")?;
11889    let rep = unsafe {
11890        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
11891            objc2_app_kit::NSBitmapImageRep::alloc(),
11892            &cropped,
11893        )
11894    };
11895    png_of_rep(&rep)
11896}
11897
11898/// Capture a window content view as PNG (the dayscript screenshot seam, §14).
11899///
11900/// The window server first, because it is the only one of the two that can show macOS's own
11901/// composited materials; the offscreen render when it declines, because it is the only one of the
11902/// two that works with no window on screen. See each for why.
11903/// Put a [`Transform`] on a view through its own geometry rather than its layer: the frame is
11904/// the laid-out `base` scaled about its center and moved by the translation, the bounds keep the
11905/// laid-out size (so the content draws at the scale), and the rotation is the frame's center
11906/// rotation (positive is clockwise on screen: Day's parents are flipped, y down).
11907fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
11908    let [x, y, w, h] = base;
11909    let (sw, sh) = (w * t.sx, h * t.sy);
11910    let frame = NSRect::new(
11911        NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
11912        NSSize::new(sw, sh),
11913    );
11914    unsafe {
11915        // The rotation goes first and comes back last: a rotated view's frame is its bounding
11916        // box, so setting the frame of a rotated view would scale it.
11917        v.setFrameCenterRotation(0.0);
11918        v.setFrame(frame);
11919        v.setBoundsSize(NSSize::new(w, h));
11920        if t.rotate_deg != 0.0 {
11921            v.setFrameCenterRotation(t.rotate_deg);
11922        }
11923    }
11924}
11925
11926fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
11927    let modal = content
11928        .window()
11929        .and_then(|w| w.attachedSheet())
11930        .and_then(|s| s.contentView());
11931    let content = modal.as_deref().unwrap_or(content);
11932    match snapshot_via_window_server(content, false) {
11933        Ok(bytes) => Ok(bytes),
11934        Err(_) => snapshot_view_cache(content),
11935    }
11936}
11937
11938/// Capture a window *with* its chrome — the titlebar and toolbar the content capture crops away
11939/// (`day::window_image().chrome()`, docs/window-image.md).
11940///
11941/// Only the window server can produce this: the offscreen path renders the content view's own
11942/// hierarchy, which the titlebar is not part of. When it declines (an offscreen or hidden window)
11943/// the content capture stands in — a smaller image beats no image, and it is what the caller
11944/// would have got from the plain duty.
11945fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
11946    let modal = content
11947        .window()
11948        .and_then(|w| w.attachedSheet())
11949        .and_then(|s| s.contentView());
11950    let content = modal.as_deref().unwrap_or(content);
11951    match snapshot_via_window_server(content, true) {
11952        Ok(bytes) => Ok(bytes),
11953        Err(_) => snapshot_view_cache(content),
11954    }
11955}
11956
11957/// The offscreen fallback: `cacheDisplayInRect` over a window-background pre-fill resolved for
11958/// the view's light/dark appearance. Renders the view hierarchy Day drew, and nothing the window
11959/// server composites (see `snapshot_via_window_server`).
11960fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
11961    let bounds = content.bounds();
11962    let rep =
11963        unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
11964    // Day containers are transparent (the window server paints the backdrop), so pre-fill
11965    // the rep with the window background — resolved for the window's light/dark appearance —
11966    // before compositing the view hierarchy over it (§14).
11967    let ctx =
11968        NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
11969    NSGraphicsContext::saveGraphicsState_class();
11970    NSGraphicsContext::setCurrentContext(Some(&ctx));
11971    content
11972        .effectiveAppearance()
11973        .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
11974            NSColor::windowBackgroundColor().setFill();
11975            objc2_app_kit::NSRectFill(bounds);
11976        }));
11977    NSGraphicsContext::restoreGraphicsState_class();
11978    unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
11979    png_of_rep(&rep)
11980}
11981
11982/// The screen a scripted run asked to open on: `DAY_WINDOW_SCREEN`, the CGDirectDisplayID of the
11983/// capture display `day launch --script` provides when no attached display has the capture's
11984/// scale. `None` when unset or when no screen has that id, which leaves the window where it was.
11985/// Center `window` on `primary`'s screen when `center` put it on another, as high as `center`
11986/// places a window (a third of the free height above it, two below).
11987fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
11988    let Some(screen) = primary.and_then(|w| w.screen()) else {
11989        return;
11990    };
11991    if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
11992        return;
11993    }
11994    let (visible, frame) = (screen.visibleFrame(), window.frame());
11995    window.setFrameOrigin(NSPoint::new(
11996        visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
11997        visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
11998    ));
11999}
12000
12001fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
12002    let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
12003        .ok()?
12004        .trim()
12005        .parse()
12006        .ok()?;
12007    let key = NSString::from_str("NSScreenNumber");
12008    objc2_app_kit::NSScreen::screens(mtm)
12009        .into_iter()
12010        .find(|screen| {
12011            let number: Option<Retained<objc2_foundation::NSNumber>> =
12012                unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
12013            number.is_some_and(|n| n.unsignedIntValue() == wanted)
12014        })
12015}
12016
12017/// Recursively mark a view tree as needing display (startup first-frame fix, see `run`).
12018fn mark_tree_needs_display(view: &NSView) {
12019    view.setNeedsDisplay(true);
12020    for sub in view.subviews() {
12021        mark_tree_needs_display(&sub);
12022    }
12023}
12024
12025/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
12026/// macOS has no true background/foreground or memory-warning lifecycle. `const` so
12027/// `day::require_lifecycle!` can reject unsupported phases at compile time. Must agree with the
12028/// `Toolkit::supports_lifecycle` default (which also returns `is_universal`).
12029pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
12030    phase.is_universal()
12031}
12032
12033/// Follow the SYSTEM appearance while the app runs: macOS posts the distributed
12034/// "AppleInterfaceThemeChangedNotification" on a theme switch, and AppKit updates
12035/// `effectiveAppearance` just after — so re-read on the next main-queue turn and refresh
12036/// day-core's reactive dark-mode signal (palette closures recolor live instead of going
12037/// stale until the next rebuild). The token is leaked to observe for the app's lifetime.
12038fn install_appearance_observer() {
12039    use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
12040    let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
12041    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12042        dispatch2::DispatchQueue::main()
12043            .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
12044    });
12045    let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
12046    let token = unsafe {
12047        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
12048    };
12049    std::mem::forget(token);
12050}
12051
12052/// Follow the SYSTEM reduce-motion switch while the app runs: NSWorkspace posts
12053/// `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification` on its own notification
12054/// center when any Accessibility › Display option flips, and
12055/// `accessibilityDisplayShouldReduceMotion` already answers the new value by then. The
12056/// notification arrives on the main thread; the main-queue hop keeps the re-read off the
12057/// poster's stack, as the appearance observer does. The token is leaked to observe for the
12058/// app's lifetime.
12059fn install_reduce_motion_observer() {
12060    use objc2_foundation::NSNotification;
12061    let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
12062    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12063        dispatch2::DispatchQueue::main()
12064            .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
12065    });
12066    let token = unsafe {
12067        center.addObserverForName_object_queue_usingBlock(
12068            Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
12069            None,
12070            None,
12071            &block,
12072        )
12073    };
12074    std::mem::forget(token);
12075}
12076
12077/// Bridge the NSApplication activation/termination notifications to day lifecycle events
12078/// (docs/lifecycle.md). The observer tokens are leaked to live for the whole app.
12079fn install_lifecycle_observers() {
12080    use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
12081    let center = unsafe { NSNotificationCenter::defaultCenter() };
12082    let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
12083        let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
12084            ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
12085        });
12086        let token = unsafe {
12087            center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
12088        };
12089        std::mem::forget(token); // observe for the app's lifetime
12090    };
12091    unsafe {
12092        observe(
12093            NSApplicationDidBecomeActiveNotification,
12094            day_spec::Lifecycle::DidBecomeActive,
12095        );
12096        observe(
12097            NSApplicationWillResignActiveNotification,
12098            day_spec::Lifecycle::WillResignActive,
12099        );
12100        observe(
12101            NSApplicationWillTerminateNotification,
12102            day_spec::Lifecycle::WillTerminate,
12103        );
12104        // `terminate:` exits the process from inside the run loop, so the loop never returns to
12105        // `launch_with`: the last Day code to run is this notification's second observer, which
12106        // NSNotificationCenter calls after the first (docs/lifecycle.md).
12107        observe(
12108            NSApplicationWillTerminateNotification,
12109            day_spec::Lifecycle::DidExit,
12110        );
12111    }
12112}
12113
12114day_localization_ui::locales!();
12115
12116/// Shared by the initial menu and every reactive replacement. AppKit owns Services
12117/// and the hide actions; these commands must not depend on a window or app callback.
12118fn install_application_menu(
12119    mtm: MainThreadMarker,
12120    menubar: &NSMenu,
12121    title: &str,
12122    about: Option<day_spec::MenuItem>,
12123    updates: Option<day_spec::MenuItem>,
12124    prefs: Option<day_spec::MenuItem>,
12125    quit: Option<day_spec::MenuItem>,
12126) -> Retained<NSMenu> {
12127    let app = NSApplication::sharedApplication(mtm);
12128    use day_spec::{MenuItem as M, MenuRole as R};
12129    let standard = |role, label| M::Action {
12130        id: None,
12131        action: 0,
12132        label,
12133        shortcut: None,
12134        enabled: true,
12135        checked: None,
12136        role: Some(role),
12137        icon: None,
12138    };
12139    let mut about =
12140        about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
12141    let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
12142    for (item, title) in [
12143        (&mut about, res::str::about_app(title).format()),
12144        (&mut quit, res::str::quit_app(title).format()),
12145    ] {
12146        if let M::Action { label, .. } = item {
12147            *label = title;
12148        }
12149    }
12150    // A registered Day About (docs/settings.md) replaces the stock Info.plist panel: the
12151    // item fires the dispatch action instead of `orderFrontStandardAboutPanel:`.
12152    if let M::Action { action, .. } = &mut about
12153        && *action == 0
12154    {
12155        *action = day_core::windows::about_action_id();
12156    }
12157    // Check for Updates… sits directly under About (the Sparkle convention), whether the app
12158    // placed the role itself or the updater only registered its action.
12159    let updates_id = day_core::windows::check_for_updates_action_id();
12160    let updates = updates.or_else(|| {
12161        (updates_id != 0).then(|| {
12162            standard(
12163                R::CheckForUpdates,
12164                day_localization::t(day_localization::key::day_check_for_updates),
12165            )
12166        })
12167    });
12168    let mut head = vec![about];
12169    if let Some(mut updates) = updates {
12170        if let M::Action { action, .. } = &mut updates
12171            && *action == 0
12172        {
12173            *action = updates_id;
12174        }
12175        head.push(updates);
12176    }
12177    head.push(M::Separator);
12178    let menu = build_ns_menu(mtm, title, &head);
12179    if let Some(mut prefs) = prefs {
12180        if let M::Action { label, .. } = &mut prefs {
12181            *label = res::str::settings().format();
12182        }
12183        let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
12184        for item in section.itemArray() {
12185            section.removeItem(&item);
12186            menu.addItem(&item);
12187        }
12188    }
12189    // AppKit keeps the registered Services menu across main-menu replacements.
12190    // Move that same menu to the new bar rather than abandoning its system-populated items.
12191    let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
12192    if let Some(parent) = unsafe { services.supermenu() } {
12193        let index = parent.indexOfItemWithSubmenu(Some(&services));
12194        if index >= 0 {
12195            parent.itemAtIndex(index).unwrap().setSubmenu(None);
12196        }
12197    }
12198    let services_item = NSMenuItem::new(mtm);
12199    services_item.setTitle(&NSString::from_str(&res::str::services().format()));
12200    services_item.setSubmenu(Some(&services));
12201    menu.addItem(&services_item);
12202    menu.addItem(&NSMenuItem::separatorItem(mtm));
12203    for (label, selector, shortcut) in [
12204        (
12205            res::str::hide_app(title).format(),
12206            sel!(hide:),
12207            Some(day_spec::Shortcut::primary("h")),
12208        ),
12209        (
12210            res::str::hide_others().format(),
12211            sel!(hideOtherApplications:),
12212            Some(day_spec::Shortcut::primary("h").alt()),
12213        ),
12214        (
12215            res::str::show_all().format(),
12216            sel!(unhideAllApplications:),
12217            None,
12218        ),
12219    ] {
12220        let item = unsafe {
12221            NSMenuItem::initWithTitle_action_keyEquivalent(
12222                NSMenuItem::alloc(mtm),
12223                &NSString::from_str(&label),
12224                Some(selector),
12225                &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
12226            )
12227        };
12228        if let Some(shortcut) = shortcut {
12229            item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
12230        }
12231        // Explicitly target the application so window responders cannot override Hide.
12232        unsafe { item.setTarget(Some(&app)) };
12233        menu.addItem(&item);
12234    }
12235    menu.addItem(&NSMenuItem::separatorItem(mtm));
12236    let section = build_ns_menu(mtm, title, &[quit]);
12237    let quit = section.itemAtIndex(0).unwrap();
12238    section.removeItem(&quit);
12239    menu.addItem(&quit);
12240    let item = NSMenuItem::new(mtm);
12241    item.setSubmenu(Some(&menu));
12242    menubar.addItem(&item);
12243    services
12244}
12245
12246/// The default main menu (§21.2 M2): standard application menu; Edit menu wired to the responder
12247/// chain so Cmd+C/V/X/A work in NSTextFields; Window menu basics.
12248fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
12249    let menubar = NSMenu::new(mtm);
12250
12251    let prefs_id = day_core::windows::preferences_action_id();
12252    let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
12253        id: None,
12254        action: prefs_id,
12255        label: res::str::settings().format(),
12256        shortcut: None,
12257        enabled: true,
12258        checked: None,
12259        role: Some(day_spec::MenuRole::Preferences),
12260        icon: None,
12261    });
12262    let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
12263
12264    // File ▸ New Window / Close, when the app registered a new-window builder — the same
12265    // zero-menu-code rule as Settings…/⌘, above (docs/windows.md). Without this an app that
12266    // never calls `app_menu` gets the tab-bar "+" and the Window menu's tab commands but no
12267    // File ▸ New Window, because the default menu bar has no File menu to put it in.
12268    let new_window_id = day_core::windows::new_window_action_id();
12269    if new_window_id != 0 {
12270        let file_item = NSMenuItem::new(mtm);
12271        let file_menu = unsafe {
12272            NSMenu::initWithTitle(
12273                NSMenu::alloc(mtm),
12274                &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
12275            )
12276        };
12277        let new_window = unsafe {
12278            NSMenuItem::initWithTitle_action_keyEquivalent(
12279                NSMenuItem::alloc(mtm),
12280                &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
12281                Some(sel!(fire:)),
12282                &NSString::from_str("n"),
12283            )
12284        };
12285        let target = menu_target(mtm);
12286        let tobj: &objc2::runtime::AnyObject = target.as_ref();
12287        unsafe { new_window.setTarget(Some(tobj)) };
12288        new_window.setTag(new_window_id as isize);
12289        file_menu.addItem(&new_window);
12290        file_menu.addItem(&NSMenuItem::separatorItem(mtm));
12291        // Nil-targeted, so it closes whatever window is key — the standard responder route.
12292        let close = unsafe {
12293            NSMenuItem::initWithTitle_action_keyEquivalent(
12294                NSMenuItem::alloc(mtm),
12295                &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
12296                Some(sel!(performClose:)),
12297                &NSString::from_str("w"),
12298            )
12299        };
12300        file_menu.addItem(&close);
12301        file_item.setSubmenu(Some(&file_menu));
12302        menubar.addItem(&file_item);
12303    }
12304
12305    let edit_item = NSMenuItem::new(mtm);
12306    let edit_menu = unsafe {
12307        NSMenu::initWithTitle(
12308            NSMenu::alloc(mtm),
12309            &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
12310        )
12311    };
12312    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12313        let item = unsafe {
12314            NSMenuItem::initWithTitle_action_keyEquivalent(
12315                NSMenuItem::alloc(mtm),
12316                &NSString::from_str(&day_localization::t(key)),
12317                Some(action),
12318                &NSString::from_str(accel),
12319            )
12320        };
12321        edit_menu.addItem(&item);
12322    };
12323    add("day_undo", sel!(undo:), "z");
12324    add("day_redo", sel!(redo:), "Z");
12325    edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
12326    add("day_cut", sel!(cut:), "x");
12327    add("day_copy", sel!(copy:), "c");
12328    add("day_paste", sel!(paste:), "v");
12329    add("day_select_all", sel!(selectAll:), "a");
12330    edit_item.setSubmenu(Some(&edit_menu));
12331    menubar.addItem(&edit_item);
12332
12333    install_windows_menu(mtm, app, &menubar);
12334
12335    app.setMainMenu(Some(&menubar));
12336    unsafe { app.setServicesMenu(Some(&services)) };
12337}
12338
12339/// The standard Window menu (docs/windows.md): Minimize ⌘M / Zoom / Bring All to Front,
12340/// registered as `NSApp.windowsMenu` — AppKit then appends the open-window list and, with
12341/// tabbing live, the tab commands (Show Next/Previous Tab, Merge All Windows) itself. All
12342/// nav hosts are nil-targeted (responder chain), so they act on the key window.
12343fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
12344    let menu = unsafe {
12345        NSMenu::initWithTitle(
12346            NSMenu::alloc(mtm),
12347            &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
12348        )
12349    };
12350    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
12351        let item = unsafe {
12352            NSMenuItem::initWithTitle_action_keyEquivalent(
12353                NSMenuItem::alloc(mtm),
12354                &NSString::from_str(&day_localization::t(key)),
12355                Some(action),
12356                &NSString::from_str(accel),
12357            )
12358        };
12359        menu.addItem(&item);
12360    };
12361    add("day_minimize", sel!(performMiniaturize:), "m");
12362    add("day_zoom", sel!(performZoom:), "");
12363    menu.addItem(&NSMenuItem::separatorItem(mtm));
12364    add("day_bring_all_front", sel!(arrangeInFront:), "");
12365    let item = NSMenuItem::new(mtm);
12366    item.setTitle(&NSString::from_str(&day_localization::t(
12367        day_localization::key::day_window,
12368    )));
12369    item.setSubmenu(Some(&menu));
12370    menubar.addItem(&item);
12371    unsafe { app.setWindowsMenu(Some(&menu)) };
12372}
12373
12374/// Hoist application roles even from nested menus. First declaration wins; remove
12375/// duplicates and empty containers, then normalize separators left by the move.
12376fn extract_app_role(
12377    items: &mut Vec<day_spec::MenuItem>,
12378    role: day_spec::MenuRole,
12379) -> Option<day_spec::MenuItem> {
12380    use day_spec::MenuItem as M;
12381    let mut found = None;
12382    let mut remaining = Vec::new();
12383    for mut item in items.drain(..) {
12384        match &mut item {
12385            M::Action { role: Some(r), .. } if *r == role => {
12386                found.get_or_insert(item);
12387                continue;
12388            }
12389            M::Submenu { items, .. } => {
12390                let nested = extract_app_role(items, role);
12391                if found.is_none() {
12392                    found = nested;
12393                }
12394                if items.is_empty() {
12395                    continue;
12396                }
12397            }
12398            M::Separator
12399                if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
12400            {
12401                continue;
12402            }
12403            _ => {}
12404        }
12405        remaining.push(item);
12406    }
12407    while matches!(remaining.last(), Some(M::Separator)) {
12408        remaining.pop();
12409    }
12410    *items = remaining;
12411    found
12412}
12413
12414/// Whether any action in the model (recursively) carries `role`.
12415fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
12416    items.iter().any(|it| match it {
12417        day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
12418        day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
12419        day_spec::MenuItem::Separator => false,
12420    })
12421}
12422
12423// ---------------------------------------------------------------------------
12424// Menus (§ menus): render day's MenuItem model with NSMenu. Custom items route to a shared
12425// DayMenuTarget (id in the item's tag → Event::MenuAction); role items use the native selector.
12426// ---------------------------------------------------------------------------
12427
12428define_class!(
12429    #[unsafe(super(NSObject))]
12430    #[thread_kind = MainThreadOnly]
12431    #[name = "DayMenuTarget"]
12432    #[ivars = ()]
12433    struct DayMenuTarget;
12434
12435    unsafe impl NSObjectProtocol for DayMenuTarget {}
12436
12437    impl DayMenuTarget {
12438        #[unsafe(method(fire:))]
12439        fn fire(&self, sender: &NSMenuItem) {
12440            ffi_guard::contain((), || {
12441                let id = sender.tag() as u64;
12442                if id != 0 {
12443                    emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
12444                }
12445            })
12446        }
12447    }
12448);
12449
12450/// The primary window's content view (set once in `run`).
12451/// Pin the window's content coordinate space under its title bar and toolbar (§7.7). The
12452/// content view is full-size (`FullSizeContentView`, for the unified toolbar), so it runs
12453/// beneath the bar; moving its bounds origin up by that strip makes Day's root, laid out from
12454/// (0, 0), start below the bar — the way UIKit pins the root inside `safeAreaInsets` — while
12455/// the view's own background still paints edge to edge. Returns the size Day lays out at, the
12456/// window's `contentLayoutRect`. Called wherever that rect can change: window creation, every
12457/// resize, and a toolbar coming or going.
12458pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
12459    let content = window.contentView()?;
12460    let full = content.frame().size;
12461    let layout = unsafe { window.contentLayoutRect() }.size;
12462    let top = (full.height - layout.height).max(0.0);
12463    // An overlay title bar (docs/window-chrome.md) is the one place the content belongs under
12464    // the bar: it keeps the full height, and the bar's height goes to the app as a safe-area
12465    // inset so it can pad its own content.
12466    if window_chrome::is_overlay(window) {
12467        unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
12468        window_chrome::report_title_bar_inset(window, top);
12469        return Some(Size::new(full.width, full.height));
12470    }
12471    unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
12472    Some(Size::new(full.width, (full.height - top).max(0.0)))
12473}
12474
12475/// The text a widget displays, for `read_native`: a label's or text field's string, a
12476/// button's title, a text area's contents. `None` for a secure field (it masks its text), an
12477/// icon-only button (its title is a tooltip), and every other view.
12478fn native_text(h: &NSView) -> Option<String> {
12479    if h.downcast_ref::<NSSecureTextField>().is_some() {
12480        return None;
12481    }
12482    if let Some(tf) = h.downcast_ref::<NSTextField>() {
12483        // `stringValue` answers the field editor's live text while the field edits.
12484        return Some(tf.stringValue().to_string());
12485    }
12486    if let Some(btn) = h.downcast_ref::<NSButton>() {
12487        if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
12488            return None;
12489        }
12490        return Some(btn.title().to_string());
12491    }
12492    // A text area is an NSTextView inside the scroll view its handle names (textarea.rs).
12493    let sv = h.downcast_ref::<NSScrollView>()?;
12494    let doc = sv.documentView()?;
12495    let tv = doc.downcast_ref::<NSTextView>()?;
12496    Some(tv.string().to_string())
12497}
12498
12499/// A slider's value or a determinate progress bar's fraction, for `read_native`. Both native
12500/// ranges are the ones Day gave: the slider is built with Day's min and max, the bar runs 0–1.
12501fn native_number(h: &NSView) -> Option<f64> {
12502    if let Some(sl) = h.downcast_ref::<NSSlider>() {
12503        return Some(sl.doubleValue());
12504    }
12505    let pi = h.downcast_ref::<NSProgressIndicator>()?;
12506    (!pi.isIndeterminate()).then(|| pi.doubleValue())
12507}
12508
12509/// The view's frame in its window's content coordinates, origin top left, for `read_native`.
12510/// The content view is flipped and pinned below the title bar (`pin_below_title_bar`), so
12511/// converting into it gives Day's layout space; an unflipped content view is flipped here.
12512fn native_frame(h: &NSView) -> Option<Rect> {
12513    let content = h.window()?.contentView()?;
12514    let r = h.convertRect_toView(h.bounds(), Some(&content));
12515    let y = if content.isFlipped() {
12516        r.origin.y
12517    } else {
12518        let b = content.bounds();
12519        b.origin.y + b.size.height - (r.origin.y + r.size.height)
12520    };
12521    Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
12522}
12523
12524/// The strip a pinned content view keeps above its layout origin (see `pin_below_title_bar`).
12525fn title_bar_inset(content: &NSView) -> f64 {
12526    (-content.bounds().origin.y).max(0.0)
12527}
12528
12529fn primary_content() -> Option<Retained<NSView>> {
12530    PRIMARY_CONTENT.with(|c| c.borrow().clone())
12531}
12532
12533fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
12534    MENU_TARGET.with(|t| {
12535        t.borrow_mut()
12536            .get_or_insert_with(|| {
12537                let this = DayMenuTarget::alloc(mtm).set_ivars(());
12538                let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
12539                obj
12540            })
12541            .clone()
12542    })
12543}
12544
12545fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
12546    use objc2_app_kit::NSEventModifierFlags as F;
12547    let mut m = F::empty();
12548    if s.primary {
12549        m |= F::Command;
12550    }
12551    if s.shift {
12552        m |= F::Shift;
12553    }
12554    if s.alt {
12555        m |= F::Option;
12556    }
12557    if s.control {
12558        m |= F::Control;
12559    }
12560    m
12561}
12562
12563/// A shortcut's key-equivalent string. Single chars pass through (lowercased); a few named keys map
12564/// to their control characters. Modifiers ride separately via `setKeyEquivalentModifierMask`.
12565fn ns_key_equivalent(key: &str) -> String {
12566    match key {
12567        "Return" | "Enter" => "\r".into(),
12568        "Tab" => "\t".into(),
12569        "Delete" | "Backspace" => "\u{8}".into(),
12570        "Escape" => "\u{1b}".into(),
12571        "Space" => " ".into(),
12572        k if k.chars().count() == 1 => k.to_lowercase(),
12573        _ => String::new(), // named keys we don't map get no key-equivalent (still shown in menu)
12574    }
12575}
12576
12577/// A standard role → (default label, nav host, default shortcut). Nav host `None` = no native action
12578/// (the app should attach its own via a custom item); the role then only supplies label placement.
12579fn role_spec(
12580    role: day_spec::MenuRole,
12581) -> (
12582    &'static str,
12583    Option<objc2::runtime::Sel>,
12584    Option<day_spec::Shortcut>,
12585) {
12586    use day_spec::MenuRole as R;
12587    use day_spec::Shortcut as S;
12588    match role {
12589        R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
12590        R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
12591        R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
12592        R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
12593        R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
12594        R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
12595        R::Delete => ("Delete", Some(sel!(delete:)), None),
12596        R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
12597        R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
12598        R::Preferences => ("Settings…", None, Some(S::primary(","))),
12599        R::Minimize => (
12600            "Minimize",
12601            Some(sel!(performMiniaturize:)),
12602            Some(S::primary("m")),
12603        ),
12604        R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
12605        R::Fullscreen => (
12606            "Enter Full Screen",
12607            Some(sel!(toggleFullScreen:)),
12608            Some(S::primary("f").control()),
12609        ),
12610        // No native selector (docs/windows.md): the item dispatches the registered
12611        // new-window action through the ordinary custom-item path (`fire:`).
12612        R::NewWindow => ("New Window", None, Some(S::primary("n"))),
12613        // Likewise: no selector, the registered updater action fires through `fire:`.
12614        R::CheckForUpdates => ("Check for Updates…", None, None),
12615    }
12616}
12617
12618pub(crate) fn build_ns_menu(
12619    mtm: MainThreadMarker,
12620    title: &str,
12621    items: &[day_spec::MenuItem],
12622) -> Retained<NSMenu> {
12623    use day_spec::MenuItem as MI;
12624    let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
12625    let target = menu_target(mtm);
12626    for item in items {
12627        match item {
12628            MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
12629            MI::Submenu { label, items, .. } => {
12630                let sub = build_ns_menu(mtm, label, items);
12631                let it = NSMenuItem::new(mtm);
12632                it.setTitle(&NSString::from_str(label));
12633                it.setSubmenu(Some(&sub));
12634                menu.addItem(&it);
12635            }
12636            MI::Action {
12637                action,
12638                label,
12639                shortcut,
12640                enabled,
12641                checked,
12642                role,
12643                icon,
12644                ..
12645            } => {
12646                // Resolve label/nav host/shortcut, folding in the role's native defaults.
12647                let (mut lbl, sel, mut sc) = match role {
12648                    Some(r) => {
12649                        let (dl, ds, dsc) = role_spec(*r);
12650                        (dl.to_string(), ds, dsc)
12651                    }
12652                    None => (String::new(), None, None),
12653                };
12654                if !label.is_empty() {
12655                    lbl = label.clone();
12656                }
12657                if shortcut.is_some() {
12658                    sc = shortcut.clone();
12659                }
12660                // Custom action (nonzero id) overrides any role nav host and targets our
12661                // trampoline — except the responder-routed set (undo pair, clipboard trio),
12662                // whose nonzero ids are only the other platforms' fallback dispatchers: here
12663                // the nil-target nav hosts must stay, so the responder chain resolves the
12664                // acting object (a focused text field before the app's bridge).
12665                let responder_role = matches!(
12666                    role,
12667                    Some(
12668                        day_spec::MenuRole::Undo
12669                            | day_spec::MenuRole::Redo
12670                            | day_spec::MenuRole::Cut
12671                            | day_spec::MenuRole::Copy
12672                            | day_spec::MenuRole::Paste
12673                            | day_spec::MenuRole::SelectAll
12674                    )
12675                );
12676                let custom = *action != 0 && !responder_role;
12677                let key = sc
12678                    .as_ref()
12679                    .map(|s| ns_key_equivalent(&s.key))
12680                    .unwrap_or_default();
12681                let it = unsafe {
12682                    NSMenuItem::initWithTitle_action_keyEquivalent(
12683                        NSMenuItem::alloc(mtm),
12684                        &NSString::from_str(&lbl),
12685                        if custom { Some(sel!(fire:)) } else { sel },
12686                        &NSString::from_str(&key),
12687                    )
12688                };
12689                if let Some(s) = &sc {
12690                    it.setKeyEquivalentModifierMask(ns_modifiers(s));
12691                    // AppKit's own per-layout/per-language adjustments (macOS 12+): remap a
12692                    // key equivalent the current keyboard layout cannot type, and MIRROR
12693                    // directional pairs (⌘[ / ⌘]) under RTL languages — the system half of
12694                    // shortcut localization; the catalog half is the `.key` attribute
12695                    // (docs/localization.md).
12696                    it.setAllowsAutomaticKeyEquivalentLocalization(true);
12697                    it.setAllowsAutomaticKeyEquivalentMirroring(true);
12698                }
12699                if custom {
12700                    let tobj: &objc2::runtime::AnyObject = target.as_ref();
12701                    unsafe { it.setTarget(Some(tobj)) };
12702                    it.setTag(*action as isize);
12703                }
12704                it.setEnabled(*enabled);
12705                // A checkable item takes NSMenuItem's own state, so macOS draws the ✓ it draws
12706                // everywhere else and reserves the mark's column when it is off (docs/menus.md).
12707                if let Some(on) = checked {
12708                    it.setState(if *on {
12709                        NSControlStateValueOn
12710                    } else {
12711                        NSControlStateValueOff
12712                    });
12713                }
12714                // The item's glyph, drawn the way NSMenuItem draws its own (docs/menus.md):
12715                // template-tinted, sized to the menu's text.
12716                if let Some(icon) = icon
12717                    && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
12718                {
12719                    img.setSize(NSSize::new(16.0, 16.0));
12720                    it.setImage(Some(&img));
12721                }
12722                menu.addItem(&it);
12723            }
12724        }
12725    }
12726    menu
12727}
12728
12729// AppKit's TLS may be destroyed before the reactive arena drops its last Bitmap.
12730// The registry already released the native images in that case.
12731fn release_bitmap(id: day_spec::BitmapId) {
12732    let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
12733}
12734
12735#[cfg(test)]
12736mod bitmap_teardown_tests {
12737    use super::*;
12738
12739    #[test]
12740    fn releasing_after_bitmap_registry_teardown_does_not_abort() {
12741        // Isolate destructor panics: Rust aborts the process when a TLS destructor unwinds.
12742        const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
12743        if std::env::var_os(CHILD).is_some() {
12744            struct LateRelease;
12745            impl Drop for LateRelease {
12746                fn drop(&mut self) {
12747                    assert!(BITMAPS.try_with(|_| ()).is_err());
12748                    // Same duty called by Bitmap::drop; no NSApplication is needed.
12749                    release_bitmap(day_spec::BitmapId(1));
12750                }
12751            }
12752            std::thread_local! {
12753                static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
12754            }
12755            std::thread::spawn(|| {
12756                LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
12757                BITMAPS.with(|_| ()); // initialized last, destroyed first
12758            })
12759            .join()
12760            .unwrap();
12761            return;
12762        }
12763        let output = std::process::Command::new(std::env::current_exe().unwrap())
12764            .args([
12765                "--exact",
12766                "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
12767                "--nocapture",
12768            ])
12769            .env(CHILD, "1")
12770            .output()
12771            .unwrap();
12772        assert!(
12773            output.status.success(),
12774            "{}",
12775            String::from_utf8_lossy(&output.stderr)
12776        );
12777    }
12778}