Skip to main content

day_toolkit_appkit/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-toolkit-appkit: the macos-appkit backend (DESIGN.md §9). objc2, pure Rust, no shim.
5//!
6//! `Handle = Retained<NSView>`. Containers are flipped `NSView`s (top-left origin, so Day's
7//! frames apply directly and survive diffing). One custom target class (`DayTarget`) forwards
8//! target/action + text-delegate callbacks into the Day event sink, node-id keyed (§8.3).
9
10#![allow(unused_unsafe)]
11#![cfg(target_os = "macos")]
12
13mod controls;
14
15mod applications;
16mod nav_progress;
17
18use std::any::Any;
19use std::cell::{Cell, RefCell};
20use std::collections::HashMap;
21use std::rc::Rc;
22
23use linkme::distributed_slice;
24use objc2::Message as _;
25use objc2::rc::Retained;
26use objc2::runtime::{AnyObject, NSObjectProtocol, ProtocolObject, Sel};
27use objc2::{
28    AllocAnyThread, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel,
29};
30use objc2_app_kit::NSAccessibility as _;
31use objc2_app_kit::NSAppearanceCustomization as _;
32use objc2_app_kit::NSDraggingInfo as _;
33use objc2_app_kit::NSSplitViewDelegate;
34use objc2_app_kit::NSTextContent as _;
35use objc2_app_kit::NSTextInputClient;
36use objc2_app_kit::NSUserInterfaceItemIdentification as _;
37use objc2_app_kit::{
38    NSAffineTransformNSAppKitAdditions, NSClickGestureRecognizer, NSGestureRecognizer,
39    NSGestureRecognizerState, NSPanGestureRecognizer, NSPasteboard,
40};
41use objc2_app_kit::{
42    NSAnimationContext, NSApplication, NSApplicationActivationPolicy, NSBackingStoreType,
43    NSBitmapImageFileType, NSBox, NSBoxType, NSButton, NSColor, NSControl, NSControlStateValueOff,
44    NSControlStateValueOn, NSControlTextEditingDelegate, NSCursor, NSCursorFrameResizeDirections,
45    NSCursorFrameResizePosition, NSEvent, NSEventModifierFlags, NSEventType, NSFont,
46    NSGraphicsContext, NSLineBreakMode, NSMenu, NSMenuItem, NSProgressIndicator,
47    NSProgressIndicatorStyle, NSResponder, NSScrollView, NSSecureTextField, NSSlider, NSSwitch,
48    NSTabViewDelegate, NSText, NSTextField, NSTextFieldDelegate, NSTextMovement,
49    NSTextMovementUserInfoKey, NSTrackingArea, NSTrackingAreaOptions, NSView, NSWindow,
50    NSWindowDelegate, NSWindowStyleMask,
51};
52use objc2_app_kit::{
53    NSApplicationDidBecomeActiveNotification, NSApplicationWillResignActiveNotification,
54    NSApplicationWillTerminateNotification,
55};
56use objc2_app_kit::{
57    NSOutlineViewDataSource, NSOutlineViewDelegate, NSTextDelegate, NSTextView, NSTextViewDelegate,
58};
59use objc2_app_kit::{NSTableColumn, NSTableView, NSTableViewDataSource, NSTableViewDelegate};
60use objc2_core_foundation::CGAffineTransform;
61use objc2_foundation::{
62    NSAffineTransform, NSAffineTransformStruct, NSArray, NSData, NSDictionary, NSNotification,
63    NSNumber, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString,
64};
65use objc2_quartz_core::{
66    CAMediaTimingFunction, CATransaction, kCAMediaTimingFunctionEaseIn,
67    kCAMediaTimingFunctionEaseInEaseOut, kCAMediaTimingFunctionEaseOut,
68    kCAMediaTimingFunctionLinear,
69};
70
71use day_spec::ffi_guard;
72use day_spec::present;
73use day_spec::props::*;
74use day_spec::sidetable::SideTable;
75use day_spec::{
76    A11yProps, AnimSpec, Builtin, Cap, Cursor, Curve, DrawOp, Event, EventSink, Font, InputPurpose,
77    InputTraits, ListSource, MoveVerdict, NodeId, PieceKind, Platform, Point, Proposal, RawHandle,
78    Rect, Registry, Renderer, Size, Support, Toolkit, Transform, TreeSource, WINDOW_NODE,
79    WindowOptions, kinds, props_of,
80};
81
82pub type Handle = Retained<NSView>;
83
84/// Icon resolution for a piece renderer's own `NSToolbar` items (see `toolbar::image_for`).
85pub use toolbar::image_for as toolbar_image;
86
87// Built-in leaf pieces split into modules (moved in from their satellite crates 2026-07).
88mod dock;
89mod documents;
90mod frame;
91mod picker;
92mod status_item;
93mod textarea;
94mod toolbar;
95mod transfer;
96mod window_chrome;
97use objc2_app_kit::NSDraggingSource;
98
99pub mod ext;
100pub use ext::*;
101
102// ---------------------------------------------------------------------------
103// Event plumbing: node-id keyed sink, thread-local (single UI thread)
104// ---------------------------------------------------------------------------
105
106/// The day-core event sink (node-id keyed).
107type Sink = Rc<dyn Fn(NodeId, Event)>;
108
109day_core::tls_group! {
110    static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
111    /// Keeps each control's `DayTarget` alive (target/action holds it weakly).
112    static TARGETS: RefCell<HashMap<usize, Retained<DayTarget>>> = RefCell::new(HashMap::new());
113    /// The style each button currently carries, keyed by its view pointer.
114    ///
115    /// Needed because a tinted title is an attributed string (see `set_button_title`), and
116    /// `ButtonPatch::Title` would otherwise replace it with a plain one and lose the color.
117    static BUTTON_STYLES: RefCell<HashMap<usize, day_spec::props::ButtonStyleSpec>> =
118        RefCell::new(HashMap::new());
119    /// Original template images, retained across tint changes and swept on view release.
120    static BUTTON_IMAGES: SideTable<Retained<objc2_app_kit::NSImage>> = SideTable::new();
121    /// Each button's selected state (`ButtonProps::selected`), keyed by its view pointer: what
122    /// the `action:` handler restores after a click toggles a push-on/push-off button, and the
123    /// buttons whose `state` `read_native` reports as `checked`.
124    static BUTTON_SELECTED: RefCell<HashMap<usize, bool>> = RefCell::new(HashMap::new());
125
126    /// Canvas ptr → its display list. A [`SideTable`], so the release sweep reclaims it
127    /// (replay inserted but nothing ever removed).
128    static OPS: SideTable<Vec<DrawOp>> = SideTable::new();
129    /// Views the app gave an accessibility label (`set_a11y`): a button's title change must then
130    /// leave the label alone (`apply_button_content`). Swept on release like the other tables.
131    static APP_LABELED: SideTable<()> = SideTable::new();
132    /// How each image view renders its glyph (docs/vectors.md "Tint", "Template"): whether it
133    /// was realized as a template, and whether a tint is on it now. Template rendering is a
134    /// property of the NSImage, so a source swap has to re-apply it, and a tint patch of `None`
135    /// keeps a template in the neutral tint rather than returning to the authored art. Swept
136    /// on release.
137    static IMAGE_MODES: SideTable<ImageMode> = SideTable::new();
138    /// Each transformed view's `Transform` (`set_transform`). AppKit owns a layer-backed view's
139    /// layer geometry and re-syncs it from the view, so a transform written into the layer
140    /// never showed. It is expressed in the view's own geometry instead (`apply_geometry`).
141    static TRANSFORMS: SideTable<Transform> = SideTable::new();
142    /// Each view's frame as Day laid it out, before any translation, so a translation change can
143    /// move the view without waiting for the next layout.
144    static BASE_FRAMES: SideTable<[f64; 4]> = SideTable::new();
145    static COVER_SHEETS: SideTable<CoverSheet> = SideTable::new();
146    /// A presented cover sheet's window → its cover node, for Escape (docs/cover.md).
147    static SHEET_NODES: SideTable<NodeId> = SideTable::new();
148    static SHEET_ESCAPE_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
149    /// View ptr → node for `GestureKind::Pan` (docs/shapes.md): macOS pans arrive as trackpad
150    /// scroll events, so `DayCanvas::scrollWheel:` reports them here instead of a recognizer.
151    static PAN_NODES: SideTable<NodeId> = SideTable::new();
152    static PAN_MONITOR: RefCell<Option<PanMonitor>> = const { RefCell::new(None) };
153    /// View ptr → node for `GestureKind::Hover` (docs/canvas.md "Interaction"). Hover is not a
154    /// recognizer on macOS either: it is an `NSTrackingArea` plus the three mouse methods, so
155    /// like [`PAN_NODES`] this holds the canvases that asked and `DayCanvas` reports for them.
156    static HOVER_NODES: SideTable<NodeId> = SideTable::new();
157    /// View ptr → node for `GestureKind::Rotate` (docs/canvas.md "Zoom and pan"). A trackpad
158    /// rotation arrives as `NSEventTypeRotate` events at the view under it, alongside the
159    /// magnify events the pinch recognizer reads, so `DayCanvas::rotateWithEvent:` reports
160    /// it and the two gestures run at once rather than competing as two recognizers would.
161    static ROTATE_NODES: SideTable<NodeId> = SideTable::new();
162    /// Canvas view ptr → the rotation accumulated since the trackpad gesture's `Began`, in
163    /// radians: the events carry per-event degrees, and Day's contract is cumulative.
164    static ROTATE_ANGLE: SideTable<f64> = SideTable::new();
165    /// Canvas view ptr → its node, so the view's own `keyDown:` knows who to report to. Every
166    /// canvas is registered at realize (unlike [`PAN_NODES`], which only holds the ones that
167    /// asked for a pan) because focus, not a gesture, is what decides who hears a key.
168    static KEY_NODES: SideTable<NodeId> = SideTable::new();
169    /// Focusable container view ptr → its node (docs/focus.md): `Decorate::focusable` opts a
170    /// `DayFlipped` into the canvas contract (accepts first responder, takes focus on a
171    /// press, reports both directions, hears the arrows). Empty for every container that
172    /// never asked, whose behavior is exactly as before.
173    static FOCUSABLE_NODES: SideTable<NodeId> = SideTable::new();
174    /// Canvas view ptr → the text an input method is still composing in it (docs/menus.md
175    /// "The full route"): a dead key's accent, a Japanese reading. Nothing reaches the app
176    /// until the input method commits; the entry is gone the moment it does or cancels.
177    static MARKED: SideTable<String> = SideTable::new();
178    /// The key press the text input system is interpreting right now: its unmodified name and
179    /// the modifier mask, so the text it commits is named by the key that typed it.
180    static INTERPRETING: RefCell<Option<(String, u8)>> = const { RefCell::new(None) };
181
182    /// Keeps each view's gesture targets alive + records which gestures are attached (idempotent).
183    static GESTURES: RefCell<HashMap<usize, Vec<Retained<DayGesture>>>> =
184        RefCell::new(HashMap::new());
185
186    static NAV_STATE: RefCell<HashMap<usize, NavState>> = RefCell::new(HashMap::new());
187    /// Handles whose frames are native-owned (nav pages): set_frame skips them.
188    static NAV_PAGES: RefCell<std::collections::HashSet<usize>> =
189        RefCell::new(std::collections::HashSet::new());
190    /// Each nav page's pane, recorded at realize because `insert` sees only handles
191    /// (docs/size-classes.md). Identity rather than position: a re-present re-homes the pages
192    /// without changing their order, so "index 0 is the sidebar" stops being true the moment a
193    /// host can morph. A [`SideTable`]: `remove` clears it on the normal path, and the release
194    /// sweep catches a page released without one (a stale entry could mis-pane a recycled ptr).
195    static PAGE_PANE: SideTable<day_spec::props::Pane> = SideTable::new();
196
197    static INSPECTOR_STATE: RefCell<HashMap<usize, InspectorState>> = RefCell::new(HashMap::new());
198    /// INSPECTOR_PANE ptr → is-panel, recorded at realize because `insert` sees only handles.
199    /// A [`SideTable`]: the release sweep drops it with the view.
200    static INSPECTOR_PANES: SideTable<bool> = SideTable::new();
201
202    /// Split host (the wrap around an `NSSplitView`, docs/split.md) ptr → its state.
203    static SPLIT_STATE: RefCell<HashMap<usize, SplitState>> = RefCell::new(HashMap::new());
204    /// SPLIT_PANE ptr → is-second, recorded at realize because `insert` sees only handles.
205    static SPLIT_PANES: SideTable<bool> = SideTable::new();
206
207    /// Outline ptr → its data source, for [`DayNavOutlineView::menu_for_event`]'s row lookup.
208    /// A [`SideTable`], reclaimed by the outline-keyed auxiliary sweep in `release`: the entry
209    /// used to outlive its host, so a recycled outline address served the dead menu's rows.
210    static NAV_OUTLINE_MENUS: SideTable<Retained<DayNavMenuData>> = SideTable::new();
211
212    static LIST_STATE: RefCell<HashMap<usize, ListEntry>> = RefCell::new(HashMap::new());
213    /// Tree host scroll-view ptr → (outline, data source) (docs/tree.md).
214    static TREE_STATE: RefCell<HashMap<usize, TreeEntry>> = RefCell::new(HashMap::new());
215
216    /// `BitmapId` → the decoded image (docs/images.md). Keyed by the id day-core minted, not by
217    /// a view pointer: a bitmap outlives any one view and may be drawn by several at once.
218    /// Entries leave only through `release_image`, which day-core calls when the app drops its
219    /// last `Bitmap` handle.
220    static BITMAPS: RefCell<HashMap<u64, AppKitBitmap>> = RefCell::new(HashMap::new());
221    /// The fonts a painting thread's text ops resolve to, keyed by (size bits, font): filled
222    /// by [`OffscreenResources`] for one export at a time (docs/canvas.md "Exporting"), since
223    /// `NSFontManager` belongs to the UI thread. Empty on the UI thread itself.
224    static OFFSCREEN_FONTS: RefCell<Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>> =
225        const { RefCell::new(Vec::new()) };
226    /// View ptr → its summon-time context-menu provider (docs/menus.md). Swept on release
227    /// via `day_spec::sidetable`.
228    static CTX_MENU_FNS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
229    /// Menu button ptr → the provider its press opens (`set_button_menu`, docs/menus.md "Menu
230    /// buttons"). Swept on release like `CTX_MENU_FNS`.
231    static BUTTON_MENUS: SideTable<day_spec::ContextMenuFn> = SideTable::new();
232
233    /// NAV_MENU scroll-view ptr → (outline, data source) for patches and measure.
234    static NAV_MENUS: RefCell<HashMap<usize, NavMenuEntry>> = RefCell::new(HashMap::new());
235
236    /// The app's edit-bridge state (`set_edit_state`), which validateMenuItem consults.
237    static EDIT_STATE: std::cell::Cell<day_spec::EditState> =
238        const { std::cell::Cell::new(day_spec::EditState { can_cut: false, can_copy: false, can_paste: false, can_select_all: false }) };
239    static UNDO_FRONT: std::cell::RefCell<Option<Retained<DayUndoManager>>> =
240        const { std::cell::RefCell::new(None) };
241
242    /// Live modal sheets keyed by request id (for programmatic dismissal).
243    static PRESENT_ALERTS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSAlert>>> =
244        RefCell::new(HashMap::new());
245    /// Live file-picker sheets (NSOpenPanel is stored via its NSSavePanel supertype).
246    static PRESENT_PANELS: RefCell<HashMap<u64, Retained<objc2_app_kit::NSSavePanel>>> =
247        RefCell::new(HashMap::new());
248
249    // NSMenuItem does not retain its target, so one shared target is kept alive for the app's
250    // lifetime.
251    static MENU_TARGET: std::cell::RefCell<Option<Retained<DayMenuTarget>>> =
252        const { std::cell::RefCell::new(None) };
253    /// The primary window's content view, for call sites without backend access that must
254    /// address the main window specifically (cover re-homing, DAY_DUMP). With secondary
255    /// windows open, `app.windows().firstObject()` is arbitrary (docs/windows.md).
256    static PRIMARY_CONTENT: std::cell::RefCell<Option<Retained<NSView>>> =
257        const { std::cell::RefCell::new(None) };
258
259}
260
261/// Emit an event into day-core's queue (public: external Day Piece renderers use this too).
262pub fn emit(id: NodeId, ev: Event) {
263    let sink = SINK.with(|s| s.borrow().clone());
264    if let Some(sink) = sink {
265        sink(id, ev);
266    }
267}
268
269fn ptr_of(v: &NSView) -> usize {
270    (v as *const NSView).cast::<()>() as usize
271}
272
273/// Open a menu button's menu under it (docs/menus.md "Menu buttons"): asks the provider now, so
274/// the entries are the current ones, and pops the `NSMenu` from the button's bottom-leading
275/// corner, the place a pull-down `NSPopUpButton` puts its menu. The button stays highlighted
276/// while the menu tracks, as a pressed pull-down does. Guarded: the provider is app code.
277fn pop_button_menu(btn: &NSButton, f: &day_spec::ContextMenuFn) {
278    ffi_guard::contain((), || {
279        // The provider may remove this button; then no menu opens (docs/menus.md).
280        let key = ptr_of(btn);
281        let Some(items) =
282            day_spec::resolve_button_menu(f, || BUTTON_MENUS.with(|t| t.get(key)).is_some())
283        else {
284            return;
285        };
286        let menu = build_ns_menu(btn.mtm(), "", &items);
287        let bounds = btn.bounds();
288        let y = if btn.isFlipped() {
289            bounds.size.height + 2.0
290        } else {
291            -2.0
292        };
293        unsafe {
294            btn.highlight(true);
295            // Modal until the menu closes; a chosen item has queued its `MenuAction` by then.
296            menu.popUpMenuPositioningItem_atLocation_inView(
297                None,
298                objc2_foundation::NSPoint::new(0.0, y),
299                Some(btn),
300            );
301            btn.highlight(false);
302        }
303    });
304}
305
306/// An image view's rendering (`IMAGE_MODES`).
307#[derive(Clone, Copy)]
308struct ImageMode {
309    template: bool,
310    tinted: bool,
311}
312
313impl ImageMode {
314    /// Template rendering: the glyph's alpha as a mask, filled with the tint or the neutral
315    /// template color.
316    fn renders_template(self) -> bool {
317        self.template || self.tinted
318    }
319}
320
321/// A decoded bitmap (docs/images.md), held until day-core drops its last handle.
322///
323/// The `NSBitmapImageRep` is kept beside the image rather than fetched on demand for two
324/// reasons: it is the only thing here that can re-encode to other formats, and it is the only
325/// accurate source of pixel dimensions, since `NSImage.size` is in points and reports a @2x
326/// asset at half its real width.
327struct AppKitBitmap {
328    image: Retained<objc2_app_kit::NSImage>,
329    rep: Option<Retained<objc2_app_kit::NSBitmapImageRep>>,
330    info: day_spec::BitmapInfo,
331}
332
333/// Draw a decoded image into a fresh bitmap `scale`× its pixel size, for [`day_spec::EncodeSpec`]'s
334/// `fit`.
335///
336/// 8 bits across 4 samples with alpha is the one layout every writer here accepts, and the only
337/// one that carries transparency through a PNG round-trip intact.
338fn scaled_rep(
339    image: &objc2_app_kit::NSImage,
340    pixels: Size,
341    scale: f64,
342) -> Option<Retained<objc2_app_kit::NSBitmapImageRep>> {
343    use objc2::AllocAnyThread as _;
344    let w = (pixels.width * scale).round().max(1.0);
345    let h = (pixels.height * scale).round().max(1.0);
346    let rep = unsafe {
347        objc2_app_kit::NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
348            objc2_app_kit::NSBitmapImageRep::alloc(),
349            std::ptr::null_mut(),
350            w as isize,
351            h as isize,
352            8,
353            4,
354            true,
355            false,
356            objc2_app_kit::NSDeviceRGBColorSpace,
357            0,
358            0,
359        )
360    }?;
361    let ctx = objc2_app_kit::NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep)?;
362    NSGraphicsContext::saveGraphicsState_class();
363    objc2_app_kit::NSGraphicsContext::setCurrentContext(Some(&ctx));
364    unsafe {
365        image.drawInRect_fromRect_operation_fraction(
366            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(w, h)),
367            NSRect::ZERO,
368            objc2_app_kit::NSCompositingOperation::SourceOver,
369            1.0,
370        );
371    }
372    NSGraphicsContext::restoreGraphicsState_class();
373    Some(rep)
374}
375
376/// Re-encode a decoded bitmap (docs/images.md).
377///
378/// A free function rather than the duty's body so each refusal reads as an early return instead
379/// of another copy of the same emit.
380fn encode_bitmap(
381    id: day_spec::BitmapId,
382    spec: &day_spec::EncodeSpec,
383) -> Result<Vec<u8>, day_spec::ImageError> {
384    use day_spec::ImageFormat as F;
385    use objc2_app_kit::NSBitmapImageFileType as T;
386    let file_type = match spec.format {
387        F::Png => T::PNG,
388        F::Jpeg => T::JPEG,
389        F::Tiff => T::TIFF,
390        F::Bmp => T::BMP,
391        F::Gif => T::GIF,
392        // Readable here but not writable: `NSBitmapImageRep` ships no WebP or HEIF writer. That
393        // asymmetry is why `encode_formats` exists instead of letting `Cap::ImageEncode` imply
394        // that everything decodable is also encodable.
395        _ => return Err(day_spec::ImageError::Encode),
396    };
397    let held = BITMAPS.with(|m| {
398        m.borrow()
399            .get(&id.0)
400            .map(|b| (b.rep.clone(), b.image.clone(), b.info))
401    });
402    let (rep, image, info) = held.ok_or(day_spec::ImageError::Gone)?;
403    let rep = rep.ok_or(day_spec::ImageError::Encode)?;
404
405    // `fit` scales the longest side down first. A box larger than the original is ignored:
406    // upscaling on an export path inflates the bytes without adding any detail.
407    let rep = match spec.fit {
408        Some(fit) if info.pixels.width > 0.0 && info.pixels.height > 0.0 => {
409            let scale = (fit.width / info.pixels.width)
410                .min(fit.height / info.pixels.height)
411                .min(1.0);
412            if scale < 1.0 {
413                scaled_rep(&image, info.pixels, scale).ok_or(day_spec::ImageError::Encode)?
414            } else {
415                rep
416            }
417        }
418        _ => rep,
419    };
420
421    let props: Retained<NSDictionary<NSString, objc2::runtime::AnyObject>> = match spec.quality {
422        // AppKit's own compression-factor property; a lossless writer ignores it.
423        Some(q) => {
424            let key: &NSString = unsafe { objc2_app_kit::NSImageCompressionFactor };
425            let number = NSNumber::new_f64(q.clamp(0.0, 1.0));
426            let value: &objc2::runtime::AnyObject = &number;
427            NSDictionary::from_slices::<NSString>(&[key], &[value])
428        }
429        None => NSDictionary::new(),
430    };
431    let data = unsafe { rep.representationUsingType_properties(file_type, &props) }
432        .ok_or(day_spec::ImageError::Encode)?;
433    Ok(data.to_vec())
434}
435
436/// Replay a display list into the current graphics context. The one painter both the on-screen
437/// `DayCanvas` (its `drawRect:`) and the canvas exports run, so the two cannot drift apart
438/// (docs/canvas.md "Exporting").
439fn paint_ops(ops: &[DrawOp]) {
440    // SAFETY: reading the current graphics context on the thread that set it.
441    let cg = unsafe { NSGraphicsContext::currentContext().map(|c| c.CGContext()) };
442    let Some(cg) = cg else {
443        for op in ops {
444            draw_op(op);
445        }
446        return;
447    };
448    cg_begin_replay(&cg);
449    for op in ops {
450        if !cg_fast_op(&cg, op) {
451            draw_op(op);
452        }
453    }
454}
455
456/// Paint one op straight into the Core Graphics context when it is a solid fill, a solid
457/// stroke or a clip of a shape the context can take as path calls, and say whether it did.
458/// This is the hot path of a dense drawing (a map tile is a few thousand of these), and the
459/// path object route below it costs an order of magnitude more: every `NSBezierPath` is an
460/// allocation and a message per segment, and its fill or stroke re-derives the graphics state
461/// the context already holds. Everything else (text, images, gradients, stamps, rounded rects
462/// and arcs) keeps the full painter. The fill and stroke color spaces are set to sRGB once per
463/// replay by `cg_begin_replay`, so the components here read as the ones `nscolor` would make.
464fn cg_fast_op(cg: &objc2_core_graphics::CGContext, op: &DrawOp) -> bool {
465    use objc2_core_graphics::{CGContext, CGImage};
466    match op {
467        DrawOp::Fill(shape, day_spec::Paint::Solid(color)) => {
468            let Some(even_odd) = cg_add_shape(cg, shape) else {
469                return false;
470            };
471            let c = [color.r, color.g, color.b, color.a];
472            // SAFETY: four components for the sRGB fill space set at the start of the replay.
473            unsafe { CGContext::set_fill_color(Some(cg), c.as_ptr()) };
474            if even_odd {
475                CGContext::eo_fill_path(Some(cg));
476            } else {
477                CGContext::fill_path(Some(cg));
478            }
479            true
480        }
481        DrawOp::Stroke(shape, day_spec::Paint::Solid(color), style) => {
482            if cg_add_shape(cg, shape).is_none() {
483                return false;
484            }
485            let c = [color.r, color.g, color.b, color.a];
486            // SAFETY: four components for the sRGB stroke space set at the start of the replay.
487            unsafe { CGContext::set_stroke_color(Some(cg), c.as_ptr()) };
488            cg_stroke_style(cg, style);
489            CGContext::stroke_path(Some(cg));
490            true
491        }
492        DrawOp::Clip(shape) => {
493            let Some(even_odd) = cg_add_shape(cg, shape) else {
494                return false;
495            };
496            if even_odd {
497                CGContext::eo_clip(Some(cg));
498            } else {
499                CGContext::clip(Some(cg));
500            }
501            true
502        }
503        DrawOp::Image {
504            image,
505            rect,
506            opacity,
507            source,
508        } => {
509            // The bitmap's pixels straight to the context (`drawInRect:` on the image object
510            // costs tens of microseconds per call, and a pattern fill is hundreds of copies).
511            let Some((cg_image, pixels)) = BITMAPS.with(|m| {
512                m.borrow().get(&image.0).and_then(|b| {
513                    // SAFETY: reading the rep's immutable CGImage on the thread holding it.
514                    let cg = unsafe { b.rep.as_ref()?.CGImage() }?;
515                    Some((cg, b.info.pixels))
516                })
517            }) else {
518                return false;
519            };
520            // A region is in the bitmap's pixels with a top-left origin, which is also how
521            // `CGImageCreateWithImageInRect` counts; the shared clamp keeps its mapping into
522            // `rect` when it overhangs the bitmap.
523            let (cropped, dest) = match source {
524                None => (None, *rect),
525                Some(src) => {
526                    let Some((src, dest)) = day_spec::clamp_image_source(*src, *rect, pixels)
527                    else {
528                        return true;
529                    };
530                    let crop = CGImage::with_image_in_rect(
531                        Some(&cg_image),
532                        NSRect::new(
533                            NSPoint::new(src.origin.x, src.origin.y),
534                            NSSize::new(src.size.width, src.size.height),
535                        ),
536                    );
537                    let Some(crop) = crop else {
538                        return true;
539                    };
540                    (Some(crop), dest)
541                }
542            };
543            if dest.size.width <= 0.0 || dest.size.height <= 0.0 {
544                return true;
545            }
546            // The canvas is y-down and `CGContextDrawImage` puts the image's first row at the
547            // TOP of `rect` only in a y-up space, so the image is drawn through a local flip.
548            CGContext::save_g_state(Some(cg));
549            CGContext::set_alpha(Some(cg), opacity.clamp(0.0, 1.0));
550            CGContext::translate_ctm(Some(cg), dest.origin.x, dest.origin.y + dest.size.height);
551            CGContext::scale_ctm(Some(cg), 1.0, -1.0);
552            CGContext::draw_image(
553                Some(cg),
554                NSRect::new(
555                    NSPoint::new(0.0, 0.0),
556                    NSSize::new(dest.size.width, dest.size.height),
557                ),
558                Some(cropped.as_deref().unwrap_or(&cg_image)),
559            );
560            CGContext::restore_g_state(Some(cg));
561            true
562        }
563        _ => false,
564    }
565}
566
567/// Begin a replay on `cg`: fill and stroke colors are given as sRGB components from here on.
568fn cg_begin_replay(cg: &objc2_core_graphics::CGContext) {
569    use objc2_core_graphics::{CGColorSpace, CGContext};
570    // SAFETY: `kCGColorSpaceSRGB` is an immutable CFString constant.
571    let srgb = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }));
572    CGContext::set_fill_color_space(Some(cg), srgb.as_deref());
573    CGContext::set_stroke_color_space(Some(cg), srgb.as_deref());
574}
575
576/// Add `shape` as the context's current path and say whether it fills even-odd, or `None` for
577/// a shape that takes the path object route (a rounded rect or an arc).
578fn cg_add_shape(cg: &objc2_core_graphics::CGContext, shape: &day_spec::Shape) -> Option<bool> {
579    use day_spec::{PathSeg, Shape};
580    use objc2_core_graphics::CGContext;
581    CGContext::begin_path(Some(cg));
582    match shape {
583        Shape::Rect(r) => CGContext::add_rect(Some(cg), ns_rect(*r)),
584        Shape::Ellipse(r) => CGContext::add_ellipse_in_rect(Some(cg), ns_rect(*r)),
585        Shape::Line(a, b) => {
586            CGContext::move_to_point(Some(cg), a.x, a.y);
587            CGContext::add_line_to_point(Some(cg), b.x, b.y);
588        }
589        Shape::Polygon(pts) => {
590            let (first, rest) = pts.split_first()?;
591            if rest.is_empty() {
592                return None;
593            }
594            CGContext::move_to_point(Some(cg), first.x, first.y);
595            for p in rest {
596                CGContext::add_line_to_point(Some(cg), p.x, p.y);
597            }
598            CGContext::close_path(Some(cg));
599        }
600        Shape::Path(path) => {
601            if path.segs.is_empty() {
602                return None;
603            }
604            for seg in &path.segs {
605                match seg {
606                    PathSeg::Move(a) => CGContext::move_to_point(Some(cg), a.x, a.y),
607                    PathSeg::Line(a) => CGContext::add_line_to_point(Some(cg), a.x, a.y),
608                    PathSeg::Quad(c, a) => {
609                        CGContext::add_quad_curve_to_point(Some(cg), c.x, c.y, a.x, a.y)
610                    }
611                    PathSeg::Cubic(c1, c2, a) => {
612                        CGContext::add_curve_to_point(Some(cg), c1.x, c1.y, c2.x, c2.y, a.x, a.y)
613                    }
614                    PathSeg::Close => CGContext::close_path(Some(cg)),
615                }
616            }
617            return Some(path.rule == day_spec::FillRule::EvenOdd);
618        }
619        Shape::RoundedRect(..) | Shape::Arc { .. } => return None,
620    }
621    Some(false)
622}
623
624/// Put a [`day_spec::StrokeStyle`] on the context. Every field is set, because the graphics
625/// state keeps the previous stroke's cap, join and dash and a plain stroke must not inherit
626/// them.
627fn cg_stroke_style(cg: &objc2_core_graphics::CGContext, style: &day_spec::StrokeStyle) {
628    use day_spec::{LineCap, LineJoin};
629    use objc2_core_graphics::{CGContext, CGLineCap, CGLineJoin};
630    CGContext::set_line_width(Some(cg), style.width);
631    CGContext::set_line_cap(
632        Some(cg),
633        match style.cap {
634            LineCap::Butt => CGLineCap::Butt,
635            LineCap::Round => CGLineCap::Round,
636            LineCap::Square => CGLineCap::Square,
637        },
638    );
639    CGContext::set_line_join(
640        Some(cg),
641        match style.join {
642            LineJoin::Miter => CGLineJoin::Miter,
643            LineJoin::Round => CGLineJoin::Round,
644            LineJoin::Bevel => CGLineJoin::Bevel,
645        },
646    );
647    CGContext::set_miter_limit(Some(cg), style.miter_limit);
648    if style.dash.is_empty() {
649        // SAFETY: a null pattern with a zero count clears the dash, per the CGContext docs.
650        unsafe { CGContext::set_line_dash(Some(cg), 0.0, core::ptr::null(), 0) };
651    } else {
652        let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.clone();
653        // SAFETY: `pattern` outlives the call, and `count` is its length.
654        unsafe {
655            CGContext::set_line_dash(Some(cg), style.dash_phase, pattern.as_ptr(), pattern.len())
656        };
657    }
658}
659
660/// Paint `ops` into `cg` with a top-left origin and y down, as the flipped `DayCanvas` sees
661/// them. `height` is the context's own height in its base units (pixels for a bitmap, points for
662/// a PDF page) and `scale` its units per canvas point.
663///
664/// The CTM flip turns the geometry the right way up; wrapping the context as a FLIPPED
665/// `NSGraphicsContext` is what tells AppKit's text and image drawing to keep glyphs and pictures
666/// upright inside that flip, exactly as they are in a flipped view's `drawRect:`.
667fn paint_flipped(cg: &objc2_core_graphics::CGContext, height: f64, scale: f64, ops: &[DrawOp]) {
668    use objc2_core_graphics::CGContext;
669    CGContext::save_g_state(Some(cg));
670    CGContext::translate_ctm(Some(cg), 0.0, height);
671    CGContext::scale_ctm(Some(cg), scale, -scale);
672    let ns = NSGraphicsContext::graphicsContextWithCGContext_flipped(cg, true);
673    NSGraphicsContext::saveGraphicsState_class();
674    NSGraphicsContext::setCurrentContext(Some(&ns));
675    paint_ops(ops);
676    NSGraphicsContext::restoreGraphicsState_class();
677    CGContext::restore_g_state(Some(cg));
678}
679
680/// A Cocoa object on its way to or from a painting thread (docs/canvas.md "Exporting").
681struct Sendable<T>(T);
682
683// SAFETY: wrapped only around objects AppKit documents as usable from any thread while nothing
684// mutates them — `NSImage` and `NSBitmapImageRep` for drawing, `NSFont`, and a `CGImage`,
685// which is immutable — and a stored bitmap is never mutated after `BITMAPS` takes it. Each
686// wrapped value is used by one thread at a time: the painter borrows it for one export, then
687// the UI thread owns the result.
688unsafe impl<T> Send for Sendable<T> {}
689
690/// Everything the painter would read from the UI thread's tables, resolved there before an
691/// export leaves for a painting thread (docs/canvas.md "Exporting"): the decoded images its
692/// image ops draw, and the font each of its text runs needs, which only the UI thread may ask
693/// `NSFontManager` for.
694struct OffscreenResources {
695    images: Vec<(u64, AppKitBitmap)>,
696    fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)>,
697}
698
699impl OffscreenResources {
700    /// Walk `ops` on the UI thread. An image whose handle was already released is simply
701    /// absent, and the painter draws nothing for it, as it does on screen.
702    fn collect(ops: &[DrawOp]) -> Self {
703        let mut images: Vec<(u64, AppKitBitmap)> = Vec::new();
704        let mut fonts: Vec<((u64, day_spec::CanvasFont), Retained<NSFont>)> = Vec::new();
705        for op in ops {
706            match op {
707                DrawOp::Image { image, .. } => {
708                    if images.iter().any(|(id, _)| *id == image.0) {
709                        continue;
710                    }
711                    let held = BITMAPS.with(|m| {
712                        m.borrow().get(&image.0).map(|b| AppKitBitmap {
713                            image: b.image.clone(),
714                            rep: b.rep.clone(),
715                            info: b.info,
716                        })
717                    });
718                    if let Some(bitmap) = held {
719                        images.push((image.0, bitmap));
720                    }
721                }
722                DrawOp::Text { size, font, .. } => {
723                    let key = (size.to_bits(), font.clone());
724                    if fonts.iter().any(|(k, _)| *k == key) {
725                        continue;
726                    }
727                    let resolved = canvas_nsfont(*size, font);
728                    fonts.push((key, resolved));
729                }
730                _ => {}
731            }
732        }
733        Self { images, fonts }
734    }
735
736    /// Run `paint` with these as the calling thread's own tables, then take them back out.
737    /// Only entries this call added are removed afterwards, so a run on the UI thread itself
738    /// (no painting thread could start) leaves its tables as they were.
739    fn with_installed<R>(self, paint: impl FnOnce() -> R) -> R {
740        let mut added_images = Vec::with_capacity(self.images.len());
741        BITMAPS.with(|m| {
742            let mut m = m.borrow_mut();
743            for (id, bitmap) in self.images {
744                if let std::collections::hash_map::Entry::Vacant(slot) = m.entry(id) {
745                    slot.insert(bitmap);
746                    added_images.push(id);
747                }
748            }
749        });
750        let added_fonts = self.fonts.len();
751        OFFSCREEN_FONTS.with(|t| t.borrow_mut().extend(self.fonts));
752        let out = paint();
753        OFFSCREEN_FONTS.with(|t| {
754            let mut t = t.borrow_mut();
755            let keep = t.len().saturating_sub(added_fonts);
756            t.truncate(keep);
757        });
758        BITMAPS.with(|m| {
759            let mut m = m.borrow_mut();
760            for id in added_images {
761                m.remove(&id);
762            }
763        });
764        out
765    }
766}
767
768/// Render a canvas display list offscreen (docs/canvas.md "Exporting"): `export_pixels` of
769/// transparent sRGB, premultiplied RGBA, painted at `scale` pixels per point. The half of the
770/// export that runs on a painting thread: CoreGraphics draws into a bitmap context from any
771/// thread, and the painter's AppKit objects (paths, colors, gradients, fonts, string drawing,
772/// image drawing) are documented safe off the main thread when nothing mutates them.
773///
774/// A `CGBitmapContext` rather than `NSGraphicsContext(bitmapImageRep:)`: it carries a real sRGB
775/// color space, so the `NSBitmapImageRep` built from its image is tagged sRGB like every canvas
776/// color, shows on the display through the same color matching the live canvas gets, and writes
777/// that profile into a PNG.
778fn render_bitmap_cgimage(
779    ops: &[DrawOp],
780    size: Size,
781    scale: f64,
782) -> Result<objc2_core_foundation::CFRetained<objc2_core_graphics::CGImage>, day_spec::ExportError>
783{
784    use objc2_core_graphics::{
785        CGBitmapContextCreate, CGBitmapContextCreateImage, CGColorSpace, CGImageAlphaInfo,
786    };
787    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
788    let (pw, ph) = day_spec::export_pixels(size, scale);
789    // SAFETY: `kCGColorSpaceSRGB` is an immutable CoreGraphics constant, valid for the process.
790    let space = CGColorSpace::with_name(Some(unsafe { objc2_core_graphics::kCGColorSpaceSRGB }))
791        .ok_or_else(|| failed("CoreGraphics has no sRGB color space"))?;
792    // SAFETY: a null data pointer asks CoreGraphics to allocate (and own) the buffer, and a zero
793    // row stride lets it choose one; 8 bits × RGBA premultiplied is a supported layout.
794    let cg = unsafe {
795        CGBitmapContextCreate(
796            std::ptr::null_mut(),
797            pw as usize,
798            ph as usize,
799            8,
800            0,
801            Some(&space),
802            CGImageAlphaInfo::PremultipliedLast.0,
803        )
804    }
805    .ok_or_else(|| {
806        day_spec::ExportError::Failed(format!("CGBitmapContextCreate refused {pw}x{ph}"))
807    })?;
808    // A new bitmap context starts zeroed, which is the transparent background.
809    paint_flipped(&cg, ph as f64, scale, ops);
810    CGBitmapContextCreateImage(Some(&cg))
811        .ok_or_else(|| failed("CGBitmapContextCreateImage returned nothing"))
812}
813
814/// The UI-thread half of a bitmap export: the painted `CGImage` wrapped as the `NSBitmapImageRep`
815/// and `NSImage` a decoded bitmap is stored as, so `image`, `encode_image` and `DrawOp::Image`
816/// take it like one.
817fn bitmap_from_cgimage(cg_image: &objc2_core_graphics::CGImage, scale: f64) -> AppKitBitmap {
818    use objc2::AllocAnyThread as _;
819    let rep = unsafe {
820        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
821            objc2_app_kit::NSBitmapImageRep::alloc(),
822            cg_image,
823        )
824    };
825    let (pw, ph) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
826    // Sized in POINTS, pixels over scale, so the image draws at the drawing's size and stays
827    // sharp at `scale`× — the same shape as a staged @2x asset.
828    let points = NSSize::new(pw / scale, ph / scale);
829    unsafe { rep.setSize(points) };
830    let image =
831        unsafe { objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), points) };
832    unsafe { image.addRepresentation(&rep) };
833    AppKitBitmap {
834        image,
835        rep: Some(rep),
836        info: day_spec::BitmapInfo {
837            pixels: Size::new(pw, ph),
838            scale,
839            format: None,
840            has_alpha: true,
841        },
842    }
843}
844
845/// Write `pages` as one PDF document (docs/canvas.md "Exporting"): a `CGPDFContext` on a
846/// `CGDataConsumer` over memory, one page per drawing with its own media box, the title and
847/// author in the document info. Shapes and text stay vector: the same painter draws into the PDF
848/// context, and AppKit's string drawing there emits real glyphs from embedded font subsets.
849fn render_pdf_bytes(
850    pages: &[day_spec::PdfPage],
851    info: &day_spec::PdfInfo,
852) -> Result<Vec<u8>, day_spec::ExportError> {
853    use objc2_core_foundation::{
854        CFDictionary, CFMutableData, CFRetained, CFString, CGPoint, CGRect, CGSize,
855    };
856    use objc2_core_graphics::{CGContext, CGDataConsumer, CGPDFContextClose, CGPDFContextCreate};
857    let failed = |what: &str| day_spec::ExportError::Failed(what.to_string());
858    let media =
859        |size: Size| CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(size.width, size.height));
860    let first = pages.first().ok_or(day_spec::ExportError::Invalid)?;
861    let data = CFMutableData::new(None, 0)
862        .ok_or_else(|| failed("CFDataCreateMutable returned nothing"))?;
863    let consumer = CGDataConsumer::with_cf_data(Some(&data))
864        .ok_or_else(|| failed("CGDataConsumerCreateWithCFData returned nothing"))?;
865
866    let mut keys: Vec<&CFString> = Vec::new();
867    let mut values: Vec<CFRetained<CFString>> = Vec::new();
868    // SAFETY: the auxiliary-info keys are immutable CoreGraphics constants.
869    let (title_key, author_key) = unsafe {
870        (
871            objc2_core_graphics::kCGPDFContextTitle,
872            objc2_core_graphics::kCGPDFContextAuthor,
873        )
874    };
875    for (key, value) in [(title_key, &info.title), (author_key, &info.author)] {
876        if let Some(value) = value {
877            keys.push(key);
878            values.push(CFString::from_str(value));
879        }
880    }
881    let values: Vec<&CFString> = values.iter().map(|v| &**v).collect();
882    let aux = CFDictionary::<CFString, CFString>::from_slices(&keys, &values);
883
884    let first_box = media(first.size);
885    // SAFETY: `first_box` outlives the call, and the dictionary maps the documented
886    // auxiliary-info string keys to strings, which is the type those keys take.
887    let pdf = unsafe { CGPDFContextCreate(Some(&consumer), &first_box, Some(aux.as_opaque())) }
888        .ok_or_else(|| failed("CGPDFContextCreate refused the document"))?;
889    for page in pages {
890        let page_box = media(page.size);
891        // SAFETY: `page_box` outlives the call; in a PDF context it becomes the page's MediaBox.
892        unsafe { CGContext::begin_page(Some(&pdf), &page_box) };
893        paint_flipped(&pdf, page.size.height, 1.0, &page.ops);
894        CGContext::end_page(Some(&pdf));
895    }
896    // Closing flushes the trailer into the consumer; the bytes are complete only after it.
897    CGPDFContextClose(Some(&pdf));
898    drop(pdf);
899    drop(consumer);
900    Ok(data.to_vec())
901}
902
903thread_local! {
904    /// Each realized list item's current props, by its view: a patch updates one part and the
905    /// item is re-dressed from the whole (docs/list.md "List items").
906    static LIST_ITEMS: std::cell::RefCell<std::collections::HashMap<usize, day_spec::props::ListItemProps>> =
907        std::cell::RefCell::new(std::collections::HashMap::new());
908}
909
910/// A list row's standard content (docs/list.md "List items"), as an image-and-text table cell
911/// draws it: a 16pt template image, the title in the system font with a smaller secondary
912/// subtitle under it, a secondary trailing value, and the accent checkmark, in a horizontal
913/// stack at least 28pt tall. Parts that are absent are hidden, and the stack closes up around
914/// them.
915///
916/// The row's width is spoken for explicitly, as an image-and-text cell's is: the stack fills
917/// its frame edge to edge, the words take every spare point and give way first, and the
918/// trailing parts keep their own size. Left to the stack's default gravity areas, the spare
919/// width had two equally weak claims, the words' column and the gap before the trailing parts,
920/// so Auto Layout settled it from whatever the row's last layout had been: a checkmark landed
921/// beside the title in one row and at the trailing edge in the next, and stayed put.
922fn make_list_item(p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) -> Retained<NSView> {
923    use objc2_app_kit::{
924        NSImageView, NSLayoutAttribute, NSStackView, NSUserInterfaceLayoutOrientation,
925    };
926    let label = |text: &str, size: f64, secondary: bool| {
927        let tf = unsafe { NSTextField::labelWithString(&NSString::from_str(text), mtm) };
928        unsafe {
929            tf.setFont(Some(&objc2_app_kit::NSFont::systemFontOfSize(size)));
930            if secondary {
931                tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
932            }
933            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
934        }
935        tf
936    };
937    let size = unsafe { objc2_app_kit::NSFont::systemFontSize() };
938    let small = unsafe { objc2_app_kit::NSFont::smallSystemFontSize() };
939    const ACROSS: objc2_app_kit::NSLayoutConstraintOrientation =
940        objc2_app_kit::NSLayoutConstraintOrientation::Horizontal;
941    // Hugging: the words stretch (1), the trailing parts hold their size (750), and the stack
942    // keeps its edges on its first and last parts (750), so exactly one part takes the slack.
943    const STRETCH: f32 = 1.0;
944    const HOLD: f32 = 750.0;
945    let stack = NSStackView::new(mtm);
946    stack.setOrientation(NSUserInterfaceLayoutOrientation::Horizontal);
947    stack.setDistribution(objc2_app_kit::NSStackViewDistribution::Fill);
948    stack.setAlignment(NSLayoutAttribute::CenterY);
949    stack.setHuggingPriority_forOrientation(HOLD, ACROSS);
950    stack.setSpacing(6.0);
951    // A table row's breathing room above and below; the list gives the sides.
952    stack.setEdgeInsets(objc2_foundation::NSEdgeInsets {
953        top: 4.0,
954        left: 0.0,
955        bottom: 4.0,
956        right: 0.0,
957    });
958    let icon = unsafe { NSImageView::new(mtm) };
959    unsafe {
960        icon.setImageScaling(objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown);
961        icon.widthAnchor()
962            .constraintEqualToConstant(16.0)
963            .setActive(true);
964        icon.heightAnchor()
965            .constraintEqualToConstant(16.0)
966            .setActive(true);
967    }
968    stack.addArrangedSubview(&icon);
969    // The title and subtitle span the words' column (Width alignment), so the column's width is
970    // theirs and nothing is left over inside it.
971    let texts = NSStackView::new(mtm);
972    texts.setOrientation(NSUserInterfaceLayoutOrientation::Vertical);
973    texts.setAlignment(NSLayoutAttribute::Width);
974    texts.setSpacing(1.0);
975    // Its height is its lines', centered in the row, not the row's height with the lines
976    // floating somewhere inside it.
977    texts.setHuggingPriority_forOrientation(
978        HOLD,
979        objc2_app_kit::NSLayoutConstraintOrientation::Vertical,
980    );
981    let title = label("", size, false);
982    let subtitle = label("", small, true);
983    // The words take the width and give way first, truncating, before the trailing parts.
984    for line in [&title, &subtitle] {
985        line.setContentHuggingPriority_forOrientation(STRETCH, ACROSS);
986        line.setContentCompressionResistancePriority_forOrientation(250.0, ACROSS);
987    }
988    texts.addArrangedSubview(&title);
989    texts.addArrangedSubview(&subtitle);
990    stack.addArrangedSubview(&texts);
991    let detail = label("", size, true);
992    detail.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
993    detail.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
994    stack.addArrangedSubview(&detail);
995    let check = unsafe { NSImageView::new(mtm) };
996    unsafe {
997        check.setImage(
998            objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
999                &NSString::from_str("checkmark"),
1000                None,
1001            )
1002            .as_deref(),
1003        );
1004        check.setContentTintColor(Some(&objc2_app_kit::NSColor::controlAccentColor()));
1005    }
1006    check.setContentHuggingPriority_forOrientation(HOLD, ACROSS);
1007    check.setContentCompressionResistancePriority_forOrientation(HOLD, ACROSS);
1008    stack.addArrangedSubview(&check);
1009    let view = Retained::from(<NSStackView as AsRef<NSView>>::as_ref(&stack));
1010    LIST_ITEMS.with(|m| m.borrow_mut().insert(ptr_of(&view), p.clone()));
1011    dress_list_item(&view, p, mtm);
1012    view
1013}
1014
1015/// Show `p` on a list item's stack (see [`make_list_item`]), as one accessibility element.
1016fn dress_list_item(view: &NSView, p: &day_spec::props::ListItemProps, mtm: MainThreadMarker) {
1017    use objc2_app_kit::{NSImageView, NSStackView};
1018    let Some(stack) = view.downcast_ref::<NSStackView>() else {
1019        return;
1020    };
1021    let parts = stack.arrangedSubviews();
1022    if parts.len() < 4 {
1023        return;
1024    }
1025    let icon = parts.objectAtIndex(0);
1026    if let Some(iv) = icon.downcast_ref::<NSImageView>() {
1027        let image = p
1028            .icon
1029            .as_ref()
1030            .and_then(|i| toolbar::image_for(i, &p.title, mtm));
1031        unsafe {
1032            iv.setImage(image.as_deref());
1033            iv.setContentTintColor(p.icon_tint.map(nscolor).as_deref());
1034        }
1035    }
1036    icon.setHidden(p.icon.is_none());
1037    if let Some(texts) = parts.objectAtIndex(1).downcast_ref::<NSStackView>() {
1038        let lines = texts.arrangedSubviews();
1039        if lines.len() == 2 {
1040            if let Some(tf) = lines.objectAtIndex(0).downcast_ref::<NSTextField>() {
1041                tf.setStringValue(&NSString::from_str(&p.title));
1042            }
1043            let sub = lines.objectAtIndex(1);
1044            if let Some(tf) = sub.downcast_ref::<NSTextField>() {
1045                tf.setStringValue(&NSString::from_str(&p.subtitle));
1046            }
1047            sub.setHidden(p.subtitle.is_empty());
1048        }
1049    }
1050    let detail = parts.objectAtIndex(2);
1051    if let Some(tf) = detail.downcast_ref::<NSTextField>() {
1052        tf.setStringValue(&NSString::from_str(&p.detail));
1053    }
1054    detail.setHidden(p.detail.is_empty());
1055    parts.objectAtIndex(3).setHidden(!p.checked);
1056    let words = [&p.title, &p.subtitle, &p.detail]
1057        .into_iter()
1058        .filter(|w| !w.is_empty())
1059        .map(String::as_str)
1060        .collect::<Vec<_>>()
1061        .join(", ");
1062    unsafe {
1063        view.setAccessibilityElement(true);
1064        view.setAccessibilityLabel(Some(&NSString::from_str(&words)));
1065        view.setAccessibilitySelected(p.checked);
1066    }
1067}
1068
1069/// The `NSImage` behind an [`day_spec::ImageSource`] (docs/images.md).
1070///
1071/// Shared by realize and the `Source` patch: a swapped source must load exactly what a fresh
1072/// realize would have, or a piece would show different pixels depending on whether it was
1073/// built or updated.
1074fn appkit_image_for(source: &day_spec::ImageSource) -> Option<Retained<objc2_app_kit::NSImage>> {
1075    use objc2::AllocAnyThread as _;
1076    match source {
1077        // A vector glyph's SVG first (docs/vectors.md): NSImage renders SVG at display size
1078        // (macOS 11+), so vectors stay vector with no build-time raster resampling. Then the
1079        // shared image-file resolver (images/ then assets/ then bundle), which is macOS's native
1080        // path: a bundle file loaded straight into NSImage (§18.3).
1081        day_spec::ImageSource::Named(name) => day_spec::resource::resolve_vector_svg(name)
1082            .or_else(|| day_spec::resource::resolve_image_file(name))
1083            .and_then(|path| unsafe {
1084                objc2_app_kit::NSImage::initWithContentsOfFile(
1085                    objc2_app_kit::NSImage::alloc(),
1086                    &NSString::from_str(&path.to_string_lossy()),
1087                )
1088            }),
1089        // Bytes the app already holds (a download, a picked file, a paste) with no staged
1090        // resource behind them.
1091        day_spec::ImageSource::Bytes(bytes) => unsafe {
1092            objc2_app_kit::NSImage::initWithData(
1093                objc2_app_kit::NSImage::alloc(),
1094                &NSData::with_bytes(bytes),
1095            )
1096        },
1097        // Already decoded: share the one NSImage rather than parsing the same bytes twice.
1098        day_spec::ImageSource::Decoded(id) => {
1099            BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.image.clone()))
1100        }
1101    }
1102}
1103
1104/// Day `Role` → the `NSAccessibilityRole` constant to apply (§13). `None` for `Role::None`:
1105/// Day leaves native controls' roles untouched and only applies explicit canvas/custom roles.
1106fn ns_role(role: day_spec::Role) -> Option<&'static objc2_app_kit::NSAccessibilityRole> {
1107    use day_spec::Role;
1108    use objc2_app_kit::{
1109        NSAccessibilityButtonRole, NSAccessibilityCheckBoxRole, NSAccessibilityGroupRole,
1110        NSAccessibilityHeadingRole, NSAccessibilityImageRole, NSAccessibilityLevelIndicatorRole,
1111        NSAccessibilityOutlineRole, NSAccessibilityRadioButtonRole, NSAccessibilityRowRole,
1112        NSAccessibilitySliderRole, NSAccessibilityTabGroupRole, NSAccessibilityTextFieldRole,
1113    };
1114    unsafe {
1115        Some(match role {
1116            Role::Button => NSAccessibilityButtonRole,
1117            Role::Toggle => NSAccessibilityCheckBoxRole,
1118            // A tab is a radio button with the tab-button subrole (`set_a11y` adds it), which
1119            // is how NSTabView's own tabs read to VoiceOver; the strip is a tab group.
1120            Role::Tab => NSAccessibilityRadioButtonRole,
1121            Role::TabList => NSAccessibilityTabGroupRole,
1122            Role::Slider => NSAccessibilitySliderRole,
1123            Role::TextInput => NSAccessibilityTextFieldRole,
1124            // `AXHeading` lands the label in VoiceOver's headings rotor. The level has no
1125            // AppKit attribute of its own: the only convention (the level as `AXValue`) would
1126            // displace the text an NSTextField reports as its value, so the level stays
1127            // unspoken.
1128            Role::Heading(_) => NSAccessibilityHeadingRole,
1129            Role::Image => NSAccessibilityImageRole,
1130            Role::Meter => NSAccessibilityLevelIndicatorRole,
1131            Role::Group => NSAccessibilityGroupRole,
1132            // NSOutlineView already reports these itself; the mapping is for the audit's
1133            // expectation and for any composed stand-in (docs/tree.md).
1134            Role::Tree => NSAccessibilityOutlineRole,
1135            Role::TreeItem => NSAccessibilityRowRole,
1136            Role::None => return None,
1137        })
1138    }
1139}
1140
1141/// Native `AXRole` string → Day `Role` (best-effort, for `read_native`/`a11y_audit`).
1142fn day_role_from_ns(ax: &str) -> day_spec::Role {
1143    use day_spec::Role;
1144    match ax {
1145        "AXButton" => Role::Button,
1146        "AXCheckBox" => Role::Toggle,
1147        "AXSlider" => Role::Slider,
1148        "AXTextField" => Role::TextInput,
1149        // Plain text is ambiguous with a heading, and neither carries a level; the audit
1150        // ignores the level either way.
1151        "AXStaticText" | "AXHeading" => Role::Heading(0),
1152        "AXOutline" => Role::Tree,
1153        "AXImage" => Role::Image,
1154        "AXLevelIndicator" | "AXProgressIndicator" => Role::Meter,
1155        "AXGroup" => Role::Group,
1156        "AXRadioButton" => Role::Tab,
1157        "AXTabGroup" => Role::TabList,
1158        _ => Role::None,
1159    }
1160}
1161
1162// ---------------------------------------------------------------------------
1163// DayTarget: target/action + text delegate trampoline
1164// ---------------------------------------------------------------------------
1165
1166struct TargetIvars {
1167    node: NodeId,
1168}
1169
1170define_class!(
1171    #[unsafe(super(NSObject))]
1172    #[thread_kind = MainThreadOnly]
1173    #[name = "DayTarget"]
1174    #[ivars = TargetIvars]
1175    struct DayTarget;
1176
1177    unsafe impl NSObjectProtocol for DayTarget {}
1178    unsafe impl NSTextFieldDelegate for DayTarget {}
1179
1180    /// A tabs host's `NSTabView` (docs/navigation.md). A pick emits against the NAV_MENU's
1181    /// node, exactly as the sidebar's outline view does, so as far as everything above this
1182    /// backend is concerned, picking a tab and clicking a sidebar row are the same event, and
1183    /// neither the pieces layer nor dayscript needs to know which chrome the window wears.
1184    unsafe impl NSTabViewDelegate for DayTarget {
1185        #[unsafe(method(tabView:didSelectTabViewItem:))]
1186        fn tab_view_did_select(
1187            &self,
1188            tab_view: &objc2_app_kit::NSTabView,
1189            item: Option<&objc2_app_kit::NSTabViewItem>,
1190        ) {
1191            ffi_guard::contain((), || {
1192                if TAB_PICK_SUPPRESS.with(|s| s.get()) {
1193                    return;
1194                }
1195                if let Some(item) = item {
1196                    let idx = unsafe { tab_view.indexOfTabViewItem(item) };
1197                    if idx >= 0 {
1198                        emit(self.ivars().node, Event::SelectionChanged(idx as i64));
1199                    }
1200                }
1201            })
1202        }
1203    }
1204
1205    impl DayTarget {
1206        // Every trampoline that dispatches into the sink (and through it, app handlers) runs
1207        // its body through `ffi_guard::contain` (§8.5): a Rust panic unwinding out of an ObjC
1208        // frame is an abort, so it is caught, reported, and the reactive runtime recovered.
1209        // The same guard wraps every other target/delegate entry in this backend.
1210        #[unsafe(method(action:))]
1211        fn action(&self, sender: &NSControl) {
1212            ffi_guard::contain((), || {
1213                let node = self.ivars().node;
1214                if sender.downcast_ref::<NSSwitch>().is_some() {
1215                    emit(node, Event::ToggleChanged(unsafe { sender.integerValue() } != 0));
1216                } else if sender.downcast_ref::<NSSlider>().is_some() {
1217                    let value = unsafe { sender.doubleValue() };
1218                    // The live value first: bindings follow this, so the UI tracks the thumb.
1219                    emit(node, Event::ValueChanged(value));
1220                    // Then, once, the value the user settled on. The slider is `continuous`, so
1221                    // this action fires on every tick of a drag; AppKit's way to tell where in the
1222                    // gesture you are is the event that provoked it. A mouse-up ends a drag; a key
1223                    // press (arrow keys) moves the value by one discrete step and is already settled;
1224                    // anything else (mouse-down, mouse-dragged) is mid-gesture and commits nothing.
1225                    if slider_value_settled() {
1226                        emit(node, Event::ValueCommitted(value));
1227                    }
1228                } else if let (Some(f), Some(btn)) = (
1229                    BUTTON_MENUS.with(|t| t.get(ptr_of(sender))),
1230                    sender.downcast_ref::<NSButton>(),
1231                ) {
1232                    // A menu button's press opens its menu rather than reporting a press.
1233                    pop_button_menu(btn, &f);
1234                } else {
1235                    emit(node, Event::Pressed);
1236                    // A push-on/push-off button toggled its state on the click; Day owns the
1237                    // selected state (`set_button_selected`), so put back what it last asked.
1238                    let wanted = BUTTON_SELECTED.with(|m| m.borrow().get(&ptr_of(sender)).copied());
1239                    if let (Some(on), Some(btn)) = (wanted, sender.downcast_ref::<NSButton>()) {
1240                        unsafe {
1241                            btn.setState(if on {
1242                                NSControlStateValueOn
1243                            } else {
1244                                NSControlStateValueOff
1245                            })
1246                        };
1247                    }
1248                }
1249            })
1250        }
1251
1252        /// The stack-nav back header's button (docs/navigation.md): a day-initiated pop. The
1253        /// nav host's handler writes it into the path signal, which reconciles the pop.
1254        #[unsafe(method(navBack:))]
1255        fn nav_back(&self, _sender: &NSControl) {
1256            ffi_guard::contain((), || {
1257                emit(
1258                    self.ivars().node,
1259                    Event::NavBack {
1260                        already_popped: false,
1261                    },
1262                );
1263            })
1264        }
1265    }
1266
1267    unsafe impl NSControlTextEditingDelegate for DayTarget {
1268        #[unsafe(method(controlTextDidChange:))]
1269        fn control_text_did_change(&self, notification: &NSNotification) {
1270            ffi_guard::contain((), || {
1271                let node = self.ivars().node;
1272                if let Some(obj) = unsafe { notification.object() }
1273                    && let Ok(tf) = obj.downcast::<NSTextField>() {
1274                        emit(node, Event::TextChanged(unsafe { tf.stringValue() }.to_string()));
1275                    }
1276            })
1277        }
1278
1279        /// The field editor's commands for a text field with a key handler
1280        /// (docs/textfield.md "Keys"): the plain arrows and Escape arrive as `moveUp:`,
1281        /// `moveDown:` and `cancelOperation:`, which the field claims and reports as
1282        /// `Event::Key`, so the caret stays put and Escape does not open the completion list.
1283        /// Every other command, and these three on a field with no handler, is AppKit's.
1284        #[unsafe(method(control:textView:doCommandBySelector:))]
1285        fn control_do_command(
1286            &self,
1287            _control: &NSControl,
1288            _tv: &NSTextView,
1289            command: objc2::runtime::Sel,
1290        ) -> objc2::runtime::Bool {
1291            ffi_guard::contain(objc2::runtime::Bool::NO, || {
1292                let node = self.ivars().node;
1293                let key = if command == sel!(moveUp:) {
1294                    "ArrowUp"
1295                } else if command == sel!(moveDown:) {
1296                    "ArrowDown"
1297                } else if command == sel!(cancelOperation:) {
1298                    "Escape"
1299                } else {
1300                    return objc2::runtime::Bool::NO;
1301                };
1302                if !day_spec::keys::field_claims(node, key, 0) {
1303                    return objc2::runtime::Bool::NO;
1304                }
1305                emit(node, Event::Key(day_spec::KeyEvent::named(key, 0)));
1306                objc2::runtime::Bool::YES
1307            })
1308        }
1309
1310        /// End of an editing session (docs/focus.md). Return submits: AppKit keeps the field
1311        /// first responder and re-selects, so it is not a focus loss; every other movement
1312        /// (tab, click-away, cancel) reports `FocusChanged(false)`.
1313        #[unsafe(method(controlTextDidEndEditing:))]
1314        fn control_text_did_end_editing(&self, notification: &NSNotification) {
1315            ffi_guard::contain((), || {
1316                let node = self.ivars().node;
1317                let movement = unsafe { notification.userInfo() }
1318                    .and_then(|ui| ui.objectForKey(unsafe { NSTextMovementUserInfoKey }.as_ref()))
1319                    .and_then(|n| n.downcast::<NSNumber>().ok())
1320                    .map(|n| NSTextMovement(n.integerValue()))
1321                    .unwrap_or(NSTextMovement::Other);
1322                if movement == NSTextMovement::Return {
1323                    emit(node, Event::Submitted);
1324                } else {
1325                    emit(node, Event::FocusChanged(false));
1326                }
1327            })
1328        }
1329    }
1330);
1331
1332impl DayTarget {
1333    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1334        let this = Self::alloc(mtm).set_ivars(TargetIvars { node });
1335        unsafe { msg_send![super(this), init] }
1336    }
1337}
1338
1339// ---------------------------------------------------------------------------
1340// DayCursorOwner: the `.cursor()` decorator's tracking-area owner (docs/cursor.md)
1341// ---------------------------------------------------------------------------
1342
1343struct CursorIvars {
1344    /// The shape to set on `cursorUpdate:`; `None` leaves the platform's own choice.
1345    cursor: RefCell<Option<Retained<NSCursor>>>,
1346    /// `Cursor::None`: hide the pointer while it is inside, unhide on exit.
1347    hidden: Cell<bool>,
1348    /// Whether this owner is the one that hid the pointer (balanced by `unhide`).
1349    hiding: Cell<bool>,
1350}
1351
1352// AppKit only re-evaluates the pointer's shape on `cursorUpdate:`, which it sends to a
1353// tracking area's owner when the pointer enters the area (and on request through
1354// `invalidateCursorRectsForView:`). One owner per view keeps the view class untouched: a label,
1355// a button, or a plain container all get the same treatment without subclassing. Nested areas
1356// resolve by entry order: the innermost is entered last, so its shape is the one that stays.
1357define_class!(
1358    #[unsafe(super(NSObject))]
1359    #[thread_kind = MainThreadOnly]
1360    #[name = "DayCursorOwner"]
1361    #[ivars = CursorIvars]
1362    struct DayCursorOwner;
1363
1364    unsafe impl NSObjectProtocol for DayCursorOwner {}
1365
1366    impl DayCursorOwner {
1367        #[unsafe(method(cursorUpdate:))]
1368        fn cursor_update(&self, _event: &NSEvent) {
1369            let iv = self.ivars();
1370            if iv.hidden.get() {
1371                if !iv.hiding.replace(true) {
1372                    NSCursor::hide();
1373                }
1374                return;
1375            }
1376            if let Some(c) = iv.cursor.borrow().as_ref() {
1377                c.set();
1378            }
1379        }
1380
1381        #[unsafe(method(mouseExited:))]
1382        fn mouse_exited(&self, _event: &NSEvent) {
1383            if self.ivars().hiding.replace(false) {
1384                NSCursor::unhide();
1385            }
1386        }
1387    }
1388);
1389
1390impl DayCursorOwner {
1391    fn new(mtm: MainThreadMarker) -> Retained<Self> {
1392        let this = Self::alloc(mtm).set_ivars(CursorIvars {
1393            cursor: RefCell::new(None),
1394            hidden: Cell::new(false),
1395            hiding: Cell::new(false),
1396        });
1397        unsafe { msg_send![super(this), init] }
1398    }
1399}
1400
1401/// The `NSCursor` for a [`Cursor`], or `None` where the platform's own choice should stand
1402/// (`Cursor::None`, which the owner hides instead, and a native name AppKit does not have).
1403/// AppKit has no wait, progress, help, or move shape, so those take the arrow; the zoom, frame
1404/// (diagonal) resize, and column/row resize cursors arrived in macOS 15 and are probed by
1405/// nav host, with the nearest older shape below it.
1406// `resizeLeftRightCursor` and `resizeUpDownCursor` are deprecated in favor of the macOS 15
1407// column/row resize cursors, which are probed above them; below 15 they are the shape.
1408#[allow(deprecated)]
1409fn ns_cursor(c: &Cursor) -> Option<Retained<NSCursor>> {
1410    let has = |sel: objc2::runtime::Sel| <NSCursor as objc2::ClassType>::class().responds_to(sel);
1411    Some(match c {
1412        Cursor::Default | Cursor::Wait | Cursor::Progress | Cursor::Help => NSCursor::arrowCursor(),
1413        Cursor::Pointer => NSCursor::pointingHandCursor(),
1414        Cursor::Text => NSCursor::IBeamCursor(),
1415        Cursor::VerticalText => NSCursor::IBeamCursorForVerticalLayout(),
1416        Cursor::Crosshair | Cursor::Cell => NSCursor::crosshairCursor(),
1417        Cursor::Move | Cursor::Grab => NSCursor::openHandCursor(),
1418        Cursor::Grabbing => NSCursor::closedHandCursor(),
1419        Cursor::NotAllowed => NSCursor::operationNotAllowedCursor(),
1420        Cursor::ContextMenu => NSCursor::contextualMenuCursor(),
1421        Cursor::Copy => NSCursor::dragCopyCursor(),
1422        Cursor::Alias => NSCursor::dragLinkCursor(),
1423        Cursor::ZoomIn if has(sel!(zoomInCursor)) => NSCursor::zoomInCursor(),
1424        Cursor::ZoomOut if has(sel!(zoomOutCursor)) => NSCursor::zoomOutCursor(),
1425        Cursor::ZoomIn | Cursor::ZoomOut => NSCursor::arrowCursor(),
1426        Cursor::NsResize => NSCursor::resizeUpDownCursor(),
1427        Cursor::EwResize => NSCursor::resizeLeftRightCursor(),
1428        Cursor::NeswResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1429            NSCursor::frameResizeCursorFromPosition_inDirections(
1430                NSCursorFrameResizePosition::TopRight,
1431                NSCursorFrameResizeDirections::All,
1432            )
1433        }
1434        Cursor::NwseResize if has(sel!(frameResizeCursorFromPosition:inDirections:)) => {
1435            NSCursor::frameResizeCursorFromPosition_inDirections(
1436                NSCursorFrameResizePosition::TopLeft,
1437                NSCursorFrameResizeDirections::All,
1438            )
1439        }
1440        Cursor::NeswResize | Cursor::NwseResize => NSCursor::arrowCursor(),
1441        Cursor::ColResize if has(sel!(columnResizeCursor)) => NSCursor::columnResizeCursor(),
1442        Cursor::ColResize => NSCursor::resizeLeftRightCursor(),
1443        Cursor::RowResize if has(sel!(rowResizeCursor)) => NSCursor::rowResizeCursor(),
1444        Cursor::RowResize => NSCursor::resizeUpDownCursor(),
1445        Cursor::None => return None,
1446        Cursor::Native(name) => match &**name {
1447            "disappearingItem" => NSCursor::disappearingItemCursor(),
1448            "dragCopy" => NSCursor::dragCopyCursor(),
1449            "dragLink" => NSCursor::dragLinkCursor(),
1450            "contextualMenu" => NSCursor::contextualMenuCursor(),
1451            "IBeamCursorForVerticalLayout" => NSCursor::IBeamCursorForVerticalLayout(),
1452            _ => return None,
1453        },
1454    })
1455}
1456
1457/// Whether the NSEvent currently being dispatched ends a slider's interaction (see the
1458/// `ValueCommitted` emission in `DayTarget::action:`). AppKit gives a continuous slider no
1459/// "drag ended" callback, so the event that provoked the action is what says where in the gesture
1460/// we are: a mouse-up ends a drag, an arrow key moves one discrete step and is already settled,
1461/// and mouse-down/mouse-dragged are mid-gesture. No current event at all (a programmatic
1462/// `setDoubleValue:` that fires the action) is not a user commit either.
1463fn slider_value_settled() -> bool {
1464    let Some(mtm) = MainThreadMarker::new() else {
1465        return false;
1466    };
1467    let Some(event) = NSApplication::sharedApplication(mtm).currentEvent() else {
1468        return false;
1469    };
1470    matches!(
1471        unsafe { event.r#type() },
1472        NSEventType::LeftMouseUp | NSEventType::KeyDown | NSEventType::KeyUp
1473    )
1474}
1475
1476// ---------------------------------------------------------------------------
1477// DayTextField: NSTextField that reports focus gain (docs/focus.md)
1478// ---------------------------------------------------------------------------
1479
1480struct FieldIvars {
1481    node: NodeId,
1482}
1483
1484/// The share picker's delegate (docs/sharing.md): offers the app's own actions as sharing
1485/// services beside the system's, each reporting its choice as `Event::MenuAction`.
1486struct SharePickerIvars {
1487    actions: Vec<day_spec::share::ShareAction>,
1488}
1489
1490define_class!(
1491    #[unsafe(super(NSObject))]
1492    #[thread_kind = MainThreadOnly]
1493    #[name = "DaySharePickerDelegate"]
1494    #[ivars = SharePickerIvars]
1495    struct DaySharePickerDelegate;
1496
1497    unsafe impl NSObjectProtocol for DaySharePickerDelegate {}
1498
1499    impl DaySharePickerDelegate {
1500        #[unsafe(method_id(sharingServicePicker:sharingServicesForItems:proposedSharingServices:))]
1501        fn services(
1502            &self,
1503            _picker: &AnyObject,
1504            _items: &AnyObject,
1505            proposed: &objc2_foundation::NSArray<AnyObject>,
1506        ) -> Retained<objc2_foundation::NSArray<AnyObject>> {
1507            let mut services: Vec<Retained<AnyObject>> = Vec::new();
1508            for action in &self.ivars().actions {
1509                let id = action.id;
1510                let handler = block2::RcBlock::new(move || {
1511                    ffi_guard::contain((), || emit(WINDOW_NODE, Event::MenuAction(id)));
1512                });
1513                let image = action.symbol.and_then(|s| {
1514                    objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
1515                        &NSString::from_str(day_spec::sf_symbol_name(s)),
1516                        None,
1517                    )
1518                });
1519                // SAFETY: NSSharingService's documented initializer for a custom service; the
1520                // handler block is copied by the service.
1521                let service: Option<Retained<AnyObject>> = unsafe {
1522                    let alloc: objc2::rc::Allocated<AnyObject> =
1523                        msg_send![objc2::class!(NSSharingService), alloc];
1524                    msg_send![
1525                        alloc,
1526                        initWithTitle: &*NSString::from_str(&action.title),
1527                        image: image.as_deref(),
1528                        alternateImage: None::<&AnyObject>,
1529                        handler: &*handler
1530                    ]
1531                };
1532                services.extend(service);
1533            }
1534            // The system's targets first, then the app's own, as Safari lists Add Bookmark
1535            // after them.
1536            let mut all: Vec<Retained<AnyObject>> = proposed.to_vec();
1537            all.extend(services);
1538            objc2_foundation::NSArray::from_retained_slice(&all)
1539        }
1540    }
1541);
1542
1543define_class!(
1544    #[unsafe(super(NSTextField))]
1545    #[thread_kind = MainThreadOnly]
1546    #[name = "DayTextField"]
1547    #[ivars = FieldIvars]
1548    struct DayTextField;
1549
1550    impl DayTextField {
1551        /// Focus gain. Key events go to the shared field editor, but the field itself receives
1552        /// `becomeFirstResponder` first, the reliable gain hook (`controlTextDidBeginEditing:`
1553        /// waits for the first keystroke). Loss comes from `controlTextDidEndEditing:` on the
1554        /// delegate.
1555        #[unsafe(method(becomeFirstResponder))]
1556        fn become_first_responder(&self) -> bool {
1557            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1558            if ok {
1559                field_gained_focus(self.ivars().node);
1560            }
1561            ok
1562        }
1563    }
1564);
1565
1566impl DayTextField {
1567    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1568        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1569        unsafe { msg_send![super(this), init] }
1570    }
1571}
1572
1573// The secure twin (docs/textfield.md). AppKit hides characters with a class, not a property:
1574// `NSSecureTextField` brings its own cell and field editor, which keep the text out of the
1575// pasteboard, the spelling checker and the accessibility value. A `text_field` that turns
1576// `secure` is rebuilt as this class (`set_input_traits`), with the same focus hook.
1577define_class!(
1578    #[unsafe(super(NSSecureTextField))]
1579    #[thread_kind = MainThreadOnly]
1580    #[name = "DaySecureTextField"]
1581    #[ivars = FieldIvars]
1582    struct DaySecureTextField;
1583
1584    impl DaySecureTextField {
1585        /// Focus gain, as on `DayTextField`.
1586        #[unsafe(method(becomeFirstResponder))]
1587        fn become_first_responder(&self) -> bool {
1588            let ok: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
1589            if ok {
1590                field_gained_focus(self.ivars().node);
1591            }
1592            ok
1593        }
1594    }
1595);
1596
1597impl DaySecureTextField {
1598    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
1599        let this = Self::alloc(mtm).set_ivars(FieldIvars { node });
1600        unsafe { msg_send![super(this), init] }
1601    }
1602}
1603
1604thread_local! {
1605    /// A plain/secure class swap in flight (`set_input_traits`): focus moves from the old
1606    /// field to its replacement, which the app must not see as a focus change.
1607    static FIELD_SWAP: Cell<bool> = const { Cell::new(false) };
1608}
1609
1610/// Report a text field's focus gain, unless it is a class swap handing focus to the
1611/// replacement of a field that already had it.
1612fn field_gained_focus(node: NodeId) {
1613    if FIELD_SWAP.with(|s| s.get()) {
1614        return;
1615    }
1616    // Guard only the sink dispatch: the responder change already happened, so a contained
1617    // panic must not flip the answer AppKit acts on.
1618    ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
1619}
1620
1621/// The node a `text_field`'s view reports against, or `None` when the view is not one
1622/// (a label is an `NSTextField` too).
1623fn text_field_node(v: &NSView) -> Option<NodeId> {
1624    v.downcast_ref::<DayTextField>()
1625        .map(|f| f.ivars().node)
1626        .or_else(|| {
1627            v.downcast_ref::<DaySecureTextField>()
1628                .map(|f| f.ivars().node)
1629        })
1630}
1631
1632/// Build a `text_field`'s view, plain or secure, with its delegate wired and registered.
1633/// `realize` and the class swap in `set_input_traits` both come through here, so both classes
1634/// report text, submit and focus the same way against the same node.
1635fn new_text_field(mtm: MainThreadMarker, node: NodeId, secure: bool) -> Retained<NSTextField> {
1636    let target = DayTarget::new(mtm, node);
1637    // Up to `NSTextField` (the declared superclass of both), so the AsRef<NSView> bound on
1638    // `view_of` resolves and every `NSTextField` downcast sees either class.
1639    let tf: Retained<NSTextField> = if secure {
1640        Retained::into_super(Retained::into_super(DaySecureTextField::new(mtm, node)))
1641    } else {
1642        Retained::into_super(DayTextField::new(mtm, node))
1643    };
1644    unsafe {
1645        tf.setEditable(true);
1646        tf.setBezeled(true);
1647        tf.setDelegate(Some(ProtocolObject::from_ref(&*target)));
1648    }
1649    TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&tf), target));
1650    tf
1651}
1652
1653/// Whether `h` (a text field, or the field editor's client) holds its window's focus. A
1654/// focused `NSTextField`'s first responder is the shared field editor, so unwrap it back to
1655/// the field via its delegate.
1656fn owns_first_responder(window: &NSWindow, h: &NSView) -> bool {
1657    window.firstResponder().is_some_and(|fr| {
1658        if Retained::as_ptr(&fr) as *const () as usize == ptr_of(h) {
1659            return true;
1660        }
1661        fr.downcast::<NSText>().is_ok_and(|text| {
1662            unsafe { text.delegate() }
1663                .is_some_and(|d| Retained::as_ptr(&d) as *const () as usize == ptr_of(h))
1664        })
1665    })
1666}
1667
1668/// An `NSTextContentType` constant by symbol name, or `None` on a system that predates it.
1669/// Looked up at run time because most of the vocabulary arrived in macOS 14: a direct
1670/// reference binds at launch, and one missing symbol would keep the whole app from starting
1671/// on an older system.
1672fn text_content_type(symbol: &std::ffi::CStr) -> Option<&'static NSString> {
1673    unsafe extern "C" {
1674        fn dlsym(
1675            handle: *mut std::ffi::c_void,
1676            symbol: *const std::ffi::c_char,
1677        ) -> *mut std::ffi::c_void;
1678    }
1679    // <dlfcn.h>: search every image loaded in the process.
1680    const RTLD_DEFAULT: *mut std::ffi::c_void = -2isize as *mut std::ffi::c_void;
1681    // SAFETY: `symbol` is NUL-terminated. Each name passed here is an AppKit
1682    // `NSString * const`, so a non-null result is the address of a pointer to an immortal
1683    // constant string.
1684    unsafe {
1685        let slot = dlsym(RTLD_DEFAULT, symbol.as_ptr()).cast::<*const NSString>();
1686        if slot.is_null() {
1687            None
1688        } else {
1689            (*slot).as_ref()
1690        }
1691    }
1692}
1693
1694/// Move a view-keyed entry to the view that replaces it.
1695fn rekey<V>(table: &SideTable<V>, old: usize, new: usize) {
1696    if let Some(v) = table.take(old) {
1697        table.insert(new, v);
1698    }
1699}
1700
1701/// A label is the shared field editor's delegate. AppKit does not forward
1702/// `textView:clickedOnLink:atIndex:` to an NSTextField's separate control delegate, so the
1703/// label itself must handle it to prevent the field editor from opening the target externally.
1704/// See Apple's "Working With the Field Editor" and docs/text-runs.md.
1705struct LabelIvars {
1706    node: NodeId,
1707    has_links: Cell<bool>,
1708    has_runs: Cell<bool>,
1709    selectable: Cell<bool>,
1710}
1711
1712define_class!(
1713    #[unsafe(super(NSTextField))]
1714    #[thread_kind = MainThreadOnly]
1715    #[name = "DayLabel"]
1716    #[ivars = LabelIvars]
1717    struct DayLabel;
1718
1719    impl DayLabel {
1720        #[unsafe(method_id(menuForEvent:))]
1721        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1722            ffi_guard::contain(None, || {
1723                if !self.isSelectable()
1724                    && let Some(menu) = inherited_context_menu(self, event)
1725                {
1726                    return menu;
1727                }
1728                unsafe { msg_send![super(self), menuForEvent: event] }
1729            })
1730        }
1731
1732        #[unsafe(method(drawRect:))]
1733        fn draw_rect(&self, dirty: NSRect) {
1734            // AppKit cannot propagate a table cell's background style through arbitrary
1735            // Day containers. Resolve selection at paint time so keyboard focus, window
1736            // activation, and cell reuse all use the actual native row state.
1737            let mut ancestor = unsafe { self.superview() };
1738            let mut selection_color = None;
1739            if !self.ivars().has_runs.get() {
1740                while let Some(view) = ancestor {
1741                    if let Some(row) = view.downcast_ref::<objc2_app_kit::NSTableRowView>() {
1742                        if unsafe { row.isSelected() } {
1743                            selection_color = Some(unsafe {
1744                                if row.isEmphasized() {
1745                                    objc2_app_kit::NSColor::alternateSelectedControlTextColor()
1746                                } else {
1747                                    objc2_app_kit::NSColor::unemphasizedSelectedTextColor()
1748                                }
1749                            });
1750                        }
1751                        break;
1752                    }
1753                    ancestor = unsafe { view.superview() };
1754                }
1755            }
1756            let cell = unsafe { self.cell() }
1757                .and_then(|cell| cell.downcast::<objc2_app_kit::NSTextFieldCell>().ok());
1758            if let (Some(color), Some(cell)) = (selection_color, cell) {
1759                let original = unsafe { cell.textColor() };
1760                // Mutate the cell only for this paint; changing the field would invalidate
1761                // the view again. Keep the app's normal color for deselection and reuse.
1762                unsafe {
1763                    cell.setTextColor(Some(&color));
1764                    let _: () = msg_send![super(self), drawRect: dirty];
1765                    cell.setTextColor(original.as_deref());
1766                }
1767            } else {
1768                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
1769            }
1770        }
1771    }
1772
1773    unsafe impl NSObjectProtocol for DayLabel {}
1774    unsafe impl NSTextDelegate for DayLabel {}
1775
1776    unsafe impl NSTextViewDelegate for DayLabel {
1777        #[unsafe(method(textView:clickedOnLink:atIndex:))]
1778        fn clicked_on_link(
1779            &self,
1780            _tv: &NSTextView,
1781            link: &objc2::runtime::AnyObject,
1782            _index: usize,
1783        ) -> bool {
1784            ffi_guard::contain(true, || {
1785                // NSString targets stay verbatim (including #route); accept NSURL too.
1786                let url: Retained<NSString> = unsafe { msg_send![link, description] };
1787                emit(self.ivars().node, Event::LinkActivated(url.to_string()));
1788                true // Handled: AppKit must never also open the target itself.
1789            })
1790        }
1791    }
1792);
1793
1794impl DayLabel {
1795    fn new(mtm: MainThreadMarker, node: NodeId, text: &str) -> Retained<Self> {
1796        let this = Self::alloc(mtm).set_ivars(LabelIvars {
1797            node,
1798            has_links: Cell::new(false),
1799            has_runs: Cell::new(false),
1800            selectable: Cell::new(false),
1801        });
1802        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
1803        unsafe {
1804            this.setStringValue(&NSString::from_str(text));
1805            this.setEditable(false);
1806            this.setSelectable(false);
1807            this.setBordered(false);
1808            this.setBezeled(false);
1809            this.setDrawsBackground(false);
1810        }
1811        this
1812    }
1813
1814    fn set_links(&self, has_links: bool) {
1815        self.ivars().has_links.set(has_links);
1816        unsafe {
1817            self.setSelectable(has_links || self.ivars().selectable.get());
1818            self.setAllowsEditingTextAttributes(has_links);
1819        }
1820    }
1821}
1822
1823struct PanMonitor(Retained<objc2::runtime::AnyObject>);
1824impl Drop for PanMonitor {
1825    fn drop(&mut self) {
1826        unsafe { NSEvent::removeMonitor(&self.0) };
1827    }
1828}
1829
1830// Escape closes a cover's window sheet, as it cancels any sheet on macOS (docs/cover.md
1831// "Modal sheet"): the cover hears it as its back request. A local monitor, because the key
1832// window's first responder may be a web view or a field that keeps Escape to itself. A sheet
1833// with its own sheet or alert over it, and app-modal panels, keep their Escape.
1834fn install_sheet_escape_monitor() {
1835    SHEET_ESCAPE_MONITOR.with(|slot| {
1836        if slot.borrow().is_some() {
1837            return;
1838        }
1839        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1840            let event = unsafe { raw.as_ref() };
1841            ffi_guard::contain(raw.as_ptr(), || {
1842                let Some(mtm) = MainThreadMarker::new() else {
1843                    return raw.as_ptr();
1844                };
1845                let escape = unsafe { event.charactersIgnoringModifiers() }
1846                    .is_some_and(|s| s.to_string() == "\u{1b}");
1847                let Some(window) = event.window(mtm).filter(|_| escape) else {
1848                    return raw.as_ptr();
1849                };
1850                let app = NSApplication::sharedApplication(mtm);
1851                if app.modalWindow().is_some() || window.attachedSheet().is_some() {
1852                    return raw.as_ptr();
1853                }
1854                match SHEET_NODES.with(|t| t.get(Retained::as_ptr(&window) as usize)) {
1855                    Some(node) => {
1856                        emit(
1857                            node,
1858                            Event::NavBack {
1859                                already_popped: false,
1860                            },
1861                        );
1862                        std::ptr::null_mut()
1863                    }
1864                    None => raw.as_ptr(),
1865                }
1866            })
1867        });
1868        let monitor = unsafe {
1869            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1870                objc2_app_kit::NSEventMask::KeyDown,
1871                &block,
1872            )
1873        };
1874        *slot.borrow_mut() = monitor.map(PanMonitor);
1875    });
1876}
1877
1878// A container pan observes horizontal wheel events over its descendants, including native
1879// scroll views. Leave vertical scrolling and canvas 2D pans to their existing handlers.
1880fn install_container_pan_monitor() {
1881    PAN_MONITOR.with(|slot| {
1882        if slot.borrow().is_some() {
1883            return;
1884        }
1885        let block = block2::RcBlock::new(|raw: std::ptr::NonNull<NSEvent>| -> *mut NSEvent {
1886            let event = unsafe { raw.as_ref() };
1887            ffi_guard::contain(raw.as_ptr(), || {
1888                let dx = unsafe { event.scrollingDeltaX() };
1889                let dy = unsafe { event.scrollingDeltaY() };
1890                if dx.abs() <= dy.abs() {
1891                    return raw.as_ptr();
1892                }
1893                let Some(mtm) = MainThreadMarker::new() else {
1894                    return raw.as_ptr();
1895                };
1896                let Some(window) = event.window(mtm) else {
1897                    return raw.as_ptr();
1898                };
1899                let Some(content) = window.contentView() else {
1900                    return raw.as_ptr();
1901                };
1902                let point =
1903                    content.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1904                let mut view = content.hitTest(point);
1905                while let Some(v) = view {
1906                    if let Some(node) = PAN_NODES.with(|t| t.get(ptr_of(&v))) {
1907                        if v.downcast_ref::<DayCanvas>().is_some() {
1908                            return raw.as_ptr();
1909                        }
1910                        let raw_phase = unsafe { event.phase() };
1911                        let phase = if raw_phase.contains(objc2_app_kit::NSEventPhase::Began) {
1912                            day_spec::DragPhase::Began
1913                        } else if raw_phase.intersects(
1914                            objc2_app_kit::NSEventPhase::Ended
1915                                | objc2_app_kit::NSEventPhase::Cancelled,
1916                        ) {
1917                            day_spec::DragPhase::Ended
1918                        } else {
1919                            day_spec::DragPhase::Changed
1920                        };
1921                        let p = v.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
1922                        emit(
1923                            node,
1924                            Event::Pan {
1925                                phase,
1926                                delta: Point::new(dx, dy),
1927                                location: Point::new(p.x, p.y),
1928                            },
1929                        );
1930                        return std::ptr::null_mut();
1931                    }
1932                    view = unsafe { v.superview() };
1933                }
1934                raw.as_ptr()
1935            })
1936        });
1937        *slot.borrow_mut() = unsafe {
1938            NSEvent::addLocalMonitorForEventsMatchingMask_handler(
1939                objc2_app_kit::NSEventMask::ScrollWheel,
1940                &block,
1941            )
1942        }
1943        .map(PanMonitor);
1944    });
1945}
1946
1947// ---------------------------------------------------------------------------
1948// DayFlipped: top-left-origin container view
1949// ---------------------------------------------------------------------------
1950
1951/// A `background(..)` fill: `(r, g, b, a, corner_radius)`, painted in `drawRect` with NSColor.
1952type Surface = (f64, f64, f64, f64, f64);
1953
1954#[derive(Default)]
1955struct FlippedIvars {
1956    surface: Cell<Option<Surface>>,
1957    /// SurfaceRole::SectionCard: `(radius,)`, drawn with a dynamic system fill resolved at
1958    /// draw time, so the card tracks light/dark appearance changes automatically.
1959    section_card: Cell<Option<f64>>,
1960    /// Paint the whole view with the dynamic window background before anything else: the
1961    /// inspector panel wrap (docs/inspector.md). The inspector NSSplitViewItem backs its pane
1962    /// with a vibrancy material, and the section cards' thin quaternary fill composites over
1963    /// it into near-black in dark mode (and the material itself captures black offscreen; see
1964    /// the sidebar-screenshot rule, docs/navigation.md). An opaque appearance-resolved
1965    /// backdrop gives the cards the same ground System Settings draws them on.
1966    pane_backdrop: Cell<bool>,
1967}
1968
1969define_class!(
1970    #[unsafe(super(NSView))]
1971    #[thread_kind = MainThreadOnly]
1972    #[name = "DayFlipped"]
1973    #[ivars = FlippedIvars]
1974    struct DayFlipped;
1975
1976    impl DayFlipped {
1977        #[unsafe(method_id(menuForEvent:))]
1978        fn menu_for_event(&self, event: &objc2_app_kit::NSEvent) -> Option<Retained<NSMenu>> {
1979            ffi_guard::contain(None, || {
1980                inherited_context_menu(self, event)
1981                    .unwrap_or_else(|| unsafe { msg_send![super(self), menuForEvent: event] })
1982            })
1983        }
1984
1985        #[unsafe(method(isFlipped))]
1986        fn is_flipped(&self) -> bool {
1987            true
1988        }
1989
1990        // Focus, and with it the keyboard (docs/focus.md): the canvas contract, opted into by
1991        // `Decorate::focusable`. A container never in FOCUSABLE_NODES behaves exactly as
1992        // before (refuses first responder, forwards every key).
1993        #[unsafe(method(acceptsFirstResponder))]
1994        fn accepts_first_responder(&self) -> bool {
1995            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
1996            FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
1997        }
1998
1999        // Clicking a focusable container focuses it, the way clicking a table does. The
2000        // gesture recognizers still see the press: this runs before `super`, which is what
2001        // forwards it to them.
2002        #[unsafe(method(mouseDown:))]
2003        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2004            if transfer::pressed(self, event) { return; }
2005            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
2006            if FOCUSABLE_NODES.with(|t| t.get(ptr)).is_some()
2007                && let Some(window) = self.window()
2008            {
2009                window.makeFirstResponder(Some(self));
2010            }
2011            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2012        }
2013
2014        #[unsafe(method(becomeFirstResponder))]
2015        fn become_first_responder(&self) -> bool {
2016            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
2017            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2018                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2019            }
2020            true
2021        }
2022
2023        #[unsafe(method(resignFirstResponder))]
2024        fn resign_first_responder(&self) -> bool {
2025            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
2026            if let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) {
2027                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
2028            }
2029            true
2030        }
2031
2032        /// The arrows, delivered here while this container is the first responder. Anything
2033        /// else (and every arrow when the app registered no key handler for the node) goes
2034        /// to `super`, which walks the responder chain exactly as it would have without us.
2035        #[unsafe(method(keyDown:))]
2036        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2037            let ptr = (self as *const DayFlipped).cast::<NSView>() as usize;
2038            let handled = ffi_guard::contain(false, || {
2039                let Some(node) = FOCUSABLE_NODES.with(|t| t.get(ptr)) else {
2040                    return false;
2041                };
2042                let Some(key) = key_name(event) else {
2043                    return false;
2044                };
2045                if !day_spec::keys::handled(node) {
2046                    return false;
2047                }
2048                emit(
2049                    node,
2050                    Event::Key(day_spec::KeyEvent::named(
2051                        key,
2052                        key_modifiers(event.modifierFlags()),
2053                    )),
2054                );
2055                true
2056            });
2057            if !handled {
2058                let _: () = unsafe { msg_send![super(self), keyDown: event] };
2059            }
2060        }
2061
2062        /// Show the attached context menu (docs/menus.md) explicitly rather than relying on
2063        /// `NSResponder`'s default `.menu` display: popping it ourselves is deterministic
2064        /// regardless of how the click threads through Day's container hierarchy.
2065        #[unsafe(method(rightMouseDown:))]
2066        fn right_mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2067            if let Some(menu) = self.menuForEvent(event) {
2068                unsafe {
2069                    objc2_app_kit::NSMenu::popUpContextMenu_withEvent_forView(&menu, event, self)
2070                };
2071            } else {
2072                let _: () = unsafe { msg_send![super(self), rightMouseDown: event] };
2073            }
2074        }
2075
2076        #[unsafe(method(drawRect:))]
2077        fn draw_rect(&self, _dirty: NSRect) {
2078            let paint = || {
2079                if self.ivars().pane_backdrop.get() {
2080                    let bounds = self.bounds();
2081                    unsafe {
2082                        // Resolved at draw time, like the section fill below, so the backdrop
2083                        // follows light/dark appearance changes automatically.
2084                        NSColor::windowBackgroundColor().setFill();
2085                        objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).fill();
2086                    }
2087                }
2088                if let Some(radius) = self.ivars().section_card.get() {
2089                    let bounds = self.bounds();
2090                    unsafe {
2091                        // quaternarySystemFill (macOS 14+) is the grouped-card material System
2092                        // Settings uses; older systems fall back to the control background.
2093                        let cls = objc2::class!(NSColor);
2094                        let has: bool = msg_send![cls, respondsToSelector: objc2::sel!(quaternarySystemFillColor)];
2095                        let color: objc2::rc::Retained<NSColor> = if has {
2096                            msg_send![cls, quaternarySystemFillColor]
2097                        } else {
2098                            msg_send![cls, controlBackgroundColor]
2099                        };
2100                        color.setFill();
2101                        let path = objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2102                            bounds, radius, radius,
2103                        );
2104                        path.fill();
2105                    }
2106                }
2107                if let Some((r, g, b, a, radius)) = self.ivars().surface.get() {
2108                    let bounds = self.bounds();
2109                    unsafe {
2110                        NSColor::colorWithSRGBRed_green_blue_alpha(r, g, b, a).setFill();
2111                        let path = if radius > 0.0 {
2112                            objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
2113                                bounds, radius, radius,
2114                            )
2115                        } else {
2116                            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds)
2117                        };
2118                        path.fill();
2119                    }
2120                }
2121            };
2122            // Paint under the standard counterpart of this view's appearance. Inside an
2123            // NSVisualEffectView subtree (the inspector pane) the effective appearance is
2124            // a vibrant one (NSAppearanceNameVibrantDark/-Light), and the system fills'
2125            // vibrant variants are opaque blend colors that only composite correctly in an
2126            // `allowsVibrancy` view: drawn plainly, dark-mode quaternary fill comes out
2127            // near-black instead of lightening. Resolving under aqua/darkAqua gives exactly
2128            // the fills System Settings draws with, and re-resolves on every theme change
2129            // (this runs per draw, and appearance flips redraw).
2130            unsafe {
2131                let names = objc2_foundation::NSArray::from_slice(&[
2132                    objc2_app_kit::NSAppearanceNameAqua,
2133                    objc2_app_kit::NSAppearanceNameDarkAqua,
2134                ]);
2135                let standard = self
2136                    .effectiveAppearance()
2137                    .bestMatchFromAppearancesWithNames(&names)
2138                    .and_then(|n| objc2_app_kit::NSAppearance::appearanceNamed(&n));
2139                match standard {
2140                    Some(appearance) => {
2141                        let block = block2::StackBlock::new(paint);
2142                        appearance.performAsCurrentDrawingAppearance(&block);
2143                    }
2144                    None => paint(),
2145                }
2146            }
2147        }
2148    }
2149    unsafe impl NSObjectProtocol for DayFlipped {}
2150    unsafe impl NSDraggingSource for DayFlipped {
2151        #[unsafe(method(draggingSession:sourceOperationMaskForDraggingContext:))]
2152        fn source_mask(&self, _session: &objc2_app_kit::NSDraggingSession, _context: objc2_app_kit::NSDraggingContext) -> objc2_app_kit::NSDragOperation { objc2_app_kit::NSDragOperation::Copy }
2153    }
2154    impl DayFlipped {
2155        #[unsafe(method(mouseDragged:))]
2156        fn transfer_dragged(&self, event: &NSEvent) {
2157            if !transfer::dragged(self, event) { let _: () = unsafe { msg_send![super(self), mouseDragged: event] }; }
2158        }
2159        #[unsafe(method(draggingEntered:))]
2160        fn transfer_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
2161        #[unsafe(method(draggingUpdated:))]
2162        fn transfer_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation { transfer::proposal(self, info) }
2163        #[unsafe(method(performDragOperation:))]
2164        fn transfer_drop(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool { transfer::receive(self, info) }
2165    }
2166
2167);
2168
2169impl DayFlipped {
2170    fn new(mtm: MainThreadMarker) -> Retained<Self> {
2171        let this = Self::alloc(mtm).set_ivars(FlippedIvars::default());
2172        unsafe { msg_send![super(this), init] }
2173    }
2174
2175    /// Apply a `background`/`corner_radius` surface. The fill (rounded by `corner_radius`) is
2176    /// drawn in `drawRect` with NSColor, not via the layer's `backgroundColor`, whose CGColorRef
2177    /// argument objc2's `msg_send` cannot type-check. A rounded child clip does use the CALayer
2178    /// (`cornerRadius` + `masksToBounds` are a CGFloat + `BOOL`, which are fine).
2179    /// SurfaceRole::SectionCard: the fill resolves dynamically in drawRect (theme-adaptive).
2180    fn set_section_card(&self, corner_radius: f64) {
2181        self.ivars().section_card.set(Some(corner_radius));
2182        unsafe {
2183            let _: () = msg_send![self, setNeedsDisplay: true];
2184        }
2185    }
2186
2187    /// Opaque window-background backdrop (the inspector panel wrap; see `FlippedIvars`).
2188    fn set_pane_backdrop(&self) {
2189        self.ivars().pane_backdrop.set(true);
2190        unsafe {
2191            let _: () = msg_send![self, setNeedsDisplay: true];
2192        }
2193    }
2194
2195    fn set_surface(&self, bg: Option<day_spec::Color>, corner_radius: f64, clips: bool) {
2196        self.ivars()
2197            .surface
2198            .set(bg.map(|c| (c.r, c.g, c.b, c.a, corner_radius)));
2199        unsafe {
2200            let _: () = msg_send![self, setNeedsDisplay: true];
2201            if clips || corner_radius > 0.0 {
2202                let _: () = msg_send![self, setWantsLayer: true];
2203                let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
2204                if !layer.is_null() {
2205                    let _: () = msg_send![layer, setCornerRadius: corner_radius];
2206                    let _: () = msg_send![layer, setMasksToBounds: true];
2207                }
2208            }
2209        }
2210    }
2211}
2212
2213// ---------------------------------------------------------------------------
2214// DayCanvas — a flipped view replaying the Day display list in drawRect (§11)
2215// ---------------------------------------------------------------------------
2216
2217struct CanvasIvars;
2218
2219define_class!(
2220    #[unsafe(super(NSView))]
2221    #[thread_kind = MainThreadOnly]
2222    #[name = "DayCanvas"]
2223    #[ivars = CanvasIvars]
2224    struct DayCanvas;
2225
2226    impl DayCanvas {
2227        #[unsafe(method(isFlipped))]
2228        fn is_flipped(&self) -> bool {
2229            true
2230        }
2231
2232        /// A summon-time context menu (docs/menus.md): built when the right-click lands,
2233        /// from the provider `set_context_menu_fn` registered — so a canvas can select what
2234        /// is under the pointer and offer commands for that selection.
2235        #[unsafe(method_id(menuForEvent:))]
2236        fn menu_for_event(
2237            &self,
2238            event: &objc2_app_kit::NSEvent,
2239        ) -> Option<Retained<NSMenu>> {
2240            let f = CTX_MENU_FNS.with(|t| t.get(self as *const Self as usize));
2241            let Some(f) = f else {
2242                return unsafe { msg_send![super(self), menuForEvent: event] };
2243            };
2244            // Guarded: the provider is app code (it usually re-selects, then builds).
2245            ffi_guard::contain(None, || {
2246                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
2247                let items = f(day_spec::Point::new(p.x, p.y));
2248                if items.is_empty() {
2249                    return None;
2250                }
2251                Some(build_ns_menu(self.mtm(), "", &items))
2252            })
2253        }
2254
2255        // Focus, and with it the keyboard (docs/focus.md, docs/menus.md). A canvas is the one
2256        // built-in piece with no native control under it, so nothing else would ever make it
2257        // the first responder — and without that, arrow keys aimed at what it draws could only
2258        // be caught by watching the whole app.
2259        #[unsafe(method(acceptsFirstResponder))]
2260        fn accepts_first_responder(&self) -> bool {
2261            true
2262        }
2263
2264        // Clicking a canvas focuses it, the way clicking a table or a text field does. The
2265        // gesture recognizers (tap/drag) still see the press — this runs before `super`, which
2266        // is what forwards it to them.
2267        #[unsafe(method(mouseDown:))]
2268        fn mouse_down(&self, event: &objc2_app_kit::NSEvent) {
2269            if let Some(window) = self.window() {
2270                window.makeFirstResponder(Some(self));
2271            }
2272            let _: () = unsafe { msg_send![super(self), mouseDown: event] };
2273        }
2274
2275        // Report focus both ways, so `.focused(signal)` binds two-way and dayscript's
2276        // `assert_focused` can see it.
2277        #[unsafe(method(becomeFirstResponder))]
2278        fn become_first_responder(&self) -> bool {
2279            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2280            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
2281                ffi_guard::contain((), || emit(node, Event::FocusChanged(true)));
2282            }
2283            true
2284        }
2285
2286        #[unsafe(method(resignFirstResponder))]
2287        fn resign_first_responder(&self) -> bool {
2288            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2289            // A composition in progress goes with the focus: the input method is told, so it
2290            // does not commit into whatever is focused next.
2291            if MARKED.with(|t| t.remove(ptr)).is_some()
2292                && let Some(context) = self.inputContext()
2293            {
2294                context.discardMarkedText();
2295            }
2296            if let Some(node) = KEY_NODES.with(|t| t.get(ptr)) {
2297                ffi_guard::contain((), || emit(node, Event::FocusChanged(false)));
2298            }
2299            true
2300        }
2301
2302        /// The keys, delivered to this canvas because it is the first responder. On the short
2303        /// route the arrows and digits; on the full route (docs/menus.md "The full route")
2304        /// every key, through the text input system for the ones that type. Anything
2305        /// unclaimed — and every key when the app registered no handler for this node — goes
2306        /// to `super`, which walks the responder chain exactly as it would have without us.
2307        #[unsafe(method(keyDown:))]
2308        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
2309            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2310            let handled = ffi_guard::contain(false, || {
2311                let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
2312                    return false;
2313                };
2314                // A canvas nobody asked keys from does not get to keep them: an enclosing
2315                // scroll view still scrolls, and an unclaimed key still beeps the way the
2316                // platform means it to.
2317                if !day_spec::keys::handled(node) {
2318                    return false;
2319                }
2320                if day_spec::keys::text(node) {
2321                    return full_route_key_down(self, node, event);
2322                }
2323                let Some(key) = key_name(event) else {
2324                    return false;
2325                };
2326                emit(
2327                    node,
2328                    Event::Key(day_spec::KeyEvent::named(
2329                        key,
2330                        key_modifiers(event.modifierFlags()),
2331                    )),
2332                );
2333                true
2334            });
2335            if !handled {
2336                let _: () = unsafe { msg_send![super(self), keyDown: event] };
2337            }
2338        }
2339
2340        /// The text input context, only for a canvas on the full route: an input context is
2341        /// what makes the input method (and the keyboard layout's dead keys) address this
2342        /// view, and a drawing canvas that hears the arrows alone must not look like a text
2343        /// field to it.
2344        #[unsafe(method_id(inputContext))]
2345        fn input_context(&self) -> Option<Retained<objc2_app_kit::NSTextInputContext>> {
2346            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2347            let takes_keyboard = KEY_NODES
2348                .with(|t| t.get(ptr))
2349                .is_some_and(|node| ffi_guard::contain(false, || day_spec::keys::text(node)));
2350            if takes_keyboard {
2351                unsafe { msg_send![super(self), inputContext] }
2352            } else {
2353                None
2354            }
2355        }
2356
2357        #[unsafe(method(drawRect:))]
2358        fn draw_rect(&self, _dirty: NSRect) {
2359            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2360            let ops = OPS.with(|t| t.get(ptr)).unwrap_or_default();
2361            paint_ops(&ops);
2362        }
2363
2364        /// Hover entry/motion/exit (docs/canvas.md "Interaction"). The tracking area is installed
2365        /// by `enable_gesture`; `updateTrackingAreas` below keeps it the size of the view.
2366        #[unsafe(method(mouseEntered:))]
2367        fn mouse_entered(&self, event: &objc2_app_kit::NSEvent) {
2368            self.report_hover(event, day_spec::DragPhase::Began);
2369        }
2370
2371        #[unsafe(method(mouseMoved:))]
2372        fn mouse_moved(&self, event: &objc2_app_kit::NSEvent) {
2373            self.report_hover(event, day_spec::DragPhase::Changed);
2374        }
2375
2376        #[unsafe(method(mouseExited:))]
2377        fn mouse_exited(&self, event: &objc2_app_kit::NSEvent) {
2378            self.report_hover(event, day_spec::DragPhase::Ended);
2379        }
2380
2381        /// A trackpad rotation (docs/canvas.md "Zoom and pan"). Each event's `rotation` is that
2382        /// event's own angle in degrees, counterclockwise positive; Day wants radians, clockwise
2383        /// positive, cumulative since `Began`. A gesture is bracketed by the event phases; an
2384        /// event with no phase is a lone `Changed` carrying its own angle.
2385        #[unsafe(method(rotateWithEvent:))]
2386        fn rotate_with_event(&self, event: &objc2_app_kit::NSEvent) {
2387            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2388            let Some(node) = ROTATE_NODES.with(|t| t.get(ptr)) else {
2389                let _: () = unsafe { msg_send![super(self), rotateWithEvent: event] };
2390                return;
2391            };
2392            ffi_guard::contain((), || {
2393                let tick = -f64::from(event.rotation()).to_radians();
2394                let raw = event.phase();
2395                let (phase, rotation) = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
2396                    ROTATE_ANGLE.with(|t| t.insert(ptr, tick));
2397                    (day_spec::DragPhase::Began, tick)
2398                } else if raw.intersects(
2399                    objc2_app_kit::NSEventPhase::Ended | objc2_app_kit::NSEventPhase::Cancelled,
2400                ) {
2401                    let total = ROTATE_ANGLE.with(|t| t.remove(ptr)).unwrap_or(0.0) + tick;
2402                    (day_spec::DragPhase::Ended, total)
2403                } else if raw.contains(objc2_app_kit::NSEventPhase::Changed) {
2404                    let total = ROTATE_ANGLE
2405                        .with(|t| {
2406                            t.with(ptr, |a| {
2407                                *a += tick;
2408                                *a
2409                            })
2410                        })
2411                        .unwrap_or(tick);
2412                    (day_spec::DragPhase::Changed, total)
2413                } else {
2414                    (day_spec::DragPhase::Changed, tick)
2415                };
2416                let win = event.locationInWindow();
2417                let loc = self.convertPoint_fromView(win, None);
2418                emit(
2419                    node,
2420                    Event::Rotate {
2421                        phase,
2422                        rotation,
2423                        location: Point::new(loc.x, loc.y),
2424                    },
2425                );
2426            })
2427        }
2428
2429        #[unsafe(method(scrollWheel:))]
2430        fn scroll_wheel(&self, event: &objc2_app_kit::NSEvent) {
2431            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2432            let Some(node) = PAN_NODES.with(|t| t.get(ptr)) else {
2433                let _: () = unsafe { msg_send![super(self), scrollWheel: event] };
2434                return;
2435            };
2436            ffi_guard::contain((), || {
2437                // Trackpads bracket a pan with phases; a discrete wheel tick has none and
2438                // arrives as a lone Changed — exactly the Event::Pan contract.
2439                let raw = unsafe { event.phase() };
2440                let phase = if raw.contains(objc2_app_kit::NSEventPhase::Began) {
2441                    day_spec::DragPhase::Began
2442                } else if raw.contains(objc2_app_kit::NSEventPhase::Ended)
2443                    || raw.contains(objc2_app_kit::NSEventPhase::Cancelled)
2444                {
2445                    day_spec::DragPhase::Ended
2446                } else {
2447                    day_spec::DragPhase::Changed
2448                };
2449                let delta = Point::new(unsafe { event.scrollingDeltaX() }, unsafe {
2450                    event.scrollingDeltaY()
2451                });
2452                let win = unsafe { event.locationInWindow() };
2453                let loc = self.convertPoint_fromView(win, None);
2454                emit(
2455                    node,
2456                    Event::Pan {
2457                        phase,
2458                        delta,
2459                        location: Point::new(loc.x, loc.y),
2460                    },
2461                );
2462            })
2463        }
2464    }
2465
2466    unsafe impl NSObjectProtocol for DayCanvas {}
2467
2468    /// The text input system's client (docs/menus.md "The full route"): the view a dead key
2469    /// or an input method composes into. A canvas has no document, so the marked text is
2470    /// held here and never shown; what the input method commits is the key event's text.
2471    unsafe impl NSTextInputClient for DayCanvas {
2472        #[unsafe(method(insertText:replacementRange:))]
2473        unsafe fn insert_text(&self, string: &AnyObject, _replacement: NSRange) {
2474            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2475            MARKED.with(|t| t.remove(ptr));
2476            let Some(node) = KEY_NODES.with(|t| t.get(ptr)) else {
2477                return;
2478            };
2479            let text = text_of_input_string(string);
2480            if text.is_empty() {
2481                return;
2482            }
2483            ffi_guard::contain((), || {
2484                let interpreting = INTERPRETING.with(|i| i.borrow().clone());
2485                let event = match interpreting {
2486                    // One character typed by the key being interpreted: named by that key.
2487                    Some((key, mods)) if text.chars().count() == 1 => {
2488                        day_spec::KeyEvent::typed_by(key, text, mods)
2489                    }
2490                    Some((_, mods)) => day_spec::KeyEvent::typed_text(text, mods),
2491                    // Committed outside any key press (the Character Viewer, dictation).
2492                    None => day_spec::KeyEvent::typed_text(text, 0),
2493                };
2494                emit(node, Event::Key(event));
2495            });
2496        }
2497
2498        /// A key the text input system turned into an editing command (`insertNewline:`,
2499        /// `moveLeft:`, …). `keyDown:` already named every key the route carries before it
2500        /// asked the input system, so nothing is left to do here; anything else (a `noop:`
2501        /// for a function key the vocabulary lacks) types nothing, by design.
2502        #[unsafe(method(doCommandBySelector:))]
2503        unsafe fn do_command_by_selector(&self, _selector: Sel) {}
2504
2505        #[unsafe(method(setMarkedText:selectedRange:replacementRange:))]
2506        unsafe fn set_marked_text(&self, string: &AnyObject, _selected: NSRange, _replacement: NSRange) {
2507            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2508            let text = text_of_input_string(string);
2509            if text.is_empty() {
2510                MARKED.with(|t| t.remove(ptr));
2511            } else {
2512                MARKED.with(|t| t.insert(ptr, text));
2513            }
2514        }
2515
2516        #[unsafe(method(unmarkText))]
2517        fn unmark_text(&self) {
2518            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2519            MARKED.with(|t| t.remove(ptr));
2520        }
2521
2522        #[unsafe(method(selectedRange))]
2523        fn selected_range(&self) -> NSRange {
2524            NSRange::new(objc2_foundation::NSNotFound as usize, 0)
2525        }
2526
2527        #[unsafe(method(markedRange))]
2528        fn marked_range(&self) -> NSRange {
2529            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2530            match MARKED.with(|t| t.get(ptr)) {
2531                Some(marked) => NSRange::new(0, marked.encode_utf16().count()),
2532                None => NSRange::new(objc2_foundation::NSNotFound as usize, 0),
2533            }
2534        }
2535
2536        #[unsafe(method(hasMarkedText))]
2537        fn has_marked_text(&self) -> bool {
2538            let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2539            MARKED.with(|t| t.contains(ptr))
2540        }
2541
2542        #[unsafe(method_id(attributedSubstringForProposedRange:actualRange:))]
2543        unsafe fn attributed_substring(
2544            &self,
2545            _range: NSRange,
2546            _actual: objc2_foundation::NSRangePointer,
2547        ) -> Option<Retained<objc2_foundation::NSAttributedString>> {
2548            None
2549        }
2550
2551        #[unsafe(method_id(validAttributesForMarkedText))]
2552        fn valid_attributes(&self) -> Retained<NSArray<objc2_foundation::NSAttributedStringKey>> {
2553            NSArray::new()
2554        }
2555
2556        /// Where the input method puts its candidate window: under the canvas, since the
2557        /// canvas does not say where its caret is.
2558        #[unsafe(method(firstRectForCharacterRange:actualRange:))]
2559        unsafe fn first_rect(&self, _range: NSRange, _actual: objc2_foundation::NSRangePointer) -> NSRect {
2560            let bounds = self.bounds();
2561            let in_window = self.convertRect_toView(bounds, None);
2562            match self.window() {
2563                Some(window) => window.convertRectToScreen(in_window),
2564                None => in_window,
2565            }
2566        }
2567
2568        #[unsafe(method(characterIndexForPoint:))]
2569        fn character_index_for_point(&self, _point: NSPoint) -> objc2_foundation::NSUInteger {
2570            objc2_foundation::NSNotFound as objc2_foundation::NSUInteger
2571        }
2572    }
2573);
2574
2575impl DayCanvas {
2576    fn new(mtm: MainThreadMarker) -> Retained<Self> {
2577        let this = Self::alloc(mtm).set_ivars(CanvasIvars);
2578        unsafe { msg_send![super(this), init] }
2579    }
2580
2581    /// One hover phase, reported to whichever node asked for it (docs/canvas.md "Interaction").
2582    ///
2583    /// `mouseEntered:`/`mouseExited:` are scoped by the tracking area, but **`mouseMoved:` is
2584    /// not**: it walks the responder chain, so a focused canvas hears about motion anywhere in
2585    /// its window — including outside itself. Hence the bounds test, without which a canvas
2586    /// reports a hover for a pointer that is nowhere near it (measured: a pointer parked outside
2587    /// the window entirely still produced hover positions).
2588    fn report_hover(&self, event: &objc2_app_kit::NSEvent, phase: day_spec::DragPhase) {
2589        let ptr = (self as *const DayCanvas).cast::<NSView>() as usize;
2590        let Some(node) = HOVER_NODES.with(|t| t.get(ptr)) else {
2591            return;
2592        };
2593        ffi_guard::contain((), || {
2594            let win = unsafe { event.locationInWindow() };
2595            let loc = self.convertPoint_fromView(win, None);
2596            let b = self.bounds();
2597            let inside = loc.x >= b.origin.x
2598                && loc.x <= b.origin.x + b.size.width
2599                && loc.y >= b.origin.y
2600                && loc.y <= b.origin.y + b.size.height;
2601            // An exit is reported wherever it happens — that is the point of it — but a move
2602            // outside the view is not this view's hover.
2603            if !inside && phase != day_spec::DragPhase::Ended {
2604                return;
2605            }
2606            emit(
2607                node,
2608                Event::Hover {
2609                    phase,
2610                    location: Point::new(loc.x, loc.y),
2611                },
2612            );
2613        });
2614    }
2615}
2616
2617/// The tracking area a hovering canvas needs. `InVisibleRect` makes it follow the view's bounds,
2618/// so there is no rect to keep in step with layout; `ActiveInKeyWindow` matches the cursor areas
2619/// already installed here — a background window does not report hovers.
2620fn install_tracking_area(h: &NSView) {
2621    let opts = NSTrackingAreaOptions::MouseEnteredAndExited
2622        | NSTrackingAreaOptions::MouseMoved
2623        | NSTrackingAreaOptions::ActiveInKeyWindow
2624        | NSTrackingAreaOptions::InVisibleRect;
2625    let any: &objc2::runtime::AnyObject = h;
2626    let area = unsafe {
2627        NSTrackingArea::initWithRect_options_owner_userInfo(
2628            NSTrackingArea::alloc(),
2629            NSRect::ZERO,
2630            opts,
2631            Some(any),
2632            None,
2633        )
2634    };
2635    unsafe { h.addTrackingArea(&area) };
2636}
2637
2638// ---------------------------------------------------------------------------
2639// DayGesture — tap/drag recognizer target, node-id keyed (docs/shapes.md)
2640// ---------------------------------------------------------------------------
2641
2642struct GestureIvars {
2643    node: NodeId,
2644    kind: day_spec::GestureKind,
2645}
2646
2647define_class!(
2648    #[unsafe(super(NSObject))]
2649    #[thread_kind = MainThreadOnly]
2650    #[name = "DayGesture"]
2651    #[ivars = GestureIvars]
2652    struct DayGesture;
2653
2654    unsafe impl NSObjectProtocol for DayGesture {}
2655
2656    impl DayGesture {
2657        #[unsafe(method(fire:))]
2658        fn fire(&self, g: &NSGestureRecognizer) {
2659            ffi_guard::contain((), || {
2660                let node = self.ivars().node;
2661                let view = g.view();
2662                let loc = g.locationInView(view.as_deref());
2663                let at = Point::new(loc.x, loc.y);
2664                let phase = match g.state() {
2665                    NSGestureRecognizerState::Began => day_spec::DragPhase::Began,
2666                    NSGestureRecognizerState::Ended
2667                    | NSGestureRecognizerState::Cancelled
2668                    | NSGestureRecognizerState::Failed => day_spec::DragPhase::Ended,
2669                    _ => day_spec::DragPhase::Changed,
2670                };
2671                let obj: &objc2::runtime::AnyObject = g.as_ref();
2672                match self.ivars().kind {
2673                    day_spec::GestureKind::Drag => {
2674                        let translation = if let Some(pan) = obj.downcast_ref::<NSPanGestureRecognizer>() {
2675                            let t = unsafe { pan.translationInView(view.as_deref()) };
2676                            Point::new(t.x, t.y)
2677                        } else {
2678                            Point::ZERO
2679                        };
2680                        emit(node, Event::Drag { phase, location: at, translation });
2681                    }
2682                    day_spec::GestureKind::Pinch => {
2683                        // Cumulative since Began: `magnification` is the total delta (0 =
2684                        // unchanged), and Day's contract wants a factor.
2685                        let scale = if let Some(m) =
2686                            obj.downcast_ref::<objc2_app_kit::NSMagnificationGestureRecognizer>()
2687                        {
2688                            1.0 + unsafe { m.magnification() }
2689                        } else {
2690                            1.0
2691                        };
2692                        emit(node, Event::Pinch { phase, scale, location: at });
2693                    }
2694                    _ => emit(node, Event::Tap(at)),
2695                }
2696            })
2697        }
2698    }
2699);
2700
2701impl DayGesture {
2702    fn new(mtm: MainThreadMarker, node: NodeId, kind: day_spec::GestureKind) -> Retained<Self> {
2703        let this = Self::alloc(mtm).set_ivars(GestureIvars { node, kind });
2704        unsafe { msg_send![super(this), init] }
2705    }
2706}
2707
2708// ---------------------------------------------------------------------------
2709// Navigation (docs/navigation.md): NSSplitView host, sidebar + detail panes.
2710// Page FRAMES are pane-owned (autoresized); Day lays content inside the size each
2711// page reports from setFrameSize:. Day's set_frame on pages is skipped.
2712// ---------------------------------------------------------------------------
2713
2714/// The stack presentation's back header (desktop has no system back affordance — this bar
2715/// gives a pushed page its way out, like AdwNavigationView's header on GTK). Hidden at root.
2716struct NavHeader {
2717    bar: Retained<NSView>,
2718    title: Retained<NSTextField>,
2719    /// Title per stack level (index 0 = root); the field shows the last.
2720    titles: Vec<String>,
2721    _target: Retained<DayTarget>,
2722}
2723
2724/// Height of the stack-nav back header while a pushed page is showing.
2725const NAV_HEADER_H: f64 = 34.0;
2726
2727// Drag limits for both draggable panes come from day-spec (`NAV_SIDEBAR_MIN_W` and friends): a
2728// sidebar NSSplitViewItem enforces them itself, which is why the divider no longer needs
2729// restoring by hand after every window resize.
2730use day_spec::{NAV_LIST_MAX_W, NAV_LIST_MIN_W, NAV_SIDEBAR_MAX_W, NAV_SIDEBAR_MIN_W};
2731
2732/// The content-list width to place divider 1 at, once, the first time the pane is showing —
2733/// `None` when the pane is collapsed or has already been placed. Latches on the way out, so the
2734/// two callers (the first frame pass, and the patch that reveals the pane) cannot both spend it.
2735fn take_list_placement(state: &mut NavState) -> Option<f64> {
2736    if !state.list_visible || state.list_positioned {
2737        return None;
2738    }
2739    state.list_positioned = true;
2740    state.list_width
2741}
2742
2743/// A tabs host's `NSTabView` margins inside its pane: the sides and the foot, and the top —
2744/// deeper, since the tabs themselves stand about a segment's height above the bezel.
2745const NAV_TABVIEW_INSET: f64 = 12.0;
2746const NAV_TABVIEW_INSET_TOP: f64 = 8.0;
2747
2748/// The `NavPresentation::Tabs` container: a real `NSTabView` — the Mac's own tab control, top
2749/// tabs on a bezel — whose items own the detail pages. The page frames stay native-owned
2750/// exactly as in a split: the tab view frames the selected item's view, and the page's
2751/// `setFrameSize:` reports it. The labels come from the NAV_MENU's rows, which arrive after
2752/// the pages' host (day-core mounts top-down: the rows page joins the host before its menu is
2753/// built), so `adopt_menu_for_tabs` runs when the menu is inserted and whenever its rows are
2754/// rebuilt.
2755///
2756/// Until 2026-09-12 this was an `NSSegmentedControl` docked at the foot, built from the rows
2757/// page's menu at the moment that page was inserted — before the menu existed — so no bar was
2758/// ever built and a tabs host showed its first page alone.
2759struct TabHost {
2760    view: Retained<objc2_app_kit::NSTabView>,
2761    /// The delegate reporting a native tab pick against the NAV_MENU's node; set once the menu
2762    /// is known.
2763    target: Option<Retained<DayTarget>>,
2764}
2765
2766thread_local! {
2767    /// A Day-driven tab selection in flight (`NavPatch::Select`, a label sync): the tab view's
2768    /// delegate must not echo it back as `SelectionChanged`.
2769    static TAB_PICK_SUPPRESS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2770}
2771
2772/// Give the tab view its labels from the rows, and its selection. Rows and items are
2773/// index-aligned (destination `i` is item `i`); a count mismatch mid-rebuild labels what both
2774/// have.
2775fn sync_tab_labels(tabs: &TabHost, titles: &[String], selected: usize) {
2776    unsafe {
2777        let n = tabs.view.numberOfTabViewItems().max(0) as usize;
2778        for (i, title) in titles.iter().enumerate().take(n) {
2779            tabs.view
2780                .tabViewItemAtIndex(i as isize)
2781                .setLabel(&NSString::from_str(title));
2782        }
2783        if n > 0 {
2784            TAB_PICK_SUPPRESS.with(|s| s.set(true));
2785            tabs.view
2786                .selectTabViewItemAtIndex(selected.min(n - 1) as isize);
2787            TAB_PICK_SUPPRESS.with(|s| s.set(false));
2788        }
2789    }
2790}
2791
2792/// A NAV_MENU reached a tabs host (its rows page sits in the host's collapsed sidebar pane):
2793/// the menu's rows become the tab labels and its node the delegate's target. Walks up from the
2794/// menu, so the innermost host — the one whose rows these are — is the one that takes them.
2795fn adopt_menu_for_tabs(mtm: MainThreadMarker, menu: &NSView) {
2796    let Some((titles, node)) = NAV_MENUS.with(|m| {
2797        m.borrow().get(&ptr_of(menu)).map(|(_, d)| {
2798            let ivars = d.ivars();
2799            (
2800                ivars
2801                    .items
2802                    .borrow()
2803                    .iter()
2804                    .map(|s| s.to_string())
2805                    .collect::<Vec<String>>(),
2806                ivars.node,
2807            )
2808        })
2809    }) else {
2810        return;
2811    };
2812    let mut up = unsafe { menu.superview() };
2813    while let Some(v) = up {
2814        let reached = NAV_STATE.with(|m| {
2815            let mut m = m.borrow_mut();
2816            let Some(s) = m.get_mut(&ptr_of(&v)) else {
2817                return false;
2818            };
2819            let selected = s.selected;
2820            if let Some(tabs) = s.tabs.as_mut() {
2821                if tabs.target.is_none() {
2822                    let target = DayTarget::new(mtm, node);
2823                    unsafe {
2824                        tabs.view
2825                            .setDelegate(Some(ProtocolObject::from_ref(&*target)))
2826                    };
2827                    tabs.target = Some(target);
2828                }
2829                sync_tab_labels(tabs, &titles, selected);
2830            }
2831            true
2832        });
2833        if reached {
2834            return;
2835        }
2836        up = unsafe { v.superview() };
2837    }
2838}
2839
2840struct NavState {
2841    sidebar_wrap: Retained<NSView>,
2842    detail_wrap: Retained<NSView>,
2843    /// The container behind the host view. A view holds NO strong reference to its controller,
2844    /// and the split view controller is what owns the items, their holding priorities, the
2845    /// sidebar's material and the split's delegate duties — so it has to be retained here or
2846    /// the sidebar loses its treatment the moment this realize returns.
2847    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
2848    /// The sidebar item, for the `SidebarToggle` duty (docs/toolbars.md). AppKit's own
2849    /// `NSToolbarToggleSidebarItem` reaches the controller through the responder chain; this is
2850    /// the path dayscript and any non-toolbar caller take.
2851    sidebar_item: Retained<objc2_app_kit::NSSplitViewItem>,
2852    /// The content-list pane (docs/navigation.md), `Some` only on a host whose
2853    /// `NavProps::list_width` was set: the wrap its `Pane::List` page fills, and the
2854    /// `contentList` split item `NavPatch::ListVisible` collapses. The pane PERSISTS through
2855    /// every presentation (`Cap::NavContentList` = Native) — a narrow window collapses the
2856    /// sidebar and keeps the list, exactly as a narrow Mail.app does.
2857    list_wrap: Option<Retained<NSView>>,
2858    list_item: Option<Retained<objc2_app_kit::NSSplitViewItem>>,
2859    /// The app's requested content-list width (`NavProps::list_width`) — applied once, at the
2860    /// first frame pass, by placing divider 1 (see `set_frame`).
2861    list_width: Option<f64>,
2862    /// Whether the content-list pane is showing (`NavProps::list_visible`, then
2863    /// `NavPatch::ListVisible`). Placing divider 1 for a pane that is collapsed is what re-opens
2864    /// it, so both placement paths ask first.
2865    list_visible: bool,
2866    /// Whether divider 1 has been placed at the app's requested width yet. Separate from
2867    /// `positioned` because the pane may not exist on screen when the first frame pass runs: an
2868    /// app opening on a full-width destination has nothing to size then, and spending the
2869    /// one-time placement there is what left the list at the solver's own width when it did
2870    /// appear.
2871    list_positioned: bool,
2872    /// Detail pages in stack order (the sidebar page is not in here in split mode; in stack
2873    /// mode `split == false`, the root page is here too, so push/pop visibility covers it).
2874    pages: Vec<Retained<NSView>>,
2875    /// The host's sidebar page, once it has one — what a re-present moves between the sidebar
2876    /// pane and the head of `pages` (docs/size-classes.md).
2877    sidebar_page: Option<Retained<NSView>>,
2878    /// The content-list pane's page, re-framed when the pane is first revealed: it was inserted
2879    /// into a collapsed wrap, where autoresizing can only keep it at zero.
2880    list_page: Option<Retained<NSView>>,
2881    positioned: bool,
2882    /// Which of the four presentations is drawn right now (docs/size-classes.md). All of them are
2883    /// the same `NSSplitViewController`: a stack is that split with its sidebar collapsed, a rail
2884    /// is it with a narrow one, and a tab bar is a collapsed sidebar plus the bottom bar below.
2885    presentation: NavPresentation,
2886    /// The detail page on screen, as an index into `pages`. Maintained by every patch that
2887    /// changes it — push, pop and select alike — so a re-present can carry it across.
2888    selected: usize,
2889    /// The tab view (`NavPresentation::Tabs` only), holding the detail pages as its items and
2890    /// labeled from the same rows the sidebar's outline view shows; a pick emits
2891    /// `SelectionChanged` against the same NAV_MENU node.
2892    tabs: Option<TabHost>,
2893    /// Back header (stack presentation only).
2894    header: Option<NavHeader>,
2895    /// The host's own title, kept so a re-present into a stack can seed a fresh back header
2896    /// with the same root title the initial build would have used.
2897    root_title: String,
2898    /// The host's node, for the same reason — a back header's button targets it.
2899    node: NodeId,
2900    /// How far the host reaches up under the window's title bar (see `pane_under_title_bar`):
2901    /// the strip each pane's wrap is kept below. Zero for a host that does not start at the top
2902    /// of a pinned window.
2903    title_strip: f64,
2904}
2905
2906/// A split item's view: a transparent pane that runs the item's full height, with `wrap` (the
2907/// view Day's pages and the rest of this backend frame themselves against) inside it.
2908///
2909/// `NSSplitViewController` expects its split view to reach the top of a full-size-content window
2910/// and lays its title-bar treatment over the top of every item: a title-bar background, and on
2911/// macOS 26 and later the frosted scroll pocket. Day pins its content below the title bar
2912/// (`pin_below_title_bar`), so a split framed where Day lays it out put that treatment over the
2913/// first strip of every page instead, blurring a detail page's heading. The host is framed up
2914/// under the bar instead (`set_frame`), and each wrap is held below the strip inside its pane, so
2915/// the treatment lands on the bar, the sidebar's material runs to the top of the window as
2916/// `allowsFullHeightLayout` intends, and every page still starts where Day laid it out.
2917fn pane_under_title_bar(mtm: MainThreadMarker, wrap: &NSView) -> Retained<NSView> {
2918    let pane = view_of(DayFlipped::new(mtm));
2919    unsafe {
2920        wrap.setFrame(pane.bounds());
2921        wrap.setAutoresizingMask(
2922            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
2923                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
2924        );
2925        pane.addSubview(wrap);
2926    }
2927    pane
2928}
2929
2930/// Hold `wrap` `strip` points below the top of the pane that holds it.
2931fn place_below_strip(wrap: &NSView, strip: f64) {
2932    let Some(pane) = (unsafe { wrap.superview() }) else {
2933        return;
2934    };
2935    let b = pane.bounds();
2936    unsafe {
2937        wrap.setFrame(NSRect::new(
2938            NSPoint::new(0.0, strip),
2939            NSSize::new(b.size.width, (b.size.height - strip).max(0.0)),
2940        ))
2941    };
2942}
2943
2944/// The stack presentation's back header: a chevron + centered title docked above the pages,
2945/// hidden at the root. Desktop has no system back affordance, so a pushed page carries its own
2946/// way out (docs/navigation.md).
2947///
2948/// Built here rather than inline because a host that RE-PRESENTS into a stack needs one at that
2949/// moment (docs/size-classes.md), and a header that differed from the one a stack-at-launch host
2950/// gets would be a second shape to keep in step.
2951fn build_nav_header(
2952    mtm: MainThreadMarker,
2953    id: NodeId,
2954    detail_wrap: &NSView,
2955    root_title: &str,
2956) -> NavHeader {
2957    let bar = view_of(DayFlipped::new(mtm));
2958    let target = DayTarget::new(mtm, id);
2959    let back = unsafe {
2960        // Invariant: NSImageNameGoBackTemplate is one of AppKit's own named images, present
2961        // on every macOS release this backend builds for.
2962        let img = objc2_app_kit::NSImage::imageNamed(objc2_app_kit::NSImageNameGoBackTemplate)
2963            .expect("NSGoBackTemplate");
2964        let tobj: &objc2::runtime::AnyObject = target.as_ref();
2965        objc2_app_kit::NSButton::buttonWithImage_target_action(
2966            &img,
2967            Some(tobj),
2968            Some(sel!(navBack:)),
2969            mtm,
2970        )
2971    };
2972    let title = unsafe { NSTextField::labelWithString(&NSString::from_str(root_title), mtm) };
2973    unsafe {
2974        back.setFrame(NSRect::new(
2975            NSPoint::new(6.0, 4.0),
2976            NSSize::new(30.0, NAV_HEADER_H - 8.0),
2977        ));
2978        title.setFont(Some(&NSFont::boldSystemFontOfSize(13.0)));
2979        title.setAlignment(objc2_app_kit::NSTextAlignment::Center);
2980        title.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
2981        title.setFrame(NSRect::new(
2982            NSPoint::new(44.0, 9.0),
2983            NSSize::new((detail_wrap.bounds().size.width - 88.0).max(0.0), 18.0),
2984        ));
2985        title.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2986        bar.setFrame(NSRect::new(
2987            NSPoint::new(0.0, 0.0),
2988            NSSize::new(detail_wrap.bounds().size.width, NAV_HEADER_H),
2989        ));
2990        bar.setAutoresizingMask(objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable);
2991        bar.addSubview(&back);
2992        bar.addSubview(&title);
2993        bar.setHidden(true);
2994        detail_wrap.addSubview(&bar);
2995    }
2996    NavHeader {
2997        bar,
2998        title,
2999        titles: vec![root_title.to_string()],
3000        _target: target,
3001    }
3002}
3003
3004/// The frame a stack page occupies inside the detail wrap: full bounds at the root, inset below
3005/// the back header while a pushed page is showing. (A tabs host's pages are framed by its
3006/// `NSTabView`, never through here.)
3007fn nav_page_frame(wrap: &NSView, header_visible: bool) -> NSRect {
3008    let b = wrap.bounds();
3009    let top = if header_visible { NAV_HEADER_H } else { 0.0 };
3010    NSRect::new(
3011        NSPoint::new(0.0, top),
3012        NSSize::new(b.size.width, (b.size.height - top).max(0.0)),
3013    )
3014}
3015
3016/// The row titles and the NAV_MENU node of the menu inside `page`, if it has one.
3017///
3018/// The tab bar needs the same rows the sidebar shows, and they arrive at the NAV_MENU rather
3019/// than at the host. Rather than plumb a second copy through the props, this walks down to the
3020/// menu that is already there — the sidebar page is Day-built and shallow, so the search is a
3021/// handful of views — and reads the titles it has stored for its own outline view.
3022fn nav_menu_rows(page: &NSView) -> Option<(Vec<String>, NodeId)> {
3023    fn walk(v: &NSView, out: &mut Option<(Vec<String>, NodeId)>) {
3024        if out.is_some() {
3025            return;
3026        }
3027        let found = NAV_MENUS.with(|m| {
3028            m.borrow()
3029                .get(&(v as *const NSView as usize))
3030                .map(|(_, d)| {
3031                    let ivars = d.ivars();
3032                    (
3033                        ivars.items.borrow().iter().map(|s| s.to_string()).collect(),
3034                        ivars.node,
3035                    )
3036                })
3037        });
3038        if found.is_some() {
3039            *out = found;
3040            return;
3041        }
3042        for sub in unsafe { v.subviews() }.iter() {
3043            walk(&sub, out);
3044        }
3045    }
3046    let mut out = None;
3047    walk(page, &mut out);
3048    out
3049}
3050
3051/// Apply a presentation to the sidebar split item. All four are the same item at a different
3052/// thickness or collapsed outright, which is why a morph never rebuilds the split.
3053fn apply_sidebar_item(item: &objc2_app_kit::NSSplitViewItem, pres: NavPresentation) {
3054    let shown = matches!(pres, NavPresentation::Split | NavPresentation::Rail);
3055    unsafe {
3056        item.setCanCollapse(shown);
3057        item.setCollapsed(!shown);
3058        match pres {
3059            NavPresentation::Split => {
3060                item.setAllowsFullHeightLayout(true);
3061                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
3062                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
3063            }
3064            // macOS has no rail: nothing in AppKit is a vertical strip of icon-only
3065            // destinations, and a source list pinned to icon width just truncates every row to an
3066            // ellipsis. `NavPresentation::Rail` is explicitly ROUNDABLE for exactly this case, so
3067            // it lands on the neighbor a Mac does have — an ordinary sidebar. Windows rounds the
3068            // other way (`PaneDisplayMode = LeftCompact` is a real rail there).
3069            NavPresentation::Rail => {
3070                item.setAllowsFullHeightLayout(true);
3071                item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
3072                item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
3073            }
3074            // Zero the thickness bounds before collapsing takes effect, or the pane keeps a
3075            // minimum width and the detail never reaches the window edge.
3076            NavPresentation::Stack | NavPresentation::Tabs => {
3077                item.setMinimumThickness(0.0);
3078                item.setMaximumThickness(0.0);
3079            }
3080        }
3081    }
3082}
3083
3084/// Show/hide the stack-nav back header for the given page stack and re-frame the pages under
3085/// it. The header shows exactly while a pushed page (depth ≥ 1 above the root) is on top; each
3086/// page's `DayNavPage::setFrameSize` reports the new size so Day re-lays its content.
3087/// The split view of the navigation host in `window` that has a content-list pane, for the
3088/// tracking separator pinned to its second divider (docs/toolbars.md).
3089pub(crate) fn list_split_view(window: usize) -> Option<Retained<objc2_app_kit::NSSplitView>> {
3090    NAV_STATE.with(|m| {
3091        m.borrow()
3092            .values()
3093            .find(|st| {
3094                st.list_item.is_some()
3095                    && st
3096                        .sidebar_wrap
3097                        .window()
3098                        .is_some_and(|w| Retained::as_ptr(&w) as usize == window)
3099            })
3100            .map(|st| unsafe { st._split_vc.splitView() })
3101    })
3102}
3103
3104fn sync_nav_header(hdr: &NavHeader, wrap: &NSView, pages: &[Retained<NSView>]) {
3105    let visible = pages.len() >= 2;
3106    hdr.bar.setHidden(!visible);
3107    unsafe {
3108        hdr.title.setStringValue(&NSString::from_str(
3109            hdr.titles.last().map(String::as_str).unwrap_or(""),
3110        ));
3111    }
3112    let frame = nav_page_frame(wrap, visible);
3113    for page in pages {
3114        unsafe { page.setFrame(frame) };
3115    }
3116}
3117
3118/// Re-present a live nav host (docs/size-classes.md): the window crossed a breakpoint, so the
3119/// chrome changes but the pages do not.
3120///
3121/// Both presentations already share one `NSSplitViewController` — a stack is the same split with
3122/// its sidebar item collapsed to zero thickness — so the morph is three moves, and none of them
3123/// touches a page's CONTENT:
3124///
3125/// 1. the sidebar item collapses or expands (AppKit animates it and re-runs the titlebar
3126///    separator on its own),
3127/// 2. the sidebar PAGE moves between the sidebar wrap and the head of the detail stack,
3128/// 3. the back header appears or hides, since only a stack has one.
3129///
3130/// `addSubview` re-parents a view rather than rebuilding it, so every page keeps its subtree,
3131/// its scroll position, and its first responder across the move.
3132fn nav_present(mtm: MainThreadMarker, host: &Handle, next: NavPresentation) {
3133    let Some((sidebar_page, detail_wrap, sidebar_wrap, sidebar_item, was, root_title, id, sel)) =
3134        NAV_STATE.with(|m| {
3135            let st = m.borrow();
3136            let s = st.get(&ptr_of(host))?;
3137            Some((
3138                s.sidebar_page.clone(),
3139                s.detail_wrap.clone(),
3140                s.sidebar_wrap.clone(),
3141                s.sidebar_item.clone(),
3142                s.presentation,
3143                s.root_title.clone(),
3144                s.node,
3145                s.selected,
3146            ))
3147        })
3148    else {
3149        return;
3150    };
3151    if was == next {
3152        return;
3153    }
3154    apply_sidebar_item(&sidebar_item, next);
3155    // Settle the split now rather than at the next natural layout pass. `setCollapsed` marks the
3156    // split view as needing layout; without this the pane keeps its old width for one more frame,
3157    // which the dayscript screenshot seam captures (it renders the window offscreen the instant
3158    // the patch returns) and which a user crossing a breakpoint sees as a stutter.
3159    NAV_STATE.with(|m| {
3160        if let Some(s) = m.borrow().get(&ptr_of(host)) {
3161            unsafe { s._split_vc.splitView().layoutSubtreeIfNeeded() };
3162        }
3163    });
3164    // A stack needs a back header; nothing else may show one. Built on demand and kept
3165    // afterwards — rebuilding it on every morph would leak a target per crossing.
3166    let stacked = next == NavPresentation::Stack;
3167    let mut header = NAV_STATE.with(|m| m.borrow_mut().get_mut(&ptr_of(host))?.header.take());
3168    if stacked && header.is_none() {
3169        header = Some(build_nav_header(mtm, id, &detail_wrap, &root_title));
3170    }
3171    if let Some(hdr) = header.as_ref() {
3172        hdr.bar.setHidden(true);
3173    }
3174    // No tab view here: `Tabs` is a PINNED style on this backend (`Cap::NavTabsAdaptive` is
3175    // off), resolved the same at every width, so a host never morphs into or out of it — its
3176    // `NSTabView` is built at realize and lives for the host.
3177    // Which page is on screen, by IDENTITY: moving the sidebar page in or out of the detail list
3178    // shifts every index past it, so an index captured now would name the wrong page after.
3179    let mut pages = NAV_STATE.with(|m| {
3180        m.borrow()
3181            .get(&ptr_of(host))
3182            .map(|s| s.pages.clone())
3183            .unwrap_or_default()
3184    });
3185    let shown_page = pages.get(sel).cloned();
3186    // The sidebar page is a stack ROOT only while stacked; otherwise it lives in its own pane,
3187    // which is the sidebar in `Split`/`Rail` and a collapsed one behind a tab bar in `Tabs`.
3188    if let Some(page) = sidebar_page {
3189        pages.retain(|p| ptr_of(p) != ptr_of(&page));
3190        unsafe {
3191            if stacked {
3192                detail_wrap.addSubview(&page);
3193                pages.insert(0, page.clone());
3194            } else {
3195                page.setFrame(sidebar_wrap.bounds());
3196                sidebar_wrap.addSubview(&page);
3197            }
3198        }
3199        // A pane always shows its page; as a stack root it may have been hidden under a push.
3200        page.setHidden(false);
3201    }
3202    let shown = shown_page
3203        .and_then(|p| pages.iter().position(|q| ptr_of(q) == ptr_of(&p)))
3204        .unwrap_or_else(|| pages.len().saturating_sub(1));
3205    for (i, page) in pages.iter().enumerate() {
3206        page.setHidden(i != shown);
3207    }
3208    NAV_STATE.with(|m| {
3209        let mut m = m.borrow_mut();
3210        if let Some(s) = m.get_mut(&ptr_of(host)) {
3211            s.presentation = next;
3212            s.pages = pages;
3213            s.selected = shown;
3214            s.header = header;
3215            if let Some(hdr) = s.header.as_ref() {
3216                // Depth drives visibility, and the header is meaningless anywhere but a stack.
3217                if stacked {
3218                    sync_nav_header(hdr, &s.detail_wrap, &s.pages);
3219                } else {
3220                    hdr.bar.setHidden(true);
3221                }
3222            }
3223            if !stacked {
3224                // Leaving the stack: the pages were inset below the header, so give them the
3225                // pane back.
3226                let frame = nav_page_frame(&s.detail_wrap, false);
3227                for page in &s.pages {
3228                    unsafe { page.setFrame(frame) };
3229                }
3230            }
3231        }
3232    });
3233}
3234
3235// ---------------------------------------------------------------------------
3236// The sidebar pane holds its width through NSSplitViewController's own holding priorities
3237// (docs/navigation.md) — a sidebar NSSplitViewItem pins its thickness and lets the detail
3238// absorb a window resize, which is exactly the Finder/Mail behavior the hand-rolled
3239// `splitView:shouldAdjustSizeOfSubview:` delegate used to approximate. The controller IS the
3240// split's delegate, so Day must not install one of its own.
3241// ---------------------------------------------------------------------------
3242
3243struct CoverSheet(Retained<NSWindow>);
3244impl Drop for CoverSheet {
3245    fn drop(&mut self) {
3246        // try_with: the table may already be gone when the thread's locals tear down.
3247        let _ = SHEET_NODES.try_with(|t| t.remove(Retained::as_ptr(&self.0) as usize));
3248        // Sheet transitions may run a nested AppKit update cycle. Defer them until the
3249        // core's tree borrow has ended; this retained pointer travels only to the main queue.
3250        let raw = Retained::into_raw(self.0.clone()) as usize;
3251        dispatch2::DispatchQueue::main().exec_async(move || {
3252            ffi_guard::contain((), || unsafe {
3253                let window = Retained::from_raw(raw as *mut NSWindow).unwrap();
3254                if let Some(parent) = window.sheetParent() {
3255                    parent.endSheet(&window);
3256                }
3257                window.orderOut(None);
3258                window.setContentView(None);
3259            });
3260        });
3261    }
3262}
3263struct NavPageIvars {
3264    node: NodeId,
3265    /// A presented cover's strip under the window's title bar: the page paints it (its frame
3266    /// starts above the layout area) but lays its content out below it, and reports the
3267    /// remaining height (see `pin_below_title_bar`).
3268    top_inset: Cell<f64>,
3269    sheet: Cell<bool>,
3270    /// A half sheet (docs/cover.md): the window sheet stands half the parent's height.
3271    half: Cell<bool>,
3272    /// A large sheet (docs/cover.md "Large sheet"): the window sheet grows to
3273    /// `LARGE_SHEET_MAX`.
3274    large: Cell<bool>,
3275}
3276
3277define_class!(
3278    #[unsafe(super(NSView))]
3279    #[thread_kind = MainThreadOnly]
3280    #[name = "DayNavPage"]
3281    #[ivars = NavPageIvars]
3282    struct DayNavPage;
3283
3284    impl DayNavPage {
3285        #[unsafe(method(isFlipped))]
3286        fn is_flipped(&self) -> bool {
3287            true
3288        }
3289
3290        #[unsafe(method(setFrameSize:))]
3291        fn set_frame_size(&self, size: NSSize) {
3292            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
3293            // Pane-driven resize (splitter drag, window resize): report the usable size
3294            // so NavLayout re-lays this page's content (enqueue-only, §8.3).
3295            ffi_guard::contain((), || {
3296                let inset = self.ivars().top_inset.get();
3297                emit(
3298                    self.ivars().node,
3299                    Event::FrameChanged(Size::new(size.width, (size.height - inset).max(0.0))),
3300                );
3301            })
3302        }
3303    }
3304);
3305
3306impl DayNavPage {
3307    fn new(mtm: MainThreadMarker, node: NodeId) -> Retained<Self> {
3308        let this = Self::alloc(mtm).set_ivars(NavPageIvars {
3309            node,
3310            top_inset: Cell::new(0.0),
3311            sheet: Cell::new(false),
3312            half: Cell::new(false),
3313            large: Cell::new(false),
3314        });
3315        unsafe { msg_send![super(this), init] }
3316    }
3317}
3318
3319// ---------------------------------------------------------------------------
3320// Inspector (docs/inspector.md): an NSSplitViewController whose trailing pane is a REAL
3321// inspector item (`inspectorWithViewController:`) — the system treatment for exactly this
3322// surface: its own backing material, the standard thickness handling, full-height layout
3323// under the titlebar. Day's bound signal is the only visibility driver (the item cannot be
3324// user-collapsed), so this backend never emits `Event::InspectorChanged`.
3325// ---------------------------------------------------------------------------
3326
3327struct InspectorState {
3328    content_wrap: Handle,
3329    panel_wrap: Handle,
3330    /// Retained so the controller (the split's delegate) lives as long as its split.
3331    _split_vc: Retained<objc2_app_kit::NSSplitViewController>,
3332    panel_item: Retained<objc2_app_kit::NSSplitViewItem>,
3333}
3334
3335// ---------------------------------------------------------------------------
3336// Split (docs/split.md): a plain `NSSplitView` inside a flipped wrap (the wrap is the handle,
3337// so `set_frame`'s nav-host treatment of split views never sees it), two arranged flipped
3338// subviews as the panes, and a delegate that places the divider by the bound share, keeps
3339// both panes above the minimum, and reports a drag back as the new share.
3340// ---------------------------------------------------------------------------
3341
3342struct SplitState {
3343    split: Retained<objc2_app_kit::NSSplitView>,
3344    first_wrap: Handle,
3345    second_wrap: Handle,
3346    delegate: Retained<DaySplitDelegate>,
3347}
3348
3349struct SplitDelegateIvars {
3350    node: NodeId,
3351    min_pane: f64,
3352    /// The share as last patched or reported: what a report is compared against, and where
3353    /// the divider goes when the split first has a size or turns.
3354    share: Cell<f64>,
3355    /// The divider has been placed once; before that the split has no size to place it in.
3356    positioned: Cell<bool>,
3357    /// Day is moving the divider itself: the resize that follows is not a report.
3358    suppress: Cell<bool>,
3359}
3360
3361define_class!(
3362    #[unsafe(super(NSObject))]
3363    #[thread_kind = MainThreadOnly]
3364    #[name = "DaySplitDelegate"]
3365    #[ivars = SplitDelegateIvars]
3366    struct DaySplitDelegate;
3367
3368    unsafe impl NSObjectProtocol for DaySplitDelegate {}
3369
3370    unsafe impl NSSplitViewDelegate for DaySplitDelegate {
3371        #[unsafe(method(splitViewDidResizeSubviews:))]
3372        fn did_resize(&self, notification: &NSNotification) {
3373            ffi_guard::contain((), || {
3374                let Some(obj) = notification.object() else {
3375                    return;
3376                };
3377                let Ok(sv) = obj.downcast::<objc2_app_kit::NSSplitView>() else {
3378                    return;
3379                };
3380                let iv = self.ivars();
3381                let usable = split_usable(&sv);
3382                if usable <= 0.0 {
3383                    return;
3384                }
3385                // The first resize with a size: place the divider by the share, once.
3386                if !iv.positioned.replace(true) {
3387                    split_place(&sv, iv);
3388                    return;
3389                }
3390                if iv.suppress.get() {
3391                    return;
3392                }
3393                let Some(first) = sv.subviews().iter().next() else {
3394                    return;
3395                };
3396                let f = first.frame();
3397                let a = if sv.isVertical() {
3398                    f.size.width
3399                } else {
3400                    f.size.height
3401                };
3402                let share = (a / usable).clamp(0.0, 1.0);
3403                if (share - iv.share.get()).abs() > 1e-4 {
3404                    iv.share.set(share);
3405                    emit(iv.node, Event::ValueChanged(share));
3406                }
3407            })
3408        }
3409
3410        #[unsafe(method(splitView:constrainMinCoordinate:ofSubviewAt:))]
3411        fn constrain_min(
3412            &self,
3413            _sv: &objc2_app_kit::NSSplitView,
3414            proposed: f64,
3415            _index: isize,
3416        ) -> f64 {
3417            proposed.max(self.ivars().min_pane)
3418        }
3419
3420        #[unsafe(method(splitView:constrainMaxCoordinate:ofSubviewAt:))]
3421        fn constrain_max(
3422            &self,
3423            sv: &objc2_app_kit::NSSplitView,
3424            proposed: f64,
3425            _index: isize,
3426        ) -> f64 {
3427            proposed.min((split_usable(sv) - self.ivars().min_pane).max(0.0))
3428        }
3429    }
3430);
3431
3432impl DaySplitDelegate {
3433    fn new(mtm: MainThreadMarker, node: NodeId, min_pane: f64, share: f64) -> Retained<Self> {
3434        let this = Self::alloc(mtm).set_ivars(SplitDelegateIvars {
3435            node,
3436            min_pane,
3437            share: Cell::new(share.clamp(0.0, 1.0)),
3438            positioned: Cell::new(false),
3439            suppress: Cell::new(false),
3440        });
3441        unsafe { msg_send![super(this), init] }
3442    }
3443}
3444
3445/// The length the two panes share along the split's axis: the frame minus the divider.
3446fn split_usable(sv: &objc2_app_kit::NSSplitView) -> f64 {
3447    let frame = sv.frame();
3448    let len = if sv.isVertical() {
3449        frame.size.width
3450    } else {
3451        frame.size.height
3452    };
3453    (len - sv.dividerThickness()).max(0.0)
3454}
3455
3456/// Move the divider so the first pane takes the share, silently (Day's own write, not a drag).
3457fn split_place(sv: &objc2_app_kit::NSSplitView, iv: &SplitDelegateIvars) {
3458    let usable = split_usable(sv);
3459    if usable <= 0.0 {
3460        return;
3461    }
3462    iv.suppress.set(true);
3463    unsafe { sv.setPosition_ofDividerAtIndex(iv.share.get() * usable, 0) };
3464    iv.suppress.set(false);
3465}
3466
3467// ---------------------------------------------------------------------------
3468
3469// ---------------------------------------------------------------------------
3470// DayNavMenuData — flat NSOutlineView source list for nav_menu() (docs/navigation.md)
3471// ---------------------------------------------------------------------------
3472
3473struct NavMenuIvars {
3474    node: NodeId,
3475    items: RefCell<Vec<Retained<NSString>>>,
3476    /// Pre-resolved template icons per row (docs/navigation.md), `None` where a row has no icon.
3477    /// Template images tint with the source-list's selection/appearance, so they read in light,
3478    /// dark, and while selected — the macOS-idiomatic sidebar look (Finder/Mail).
3479    icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
3480    /// How much of each icon's box its drawing spans (`nav_icon_fill`), index-aligned with
3481    /// `icons`: the cell sizes the icon so the drawing matches a system sidebar glyph.
3482    icon_fills: RefCell<Vec<f64>>,
3483    /// Per-row icon tint (docs/vectors.md): recolors the template glyph via contentTintColor;
3484    /// `None` keeps the source-list's neutral template tint.
3485    tints: RefCell<Vec<Option<day_spec::Color>>>,
3486    /// Trailing accessory per item row (an unread count), `None` where a row has none.
3487    badges: RefCell<Vec<Option<Retained<NSString>>>>,
3488    /// Trailing accessory GLYPH per row, in the same slot as `badges` and drawn after it —
3489    /// a starred page's star. Resolved to images once per rebuild, like `icons`.
3490    icon_progress: RefCell<Vec<(usize, Option<f64>)>>,
3491    badge_icons: RefCell<Vec<Option<Retained<objc2_app_kit::NSImage>>>>,
3492    /// Tint for `badge_icons`; `None` keeps the neutral template tint.
3493    badge_tints: RefCell<Vec<Option<day_spec::Color>>>,
3494    /// Per-row context menu (docs/menus.md), empty = none. Built into an NSMenu and attached
3495    /// to the row's cell view, so a secondary click pops it like any native sidebar menu.
3496    menus: RefCell<Vec<Vec<day_spec::MenuItem>>>,
3497    /// Which items drag to reorder (`NavMenuProps::movable`); empty when none do.
3498    movable: RefCell<Vec<bool>>,
3499    /// Movable rows may cross section headers (`NavMenuProps::regroup`); set at creation.
3500    regroup: std::cell::Cell<bool>,
3501    /// Which movable items keep their section's sorted order (`NavMenuProps::sorted`).
3502    sorted: RefCell<Vec<bool>>,
3503    /// The outline's rows, in display order: `Some(i)` is item `i`, `None` is a section
3504    /// header. Day addresses rows by ITEM index, so every selection crossing the boundary
3505    /// goes through this map — a header must never shift what index 3 means.
3506    rows: RefCell<Vec<Option<usize>>>,
3507    /// One retained NSString per outline row: the row's text (a header's or an item's).
3508    row_objects: RefCell<Vec<Retained<NSString>>>,
3509    /// One NSNumber per outline row, holding the row's index: the outline's item IDENTITY.
3510    /// NSOutlineView matches items with `isEqual:`, so an NSString cannot be the identity —
3511    /// a section header titled "Controls" and an item titled "Controls" would collapse into one
3512    /// row, and the header would wear the item's icon. Row indexes are unique by construction.
3513    row_ids: RefCell<Vec<Retained<NSNumber>>>,
3514    /// Programmatic selection in flight: don't re-emit SelectionChanged.
3515    suppress: std::cell::Cell<bool>,
3516}
3517
3518struct NavCellIvars {
3519    /// The trailing accessories (an unread count, a status glyph), when the row has any: the
3520    /// label ends before them.
3521    accessory: RefCell<Option<Retained<NSView>>>,
3522    /// The unread count among them, sized to follow the row's text.
3523    count: RefCell<Option<Retained<NSTextField>>>,
3524    /// How much of the icon's box its drawing spans (`nav_icon_fill`).
3525    icon_fill: std::cell::Cell<f64>,
3526}
3527
3528define_class!(
3529    /// A sidebar row's cell. `NSTableCellView` lays out its icon and label itself, at the
3530    /// size the outline's row size style gives them: the system's Sidebar icon size setting,
3531    /// followed live (docs/navigation.md). This only makes room for the trailing accessories,
3532    /// which AppKit knows nothing about.
3533    #[unsafe(super(objc2_app_kit::NSTableCellView))]
3534    #[thread_kind = MainThreadOnly]
3535    #[name = "DayNavCell"]
3536    #[ivars = NavCellIvars]
3537    struct DayNavCell;
3538
3539    unsafe impl NSObjectProtocol for DayNavCell {}
3540
3541    impl DayNavCell {
3542        #[unsafe(method(layout))]
3543        fn layout(&self) {
3544            let _: () = unsafe { msg_send![super(self), layout] };
3545            ffi_guard::contain((), || self.fit_accessories());
3546        }
3547    }
3548);
3549
3550impl DayNavCell {
3551    fn new(mtm: MainThreadMarker) -> Retained<Self> {
3552        let this = Self::alloc(mtm).set_ivars(NavCellIvars {
3553            accessory: RefCell::new(None),
3554            count: RefCell::new(None),
3555            icon_fill: std::cell::Cell::new(1.0),
3556        });
3557        unsafe { msg_send![super(this), init] }
3558    }
3559
3560    /// After AppKit's layout: the count takes a size two points under the label's, and the
3561    /// label, which AppKit stretches to the cell's trailing edge, ends 6pt before the
3562    /// accessories so a long title truncates instead of running under its count. A showing
3563    /// progress ring re-fits the icon AppKit just sized.
3564    fn fit_accessories(&self) {
3565        let label = unsafe { self.textField() };
3566        if let (Some(label), Some(count)) = (&label, self.ivars().count.borrow().as_ref()) {
3567            let size = unsafe { label.font() }.map_or(NSFont::smallSystemFontSize(), |f| {
3568                (f.pointSize() - 2.0).max(9.0)
3569            });
3570            if unsafe { count.font() }.is_none_or(|f| f.pointSize() != size) {
3571                unsafe {
3572                    count.setFont(Some(&NSFont::monospacedDigitSystemFontOfSize_weight(
3573                        size,
3574                        objc2_app_kit::NSFontWeightRegular,
3575                    )));
3576                }
3577                self.layoutSubtreeIfNeeded();
3578            }
3579        }
3580        if let (Some(label), Some(accessory)) = (label, self.ivars().accessory.borrow().as_ref()) {
3581            let mut frame = label.frame();
3582            let end = accessory.frame().origin.x - 6.0;
3583            if frame.origin.x + frame.size.width > end {
3584                frame.size.width = (end - frame.origin.x).max(0.0);
3585                label.setFrame(frame);
3586            }
3587        }
3588        if let Some(icon) = unsafe { self.imageView() } {
3589            fit_nav_icon(&icon, self.ivars().icon_fill.get());
3590            nav_progress::fit(&icon);
3591        }
3592    }
3593}
3594
3595thread_local! {
3596    /// The side of a system sidebar glyph per symbol configuration (see `fit_nav_icon`).
3597    static NAV_GLYPH_SIDES: RefCell<HashMap<u64, f64>> = RefCell::new(HashMap::new());
3598}
3599
3600/// Draw a sidebar row's icon so its drawing is the size a system sidebar draws its SF Symbol,
3601/// centered in the slot AppKit lays out for it; `fill` is how much of the image's box the
3602/// drawing spans (`nav_icon_fill`). The slot is wider than the glyph AppKit puts there (22pt for a
3603/// 16pt glyph at Medium), and Day's icons are artwork that fills whatever frame it gets, so
3604/// left at the slot's size they read a third larger and heavier than Finder's or Mail's.
3605/// The side is measured, not tabled: a square symbol (`gearshape`) drawn with the symbol
3606/// configuration the row size style gave this image view, so it tracks the Sidebar icon size
3607/// setting and whatever a later macOS draws.
3608fn fit_nav_icon(icon: &objc2_app_kit::NSImageView, fill: f64) {
3609    let Some(config) = (unsafe { icon.symbolConfiguration() }) else {
3610        return;
3611    };
3612    let slot = icon.frame();
3613    // Configurations compare by value, and AppKit gives every cell of a row size style an
3614    // equal one, so the hash names the style.
3615    let key = config.hash() as u64;
3616    let side = NAV_GLYPH_SIDES
3617        .with(|m| m.borrow().get(&key).copied())
3618        .or_else(|| {
3619            let symbol =
3620                objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
3621                    &NSString::from_str("gearshape"),
3622                    None,
3623                )?;
3624            let side = symbol.imageWithSymbolConfiguration(&config)?.size().height;
3625            NAV_GLYPH_SIDES.with(|m| m.borrow_mut().insert(key, side));
3626            Some(side)
3627        });
3628    // The box that puts the drawing itself at the glyph's size: a Material Symbols icon keeps
3629    // the margin of its grid inside the box, so its box is that much larger.
3630    let Some(side) = side
3631        .filter(|s| *s > 0.0)
3632        .map(|s| (s / fill.clamp(0.25, 1.0)).round())
3633    else {
3634        return;
3635    };
3636    if slot.size.width <= side && slot.size.height <= side {
3637        return;
3638    }
3639    icon.setFrame(NSRect::new(
3640        NSPoint::new(
3641            (slot.origin.x + (slot.size.width - side) / 2.0).round(),
3642            (slot.origin.y + (slot.size.height - side) / 2.0).round(),
3643        ),
3644        NSSize::new(side, side),
3645    ));
3646}
3647
3648define_class!(
3649    #[unsafe(super(objc2_app_kit::NSTableRowView))]
3650    #[thread_kind = MainThreadOnly]
3651    #[name = "DayNavRowView"]
3652    struct DayNavRowView;
3653
3654    unsafe impl NSObjectProtocol for DayNavRowView {}
3655
3656    impl DayNavRowView {
3657        /// Always report the emphasized (key-window) state, so the selected sidebar row draws
3658        /// the accent pill with auto-whitened label/icon in both themes. Without this, a run
3659        /// whose window never becomes key (scripted screenshot captures) falls back to the
3660        /// unemphasized selection fill, which under a forced appearance rendered as a
3661        /// near-black pill that swallowed the row's label.
3662        #[unsafe(method(isEmphasized))]
3663        fn is_emphasized(&self) -> bool {
3664            true
3665        }
3666    }
3667);
3668
3669define_class!(
3670    #[unsafe(super(objc2_app_kit::NSOutlineView))]
3671    #[thread_kind = MainThreadOnly]
3672    #[name = "DayNavOutlineView"]
3673    struct DayNavOutlineView;
3674
3675    unsafe impl NSObjectProtocol for DayNavOutlineView {}
3676
3677    impl DayNavOutlineView {
3678        /// The clicked row's context menu (docs/menus.md): NSTableView-family views consume
3679        /// right-clicks themselves, so per-row menus are served here — resolve the row under
3680        /// the click, then build the same NSMenu the piece decorator would.
3681        #[unsafe(method_id(menuForEvent:))]
3682        fn menu_for_event(
3683            &self,
3684            event: &objc2_app_kit::NSEvent,
3685        ) -> Option<Retained<NSMenu>> {
3686            ffi_guard::contain(None, || {
3687                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
3688                let row = unsafe { self.rowAtPoint(point) };
3689                let data = NAV_OUTLINE_MENUS.with(|t| t.get(self as *const _ as usize));
3690                // `define_class!` rewrites the return, so no early `return` — one expression.
3691                match data {
3692                    None => None,
3693                    Some(d) => {
3694                        let items = d
3695                            .item_of_row(row)
3696                            .and_then(|i| d.ivars().menus.borrow().get(i).cloned())
3697                            .unwrap_or_default();
3698                        if items.is_empty() {
3699                            None
3700                        } else {
3701                            Some(build_ns_menu(d.mtm(), "", &items))
3702                        }
3703                    }
3704                }
3705            })
3706        }
3707    }
3708);
3709
3710define_class!(
3711    #[unsafe(super(NSObject))]
3712    #[thread_kind = MainThreadOnly]
3713    #[name = "DayNavMenuData"]
3714    #[ivars = NavMenuIvars]
3715    struct DayNavMenuData;
3716
3717    unsafe impl NSObjectProtocol for DayNavMenuData {}
3718
3719    unsafe impl NSOutlineViewDataSource for DayNavMenuData {
3720        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
3721        fn number_of_children(
3722            &self,
3723            _ov: &objc2_app_kit::NSOutlineView,
3724            item: Option<&objc2::runtime::AnyObject>,
3725        ) -> isize {
3726            if item.is_none() {
3727                self.ivars().row_objects.borrow().len() as isize
3728            } else {
3729                0
3730            }
3731        }
3732
3733        #[unsafe(method_id(outlineView:child:ofItem:))]
3734        fn child_of_item(
3735            &self,
3736            _ov: &objc2_app_kit::NSOutlineView,
3737            index: isize,
3738            _item: Option<&objc2::runtime::AnyObject>,
3739        ) -> Retained<objc2::runtime::AnyObject> {
3740            let ids = self.ivars().row_ids.borrow();
3741            // AppKit only asks for children it was told exist, but a stale query racing a
3742            // reload must degrade (an unmatched identity) rather than index out of bounds —
3743            // a panic here unwinds into an ObjC frame and aborts.
3744            let id = ids
3745                .get(index as usize)
3746                .cloned()
3747                .unwrap_or_else(|| NSNumber::new_isize(-1));
3748            unsafe { objc2::rc::Retained::cast_unchecked(id) }
3749        }
3750
3751        #[unsafe(method(outlineView:isItemExpandable:))]
3752        fn is_expandable(
3753            &self,
3754            _ov: &objc2_app_kit::NSOutlineView,
3755            _item: &objc2::runtime::AnyObject,
3756        ) -> bool {
3757            false
3758        }
3759
3760        // --- drag-to-reorder (docs/navigation.md "Reordering sidebar destinations"): the
3761        // outline's own drag pipeline, with the Gap placeholder Finder's sidebar shows. A row
3762        // moves within the run of movable rows around it, or, regrouping, into any section of
3763        // movable rows (`regroup_gap`); the app's data change brings the new order back as
3764        // `NavMenuPatch::Items`.
3765
3766        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
3767        fn pasteboard_writer_for_item(
3768            &self,
3769            _ov: &objc2_app_kit::NSOutlineView,
3770            item: &objc2::runtime::AnyObject,
3771        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
3772            let make = || {
3773                let row = Self::outline_row(item);
3774                let index = self.item_of_row(row)?;
3775                if !self.is_movable(index) {
3776                    return None;
3777                }
3778                let pbitem = objc2_app_kit::NSPasteboardItem::new();
3779                unsafe {
3780                    pbitem.setString_forType(
3781                        &NSString::from_str(&row.to_string()),
3782                        &NSString::from_str(DAY_NAV_PASTEBOARD_TYPE),
3783                    );
3784                }
3785                Some(ProtocolObject::from_retained(pbitem))
3786            };
3787            ffi_guard::contain(None, make)
3788        }
3789
3790        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
3791        fn validate_drop(
3792            &self,
3793            ov: &objc2_app_kit::NSOutlineView,
3794            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3795            item: Option<&objc2::runtime::AnyObject>,
3796            child_index: isize,
3797        ) -> objc2_app_kit::NSDragOperation {
3798            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
3799                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3800                    return objc2_app_kit::NSDragOperation::None;
3801                };
3802                // A drop past the run's end lands at that end: move the gap there.
3803                if drop.retarget {
3804                    unsafe { ov.setDropItem_dropChildIndex(None, drop.gap as isize) };
3805                }
3806                objc2_app_kit::NSDragOperation::Move
3807            })
3808        }
3809
3810        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
3811        fn accept_drop(
3812            &self,
3813            ov: &objc2_app_kit::NSOutlineView,
3814            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
3815            item: Option<&objc2::runtime::AnyObject>,
3816            child_index: isize,
3817        ) -> bool {
3818            ffi_guard::contain(false, || {
3819                let Some(drop) = self.nav_drop(ov, info, item, child_index) else {
3820                    return false;
3821                };
3822                // Deferred through the event queue: the app's callback never runs inside
3823                // AppKit's drop, and its data change reloads the rows in the new order.
3824                match drop.moves {
3825                    Some(NavMove::Reorder { from, to }) => {
3826                        emit(self.ivars().node, Event::ListReorder { from, to });
3827                    }
3828                    Some(NavMove::Regroup {
3829                        from,
3830                        section,
3831                        before,
3832                    }) => emit(
3833                        self.ivars().node,
3834                        Event::NavRegroup {
3835                            from,
3836                            section,
3837                            before,
3838                        },
3839                    ),
3840                    None => {}
3841                }
3842                true
3843            })
3844        }
3845    }
3846
3847    unsafe impl NSControlTextEditingDelegate for DayNavMenuData {}
3848
3849    unsafe impl NSOutlineViewDelegate for DayNavMenuData {
3850        /// Section headers are AppKit group rows: the source-list treatment (small, bold,
3851        /// secondary) comes free, and they are excluded from selection below.
3852        #[unsafe(method(outlineView:isGroupItem:))]
3853        fn is_group_item(
3854            &self,
3855            _ov: &objc2_app_kit::NSOutlineView,
3856            item: &objc2::runtime::AnyObject,
3857        ) -> bool {
3858            let row = Self::outline_row(item);
3859            row >= 0 && self.item_of_row(row).is_none()
3860        }
3861
3862        #[unsafe(method(outlineView:shouldSelectItem:))]
3863        fn should_select(
3864            &self,
3865            _ov: &objc2_app_kit::NSOutlineView,
3866            item: &objc2::runtime::AnyObject,
3867        ) -> bool {
3868            self.item_of_row(Self::outline_row(item)).is_some()
3869        }
3870
3871        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
3872        fn view_for(
3873            &self,
3874            ov: &objc2_app_kit::NSOutlineView,
3875            _col: Option<&objc2_app_kit::NSTableColumn>,
3876            item: &objc2::runtime::AnyObject,
3877        ) -> Option<Retained<NSView>> {
3878            let mtm = self.mtm();
3879            let row = Self::outline_row(item);
3880            let text = self
3881                .ivars()
3882                .row_objects
3883                .borrow()
3884                .get(usize::try_from(row).unwrap_or(usize::MAX))
3885                .cloned();
3886            // No early returns: the method_id macro owns the return conversion.
3887            text.map(|text| {
3888                let text: &NSString = &text;
3889                let Some(index) = self.item_of_row(row) else {
3890                    // A section header: a plain label. AppKit gives group rows their own
3891                    // typography and places the text, so this only supplies it.
3892                    let cell = DayNavCell::new(mtm);
3893                    let label = unsafe { NSTextField::labelWithString(text, mtm) };
3894                    unsafe {
3895                        label.cell().inspect(|c| {
3896                            c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3897                        });
3898                        cell.addSubview(&label);
3899                        cell.setTextField(Some(&label));
3900                    }
3901                    return objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell));
3902                };
3903                let icon = self
3904                    .ivars()
3905                    .icons
3906                    .borrow()
3907                    .get(index)
3908                    .and_then(|o| o.clone());
3909                let badge = self
3910                    .ivars()
3911                    .badges
3912                    .borrow()
3913                    .get(index)
3914                    .and_then(|o| o.clone());
3915                let badge_icon = self
3916                    .ivars()
3917                    .badge_icons
3918                    .borrow()
3919                    .get(index)
3920                    .and_then(|o| o.clone());
3921                let badge_tint = self
3922                    .ivars()
3923                    .badge_tints
3924                    .borrow()
3925                    .get(index)
3926                    .copied()
3927                    .flatten();
3928                // The cell places the icon and the label itself, at the row size style's size
3929                // (the system's Sidebar icon size); `DayNavCell` keeps the label clear of the
3930                // trailing accessories.
3931                let cell = DayNavCell::new(mtm);
3932                let label = unsafe { NSTextField::labelWithString(text, mtm) };
3933                unsafe {
3934                    // Feed titles are arbitrarily long, so the label truncates with an
3935                    // ellipsis within the frame the cell gives it.
3936                    label.cell().inspect(|c| {
3937                        c.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail)
3938                    });
3939                    cell.addSubview(&label);
3940                    cell.setTextField(Some(&label));
3941                    // The badge sits at the trailing edge and keeps its intrinsic width; the
3942                    // label truncates into whatever is left, so a long feed name never pushes
3943                    // its own unread count off the pane.
3944                    // Both accessories share the trailing slot: the count (if any) and then
3945                    // the status glyph (if any), in a stack so a row can carry either or both
3946                    // without the constraints below caring which it got.
3947                    let accessory = objc2_app_kit::NSStackView::new(mtm);
3948                    accessory.setTranslatesAutoresizingMaskIntoConstraints(false);
3949                    accessory.setOrientation(
3950                        objc2_app_kit::NSUserInterfaceLayoutOrientation::Horizontal,
3951                    );
3952                    accessory.setSpacing(4.0);
3953                    let mut has_accessory = false;
3954                    let trailing: Retained<NSView> = match &badge {
3955                        Some(text) => {
3956                            let b = NSTextField::labelWithString(text, mtm);
3957                            b.setTranslatesAutoresizingMaskIntoConstraints(false);
3958                            b.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()));
3959                            b.setAlignment(objc2_app_kit::NSTextAlignment::Right);
3960                            b.setFont(Some(
3961                                &objc2_app_kit::NSFont::monospacedDigitSystemFontOfSize_weight(
3962                                    objc2_app_kit::NSFont::smallSystemFontSize(),
3963                                    objc2_app_kit::NSFontWeightRegular,
3964                                ),
3965                            ));
3966                            b.setContentCompressionResistancePriority_forOrientation(
3967                                objc2_app_kit::NSLayoutPriorityRequired,
3968                                objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3969                            );
3970                            *cell.ivars().count.borrow_mut() = Some(b.clone());
3971                            accessory.addArrangedSubview(&objc2::rc::Retained::into_super(
3972                                objc2::rc::Retained::into_super(b),
3973                            ));
3974                            has_accessory = true;
3975                            let v: Retained<NSView> =
3976                                objc2::rc::Retained::into_super(accessory.clone());
3977                            v
3978                        }
3979                        None => objc2::rc::Retained::into_super(accessory.clone()),
3980                    };
3981                    // The status glyph, tinted where the app gave it a meaning-bearing color
3982                    // (a star is yellow because that is what a star IS, not because the theme
3983                    // says so). Template images take contentTintColor exactly as the row's
3984                    // leading icon does.
3985                    if let Some(img) = &badge_icon {
3986                        let iv = objc2_app_kit::NSImageView::new(mtm);
3987                        iv.setImage(Some(img));
3988                        iv.setTranslatesAutoresizingMaskIntoConstraints(false);
3989                        if let Some(c) = badge_tint {
3990                            iv.setContentTintColor(Some(&nscolor(c)));
3991                        }
3992                        iv.setContentCompressionResistancePriority_forOrientation(
3993                            objc2_app_kit::NSLayoutPriorityRequired,
3994                            objc2_app_kit::NSLayoutConstraintOrientation::Horizontal,
3995                        );
3996                        accessory.addArrangedSubview(&objc2::rc::Retained::into_super(iv));
3997                        has_accessory = true;
3998                    }
3999                    cell.addSubview(&trailing);
4000                    if has_accessory {
4001                        *cell.ivars().accessory.borrow_mut() = Some(trailing.clone());
4002                    }
4003                    objc2_app_kit::NSLayoutConstraint::activateConstraints(
4004                        &objc2_foundation::NSArray::from_retained_slice(&[
4005                            trailing
4006                                .trailingAnchor()
4007                                .constraintEqualToAnchor_constant(&cell.trailingAnchor(), -6.0),
4008                            trailing
4009                                .centerYAnchor()
4010                                .constraintEqualToAnchor(&cell.centerYAnchor()),
4011                        ]),
4012                    );
4013                }
4014                if let Some(img) = icon {
4015                    let fill = self.ivars().icon_fills.borrow().get(index).copied();
4016                    cell.ivars().icon_fill.set(fill.unwrap_or(1.0));
4017                    let tint = self.ivars().tints.borrow().get(index).copied().flatten();
4018                    let iv = unsafe { objc2_app_kit::NSImageView::new(mtm) };
4019                    unsafe {
4020                        iv.setImage(Some(&img));
4021                        // Per-row tint (docs/vectors.md): the icons are template images, so
4022                        // contentTintColor recolors the alpha mask; None keeps the neutral look.
4023                        if let Some(t) = tint {
4024                            iv.setContentTintColor(Some(&nscolor(t)));
4025                        }
4026                        iv.setImageScaling(
4027                            objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
4028                        );
4029                        cell.addSubview(&iv);
4030                        cell.setImageView(Some(&iv));
4031                        let progress = self
4032                            .ivars()
4033                            .icon_progress
4034                            .borrow()
4035                            .iter()
4036                            .find(|(row, _)| *row == index)
4037                            .map(|(_, f)| *f);
4038                        nav_progress::update(&iv, progress);
4039                    }
4040                }
4041                objc2::rc::Retained::into_super(objc2::rc::Retained::into_super(cell))
4042            })
4043        }
4044
4045        #[unsafe(method_id(outlineView:rowViewForItem:))]
4046        fn row_view_for(
4047            &self,
4048            _ov: &objc2_app_kit::NSOutlineView,
4049            _item: &objc2::runtime::AnyObject,
4050        ) -> Retained<objc2_app_kit::NSTableRowView> {
4051            let row: Retained<DayNavRowView> =
4052                unsafe { msg_send![DayNavRowView::alloc(self.mtm()), init] };
4053            objc2::rc::Retained::into_super(row)
4054        }
4055
4056        #[unsafe(method(outlineViewSelectionDidChange:))]
4057        fn selection_did_change(&self, notification: &NSNotification) {
4058            ffi_guard::contain((), || {
4059                if self.ivars().suppress.get() {
4060                    return;
4061                }
4062                let Some(obj) = (unsafe { notification.object() }) else {
4063                    return;
4064                };
4065                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
4066                    return;
4067                };
4068                let row = unsafe { ov.selectedRow() };
4069                if let Some(item) = self.item_of_row(row) {
4070                    emit(self.ivars().node, Event::SelectionChanged(item as i64));
4071                }
4072            })
4073        }
4074    }
4075);
4076
4077thread_local! {
4078    /// `nav_icon_fill` per icon name: a sidebar rebuilds its rows on every count change, and an
4079    /// icon's drawing does not change with them.
4080    static NAV_ICON_FILLS: RefCell<HashMap<String, f64>> = RefCell::new(HashMap::new());
4081}
4082
4083/// `nav_icon_fill` for each resolved icon, by name; 1 where a row has none.
4084fn nav_icon_fills(
4085    names: &[Option<String>],
4086    images: &[Option<Retained<objc2_app_kit::NSImage>>],
4087) -> Vec<f64> {
4088    names
4089        .iter()
4090        .zip(images)
4091        .map(|(name, image)| match (name, image) {
4092            (Some(name), Some(image)) => NAV_ICON_FILLS.with(|m| {
4093                *m.borrow_mut()
4094                    .entry(name.clone())
4095                    .or_insert_with(|| nav_icon_fill(image))
4096            }),
4097            _ => 1.0,
4098        })
4099        .collect()
4100}
4101
4102/// How much of an icon's box its drawing spans along its longer side, in (0, 1]: a Material
4103/// Symbols glyph keeps the 80-unit margin of its 960-unit grid (about 0.83), an SF Symbol export
4104/// is boxed to its content (1), and artwork usually fills its square. Measured from the alpha of
4105/// one small render, since a plain SVG says nothing about where its drawing sits.
4106fn nav_icon_fill(image: &objc2_app_kit::NSImage) -> f64 {
4107    const PX: f64 = 64.0;
4108    let Some(rep) = scaled_rep(image, Size::new(PX, PX), 1.0) else {
4109        return 1.0;
4110    };
4111    let (w, h) = (
4112        rep.pixelsWide().max(0) as usize,
4113        rep.pixelsHigh().max(0) as usize,
4114    );
4115    let stride = rep.bytesPerRow().max(0) as usize;
4116    let data = unsafe { rep.bitmapData() };
4117    if data.is_null() || stride < w * 4 {
4118        return 1.0;
4119    }
4120    // SAFETY: `scaled_rep` made a meshed 8-bit RGBA bitmap of `h` rows of `stride` bytes, which
4121    // `rep` owns and keeps alive for this borrow.
4122    let bytes = unsafe { std::slice::from_raw_parts(data, stride * h) };
4123    let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
4124    for y in 0..h {
4125        for x in 0..w {
4126            if bytes[y * stride + x * 4 + 3] > 24 {
4127                (x0, x1, y0, y1) = (x0.min(x), x1.max(x + 1), y0.min(y), y1.max(y + 1));
4128            }
4129        }
4130    }
4131    if x1 <= x0 || y1 <= y0 {
4132        return 1.0;
4133    }
4134    // The render stretched the image to a square; back in the image's own proportions, the
4135    // drawing's longer extent over the image's longer side is what proportional scaling keeps.
4136    let size = image.size();
4137    let (iw, ih) = (size.width.max(1.0), size.height.max(1.0));
4138    let (fx, fy) = ((x1 - x0) as f64 / w as f64, (y1 - y0) as f64 / h as f64);
4139    ((fx * iw).max(fy * ih) / iw.max(ih)).clamp(0.25, 1.0)
4140}
4141
4142fn resolve_nav_icons(icons: &[Option<String>]) -> Vec<Option<Retained<objc2_app_kit::NSImage>>> {
4143    // A bundled icon name → a template NSImage (tinted by the source list); `None` per iconless row.
4144    icons
4145        .iter()
4146        .map(|ic| {
4147            let name = ic.as_deref()?;
4148            // Prefer the glyph SVG (docs/vectors.md): NSImage renders it at display size.
4149            let path = day_spec::resource::resolve_vector_svg(name)
4150                .or_else(|| day_spec::resource::resolve_image_file(name))?;
4151            use objc2::AllocAnyThread as _;
4152            let img = unsafe {
4153                objc2_app_kit::NSImage::initWithContentsOfFile(
4154                    objc2_app_kit::NSImage::alloc(),
4155                    &NSString::from_str(&path.to_string_lossy()),
4156                )
4157            }?;
4158            // Downloaded/user-file icons are artwork; bundled glyphs remain templates.
4159            unsafe { img.setTemplate(!std::path::Path::new(name).is_absolute()) };
4160            Some(img)
4161        })
4162        .collect()
4163}
4164
4165impl DayNavMenuData {
4166    #[allow(clippy::too_many_arguments)]
4167    fn new(
4168        mtm: MainThreadMarker,
4169        node: NodeId,
4170        items: &[String],
4171        icons: &[Option<String>],
4172        badges: &[Option<String>],
4173        badge_icons: &[Option<String>],
4174        badge_tints: &[Option<day_spec::Color>],
4175        sections: &[Option<String>],
4176        tints: &[Option<day_spec::Color>],
4177        menus: &[Vec<day_spec::MenuItem>],
4178    ) -> Retained<Self> {
4179        let this = Self::alloc(mtm).set_ivars(NavMenuIvars {
4180            node,
4181            items: RefCell::new(items.iter().map(|s| NSString::from_str(s)).collect()),
4182            icon_fills: RefCell::new(nav_icon_fills(icons, &resolve_nav_icons(icons))),
4183            icons: RefCell::new(resolve_nav_icons(icons)),
4184            tints: RefCell::new(tints.to_vec()),
4185            menus: RefCell::new(menus.to_vec()),
4186            movable: RefCell::new(Vec::new()),
4187            regroup: std::cell::Cell::new(false),
4188            sorted: RefCell::new(Vec::new()),
4189            badges: RefCell::new(ns_badges(badges)),
4190            icon_progress: RefCell::new(Vec::new()),
4191            badge_icons: RefCell::new(resolve_nav_icons(badge_icons)),
4192            badge_tints: RefCell::new(badge_tints.to_vec()),
4193            rows: RefCell::new(Vec::new()),
4194            row_objects: RefCell::new(Vec::new()),
4195            row_ids: RefCell::new(Vec::new()),
4196            suppress: std::cell::Cell::new(false),
4197        });
4198        let this: Retained<Self> = unsafe { msg_send![super(this), init] };
4199        this.rebuild_rows(items, sections);
4200        this
4201    }
4202
4203    /// Data-driven rows changed (`NavMenuPatch::Items`): swap the stored decorations in place.
4204    // The parameters are the patch's payload: index-aligned per-row decoration arrays, each
4205    // landing in its own ivar. Bundling them would just move the same eight fields.
4206    #[allow(clippy::too_many_arguments)]
4207    fn set_items(
4208        &self,
4209        items: &[String],
4210        icons: &[Option<String>],
4211        badges: &[Option<String>],
4212        badge_icons: &[Option<String>],
4213        badge_tints: &[Option<day_spec::Color>],
4214        sections: &[Option<String>],
4215        tints: &[Option<day_spec::Color>],
4216        menus: &[Vec<day_spec::MenuItem>],
4217    ) {
4218        *self.ivars().items.borrow_mut() = items.iter().map(|s| NSString::from_str(s)).collect();
4219        let resolved = resolve_nav_icons(icons);
4220        *self.ivars().icon_fills.borrow_mut() = nav_icon_fills(icons, &resolved);
4221        *self.ivars().icons.borrow_mut() = resolved;
4222        *self.ivars().tints.borrow_mut() = tints.to_vec();
4223        *self.ivars().menus.borrow_mut() = menus.to_vec();
4224        *self.ivars().badges.borrow_mut() = ns_badges(badges);
4225        self.ivars().icon_progress.borrow_mut().clear();
4226        *self.ivars().badge_icons.borrow_mut() = resolve_nav_icons(badge_icons);
4227        *self.ivars().badge_tints.borrow_mut() = badge_tints.to_vec();
4228        self.rebuild_rows(items, sections);
4229    }
4230
4231    /// Flatten items + section headers into the outline's display rows. Each row gets its own
4232    /// retained NSString so the outline can tell two rows apart by identity even when their
4233    /// labels match (two feeds legitimately share a title).
4234    fn rebuild_rows(&self, items: &[String], sections: &[Option<String>]) {
4235        let mut rows = Vec::with_capacity(items.len());
4236        let mut objects = Vec::with_capacity(items.len());
4237        for (i, label) in items.iter().enumerate() {
4238            if let Some(Some(header)) = sections.get(i) {
4239                rows.push(None);
4240                objects.push(NSString::from_str(header));
4241            }
4242            rows.push(Some(i));
4243            objects.push(NSString::from_str(label));
4244        }
4245        let ids = (0..objects.len())
4246            .map(|i| NSNumber::new_isize(i as isize))
4247            .collect();
4248        *self.ivars().rows.borrow_mut() = rows;
4249        *self.ivars().row_objects.borrow_mut() = objects;
4250        *self.ivars().row_ids.borrow_mut() = ids;
4251    }
4252
4253    /// The outline row an item object names — the index its NSNumber identity carries — or
4254    /// `-1` for anything that is not one of ours (a stale query racing a reload).
4255    fn outline_row(item: &objc2::runtime::AnyObject) -> isize {
4256        item.downcast_ref::<NSNumber>()
4257            .map(|n| n.integerValue())
4258            .unwrap_or(-1)
4259    }
4260
4261    /// Outline row → day item index.
4262    fn item_of_row(&self, row: isize) -> Option<usize> {
4263        if row < 0 {
4264            return None;
4265        }
4266        self.ivars()
4267            .rows
4268            .borrow()
4269            .get(row as usize)
4270            .copied()
4271            .flatten()
4272    }
4273
4274    /// Day item index → outline row.
4275    fn row_of_item(&self, item: usize) -> Option<usize> {
4276        self.ivars()
4277            .rows
4278            .borrow()
4279            .iter()
4280            .position(|r| *r == Some(item))
4281    }
4282
4283    fn is_movable(&self, item: usize) -> bool {
4284        self.ivars()
4285            .movable
4286            .borrow()
4287            .get(item)
4288            .copied()
4289            .unwrap_or(false)
4290    }
4291
4292    /// What a drop proposal means for a reorder, or `None` when it is no drop of ours: a drag
4293    /// from another view, of a row that cannot move, or (regrouping) to a gap no rule allows.
4294    /// Reordering, the gap clamps to the run of movable rows around the dragged one, which
4295    /// section headers and fixed rows end ([`reorder_gap`]); regrouping, see [`regroup_gap`].
4296    fn nav_drop(
4297        &self,
4298        ov: &objc2_app_kit::NSOutlineView,
4299        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4300        item: Option<&objc2::runtime::AnyObject>,
4301        child_index: isize,
4302    ) -> Option<NavDrop> {
4303        let src = unsafe { info.draggingSource() }?;
4304        if Retained::as_ptr(&src).cast::<std::ffi::c_void>()
4305            != std::ptr::from_ref(ov).cast::<std::ffi::c_void>()
4306        {
4307            return None;
4308        }
4309        let pb = unsafe { info.draggingPasteboard() };
4310        let from_row = unsafe { pb.stringForType(&NSString::from_str(DAY_NAV_PASTEBOARD_TYPE)) }?
4311            .to_string()
4312            .parse::<usize>()
4313            .ok()?;
4314        let rows = self.ivars().rows.borrow();
4315        // The flat outline proposes a gap among the root's children, or a row itself (a drop
4316        // ONTO it, index -1).
4317        let proposed = match item {
4318            Some(item) => Self::outline_row(item),
4319            None => child_index,
4320        };
4321        let proposed = usize::try_from(proposed).unwrap_or(rows.len());
4322        if self.ivars().regroup.get() {
4323            regroup_gap(
4324                &rows,
4325                &self.ivars().movable.borrow(),
4326                &self.ivars().sorted.borrow(),
4327                from_row,
4328                proposed,
4329                item.is_some(),
4330            )
4331        } else {
4332            reorder_gap(
4333                &rows,
4334                &self.ivars().movable.borrow(),
4335                from_row,
4336                proposed,
4337                item.is_some(),
4338            )
4339        }
4340    }
4341}
4342
4343/// A drop in a sidebar outline (`DayNavMenuData::nav_drop`).
4344#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4345struct NavDrop {
4346    /// The gap the row drops into, among the outline's rows.
4347    gap: usize,
4348    /// The proposal named some other place, and the gap moves here.
4349    retarget: bool,
4350    /// What the drop reports, or `None` for a drop back in place.
4351    moves: Option<NavMove>,
4352}
4353
4354/// What a sidebar drop reports, in item indices (the rows before the move).
4355#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4356enum NavMove {
4357    /// `Event::ListReorder`: `from` takes `to`'s place.
4358    Reorder { from: usize, to: usize },
4359    /// `Event::NavRegroup`: `from` joins the section whose first row is `section`, before
4360    /// `before` or at the section's end.
4361    Regroup {
4362        from: usize,
4363        section: usize,
4364        before: Option<usize>,
4365    },
4366}
4367
4368/// A reorder drop at `proposed`, a gap among the outline's `rows` (`None` a header, `Some(i)`
4369/// item `i`), for the row at `from_row`; `onto` when the proposal named a row itself, which
4370/// reads as the gap above it. The gap clamps to the run of movable rows around the dragged
4371/// one, which section headers and fixed rows end. `None` when that row cannot move.
4372fn reorder_gap(
4373    rows: &[Option<usize>],
4374    movable: &[bool],
4375    from_row: usize,
4376    proposed: usize,
4377    onto: bool,
4378) -> Option<NavDrop> {
4379    let is_movable = |i: usize| movable.get(i).copied().unwrap_or(false);
4380    let from = (*rows.get(from_row)?).filter(|i| is_movable(*i))?;
4381    let in_run = |r: usize| rows[r].is_some_and(is_movable);
4382    let first = (0..from_row)
4383        .rev()
4384        .take_while(|r| in_run(*r))
4385        .last()
4386        .unwrap_or(from_row);
4387    let last = (from_row + 1..rows.len())
4388        .take_while(|r| in_run(*r))
4389        .last()
4390        .unwrap_or(from_row);
4391    let gap = proposed.clamp(first, last + 1);
4392    // The row's place once it has left its own: the row whose position it takes.
4393    let target_row = if gap > from_row { gap - 1 } else { gap };
4394    let moves = (target_row != from_row)
4395        .then(|| rows[target_row].map(|to| NavMove::Reorder { from, to }))
4396        .flatten();
4397    Some(NavDrop {
4398        gap,
4399        retarget: gap != proposed || onto,
4400        moves,
4401    })
4402}
4403
4404/// A regroup drop at `proposed`, a gap among the outline's `rows` (as [`reorder_gap`]'s), for
4405/// the row at `from_row` (docs/navigation.md "Moving rows between sections"). The gap's section
4406/// is the nearest header above it, or the rows above the first header; `before` is the item
4407/// right below the gap when that row is in the same section. A drop ONTO a header reads as
4408/// that section's first gap, onto an item as the gap above it. `None` when the row cannot
4409/// move, the gap is above the first header with no rows there, the section holds a fixed row,
4410/// or the gap is in the row's own section and the row is sorted. Gaps are never clamped.
4411fn regroup_gap(
4412    rows: &[Option<usize>],
4413    movable: &[bool],
4414    sorted: &[bool],
4415    from_row: usize,
4416    proposed: usize,
4417    onto: bool,
4418) -> Option<NavDrop> {
4419    let flag = |v: &[bool], i: usize| v.get(i).copied().unwrap_or(false);
4420    let from = (*rows.get(from_row)?).filter(|i| flag(movable, *i))?;
4421    let gap = match rows.get(proposed) {
4422        Some(None) if onto => proposed + 1,
4423        _ => proposed.min(rows.len()),
4424    };
4425    // The first outline row of the section a gap (or a row, as the gap above it) sits in.
4426    let section_start = |gap: usize| match (0..gap).rev().find(|r| rows[*r].is_none()) {
4427        Some(header) => Some(header + 1),
4428        None => rows.first().copied().flatten().map(|_| 0),
4429    };
4430    let first = section_start(gap)?;
4431    let end = (first..rows.len())
4432        .find(|r| rows[*r].is_none())
4433        .unwrap_or(rows.len());
4434    let section = rows.get(first).copied().flatten()?;
4435    if !rows[first..end]
4436        .iter()
4437        .all(|r| r.is_some_and(|i| flag(movable, i)))
4438    {
4439        return None;
4440    }
4441    let own = section_start(from_row) == Some(first);
4442    if own && flag(sorted, from) {
4443        return None;
4444    }
4445    let moves = (!own || (gap != from_row && gap != from_row + 1)).then(|| NavMove::Regroup {
4446        from,
4447        section,
4448        before: rows.get(gap).copied().flatten(),
4449    });
4450    Some(NavDrop {
4451        gap,
4452        retarget: gap != proposed || onto,
4453        moves,
4454    })
4455}
4456
4457#[cfg(test)]
4458mod nav_gap_tests {
4459    use super::{NavDrop, NavMove, regroup_gap, reorder_gap};
4460
4461    /// 0 today, 1 [news], 2 a, 3 b, 4 e, 5 [tech], 6 c, 7 d, 8 [smart], 9 starred: items 0..=6.
4462    const ROWS: [Option<usize>; 10] = [
4463        Some(0),
4464        None,
4465        Some(1),
4466        Some(2),
4467        Some(3),
4468        None,
4469        Some(4),
4470        Some(5),
4471        None,
4472        Some(6),
4473    ];
4474    /// The feeds move; today and starred are fixed.
4475    const MOVABLE: [bool; 7] = [false, true, true, true, true, true, false];
4476    const SORTED: [bool; 7] = [false, true, true, true, true, true, false];
4477    const UNSORTED: [bool; 7] = [false; 7];
4478
4479    fn regroup(from: usize, section: usize, before: Option<usize>) -> Option<NavMove> {
4480        Some(NavMove::Regroup {
4481            from,
4482            section,
4483            before,
4484        })
4485    }
4486
4487    #[test]
4488    fn regroup_gaps_name_the_section_above_and_the_row_below() {
4489        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4490        // a, into tech's first gap: before c.
4491        assert_eq!(
4492            at(2, 6),
4493            Some(NavDrop {
4494                gap: 6,
4495                retarget: false,
4496                moves: regroup(1, 4, Some(4)),
4497            })
4498        );
4499        // c, into the gap above tech's header: the end of news.
4500        assert_eq!(at(6, 5).and_then(|d| d.moves), regroup(4, 1, None));
4501        // a, between c and d, and at tech's end above smart's header.
4502        assert_eq!(at(2, 7).and_then(|d| d.moves), regroup(1, 4, Some(5)));
4503        assert_eq!(at(2, 8).and_then(|d| d.moves), regroup(1, 4, None));
4504    }
4505
4506    #[test]
4507    fn regroup_gaps_skip_fixed_sections_fixed_rows_and_a_sorted_rows_own_section() {
4508        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &SORTED, from_row, gap, false);
4509        // Smart holds starred, and the rows above the first header hold today.
4510        for gap in [0, 1, 9, 10] {
4511            assert_eq!(at(2, gap), None, "gap {gap}");
4512        }
4513        // A sorted row's own section offers no gap, its own place included.
4514        for gap in [2, 3, 4, 5] {
4515            assert_eq!(at(2, gap), None, "gap {gap}");
4516        }
4517        // Fixed rows and headers never drag.
4518        assert_eq!(at(0, 6), None);
4519        assert_eq!(at(1, 6), None);
4520        assert_eq!(at(9, 6), None);
4521    }
4522
4523    #[test]
4524    fn regroup_gaps_reorder_an_unsorted_row_in_its_own_section() {
4525        let at = |from_row, gap| regroup_gap(&ROWS, &MOVABLE, &UNSORTED, from_row, gap, false);
4526        // a, between b and e.
4527        assert_eq!(at(2, 4).and_then(|d| d.moves), regroup(1, 1, Some(3)));
4528        // a, at news's end above tech's header.
4529        assert_eq!(at(2, 5).and_then(|d| d.moves), regroup(1, 1, None));
4530        // Back in place, either side of itself: a drop that reports nothing.
4531        for gap in [2, 3] {
4532            let drop = at(2, gap).expect("offered");
4533            assert_eq!(drop.moves, None, "gap {gap}");
4534        }
4535    }
4536
4537    #[test]
4538    fn regroup_drops_onto_a_row_move_to_a_gap() {
4539        // Onto tech's header: its first gap. Onto d: the gap above d.
4540        assert_eq!(
4541            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 5, true),
4542            Some(NavDrop {
4543                gap: 6,
4544                retarget: true,
4545                moves: regroup(1, 4, Some(4)),
4546            })
4547        );
4548        assert_eq!(
4549            regroup_gap(&ROWS, &MOVABLE, &SORTED, 2, 7, true),
4550            Some(NavDrop {
4551                gap: 7,
4552                retarget: true,
4553                moves: regroup(1, 4, Some(5)),
4554            })
4555        );
4556    }
4557
4558    #[test]
4559    fn regroup_offers_nothing_above_a_leading_header() {
4560        // 0 [news], 1 a, 2 [tech], 3 b.
4561        let rows = [None, Some(0), None, Some(1)];
4562        let movable = [true, true];
4563        let at = |gap| regroup_gap(&rows, &movable, &[false, false], 1, gap, false);
4564        assert_eq!(at(0), None);
4565        assert_eq!(at(1).map(|d| d.moves), Some(None));
4566        assert_eq!(at(2).map(|d| d.moves), Some(None));
4567        assert_eq!(at(3).and_then(|d| d.moves), regroup(0, 1, Some(1)));
4568        assert_eq!(at(4).and_then(|d| d.moves), regroup(0, 1, None));
4569    }
4570
4571    #[test]
4572    fn reorder_gaps_clamp_to_the_run() {
4573        // a past the run's end lands at its end: e's place.
4574        assert_eq!(
4575            reorder_gap(&ROWS, &MOVABLE, 2, 9, false),
4576            Some(NavDrop {
4577                gap: 5,
4578                retarget: true,
4579                moves: Some(NavMove::Reorder { from: 1, to: 3 }),
4580            })
4581        );
4582        // Back in place.
4583        assert_eq!(
4584            reorder_gap(&ROWS, &MOVABLE, 2, 3, false).map(|d| d.moves),
4585            Some(None)
4586        );
4587        // b above the run's start lands at a's place; a fixed row offers nothing.
4588        assert_eq!(
4589            reorder_gap(&ROWS, &MOVABLE, 3, 0, false).and_then(|d| d.moves),
4590            Some(NavMove::Reorder { from: 2, to: 1 })
4591        );
4592        assert_eq!(reorder_gap(&ROWS, &MOVABLE, 0, 3, false), None);
4593    }
4594}
4595
4596/// The private pasteboard type carrying a dragged sidebar row (local reorder only).
4597const DAY_NAV_PASTEBOARD_TYPE: &str = "dev.daybrite.day.nav-row";
4598
4599/// Badge strings, retained once per rebuild rather than per cell.
4600fn ns_badges(badges: &[Option<String>]) -> Vec<Option<Retained<NSString>>> {
4601    badges
4602        .iter()
4603        .map(|b| b.as_deref().map(NSString::from_str))
4604        .collect()
4605}
4606
4607// ---------------------------------------------------------------------------
4608/// Force the table's visible rows to exist on the next main-loop turn — outside any `with_tree`
4609/// borrow, so `bind_row` may build them. `layoutSubtreeIfNeeded` is not enough: an occluded
4610/// window's table skips row tiling entirely, so `viewAtColumn:row:makeIfNecessary:` is the only
4611/// reliable way to realize rows without a draw pass (§10; see the Reload patch for why).
4612fn post_realize_visible_rows(key: usize) {
4613    <AppKit as Platform>::post(Box::new(move || {
4614        if let Some((table, data)) = list_entry(key) {
4615            unsafe { table.layoutSubtreeIfNeeded() };
4616            let range = unsafe { table.rowsInRect(table.visibleRect()) };
4617            if let Some(source) = data.ivars().source.borrow().clone()
4618                && let Some(report) = &source.first_visible
4619            {
4620                report(range.location.min((source.len)().saturating_sub(1)));
4621            }
4622            for row in range.location..range.location + range.length {
4623                let cell = unsafe { table.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
4624                // A snapshot/layout can have requested this cell while day-core held its
4625                // tree borrow. The delegate then returned an empty container; AppKit caches
4626                // it and will not ask viewForRow again. Complete that skipped bind here.
4627                if let Some(cell) = cell
4628                    && cell.subviews().is_empty()
4629                {
4630                    let source = data.ivars().source.borrow().clone();
4631                    if let Some(source) = source {
4632                        (source.bind_row)(row, Retained::as_ptr(&cell) as RawHandle);
4633                    }
4634                }
4635            }
4636        }
4637        // The builds above queued their styling effects; drain them now — outside the pump, no
4638        // event may arrive for a while (idle app), and a snapshot would capture bare rows.
4639        day_core::pump_events();
4640    }));
4641}
4642
4643/// A native drop changes the snapshot synchronously and suppresses the app's echo Reload.
4644/// Once AppKit has unwound its drop/gap tracking, reconcile the table with that snapshot:
4645/// the incremental move alone can leave its row tiling and scroll extent out of sync.
4646/// Preserve the user's viewport and selection; never force a jump to the moved row.
4647fn post_settle_list_drop(key: usize) {
4648    <AppKit as Platform>::post(Box::new(move || {
4649        // Publish the deferred on_reorder before reading the final row set. App code may
4650        // remove rows or close the list, so resolve the native handles only after the drain.
4651        day_core::pump_events();
4652        let Some((table, data)) = list_entry(key) else {
4653            return;
4654        };
4655        let Some(scroll) = table.enclosingScrollView() else {
4656            return;
4657        };
4658        let clip = scroll.contentView();
4659        let origin = clip.bounds().origin;
4660        let selected = table.selectedRowIndexes();
4661        let suppressed = data.ivars().suppress.replace(true);
4662        table.reloadData();
4663        // Outside with_tree: tiling is allowed to bind/rebind Day's cell contents here.
4664        table.layoutSubtreeIfNeeded();
4665        let restored = objc2_foundation::NSMutableIndexSet::new();
4666        for row in 0..table.numberOfRows().max(0) as usize {
4667            if selected.containsIndex(row) {
4668                restored.addIndex(row);
4669            }
4670        }
4671        table.selectRowIndexes_byExtendingSelection(&restored, false);
4672        let mut bounds = clip.bounds();
4673        bounds.origin = origin;
4674        clip.scrollToPoint(clip.constrainBoundsRect(bounds).origin);
4675        scroll.reflectScrolledClipView(&clip);
4676        data.ivars().suppress.set(suppressed);
4677        post_realize_visible_rows(key);
4678    }));
4679}
4680
4681// DayListData — NSTableView data-source + delegate for the recycling list (docs/list.md, §10)
4682//
4683// No custom NSTableRowView: the table runs the PLAIN style, whose standard row view lays cell
4684// views out at the full row bounds — no inset to pin away — and whose cell-frame slide is what
4685// animates a row-action swipe. (A `layout`-override pin lived here under FullWidth until
4686// 2026-08; it also froze row content mid-swipe, revealing actions behind a motionless row.)
4687// ---------------------------------------------------------------------------
4688
4689define_class!(
4690    #[unsafe(super(NSTableView))]
4691    #[thread_kind = MainThreadOnly]
4692    #[name = "DayListView"]
4693    struct DayListView;
4694    unsafe impl NSObjectProtocol for DayListView {}
4695    impl DayListView {
4696        /// NSTableView consumes right-clicks before the row's container sees them. Resolve
4697        /// its summon-time provider from the visible cell, never from the selected row.
4698        #[unsafe(method_id(menuForEvent:))]
4699        fn menu_for_event(
4700            &self,
4701            event: &objc2_app_kit::NSEvent,
4702        ) -> Option<Retained<NSMenu>> {
4703            ffi_guard::contain(None, || {
4704                let point = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4705                let row = unsafe { self.rowAtPoint(point) };
4706                let provider = if row >= 0 {
4707                    unsafe { self.viewAtColumn_row_makeIfNecessary(0, row, false) }
4708                        .and_then(|cell| list_row_menu_provider(&cell))
4709                } else {
4710                    None
4711                };
4712                match provider {
4713                    Some((view, provider)) => {
4714                        let point = view.convertPoint_fromView(
4715                            unsafe { event.locationInWindow() }, None,
4716                        );
4717                        let items = provider(day_spec::Point::new(point.x, point.y));
4718                        if items.is_empty() {
4719                            None
4720                        } else {
4721                            Some(build_ns_menu(self.mtm(), "", &items))
4722                        }
4723                    }
4724                    None => unsafe { msg_send![super(self), menuForEvent: event] },
4725                }
4726            })
4727        }
4728
4729        #[unsafe(method(becomeFirstResponder))]
4730        fn become_first_responder(&self) -> bool {
4731            let accepted: bool = unsafe { msg_send![super(self), becomeFirstResponder] };
4732            if accepted {
4733                self.report_focus(true);
4734            }
4735            accepted
4736        }
4737
4738        #[unsafe(method(resignFirstResponder))]
4739        fn resign_first_responder(&self) -> bool {
4740            let accepted: bool = unsafe { msg_send![super(self), resignFirstResponder] };
4741            if accepted {
4742                self.report_focus(false);
4743            }
4744            accepted
4745        }
4746
4747        #[unsafe(method(keyDown:))]
4748        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
4749            ffi_guard::contain((), || {
4750                let key = unsafe { event.keyCode() };
4751                if (key == 36 || key == 76) && unsafe { self.doubleAction() }.is_some() {
4752                    let row = unsafe { self.selectedRow() };
4753                    if row >= 0 && let Some(target) = unsafe { self.target() } {
4754                        let _: () = unsafe { msg_send![&*target, activateRow: self] };
4755                        return;
4756                    }
4757                }
4758                let _: () = unsafe { msg_send![super(self), keyDown: event] };
4759            });
4760        }
4761    }
4762);
4763
4764/// The cell can wrap its decorated row in layout containers. Search only this visible
4765/// cell, not other rows; cloning the provider releases the registry borrow before app code.
4766fn list_row_menu_provider(view: &NSView) -> Option<(Retained<NSView>, day_spec::ContextMenuFn)> {
4767    if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(view as *const NSView as usize)) {
4768        return Some((view.retain(), provider));
4769    }
4770    view.subviews()
4771        .iter()
4772        .find_map(|view| list_row_menu_provider(&view))
4773}
4774
4775/// Plain labels receive the mouse event before their row does. Resolve the nearest dynamic
4776/// owner without copying providers onto descendants (which would go stale on recycling).
4777/// `Some(None)` means an owner deliberately returned no menu; do not fall through to a parent.
4778fn inherited_context_menu(
4779    view: &NSView,
4780    event: &objc2_app_kit::NSEvent,
4781) -> Option<Option<Retained<NSMenu>>> {
4782    let mut current = Some(view.retain());
4783    while let Some(view) = current {
4784        if let Some(provider) = CTX_MENU_FNS.with(|t| t.get(Retained::as_ptr(&view) as usize)) {
4785            let point = view.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
4786            let items = provider(day_spec::Point::new(point.x, point.y));
4787            return Some((!items.is_empty()).then(|| build_ns_menu(view.mtm(), "", &items)));
4788        }
4789        current = unsafe { view.superview() };
4790    }
4791    None
4792}
4793
4794impl DayListView {
4795    fn report_focus(&self, focused: bool) {
4796        ffi_guard::contain((), || {
4797            if let Some(target) = unsafe { self.target() }
4798                && let Some(data) = target.downcast_ref::<DayListData>()
4799            {
4800                emit(data.ivars().node, Event::FocusChanged(focused));
4801            }
4802        });
4803    }
4804}
4805
4806struct ListIvars {
4807    node: NodeId,
4808    /// Injected by `attach_list` once day-core wires the driver.
4809    source: RefCell<Option<ListSource>>,
4810    selectable: std::cell::Cell<bool>,
4811    /// Multi-select mode (docs/list.md): every change reports the FULL selected set.
4812    multi: std::cell::Cell<bool>,
4813    /// Programmatic selection in flight: don't re-emit SelectionChanged.
4814    suppress: std::cell::Cell<bool>,
4815    /// The row-token order this table currently displays — the baseline `permutation_moves`
4816    /// diffs a Reload against (docs/list.md: a same-set reorder animates as row moves).
4817    tokens: RefCell<Vec<u64>>,
4818    /// `RowHeight::Automatic` (docs/list.md "Row heights"): each row is as tall as Day laid
4819    /// it, through `tableView:heightOfRow:`. A uniform list never answers that selector, so
4820    /// NSTableView keeps its fixed-pitch fast path.
4821    automatic: bool,
4822    /// The list has section headers (docs/list.md "Sections"): AppKit group rows, which float
4823    /// at the top as their section scrolls under them. A header sizes to its content in any
4824    /// list, so a sectioned list answers `tableView:heightOfRow:` even when it is uniform.
4825    sections: bool,
4826    /// The height a header nobody has bound yet is given, like `estimate` for rows.
4827    header_estimate: std::cell::Cell<f64>,
4828    /// Each self-sizing row's height by row token, as Day last laid it. By token, not row: a
4829    /// splice or a drag moves rows without rebinding them.
4830    heights: RefCell<std::collections::HashMap<u64, f64>>,
4831    /// The row token each bound cell shows, so `RowSizeInvalidated` (which names the cell)
4832    /// finds the height it corrects.
4833    cell_tokens: RefCell<std::collections::HashMap<usize, u64>>,
4834    /// The height a row nobody has bound yet is given: the last one Day measured, so a list
4835    /// of like rows scrolls without its rows jumping as they arrive.
4836    estimate: std::cell::Cell<f64>,
4837    /// A height pass is posted and not yet run (`post_row_heights` coalesces).
4838    heights_pending: std::cell::Cell<bool>,
4839}
4840
4841define_class!(
4842    #[unsafe(super(NSObject))]
4843    #[thread_kind = MainThreadOnly]
4844    #[name = "DayListData"]
4845    #[ivars = ListIvars]
4846    struct DayListData;
4847
4848    unsafe impl NSObjectProtocol for DayListData {}
4849    unsafe impl NSControlTextEditingDelegate for DayListData {}
4850
4851    impl DayListData {
4852        /// Only a self-sizing list answers `tableView:heightOfRow:`: NSTableView asks that
4853        /// of every row on each reload, and a uniform list's fixed `rowHeight` is the fast
4854        /// path. NSTableView reads this once, at `setDelegate:`, after `automatic` is set.
4855        #[unsafe(method(respondsToSelector:))]
4856        fn responds_to_selector(&self, selector: objc2::runtime::Sel) -> bool {
4857            if selector == objc2::sel!(tableView:heightOfRow:)
4858                && !self.ivars().automatic
4859                && !self.ivars().sections
4860            {
4861                false
4862            } else {
4863                unsafe { msg_send![super(self), respondsToSelector: selector] }
4864            }
4865        }
4866
4867        #[unsafe(method(listViewportChanged:))]
4868        fn list_viewport_changed(&self, notification: &NSNotification) {
4869            ffi_guard::contain((), || {
4870                let source = self.ivars().source.borrow().clone();
4871                if let Some(source) = source && let Some(report) = &source.first_visible
4872                    && let Some(object) = notification.object()
4873                    && let Some(clip) = object.downcast_ref::<objc2_app_kit::NSClipView>()
4874                    && let Some(document) = clip.documentView()
4875                    && let Some(table) = document.downcast_ref::<NSTableView>() {
4876                    let visible = unsafe { table.rowsInRect(table.visibleRect()) };
4877                    report(visible.location.min((source.len)().saturating_sub(1)));
4878                }
4879            });
4880        }
4881
4882        #[unsafe(method(activateRow:))]
4883        fn activate_row(&self, table: &NSTableView) {
4884            ffi_guard::contain((), || {
4885                let row = unsafe { table.selectedRow() };
4886                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4887            });
4888        }
4889        #[unsafe(method(doubleClickRow:))]
4890        fn double_click_row(&self, table: &NSTableView) {
4891            ffi_guard::contain((), || {
4892                let row = unsafe { table.clickedRow() };
4893                if row >= 0 { emit(self.ivars().node, Event::ListActivated(row as usize)); }
4894            });
4895        }
4896    }
4897
4898    unsafe impl NSTableViewDataSource for DayListData {
4899        #[unsafe(method(numberOfRowsInTableView:))]
4900        fn number_of_rows(&self, _tv: &NSTableView) -> isize {
4901            // Reads the piece's snapshot only (no tree access) — safe even when called
4902            // synchronously from reloadData inside a with_tree borrow. Guarded because
4903            // `len` is a day-core closure.
4904            ffi_guard::contain(0, || {
4905                self.ivars()
4906                    .source
4907                    .borrow()
4908                    .as_ref()
4909                    .map(|s| (s.len)() as isize)
4910                    .unwrap_or(0)
4911            })
4912        }
4913
4914        // --- drag-to-reorder (docs/list.md): NSTableView's native drag pipeline. The dragged
4915        // row rides the pasteboard as a private-typed string; `validateDrop` consults the app's
4916        // guard live (the `.gap` feedback style opens the placeholder gap only where the guard
4917        // allows), and `acceptDrop` commits through the sync seam, then animates the native move.
4918
4919        #[unsafe(method_id(tableView:pasteboardWriterForRow:))]
4920        fn pasteboard_writer_for_row(
4921            &self,
4922            _tv: &NSTableView,
4923            row: isize,
4924        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
4925            // (Closure body: define_class converts only the TAIL expression, so early `return`s
4926            // must not escape the method itself.)
4927            let make = || {
4928                // Only reorderable lists write drag items — no seam, no drag.
4929                let reorderable = self
4930                    .ivars()
4931                    .source
4932                    .borrow()
4933                    .as_ref()
4934                    .is_some_and(|s| s.reorder.is_some());
4935                // A group row (a section header) never lifts (docs/list.md "Sections").
4936                if !reorderable || row < 0 || self.is_header(row) {
4937                    return None;
4938                }
4939                let item = objc2_app_kit::NSPasteboardItem::new();
4940                unsafe {
4941                    item.setString_forType(
4942                        &NSString::from_str(&row.to_string()),
4943                        &NSString::from_str(DAY_ROW_PASTEBOARD_TYPE),
4944                    );
4945                }
4946                Some(ProtocolObject::from_retained(item))
4947            };
4948            ffi_guard::contain(None, make)
4949        }
4950
4951        #[unsafe(method(tableView:validateDrop:proposedRow:proposedDropOperation:))]
4952        fn validate_drop(
4953            &self,
4954            tv: &NSTableView,
4955            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4956            row: isize,
4957            _op: objc2_app_kit::NSTableViewDropOperation,
4958        ) -> objc2_app_kit::NSDragOperation {
4959            // Guarded: `can_move` consults the app's reorder guard closure.
4960            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
4961                let Some((from, len)) = self.drag_context(tv, info) else {
4962                    return objc2_app_kit::NSDragOperation::None;
4963                };
4964                // Normalize to an above insertion point (the gap style's semantics), convert to
4965                // the post-removal target index, and ask the guard.
4966                let ins = row.clamp(0, len as isize) as usize;
4967                let to = insertion_to_target(from, ins, len);
4968                let accepted = self.can_move(from, to);
4969                if accepted < 0 {
4970                    return objc2_app_kit::NSDragOperation::None;
4971                }
4972                let accepted = (accepted as usize).min(len.saturating_sub(1));
4973                if accepted != to {
4974                    // The guard retargeted: move the gap to where the drop would actually land.
4975                    unsafe {
4976                        tv.setDropRow_dropOperation(
4977                            target_to_insertion(from, accepted) as isize,
4978                            objc2_app_kit::NSTableViewDropOperation::Above,
4979                        );
4980                    }
4981                }
4982                objc2_app_kit::NSDragOperation::Move
4983            })
4984        }
4985
4986        #[unsafe(method(tableView:acceptDrop:row:dropOperation:))]
4987        fn accept_drop(
4988            &self,
4989            tv: &NSTableView,
4990            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
4991            row: isize,
4992            _op: objc2_app_kit::NSTableViewDropOperation,
4993        ) -> bool {
4994            // (Closure body: early `return`s must not escape the define_class method itself.)
4995            let drop = || {
4996                let Some((from, len)) = self.drag_context(tv, info) else {
4997                    return false;
4998                };
4999                let ins = row.clamp(0, len as isize) as usize;
5000                let to = insertion_to_target(from, ins, len);
5001                let accepted = self.can_move(from, to);
5002                if accepted < 0 {
5003                    return false;
5004                }
5005                let accepted = (accepted as usize).min(len.saturating_sub(1));
5006                if accepted == from {
5007                    return true; // dropped back home — nothing to commit
5008                }
5009                // Commit through the sync seam (rotates Day's snapshot, defers the app
5010                // callback), THEN animate the native move — the data source already answers in
5011                // the new order.
5012                let mv = self
5013                    .ivars()
5014                    .source
5015                    .borrow()
5016                    .as_ref()
5017                    .and_then(|s| s.reorder.as_ref().map(|r| r.move_row.clone()));
5018                let Some(mv) = mv else { return false };
5019                mv(from, accepted);
5020                // Keep the displayed-order cache in step (the commit's echo skips the Reload
5021                // that would otherwise refresh it — see `permutation_moves`).
5022                {
5023                    let mut toks = self.ivars().tokens.borrow_mut();
5024                    if from < toks.len() && accepted < toks.len() {
5025                        let t = toks.remove(from);
5026                        toks.insert(accepted, t);
5027                    }
5028                }
5029                unsafe { tv.moveRowAtIndex_toIndex(from as isize, accepted as isize) };
5030                if let Some(scroll) = tv.enclosingScrollView() {
5031                    post_settle_list_drop(ptr_of(&scroll));
5032                }
5033                true
5034            };
5035            // Guarded: the commit runs the seam's move closure into day-core and the app.
5036            ffi_guard::contain(false, drop)
5037        }
5038    }
5039
5040    unsafe impl NSTableViewDelegate for DayListData {
5041        /// A self-sizing row's height (docs/list.md "Row heights"): the height Day laid it at
5042        /// once it has been bound, the running estimate until then. Asked before the row's view
5043        /// exists, often from inside `reloadData` under a day-core borrow, so it reads only this
5044        /// table's own record and the source's token snapshot.
5045        #[unsafe(method(tableView:heightOfRow:))]
5046        fn height_of_row(&self, tv: &NSTableView, row: isize) -> f64 {
5047            ffi_guard::contain(44.0, || {
5048                let ivars = self.ivars();
5049                let header = self.is_header(row);
5050                // A uniform sectioned list: rows keep the fixed pitch, headers size themselves.
5051                if !header && !ivars.automatic {
5052                    return unsafe { tv.rowHeight() };
5053                }
5054                let token = ivars
5055                    .source
5056                    .borrow()
5057                    .as_ref()
5058                    .filter(|s| row >= 0 && (row as usize) < (s.len)())
5059                    .map(|s| (s.token_at)(row as usize));
5060                token
5061                    .and_then(|t| ivars.heights.borrow().get(&t).copied())
5062                    .unwrap_or_else(|| {
5063                        if header {
5064                            ivars.header_estimate.get()
5065                        } else {
5066                            ivars.estimate.get()
5067                        }
5068                    })
5069            })
5070        }
5071
5072        /// Section headers are AppKit group rows (docs/list.md "Sections"): drawn in the
5073        /// group style, spanning the row, and floated over their section by
5074        /// `floatsGroupRows`.
5075        #[unsafe(method(tableView:isGroupRow:))]
5076        fn is_group_row(&self, _tv: &NSTableView, row: isize) -> bool {
5077            ffi_guard::contain(false, || self.is_header(row))
5078        }
5079
5080        /// A header is not an item: clicks and arrow keys pass over it.
5081        #[unsafe(method(tableView:shouldSelectRow:))]
5082        fn should_select_row(&self, _tv: &NSTableView, row: isize) -> bool {
5083            ffi_guard::contain(true, || !self.is_header(row))
5084        }
5085
5086        #[unsafe(method_id(tableView:viewForTableColumn:row:))]
5087        fn view_for_row(
5088            &self,
5089            tv: &NSTableView,
5090            _col: Option<&NSTableColumn>,
5091            row: isize,
5092        ) -> Option<Retained<NSView>> {
5093            // Guarded: `bind_row` builds the app's row content.
5094            ffi_guard::contain(None, || {
5095                let mtm = self.mtm();
5096                // Headers pool apart from rows, so a recycled cell keeps its kind and rebinds.
5097                let header = self.is_header(row);
5098                let ident = NSString::from_str(if header { DAY_HEADER_CELL } else { DAY_ROW_CELL });
5099                // Recycle a cell view if one is free; else make a fresh flipped container.
5100                let cell: Retained<NSView> =
5101                    unsafe { tv.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5102                        let v: Retained<NSView> = Retained::into_super(DayFlipped::new(mtm));
5103                        unsafe { v.setIdentifier(Some(&ident)) };
5104                        v
5105                    });
5106                // Day builds row content the first time it sees this cell, and rebinds
5107                // (slot-write) when the cell is recycled. NSTableView calls this outside
5108                // reloadData's stack, so the re-entry into with_tree is safe.
5109                let source = self.ivars().source.borrow().clone();
5110                if let Some(source) = source {
5111                    let raw = Retained::as_ptr(&cell) as RawHandle;
5112                    (source.bind_row)(row as usize, raw);
5113                    if self.ivars().automatic || header {
5114                        self.note_row_height(tv, &source, row, raw, header);
5115                    }
5116                }
5117                Some(cell)
5118            })
5119        }
5120
5121        #[unsafe(method(tableView:didRemoveRowView:forRow:))]
5122        fn did_remove_row_view(
5123            &self,
5124            _tv: &NSTableView,
5125            row_view: &objc2_app_kit::NSTableRowView,
5126            _row: isize,
5127        ) {
5128            // The row went back to the reuse pool (a reload dropping it past a shrunk source, a
5129            // scroll): clear its day element ids so it stops answering lookups, as the tree's
5130            // `outlineView:didRemoveRowView:forRow:` does. Deferred, since this fires inside
5131            // reload stacks that hold the day-core borrow, and re-checked: a cell the same
5132            // turn's reload already reused has a window again, and its fresh ids must survive.
5133            ffi_guard::contain((), || {
5134                let Some(cell) = row_view.subviews().iter().find(|sub| {
5135                    sub.identifier()
5136                        .map(|i| {
5137                            let i = i.to_string();
5138                            i == DAY_ROW_CELL || i == DAY_HEADER_CELL
5139                        })
5140                        .unwrap_or(false)
5141                }) else {
5142                    return;
5143                };
5144                // Raw +1 pointers across the post (the closure must be Send, which Retained is
5145                // not; everything stays on the main thread). AppKit may free a removed row view.
5146                let cell = Retained::into_raw(cell) as usize;
5147                let Some(this) = (unsafe {
5148                    Retained::retain(self as *const DayListData as *mut DayListData)
5149                }) else {
5150                    return;
5151                };
5152                let this = Retained::into_raw(this) as usize;
5153                <AppKit as Platform>::post(Box::new(move || {
5154                    // Reclaim both +1s first, so every early return balances them.
5155                    let this = unsafe { Retained::from_raw(this as *mut DayListData) };
5156                    let cell = unsafe { Retained::from_raw(cell as *mut NSView) };
5157                    let (Some(this), Some(cell)) = (this, cell) else {
5158                        return;
5159                    };
5160                    if cell.window().is_some() {
5161                        return; // reused already: its ids are the live row's
5162                    }
5163                    let recycle = this
5164                        .ivars()
5165                        .source
5166                        .borrow()
5167                        .as_ref()
5168                        .map(|s| s.recycle.clone());
5169                    if let Some(recycle) = recycle {
5170                        recycle(Retained::as_ptr(&cell) as RawHandle);
5171                    }
5172                }));
5173            })
5174        }
5175
5176        #[unsafe(method(tableViewSelectionDidChange:))]
5177        fn selection_did_change(&self, notification: &NSNotification) {
5178            ffi_guard::contain((), || {
5179                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5180                    return;
5181                }
5182                let Some(obj) = (unsafe { notification.object() }) else {
5183                    return;
5184                };
5185                let Ok(tv) = obj.downcast::<NSTableView>() else {
5186                    return;
5187                };
5188                if self.ivars().multi.get() {
5189                    // Multi-select: report the FULL set (ascending; empty = cleared).
5190                    let idx = unsafe { tv.selectedRowIndexes() };
5191                    let mut rows = Vec::with_capacity(idx.count());
5192                    let mut i = idx.firstIndex();
5193                    while i != objc2_foundation::NSNotFound as usize {
5194                        rows.push(i as i64);
5195                        i = unsafe { idx.indexGreaterThanIndex(i) };
5196                    }
5197                    emit(self.ivars().node, Event::SelectionSet(rows));
5198                } else {
5199                    let row = unsafe { tv.selectedRow() };
5200                    if row >= 0 {
5201                        emit(self.ivars().node, Event::SelectionChanged(row as i64));
5202                    } else {
5203                        // CLEARED. `selectedRow()` answers -1, which is not a row, so there is
5204                        // nothing for `SelectionChanged` to carry and nothing for `on_select` to
5205                        // be called with — but the app still has to hear about it, or a detail
5206                        // pane goes on showing the row the user just deselected. The empty set is
5207                        // how that is said (`on_selection`, docs/list.md); reporting nothing was
5208                        // a silent contract break, since single-selection backends are documented
5209                        // as firing it with a one-element OR EMPTY set.
5210                        emit(self.ivars().node, Event::SelectionSet(Vec::new()));
5211                    }
5212                }
5213            })
5214        }
5215
5216        // --- swipe actions (docs/list.md): NSTableView's row-action pipeline. AppKit calls
5217        // this as the two-finger swipe starts, so the offer reflects the row's state at
5218        // GESTURE time; a full swipe across activates the first action (AppKit's own
5219        // full-slide behavior). The handler commits through the seam, which defers the app's
5220        // callback to the event drain.
5221        #[unsafe(method_id(tableView:rowActionsForRow:edge:))]
5222        fn row_actions_for_row(
5223            &self,
5224            tv: &NSTableView,
5225            row: isize,
5226            edge: objc2_app_kit::NSTableRowActionEdge,
5227        ) -> Retained<NSArray<objc2_app_kit::NSTableViewRowAction>> {
5228            // Guarded: `actions_at` runs the app's provider closure.
5229            ffi_guard::contain(NSArray::new(), || {
5230                let sw = self
5231                    .ivars()
5232                    .source
5233                    .borrow()
5234                    .as_ref()
5235                    .and_then(|s| s.swipe.clone());
5236                let Some(sw) = sw else {
5237                    return NSArray::new();
5238                };
5239                if row < 0 {
5240                    return NSArray::new();
5241                }
5242                // AppKit's Leading/Trailing already speak reading direction, same as ours.
5243                let day_edge = if edge == objc2_app_kit::NSTableRowActionEdge::Leading {
5244                    day_spec::SwipeEdge::Leading
5245                } else {
5246                    day_spec::SwipeEdge::Trailing
5247                };
5248                let offer = (sw.actions_at)(row as usize, day_edge);
5249                let actions: Vec<Retained<objc2_app_kit::NSTableViewRowAction>> = offer
5250                    .iter()
5251                    .enumerate()
5252                    .map(|(i, a)| {
5253                        let style = if a.destructive {
5254                            objc2_app_kit::NSTableViewRowActionStyle::Destructive
5255                        } else {
5256                            objc2_app_kit::NSTableViewRowActionStyle::Regular
5257                        };
5258                        let perform = sw.perform.clone();
5259                        // Retained only for the swipe session: AppKit releases the actions
5260                        // (and this block) when the revealed buttons close.
5261                        let table = tv.retain();
5262                        let handler = block2::RcBlock::new(
5263                            move |_action: std::ptr::NonNull<
5264                                objc2_app_kit::NSTableViewRowAction,
5265                            >,
5266                                  row: isize| {
5267                                ffi_guard::contain((), || {
5268                                    perform(row as usize, day_edge, i);
5269                                    // A button press leaves the buttons revealed; close
5270                                    // them (a full slide already closed itself).
5271                                    unsafe { table.setRowActionsVisible(false) };
5272                                })
5273                            },
5274                        );
5275                        let action =
5276                            objc2_app_kit::NSTableViewRowAction::rowActionWithStyle_title_handler(
5277                                style,
5278                                &NSString::from_str(&a.label),
5279                                &handler,
5280                            );
5281                        if let Some(t) = a.tint {
5282                            unsafe { action.setBackgroundColor(Some(&nscolor(t))) };
5283                        }
5284                        // Glyph above the label — the Mail row-action look. The SF symbol
5285                        // resolves per OS release; an unknown name yields no image and the
5286                        // button keeps its label alone.
5287                        if let Some(sym) = a.symbol {
5288                            let img = objc2_app_kit::NSImage::imageWithSystemSymbolName_accessibilityDescription(
5289                                &NSString::from_str(day_spec::sf_symbol_name(sym)),
5290                                None,
5291                            );
5292                            if let Some(img) = img {
5293                                unsafe { action.setImage(Some(&img)) };
5294                            }
5295                        }
5296                        action
5297                    })
5298                    .collect();
5299                NSArray::from_retained_slice(&actions)
5300            })
5301        }
5302    }
5303);
5304
5305impl DayListData {
5306    fn new(
5307        mtm: MainThreadMarker,
5308        node: NodeId,
5309        selectable: bool,
5310        multi: bool,
5311        automatic: bool,
5312        sections: bool,
5313    ) -> Retained<Self> {
5314        let this = Self::alloc(mtm).set_ivars(ListIvars {
5315            node,
5316            source: RefCell::new(None),
5317            selectable: std::cell::Cell::new(selectable),
5318            multi: std::cell::Cell::new(multi),
5319            suppress: std::cell::Cell::new(false),
5320            tokens: RefCell::new(Vec::new()),
5321            automatic,
5322            sections,
5323            header_estimate: std::cell::Cell::new(28.0),
5324            heights: RefCell::new(std::collections::HashMap::new()),
5325            cell_tokens: RefCell::new(std::collections::HashMap::new()),
5326            estimate: std::cell::Cell::new(44.0),
5327            heights_pending: std::cell::Cell::new(false),
5328        });
5329        unsafe { msg_send![super(this), init] }
5330    }
5331
5332    /// A self-sizing row was just bound to `cell`: record the height Day laid it at, and if
5333    /// the table drew the row at another height (the estimate, or the row's old content),
5334    /// correct it on the next turn. Not here: this runs inside NSTableView's own tiling.
5335    fn note_row_height(
5336        &self,
5337        table: &NSTableView,
5338        source: &ListSource,
5339        row: isize,
5340        cell: RawHandle,
5341        header: bool,
5342    ) {
5343        let height = (source.cell_height)(cell);
5344        if height <= 0.0 || row < 0 {
5345            return;
5346        }
5347        let token = (source.token_at)(row as usize);
5348        self.ivars()
5349            .cell_tokens
5350            .borrow_mut()
5351            .insert(cell as usize, token);
5352        self.ivars().heights.borrow_mut().insert(token, height);
5353        if header {
5354            self.ivars().header_estimate.set(height);
5355        } else {
5356            self.ivars().estimate.set(height);
5357        }
5358        let drawn = unsafe { table.rectOfRow(row) }.size.height;
5359        if (drawn - height).abs() > 0.5 {
5360            self.post_row_heights(table);
5361        }
5362    }
5363
5364    /// Whether display row `row` is a section header (docs/list.md "Sections").
5365    fn is_header(&self, row: isize) -> bool {
5366        row >= 0
5367            && self
5368                .ivars()
5369                .source
5370                .borrow()
5371                .as_ref()
5372                .and_then(|s| s.is_header.clone())
5373                .is_some_and(|is_header| is_header(row as usize))
5374    }
5375
5376    /// `ListPatch::RowSizeInvalidated`: the row in `cell` was re-laid at `height`. Arrives under
5377    /// the day-core borrow, so it only records the height; the table is told after the pass.
5378    fn row_resized(&self, table: &NSTableView, cell: usize, height: f64) {
5379        let token = self.ivars().cell_tokens.borrow().get(&cell).copied();
5380        if let Some(token) = token {
5381            self.ivars().heights.borrow_mut().insert(token, height);
5382            self.post_row_heights(table);
5383        }
5384    }
5385
5386    /// Tell the table, on the next main-loop turn, about every row near the viewport whose drawn
5387    /// height differs from the one Day laid it at. Coalesced: a pass that re-lays many rows
5388    /// posts one correction.
5389    fn post_row_heights(&self, table: &NSTableView) {
5390        if self.ivars().heights_pending.replace(true) {
5391            return;
5392        }
5393        // Raw +1 pointers across the post (the closure must be Send, which Retained is not;
5394        // everything stays on the main thread).
5395        let Some(this) = (unsafe { Retained::retain(self as *const Self as *mut Self) }) else {
5396            return;
5397        };
5398        let this = Retained::into_raw(this) as usize;
5399        let table = Retained::into_raw(table.retain()) as usize;
5400        <AppKit as Platform>::post(Box::new(move || {
5401            // Reclaim both +1s first, so every early return balances them.
5402            let this = unsafe { Retained::from_raw(this as *mut DayListData) };
5403            let table = unsafe { Retained::from_raw(table as *mut NSTableView) };
5404            let (Some(this), Some(table)) = (this, table) else {
5405                return;
5406            };
5407            this.ivars().heights_pending.set(false);
5408            ffi_guard::contain((), || this.apply_row_heights(&table));
5409        }));
5410    }
5411
5412    fn apply_row_heights(&self, table: &NSTableView) {
5413        let Some(source) = self.ivars().source.borrow().clone() else {
5414            return;
5415        };
5416        let count = unsafe { table.numberOfRows() }.max(0) as usize;
5417        let shown = unsafe { table.rowsInRect(table.visibleRect()) };
5418        // The viewport and the rows AppKit prepares around it.
5419        let first = shown.location.saturating_sub(8);
5420        let last = (shown.location + shown.length + 8)
5421            .min(count)
5422            .min((source.len)());
5423        let changed = objc2_foundation::NSMutableIndexSet::new();
5424        {
5425            let heights = self.ivars().heights.borrow();
5426            for row in first..last {
5427                if let Some(&height) = heights.get(&(source.token_at)(row)) {
5428                    let drawn = unsafe { table.rectOfRow(row as isize) }.size.height;
5429                    if (drawn - height).abs() > 0.5 {
5430                        unsafe { changed.addIndex(row) };
5431                    }
5432                }
5433            }
5434        }
5435        if changed.count() == 0 {
5436            return;
5437        }
5438        // Unanimated: the row takes its content's height, it does not grow into it.
5439        NSAnimationContext::beginGrouping();
5440        NSAnimationContext::currentContext().setDuration(0.0);
5441        unsafe { table.noteHeightOfRowsWithIndexesChanged(&changed) };
5442        NSAnimationContext::endGrouping();
5443    }
5444
5445    /// If this Reload is the same row set in a new order, the incremental `moveRowAtIndex`
5446    /// steps (each `(from, to)` interpreted against the already-moved rows, NSTableView's
5447    /// semantics) that transform the displayed order into the new one — and `None` for
5448    /// anything else (insert/remove/content change/no change), which reloads flat. Always
5449    /// refreshes the displayed-order cache.
5450    ///
5451    /// Every row that changes position must have a REALIZED row view (`table`): moving a
5452    /// viewless row (its old position sat outside the viewport, so it was never bound)
5453    /// animates nothing and leaves the row unbound at its new position — its content, and any
5454    /// element ids inside it, would simply not exist. Such a reorder returns `None` and
5455    /// reloads flat, which realizes and binds the row at its new position.
5456    fn permutation_moves(&self, table: &NSTableView) -> Option<Vec<(usize, usize)>> {
5457        let source = self.ivars().source.borrow();
5458        let source = source.as_ref()?;
5459        let n = (source.len)();
5460        let new: Vec<u64> = (0..n).map(|i| (source.token_at)(i)).collect();
5461        let old = std::mem::replace(&mut *self.ivars().tokens.borrow_mut(), new.clone());
5462        if old.len() != n || n == 0 || old == new {
5463            return None;
5464        }
5465        let (mut so, mut sn) = (old.clone(), new.clone());
5466        so.sort_unstable();
5467        sn.sort_unstable();
5468        if so != sn {
5469            return None;
5470        }
5471        for i in 0..n {
5472            if old[i] != new[i]
5473                && unsafe { table.rowViewAtRow_makeIfNecessary(i as isize, false) }.is_none()
5474            {
5475                return None;
5476            }
5477        }
5478        let mut work = old;
5479        let mut moves = Vec::new();
5480        for i in 0..n {
5481            if work[i] == new[i] {
5482                continue;
5483            }
5484            let j = (i + 1..n).find(|&j| work[j] == new[i])?;
5485            let t = work.remove(j);
5486            work.insert(i, t);
5487            moves.push((j, i));
5488        }
5489        Some(moves)
5490    }
5491
5492    /// The dragged row + current row count for an in-flight LOCAL reorder drag — `None` when the
5493    /// drag came from anywhere but this table (day never accepts foreign drops into a list) or
5494    /// the pasteboard doesn't carry the day row type.
5495    fn drag_context(
5496        &self,
5497        tv: &NSTableView,
5498        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5499    ) -> Option<(usize, usize)> {
5500        let src = unsafe { info.draggingSource() }?;
5501        if Retained::as_ptr(&src) as *const std::ffi::c_void
5502            != tv as *const NSTableView as *const std::ffi::c_void
5503        {
5504            return None;
5505        }
5506        let pb = unsafe { info.draggingPasteboard() };
5507        let from = unsafe { pb.stringForType(&NSString::from_str(DAY_ROW_PASTEBOARD_TYPE)) }?
5508            .to_string()
5509            .parse::<usize>()
5510            .ok()?;
5511        let len = self.ivars().source.borrow().as_ref().map(|s| (s.len)())?;
5512        (from < len).then_some((from, len))
5513    }
5514
5515    /// The guard's verdict for `from -> to` (accepted index, or -1), through the sync seam.
5516    fn can_move(&self, from: usize, to: usize) -> i64 {
5517        self.ivars()
5518            .source
5519            .borrow()
5520            .as_ref()
5521            .and_then(|s| s.reorder.as_ref().map(|r| (r.can_move)(from, to)))
5522            .unwrap_or(-1)
5523    }
5524}
5525
5526/// The reuse identifiers of a list's row cells and its section-header cells.
5527const DAY_ROW_CELL: &str = "day.cell";
5528const DAY_HEADER_CELL: &str = "day.header";
5529
5530/// The private pasteboard type carrying a dragged day list row's index (local reorder only).
5531const DAY_ROW_PASTEBOARD_TYPE: &str = "dev.daybrite.day.row";
5532
5533/// An NSTableView drop lands at an INSERTION point (`row` with `.Above` semantics, 0..=len);
5534/// day's seam speaks post-removal target indices. Dropping `from` at insertion `ins`:
5535fn insertion_to_target(from: usize, ins: usize, len: usize) -> usize {
5536    let to = if ins > from { ins - 1 } else { ins };
5537    to.min(len.saturating_sub(1))
5538}
5539
5540/// The inverse, for retargeting the drop gap: where the gap sits for a post-removal target.
5541fn target_to_insertion(from: usize, to: usize) -> usize {
5542    if to > from { to + 1 } else { to }
5543}
5544
5545/// A realized LIST's scroll view ptr → (table, data source) for attach_list / update / measure.
5546type ListEntry = (Retained<NSTableView>, Retained<DayListData>);
5547
5548/// Clone a list's (table, data) out of `LIST_STATE` under a SHORT borrow. Every caller then
5549/// talks to AppKit with the map free: table calls that look innocuous (`endUpdates`, a scroll's
5550/// tiling, `viewAtColumn:row:makeIfNecessary:`, even `layoutSubtreeIfNeeded`) can synchronously
5551/// re-enter `viewForRow` → `bind_row` → a flush that tears nodes down — and `release` must be
5552/// able to take its own borrow at that depth. Holding the map across any of them was the
5553/// "RefCell already borrowed" contained panic every list walkthrough used to log, 24 a run.
5554fn list_entry(key: usize) -> Option<ListEntry> {
5555    LIST_STATE.with(|m| m.borrow().get(&key).cloned())
5556}
5557
5558// ---------------------------------------------------------------------------
5559// DayTreeData — NSOutlineView data-source + delegate for the hierarchical tree (docs/tree.md)
5560// ---------------------------------------------------------------------------
5561
5562struct TreeIvars {
5563    node: NodeId,
5564    /// Injected by `attach_tree` once day-core wires the driver.
5565    source: RefCell<Option<TreeSource>>,
5566    selectable: std::cell::Cell<bool>,
5567    /// Programmatic selection/disclosure in flight: don't re-emit the event (echo rule).
5568    suppress: std::cell::Cell<bool>,
5569    /// token → its interned NSNumber. NSOutlineView tracks items (selection, expansion,
5570    /// rowForItem) by object identity/equality, so every query for a token must answer with
5571    /// the same object — which is also what preserves expansion across reloadData.
5572    items: RefCell<HashMap<u64, Retained<NSNumber>>>,
5573}
5574
5575define_class!(
5576    #[unsafe(super(NSObject))]
5577    #[thread_kind = MainThreadOnly]
5578    #[name = "DayTreeData"]
5579    #[ivars = TreeIvars]
5580    struct DayTreeData;
5581
5582    unsafe impl NSObjectProtocol for DayTreeData {}
5583
5584    unsafe impl NSOutlineViewDataSource for DayTreeData {
5585        #[unsafe(method(outlineView:numberOfChildrenOfItem:))]
5586        fn number_of_children(
5587            &self,
5588            _ov: &objc2_app_kit::NSOutlineView,
5589            item: Option<&objc2::runtime::AnyObject>,
5590        ) -> isize {
5591            // Reads the piece's snapshot only (no tree access) — safe even when called
5592            // synchronously from reloadData inside a with_tree borrow. Guarded because
5593            // the closures are day-core's.
5594            ffi_guard::contain(0, || {
5595                let parent = item.and_then(Self::token_of_item);
5596                if item.is_some() && parent.is_none() {
5597                    return 0; // not one of ours (stale query racing a reload)
5598                }
5599                self.ivars()
5600                    .source
5601                    .borrow()
5602                    .as_ref()
5603                    .map(|s| (s.children_len)(parent) as isize)
5604                    .unwrap_or(0)
5605            })
5606        }
5607
5608        #[unsafe(method_id(outlineView:child:ofItem:))]
5609        fn child_of_item(
5610            &self,
5611            _ov: &objc2_app_kit::NSOutlineView,
5612            index: isize,
5613            item: Option<&objc2::runtime::AnyObject>,
5614        ) -> Retained<objc2::runtime::AnyObject> {
5615            // AppKit only asks for children it was told exist, but a stale query racing a
5616            // reload must degrade (token 0, an unmatched identity) rather than panic — an
5617            // unwind here crosses an ObjC frame and aborts.
5618            let token = ffi_guard::contain(0, || {
5619                let parent = item.and_then(Self::token_of_item);
5620                self.ivars()
5621                    .source
5622                    .borrow()
5623                    .as_ref()
5624                    .map(|s| (s.child_token)(parent, index.max(0) as usize))
5625                    .unwrap_or(0)
5626            });
5627            let ns = self.intern(token);
5628            unsafe { objc2::rc::Retained::cast_unchecked(ns) }
5629        }
5630
5631        #[unsafe(method(outlineView:isItemExpandable:))]
5632        fn is_expandable(
5633            &self,
5634            _ov: &objc2_app_kit::NSOutlineView,
5635            item: &objc2::runtime::AnyObject,
5636        ) -> bool {
5637            ffi_guard::contain(false, || {
5638                let Some(token) = Self::token_of_item(item) else {
5639                    return false;
5640                };
5641                self.ivars()
5642                    .source
5643                    .borrow()
5644                    .as_ref()
5645                    .map(|s| (s.expandable)(token))
5646                    .unwrap_or(false)
5647            })
5648        }
5649
5650        // --- drag-to-move (docs/tree.md): the dragged node rides the pasteboard as a
5651        // private-typed token string; `validateDrop` consults the guard live (forbidden
5652        // cursor where it denies, including ONTO-a-row drops via childIndex -1), and
5653        // `acceptDrop` commits through the sync seam — the app's own data write reloads.
5654
5655        #[unsafe(method_id(outlineView:pasteboardWriterForItem:))]
5656        fn pasteboard_writer_for_item(
5657            &self,
5658            _ov: &objc2_app_kit::NSOutlineView,
5659            item: &objc2::runtime::AnyObject,
5660        ) -> Option<Retained<ProtocolObject<dyn objc2_app_kit::NSPasteboardWriting>>> {
5661            let make = || {
5662                let movable = self
5663                    .ivars()
5664                    .source
5665                    .borrow()
5666                    .as_ref()
5667                    .is_some_and(|s| s.moves.is_some());
5668                let token = Self::token_of_item(item)?;
5669                if !movable {
5670                    return None;
5671                }
5672                let pbitem = objc2_app_kit::NSPasteboardItem::new();
5673                unsafe {
5674                    pbitem.setString_forType(
5675                        &NSString::from_str(&token.to_string()),
5676                        &NSString::from_str(DAY_TREE_PASTEBOARD_TYPE),
5677                    );
5678                }
5679                Some(ProtocolObject::from_retained(pbitem))
5680            };
5681            ffi_guard::contain(None, make)
5682        }
5683
5684        #[unsafe(method(outlineView:validateDrop:proposedItem:proposedChildIndex:))]
5685        fn validate_drop(
5686            &self,
5687            ov: &objc2_app_kit::NSOutlineView,
5688            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5689            item: Option<&objc2::runtime::AnyObject>,
5690            child_index: isize,
5691        ) -> objc2_app_kit::NSDragOperation {
5692            ffi_guard::contain(objc2_app_kit::NSDragOperation::None, || {
5693                match self.drop_proposal(ov, info, item, child_index) {
5694                    Some((token, parent, index)) if self.can_move(token, parent, index) => {
5695                        objc2_app_kit::NSDragOperation::Move
5696                    }
5697                    _ => objc2_app_kit::NSDragOperation::None,
5698                }
5699            })
5700        }
5701
5702        #[unsafe(method(outlineView:acceptDrop:item:childIndex:))]
5703        fn accept_drop(
5704            &self,
5705            ov: &objc2_app_kit::NSOutlineView,
5706            info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
5707            item: Option<&objc2::runtime::AnyObject>,
5708            child_index: isize,
5709        ) -> bool {
5710            let drop = || {
5711                let Some((token, parent, index)) = self.drop_proposal(ov, info, item, child_index)
5712                else {
5713                    return false;
5714                };
5715                if !self.can_move(token, parent, index) {
5716                    return false;
5717                }
5718                // Commit through the sync seam: defers the app's `on_move`; the app's own
5719                // data write drives the Reload (no native row animation on this path).
5720                let mv = self
5721                    .ivars()
5722                    .source
5723                    .borrow()
5724                    .as_ref()
5725                    .and_then(|s| s.moves.as_ref().map(|m| m.move_node.clone()));
5726                let Some(mv) = mv else { return false };
5727                mv(token, parent, index);
5728                true
5729            };
5730            ffi_guard::contain(false, drop)
5731        }
5732    }
5733
5734    unsafe impl NSControlTextEditingDelegate for DayTreeData {}
5735
5736    unsafe impl NSOutlineViewDelegate for DayTreeData {
5737        #[unsafe(method(outlineView:isGroupItem:))]
5738        fn is_group_item(
5739            &self,
5740            _ov: &objc2_app_kit::NSOutlineView,
5741            item: &objc2::runtime::AnyObject,
5742        ) -> bool {
5743            Self::token_of_item(item).is_some_and(|t| {
5744                self.ivars()
5745                    .source
5746                    .borrow()
5747                    .as_ref()
5748                    .is_some_and(|s| (s.section_header)(t))
5749            })
5750        }
5751        #[unsafe(method(outlineView:shouldSelectItem:))]
5752        fn should_select_item(
5753            &self,
5754            _ov: &objc2_app_kit::NSOutlineView,
5755            item: &objc2::runtime::AnyObject,
5756        ) -> bool {
5757            Self::token_of_item(item).is_some_and(|t| {
5758                self.ivars()
5759                    .source
5760                    .borrow()
5761                    .as_ref()
5762                    .is_some_and(|s| !(s.section_header)(t))
5763            })
5764        }
5765
5766        #[unsafe(method_id(outlineView:viewForTableColumn:item:))]
5767        fn view_for_item(
5768            &self,
5769            ov: &objc2_app_kit::NSOutlineView,
5770            _col: Option<&NSTableColumn>,
5771            item: &objc2::runtime::AnyObject,
5772        ) -> Option<Retained<NSView>> {
5773            // Guarded: `bind_row` builds the app's row content.
5774            ffi_guard::contain(None, || {
5775                let mtm = self.mtm();
5776                let token = Self::token_of_item(item)?;
5777                let ident = NSString::from_str("day.tree.cell");
5778                // Recycle a cell view if one is free; else make a fresh flipped container
5779                // (DayTreeCell re-lays its Day row at its own width — indentation makes
5780                // every tree cell's width per-row).
5781                let cell: Retained<NSView> =
5782                    unsafe { ov.makeViewWithIdentifier_owner(&ident, None) }.unwrap_or_else(|| {
5783                        let v: Retained<NSView> =
5784                            Retained::into_super(Retained::into_super(DayTreeCell::new(mtm)));
5785                        unsafe { v.setIdentifier(Some(&ident)) };
5786                        v
5787                    });
5788                if let Some(source) = self.ivars().source.borrow().as_ref() {
5789                    let raw = Retained::as_ptr(&cell) as RawHandle;
5790                    if let Some(cell) = cell.downcast_ref::<DayTreeCell>() {
5791                        unsafe {
5792                            cell.setTextField(None);
5793                        }
5794                    }
5795                    (source.bind_row)(token, raw);
5796                    // Associate the actual Day label with NSTableCellView so AppKit can
5797                    // apply group typography and source-list background styles normally.
5798                    if (source.section_header)(token) {
5799                        fn label_in(view: &NSView) -> Option<Retained<NSTextField>> {
5800                            for child in unsafe { view.subviews() }.iter() {
5801                                if let Ok(label) = child.clone().downcast::<NSTextField>() {
5802                                    return Some(label);
5803                                }
5804                                if let Some(label) = label_in(&child) {
5805                                    return Some(label);
5806                                }
5807                            }
5808                            None
5809                        }
5810                        if let Some(label) = label_in(&cell) {
5811                            let cell = cell.downcast_ref::<DayTreeCell>()?;
5812                            unsafe {
5813                                cell.setTextField(Some(&label));
5814                            }
5815                        }
5816                    }
5817                }
5818                Some(cell)
5819            })
5820        }
5821
5822        #[unsafe(method_id(outlineView:typeSelectStringForTableColumn:item:))]
5823        fn type_select_string(
5824            &self,
5825            _ov: &objc2_app_kit::NSOutlineView,
5826            _col: Option<&NSTableColumn>,
5827            item: &objc2::runtime::AnyObject,
5828        ) -> Option<Retained<NSString>> {
5829            ffi_guard::contain(None, || {
5830                let token = Self::token_of_item(item)?;
5831                let text = self
5832                    .ivars()
5833                    .source
5834                    .borrow()
5835                    .as_ref()
5836                    .map(|s| (s.type_select_text)(token))
5837                    .unwrap_or_default();
5838                // Empty = this row doesn't participate in type-select.
5839                (!text.is_empty()).then(|| NSString::from_str(&text))
5840            })
5841        }
5842
5843        #[unsafe(method_id(outlineView:rowViewForItem:))]
5844        fn row_view_for_item(
5845            &self,
5846            ov: &objc2_app_kit::NSOutlineView,
5847            _item: &objc2::runtime::AnyObject,
5848        ) -> Retained<objc2_app_kit::NSTableRowView> {
5849            if unsafe { ov.style() } == objc2_app_kit::NSTableViewStyle::SourceList {
5850                // AppKit owns source-list group backgrounds, floating headers and selection.
5851                unsafe { objc2_app_kit::NSTableRowView::new(self.mtm()) }
5852            } else {
5853                // The rounded-selection row (see DayTreeRowView).
5854                let rv: Retained<DayTreeRowView> =
5855                    unsafe { msg_send![DayTreeRowView::alloc(self.mtm()), init] };
5856                Retained::into_super(rv)
5857            }
5858        }
5859
5860        #[unsafe(method(outlineViewSelectionDidChange:))]
5861        fn selection_did_change(&self, notification: &NSNotification) {
5862            ffi_guard::contain((), || {
5863                if self.ivars().suppress.get() || !self.ivars().selectable.get() {
5864                    return;
5865                }
5866                let Some(obj) = (unsafe { notification.object() }) else {
5867                    return;
5868                };
5869                let Ok(ov) = obj.downcast::<objc2_app_kit::NSOutlineView>() else {
5870                    return;
5871                };
5872                // Always the FULL token set (docs/tree.md): a tree cannot speak row indices.
5873                let idx = unsafe { ov.selectedRowIndexes() };
5874                let mut tokens = Vec::with_capacity(idx.count());
5875                let mut i = idx.firstIndex();
5876                while i != objc2_foundation::NSNotFound as usize {
5877                    if let Some(item) = unsafe { ov.itemAtRow(i as isize) }
5878                        && let Some(tok) = Self::token_of_item(&item)
5879                    {
5880                        tokens.push(tok);
5881                    }
5882                    i = unsafe { idx.indexGreaterThanIndex(i) };
5883                }
5884                emit(self.ivars().node, Event::TreeSelection(tokens));
5885            })
5886        }
5887
5888        #[unsafe(method(outlineView:didRemoveRowView:forRow:))]
5889        fn did_remove_row_view(
5890            &self,
5891            ov: &objc2_app_kit::NSOutlineView,
5892            row_view: &objc2_app_kit::NSTableRowView,
5893            _row: isize,
5894        ) {
5895            // The row went back to the reuse pool (a collapse, a reload dropping it): clear
5896            // its day element ids so it stops answering `find_by_id`. DEFERRED — this fires
5897            // inside collapse/reload stacks that hold the day-core borrow — and re-checked:
5898            // a cell already reused by the same turn's reload has a window again, and its
5899            // fresh ids must survive.
5900            ffi_guard::contain((), || {
5901                let mut cell_ptr: Option<usize> = None;
5902                for sub in row_view.subviews().iter() {
5903                    let is_cell = sub
5904                        .identifier()
5905                        .map(|i| i.to_string() == "day.tree.cell")
5906                        .unwrap_or(false);
5907                    if is_cell {
5908                        cell_ptr = Some(Retained::as_ptr(&sub) as usize);
5909                    }
5910                }
5911                let Some(cell) = cell_ptr else { return };
5912                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
5913                    return;
5914                };
5915                let key = Retained::as_ptr(&scroll) as usize;
5916                // Carry a RETAIN across the post as a raw +1 pointer (the boxed closure must
5917                // be Send, which Retained is not; we stay on the main thread throughout).
5918                // AppKit is free to dealloc removed row views — a bare pointer died here once.
5919                let retained =
5920                    unsafe { Retained::into_raw(Retained::retain(cell as *mut NSView).unwrap()) }
5921                        as usize;
5922                <AppKit as Platform>::post(Box::new(move || {
5923                    // Reclaim the +1 first, unconditionally — every early return below must
5924                    // still balance the retain.
5925                    let cell_view: Retained<NSView> =
5926                        match unsafe { Retained::from_raw(retained as *mut NSView) } {
5927                            Some(v) => v,
5928                            None => return,
5929                        };
5930                    let recycle = tree_entry(key).and_then(|(_, data)| {
5931                        data.ivars()
5932                            .source
5933                            .borrow()
5934                            .as_ref()
5935                            .map(|s| s.recycle.clone())
5936                    });
5937                    let Some(recycle) = recycle else { return };
5938                    if cell_view.window().is_some() {
5939                        return; // reused already — its ids are the live row's
5940                    }
5941                    recycle(cell as RawHandle);
5942                }));
5943            })
5944        }
5945
5946        #[unsafe(method(outlineViewItemDidExpand:))]
5947        fn item_did_expand(&self, notification: &NSNotification) {
5948            self.report_disclosure(notification, true);
5949        }
5950
5951        #[unsafe(method(outlineViewItemDidCollapse:))]
5952        fn item_did_collapse(&self, notification: &NSNotification) {
5953            self.report_disclosure(notification, false);
5954        }
5955    }
5956);
5957
5958impl DayTreeData {
5959    fn new(mtm: MainThreadMarker, node: NodeId, selectable: bool) -> Retained<Self> {
5960        let this = Self::alloc(mtm).set_ivars(TreeIvars {
5961            node,
5962            source: RefCell::new(None),
5963            selectable: std::cell::Cell::new(selectable),
5964            suppress: std::cell::Cell::new(false),
5965            items: RefCell::new(HashMap::new()),
5966        });
5967        unsafe { msg_send![super(this), init] }
5968    }
5969
5970    /// The same NSNumber for a token, every time — NSOutlineView's item identity.
5971    fn intern(&self, token: u64) -> Retained<NSNumber> {
5972        self.ivars()
5973            .items
5974            .borrow_mut()
5975            .entry(token)
5976            .or_insert_with(|| NSNumber::new_u64(token))
5977            .clone()
5978    }
5979
5980    fn token_of_item(item: &objc2::runtime::AnyObject) -> Option<u64> {
5981        item.downcast_ref::<NSNumber>().map(|n| n.as_u64())
5982    }
5983
5984    /// A native disclosure (user click, keyboard left/right) → `Event::TreeExpanded`.
5985    /// Programmatic `TreePatch::Expand` applications are suppressed (the echo rule).
5986    fn report_disclosure(&self, notification: &NSNotification, expanded: bool) {
5987        ffi_guard::contain((), || {
5988            if self.ivars().suppress.get() {
5989                return;
5990            }
5991            let token = unsafe { notification.userInfo() }
5992                .and_then(|ui| ui.objectForKey(&*NSString::from_str("NSObject")))
5993                .and_then(|item| Self::token_of_item(&item));
5994            if let Some(token) = token {
5995                emit(self.ivars().node, Event::TreeExpanded { token, expanded });
5996            }
5997        })
5998    }
5999
6000    /// The full drop proposal — `(dragged token, parent token, index)` — for a LOCAL drag
6001    /// from this outline; `None` for a foreign drag or an unparseable one. `index: None`
6002    /// means "ONTO the parent" (NSOutlineView's childIndex -1, `NSOutlineViewDropOnItemIndex`).
6003    fn drop_proposal(
6004        &self,
6005        ov: &objc2_app_kit::NSOutlineView,
6006        info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
6007        item: Option<&objc2::runtime::AnyObject>,
6008        child_index: isize,
6009    ) -> Option<(u64, Option<u64>, Option<usize>)> {
6010        let src = unsafe { info.draggingSource() }?;
6011        if Retained::as_ptr(&src) as *const std::ffi::c_void
6012            != ov as *const objc2_app_kit::NSOutlineView as *const std::ffi::c_void
6013        {
6014            return None;
6015        }
6016        let pb = unsafe { info.draggingPasteboard() };
6017        let token = unsafe { pb.stringForType(&NSString::from_str(DAY_TREE_PASTEBOARD_TYPE)) }?
6018            .to_string()
6019            .parse::<u64>()
6020            .ok()?;
6021        let parent = match item {
6022            Some(i) => Some(Self::token_of_item(i)?), // a non-token item is not ours
6023            None => None,
6024        };
6025        let index = (child_index >= 0).then_some(child_index as usize);
6026        Some((token, parent, index))
6027    }
6028
6029    /// The guard's live verdict through the sync seam.
6030    fn can_move(&self, token: u64, parent: Option<u64>, index: Option<usize>) -> bool {
6031        self.ivars()
6032            .source
6033            .borrow()
6034            .as_ref()
6035            .and_then(|s| s.moves.as_ref().map(|m| (m.can_move)(token, parent, index)))
6036            .map(|v| v == MoveVerdict::Allow)
6037            .unwrap_or(false)
6038    }
6039}
6040
6041// DayOutlineView — an NSOutlineView that PINS its width to its clip on every layout pass.
6042// A table sizes itself from its COLUMNS, and the autoresizing mask only tracks deltas, so
6043// any early pass at a different pane width leaves a permanent offset (a 233pt table in a
6044// 220pt pane, whose selection pill then clips mid-corner). Enforcing it in `layout` — not
6045// in occasional deferred posts — closes every window where a stale width could draw.
6046define_class!(
6047    #[unsafe(super(objc2_app_kit::NSOutlineView))]
6048    #[thread_kind = MainThreadOnly]
6049    #[name = "DayOutlineView"]
6050    struct DayOutlineView;
6051
6052    impl DayOutlineView {
6053        #[unsafe(method(layout))]
6054        fn layout(&self) {
6055            sync_tree_width(self);
6056            let _: () = unsafe { msg_send![super(self), layout] };
6057        }
6058
6059        /// A summon-time ROW context menu (docs/menus.md, docs/tree.md): right-click asks
6060        /// the tree's `row_menu` provider for the row under the pointer.
6061        #[unsafe(method_id(menuForEvent:))]
6062        fn menu_for_event(
6063            &self,
6064            event: &objc2_app_kit::NSEvent,
6065        ) -> Option<Retained<NSMenu>> {
6066            ffi_guard::contain(None, || {
6067                let scroll = unsafe { self.enclosingScrollView() }?;
6068                let (_, data) = tree_entry(Retained::as_ptr(&scroll) as usize)?;
6069                let row_menu = data
6070                    .ivars()
6071                    .source
6072                    .borrow()
6073                    .as_ref()
6074                    .and_then(|s| s.row_menu.clone())?;
6075                let p = self.convertPoint_fromView(unsafe { event.locationInWindow() }, None);
6076                let row = unsafe { self.rowAtPoint(p) };
6077                if row < 0 {
6078                    return None;
6079                }
6080                let token =
6081                    unsafe { self.itemAtRow(row) }.and_then(|i| DayTreeData::token_of_item(&i))?;
6082                let items = row_menu(token);
6083                if items.is_empty() {
6084                    return None;
6085                }
6086                Some(build_ns_menu(self.mtm(), "", &items))
6087            })
6088        }
6089    }
6090);
6091
6092// DayTreeRowView — a tree row with the MODERN selection: a rounded pill, inset from the
6093// pane's edges, in the system's semantic selection colors (accent when the tree has focus,
6094// the quiet gray otherwise). Drawn by hand rather than through `NSTableViewStyle::Inset`,
6095// whose machinery pads the table wider than its clip and fights day's fixed-frame layout —
6096// and a hand-drawn plain color also captures correctly offscreen, where materials go black
6097// (docs/navigation.md's sidebar-screenshot rule).
6098define_class!(
6099    #[unsafe(super(objc2_app_kit::NSTableRowView))]
6100    #[thread_kind = MainThreadOnly]
6101    #[name = "DayTreeRowView"]
6102    struct DayTreeRowView;
6103
6104    impl DayTreeRowView {
6105        #[unsafe(method(drawSelectionInRect:))]
6106        fn draw_selection_in_rect(&self, _dirty: NSRect) {
6107            if !unsafe { self.isSelected() } {
6108                return;
6109            }
6110            let color = if unsafe { self.isEmphasized() } {
6111                unsafe { objc2_app_kit::NSColor::selectedContentBackgroundColor() }
6112            } else {
6113                unsafe { objc2_app_kit::NSColor::unemphasizedSelectedContentBackgroundColor() }
6114            };
6115            let b = self.bounds();
6116            let pill = NSRect::new(
6117                NSPoint::new(b.origin.x + 5.0, b.origin.y + 1.0),
6118                NSSize::new(
6119                    (b.size.width - 10.0).max(0.0),
6120                    (b.size.height - 2.0).max(0.0),
6121                ),
6122            );
6123            unsafe {
6124                color.setFill();
6125                objc2_app_kit::NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(
6126                    pill, 5.0, 5.0,
6127                )
6128                .fill();
6129            }
6130        }
6131    }
6132);
6133
6134// DayTreeCell — a tree row's flipped cell container. NSOutlineView frames it at the row's
6135// INDENTED position, so its width is per-row; every native layout pass re-lays the Day row
6136// content inside it at that width through the seam's `layout_cell`.
6137define_class!(
6138    #[unsafe(super(objc2_app_kit::NSTableCellView))]
6139    #[thread_kind = MainThreadOnly]
6140    #[name = "DayTreeCell"]
6141    struct DayTreeCell;
6142
6143    impl DayTreeCell {
6144        #[unsafe(method(isFlipped))]
6145        fn is_flipped(&self) -> bool {
6146            true
6147        }
6148
6149        #[unsafe(method(layout))]
6150        fn layout(&self) {
6151            let _: () = unsafe { msg_send![super(self), layout] };
6152            ffi_guard::contain((), || {
6153                let width = self.bounds().size.width;
6154                if width <= 0.0 {
6155                    return;
6156                }
6157                // This cell's tree: walk up to the outline, then to its scroll host, which
6158                // keys TREE_STATE. (The cell may be in the reuse pool — no outline — or the
6159                // tree may be mid-teardown; both just skip.)
6160                let mut cur = unsafe { self.superview() };
6161                let mut outline: Option<Retained<objc2_app_kit::NSOutlineView>> = None;
6162                while let Some(v) = cur {
6163                    cur = unsafe { v.superview() };
6164                    if let Ok(ov) = v.downcast::<objc2_app_kit::NSOutlineView>() {
6165                        outline = Some(ov);
6166                        break;
6167                    }
6168                }
6169                let Some(ov) = outline else { return };
6170                let Some(scroll) = (unsafe { ov.enclosingScrollView() }) else {
6171                    return;
6172                };
6173                let f = tree_entry(Retained::as_ptr(&scroll) as usize)
6174                    .and_then(|(_, data)| {
6175                        data.ivars()
6176                            .source
6177                            .borrow()
6178                            .as_ref()
6179                            .map(|s| s.layout_cell_size.clone())
6180                    });
6181                if let Some(f) = f {
6182                    f(self as *const Self as RawHandle, Size::new(width, self.bounds().size.height));
6183                }
6184            })
6185        }
6186    }
6187);
6188
6189impl DayTreeCell {
6190    fn new(mtm: MainThreadMarker) -> Retained<Self> {
6191        unsafe { msg_send![Self::alloc(mtm), init] }
6192    }
6193}
6194
6195/// The private pasteboard type carrying a dragged day tree node's token (local moves only).
6196const DAY_TREE_PASTEBOARD_TYPE: &str = "dev.daybrite.day.tree.node";
6197
6198/// A realized TREE's scroll view ptr → (outline, data source).
6199type TreeEntry = (
6200    Retained<objc2_app_kit::NSOutlineView>,
6201    Retained<DayTreeData>,
6202);
6203
6204/// Clone a tree's (outline, data) out of `TREE_STATE` under a SHORT borrow — the same
6205/// re-entrancy rule as `list_entry` (its comment has the war story).
6206fn tree_entry(key: usize) -> Option<TreeEntry> {
6207    TREE_STATE.with(|m| m.borrow().get(&key).cloned())
6208}
6209
6210/// Keep the outline exactly as wide as its clip — DayOutlineView calls this on every layout
6211/// pass (its comment has the why). The list never noticed the width drift because it lays
6212/// row content at the HOST's width; tree rows lay out at the CELL's, which exposes it.
6213fn sync_tree_width(outline: &objc2_app_kit::NSOutlineView) {
6214    let Some(scroll) = (unsafe { outline.enclosingScrollView() }) else {
6215        return;
6216    };
6217    let clip_w = unsafe { scroll.contentView() }.bounds().size.width;
6218    let f = outline.frame();
6219    if clip_w > 0.0 && (f.size.width - clip_w).abs() > 0.5 {
6220        unsafe {
6221            outline.setFrameSize(NSSize::new(clip_w, f.size.height));
6222            outline.sizeLastColumnToFit();
6223        }
6224    }
6225}
6226
6227/// Realize the tree's visible rows on the next main-loop turn, outside any borrow — the
6228/// tree twin of `post_realize_visible_rows` (its comment explains the occluded-window trap).
6229fn post_realize_visible_tree_rows(key: usize) {
6230    <AppKit as Platform>::post(Box::new(move || {
6231        if let Some((outline, _)) = tree_entry(key) {
6232            let range = unsafe { outline.rowsInRect(outline.visibleRect()) };
6233            for row in range.location..range.location + range.length {
6234                let _ = unsafe { outline.viewAtColumn_row_makeIfNecessary(0, row as isize, true) };
6235            }
6236        }
6237        day_core::pump_events();
6238    }));
6239}
6240
6241/// A realized NAV_MENU's native outline view paired with its data-source object.
6242type NavMenuEntry = (
6243    Retained<objc2_app_kit::NSOutlineView>,
6244    Retained<DayNavMenuData>,
6245);
6246
6247fn ns_rect(r: day_spec::Rect) -> NSRect {
6248    NSRect::new(
6249        NSPoint::new(r.origin.x, r.origin.y),
6250        NSSize::new(r.size.width, r.size.height),
6251    )
6252}
6253
6254fn draw_op(op: &DrawOp) {
6255    unsafe {
6256        match op {
6257            // One path for the whole batch, then one fill or stroke: the template is appended
6258            // once per position, so the rasterizer is entered once however many copies there are
6259            // (docs/canvas.md "Stamping"). A gradient resolves against the batch's own bounds,
6260            // which is what makes a stamped scatter shade across the group rather than repeating
6261            // the ramp inside every dot.
6262            DrawOp::Stamp(st) => {
6263                let batch = unsafe { objc2_app_kit::NSBezierPath::bezierPath() };
6264                for p in &st.at {
6265                    if let Some(copy) = bezier(&st.shape.translated(p.x, p.y)) {
6266                        unsafe { batch.appendBezierPath(&copy) };
6267                    }
6268                }
6269                let color = match &st.paint {
6270                    day_spec::Paint::Solid(c) => *c,
6271                    // A gradient over a stamped batch clips to the whole batch path; the solid
6272                    // fallback below keeps the marks visible on a backend path that cannot.
6273                    _ => day_spec::Color::WHITE,
6274                };
6275                match &st.stroke {
6276                    None => {
6277                        nscolor(color).setFill();
6278                        unsafe { batch.fill() };
6279                    }
6280                    Some(style) => {
6281                        nscolor(color).setStroke();
6282                        apply_stroke_style(&batch, style);
6283                        unsafe { batch.stroke() };
6284                    }
6285                }
6286            }
6287            DrawOp::Fill(shape, paint) => match paint {
6288                day_spec::Paint::Solid(color) => {
6289                    nscolor(*color).setFill();
6290                    if let Some(p) = bezier(shape) {
6291                        p.fill();
6292                    }
6293                }
6294                day_spec::Paint::Linear(g) => {
6295                    // Native linear gradient: clip to the shape's path, then NSGradient along
6296                    // the line resolved from the gradient's unit points in the shape's bounds.
6297                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
6298                        let b = shape.bounds();
6299                        let (s, e) = (g.start.resolve(b), g.end.resolve(b));
6300                        NSGraphicsContext::saveGraphicsState_class();
6301                        p.addClip();
6302                        grad.drawFromPoint_toPoint_options(
6303                            NSPoint::new(s.x, s.y),
6304                            NSPoint::new(e.x, e.y),
6305                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6306                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
6307                        );
6308                        NSGraphicsContext::restoreGraphicsState_class();
6309                    }
6310                }
6311                day_spec::Paint::Radial(g) => {
6312                    // Native radial gradient: clip to the path, map unit space onto the bounds
6313                    // (elliptical in non-square bounds), draw circular in unit coordinates.
6314                    if let (Some(p), Some(grad)) = (bezier(shape), nsgradient(&g.stops)) {
6315                        let b = shape.bounds();
6316                        NSGraphicsContext::saveGraphicsState_class();
6317                        p.addClip();
6318                        concat_unit_to_bounds(b);
6319                        let c = NSPoint::new(g.center.x, g.center.y);
6320                        grad.drawFromCenter_radius_toCenter_radius_options(
6321                            c,
6322                            0.0,
6323                            c,
6324                            g.radius,
6325                            objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6326                                | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation,
6327                        );
6328                        NSGraphicsContext::restoreGraphicsState_class();
6329                    }
6330                }
6331            },
6332            DrawOp::Stroke(shape, paint, style) => {
6333                if let Some(p) = bezier(shape) {
6334                    apply_stroke_style(&p, style);
6335                    match paint {
6336                        day_spec::Paint::Solid(color) => {
6337                            nscolor(*color).setStroke();
6338                            p.stroke();
6339                        }
6340                        // No gradient-stroke primitive here either: turn the stroke into the
6341                        // region it covers and draw the gradient through that clip.
6342                        // No gradient-stroke primitive: convert the stroke into the REGION it
6343                        // covers (CoreGraphics can, and NSGraphicsContext hands us its context),
6344                        // clip to that, then draw the gradient through it.
6345                        _ => {
6346                            let Some(ctx) = NSGraphicsContext::currentContext() else {
6347                                return;
6348                            };
6349                            let cg = ctx.CGContext();
6350                            NSGraphicsContext::saveGraphicsState_class();
6351                            objc2_core_graphics::CGContext::add_path(Some(&cg), Some(&p.CGPath()));
6352                            objc2_core_graphics::CGContext::replace_path_with_stroked_path(Some(
6353                                &cg,
6354                            ));
6355                            objc2_core_graphics::CGContext::clip(Some(&cg));
6356                            draw_gradient_in(paint, shape.bounds());
6357                            NSGraphicsContext::restoreGraphicsState_class();
6358                        }
6359                    }
6360                }
6361            }
6362            DrawOp::Clip(shape) => {
6363                // `addClip` intersects with the current clip and honors the path's winding rule.
6364                if let Some(p) = bezier(shape) {
6365                    p.addClip();
6366                }
6367            }
6368            DrawOp::Text {
6369                text,
6370                at,
6371                size,
6372                color,
6373                anchor,
6374                font,
6375            } => {
6376                let font = canvas_nsfont(*size, font);
6377                let attrs = canvas_text_attrs(&font, *color);
6378                let ns = NSString::from_str(text);
6379                let mut origin = NSPoint::new(at.x, at.y);
6380                // `drawAtPoint:` takes the top-leading corner of the line box, so any other
6381                // anchor is an offset from it. The size comes from the attributes the draw is
6382                // about to use, which is why the alignment belongs here and not in the app: the
6383                // caller would have to ask for these same metrics through `measure_text` first.
6384                if *anchor != day_spec::TextAnchor::LEADING {
6385                    let sz: NSSize = msg_send![&ns, sizeWithAttributes: &*attrs];
6386                    let (dx, dy) = anchor.offset(sz.width, sz.height, font.ascender());
6387                    origin.x += dx;
6388                    origin.y += dy;
6389                }
6390                let _: () = msg_send![&ns, drawAtPoint: origin, withAttributes: &*attrs];
6391            }
6392            // A released bitmap draws nothing rather than a placeholder: the canvas re-records
6393            // on every tracked read, so a handle can be dropped between the record and the
6394            // replay, and a frame that flashes a grey box is worse than one that omits the image.
6395            DrawOp::Image {
6396                image,
6397                rect,
6398                opacity,
6399                source,
6400            } => {
6401                let held = BITMAPS.with(|m| {
6402                    m.borrow()
6403                        .get(&image.0)
6404                        .map(|b| (b.image.clone(), b.info.pixels))
6405                });
6406                if let Some((img, pixels)) = held {
6407                    // A zero `fromRect` means the whole image. A region (`source`, in the
6408                    // bitmap's pixels) clamps to the bitmap with its mapping into `rect` kept,
6409                    // and an empty intersection draws nothing. `fromRect` is in the image's own
6410                    // space: its point size, origin at the BOTTOM-left the way NSImage counts,
6411                    // so the pixel region converts by the points-per-pixel ratio and flips.
6412                    let region = match source {
6413                        None => Some((NSRect::ZERO, *rect)),
6414                        Some(src) => {
6415                            day_spec::clamp_image_source(*src, *rect, pixels).map(|(src, dest)| {
6416                                let sz = img.size();
6417                                let (rx, ry) = (sz.width / pixels.width, sz.height / pixels.height);
6418                                let from = NSRect::new(
6419                                    NSPoint::new(
6420                                        src.origin.x * rx,
6421                                        (pixels.height - src.origin.y - src.size.height) * ry,
6422                                    ),
6423                                    NSSize::new(src.size.width * rx, src.size.height * ry),
6424                                );
6425                                (from, dest)
6426                            })
6427                        }
6428                    };
6429                    if let Some((from, dest)) = region {
6430                        let dest = NSRect::new(
6431                            NSPoint::new(dest.origin.x, dest.origin.y),
6432                            NSSize::new(dest.size.width, dest.size.height),
6433                        );
6434                        // DayCanvas is flipped (top-left origin). Respect that context so image
6435                        // rows stay upright, including under the canvas's rotation/zoom
6436                        // transforms. `fraction` multiplies the image's alpha.
6437                        img.drawInRect_fromRect_operation_fraction_respectFlipped_hints(
6438                            dest,
6439                            from,
6440                            objc2_app_kit::NSCompositingOperation::SourceOver,
6441                            *opacity,
6442                            true,
6443                            None,
6444                        );
6445                    }
6446                }
6447            }
6448            DrawOp::Save => NSGraphicsContext::saveGraphicsState_class(),
6449            DrawOp::Restore => NSGraphicsContext::restoreGraphicsState_class(),
6450            DrawOp::Concat(m) => {
6451                let t = NSAffineTransform::new();
6452                t.setTransformStruct(NSAffineTransformStruct {
6453                    m11: m.a,
6454                    m12: m.b,
6455                    m21: m.c,
6456                    m22: m.d,
6457                    tX: m.tx,
6458                    tY: m.ty,
6459                });
6460                t.concat();
6461            }
6462        }
6463    }
6464}
6465
6466/// An `NSGradient` from a display-list gradient's stops (sRGB, like every canvas color).
6467fn nsgradient(
6468    stops: &[(f64, day_spec::Color)],
6469) -> Option<objc2::rc::Retained<objc2_app_kit::NSGradient>> {
6470    if stops.is_empty() {
6471        return None;
6472    }
6473    let colors = objc2_foundation::NSArray::from_retained_slice(
6474        &stops.iter().map(|(_, c)| nscolor(*c)).collect::<Vec<_>>(),
6475    );
6476    let locations: Vec<f64> = stops.iter().map(|(o, _)| *o).collect();
6477    unsafe {
6478        objc2_app_kit::NSGradient::initWithColors_atLocations_colorSpace(
6479            objc2_app_kit::NSGradient::alloc(),
6480            &colors,
6481            locations.as_ptr(),
6482            &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
6483        )
6484    }
6485}
6486
6487/// Concat a bounds-mapping transform (unit gradient space → `b`) onto the current context, so a
6488/// circular gradient drawn in unit coordinates renders elliptically stretched to the bounds.
6489fn concat_unit_to_bounds(b: day_spec::Rect) {
6490    let t = NSAffineTransform::new();
6491    t.setTransformStruct(NSAffineTransformStruct {
6492        m11: b.size.width,
6493        m12: 0.0,
6494        m21: 0.0,
6495        m22: b.size.height,
6496        tX: b.origin.x,
6497        tY: b.origin.y,
6498    });
6499    unsafe { t.concat() };
6500}
6501
6502/// Put a [`day_spec::StrokeStyle`] onto a path.
6503///
6504/// NOTE: this backend used to force ROUND caps on every stroke. It now honors the style, whose
6505/// default is BUTT — the same default the spec and every other backend use. A line that wants
6506/// round ends asks for `StrokeStyle::round`.
6507fn apply_stroke_style(p: &objc2_app_kit::NSBezierPath, style: &day_spec::StrokeStyle) {
6508    use day_spec::{LineCap, LineJoin};
6509    unsafe {
6510        p.setLineWidth(style.width);
6511        p.setLineCapStyle(match style.cap {
6512            LineCap::Butt => objc2_app_kit::NSLineCapStyle::Butt,
6513            LineCap::Round => objc2_app_kit::NSLineCapStyle::Round,
6514            LineCap::Square => objc2_app_kit::NSLineCapStyle::Square,
6515        });
6516        if style.is_plain() {
6517            return;
6518        }
6519        p.setLineJoinStyle(match style.join {
6520            LineJoin::Miter => objc2_app_kit::NSLineJoinStyle::Miter,
6521            LineJoin::Round => objc2_app_kit::NSLineJoinStyle::Round,
6522            LineJoin::Bevel => objc2_app_kit::NSLineJoinStyle::Bevel,
6523        });
6524        p.setMiterLimit(style.miter_limit);
6525        if !style.dash.is_empty() {
6526            let pattern: Vec<objc2_core_foundation::CGFloat> = style.dash.to_vec();
6527            p.setLineDash_count_phase(pattern.as_ptr(), pattern.len() as isize, style.dash_phase);
6528        }
6529    }
6530}
6531
6532/// Draw a gradient through whatever clip is installed, in AppKit's own NSGradient terms.
6533/// Shared by the gradient FILL arms and the gradient STROKE arm, which differ only in what they
6534/// clipped to first.
6535fn draw_gradient_in(paint: &day_spec::Paint, bounds: day_spec::Rect) {
6536    let opts = objc2_app_kit::NSGradientDrawingOptions::DrawsBeforeStartingLocation
6537        | objc2_app_kit::NSGradientDrawingOptions::DrawsAfterEndingLocation;
6538    match paint {
6539        day_spec::Paint::Linear(g) => {
6540            if let Some(grad) = nsgradient(&g.stops) {
6541                let (s, e) = (g.start.resolve(bounds), g.end.resolve(bounds));
6542                unsafe {
6543                    grad.drawFromPoint_toPoint_options(
6544                        NSPoint::new(s.x, s.y),
6545                        NSPoint::new(e.x, e.y),
6546                        opts,
6547                    )
6548                };
6549            }
6550        }
6551        day_spec::Paint::Radial(g) => {
6552            if let Some(grad) = nsgradient(&g.stops) {
6553                NSGraphicsContext::saveGraphicsState_class();
6554                concat_unit_to_bounds(bounds);
6555                let c = NSPoint::new(g.center.x, g.center.y);
6556                unsafe {
6557                    grad.drawFromCenter_radius_toCenter_radius_options(c, 0.0, c, g.radius, opts)
6558                };
6559                NSGraphicsContext::restoreGraphicsState_class();
6560            }
6561        }
6562        day_spec::Paint::Solid(_) => {}
6563    }
6564}
6565
6566fn apply_button_content(
6567    btn: &NSButton,
6568    title: &str,
6569    icon: Option<&day_spec::Icon>,
6570    icon_only: bool,
6571) {
6572    let image = icon.and_then(|i| crate::toolbar::image_for(i, title, btn.mtm()));
6573    if let Some(image) = &image {
6574        let size = image.size();
6575        let longest = size.width.max(size.height);
6576        if longest > 0.0 {
6577            image.setSize(objc2_foundation::NSSize::new(
6578                size.width * 20.0 / longest,
6579                size.height * 20.0 / longest,
6580            ));
6581        }
6582    }
6583    let style = BUTTON_STYLES
6584        .with(|m| m.borrow().get(&ptr_of(btn)).copied())
6585        .unwrap_or_default();
6586    BUTTON_IMAGES.with(|images| {
6587        images.remove(ptr_of(btn));
6588        if let Some(image) = &image {
6589            images.insert(ptr_of(btn), image.clone());
6590        }
6591    });
6592    set_button_title(btn, title, style);
6593    // The position first: the image setter pads a glyph that sits beside a title, and leaves
6594    // an icon-only one alone, by reading it.
6595    unsafe {
6596        btn.setImagePosition(if image.is_none() {
6597            objc2_app_kit::NSCellImagePosition::NoImage
6598        } else if icon_only {
6599            objc2_app_kit::NSCellImagePosition::ImageOnly
6600        } else {
6601            objc2_app_kit::NSCellImagePosition::ImageLeading
6602        });
6603    }
6604    set_button_image(btn, style);
6605    unsafe {
6606        // The title is the spoken name (an icon-only button shows none), unless the app named
6607        // the button itself; overwriting that here replaced app labels on every title change.
6608        if !APP_LABELED.with(|t| t.contains(ptr_of(btn))) {
6609            btn.setAccessibilityLabel(Some(&NSString::from_str(title)));
6610        }
6611        let tooltip = (icon_only && image.is_some()).then(|| NSString::from_str(title));
6612        btn.setToolTip(tooltip.as_deref());
6613    }
6614}
6615
6616/// Bordered buttons do not reliably apply contentTintColor to template images. Keep
6617/// the native button, but supply an image that draws the original vector's alpha in
6618/// the requested contrast color at the destination resolution.
6619fn set_button_image(btn: &NSButton, style: day_spec::props::ButtonStyleSpec) {
6620    use day_spec::props::ButtonStyleSpec as S;
6621    let image = BUTTON_IMAGES.with(|images| images.with(ptr_of(btn), |image| image.clone()));
6622    let image = image.map(|source| {
6623        let S::Tinted(fill) = style else {
6624            return source;
6625        };
6626        let size = source.size();
6627        let ink = nscolor(S::on_tint(fill));
6628        let draw = block2::RcBlock::new(move |rect: NSRect| {
6629            source.drawInRect_fromRect_operation_fraction(
6630                rect,
6631                NSRect::ZERO,
6632                objc2_app_kit::NSCompositingOperation::SourceOver,
6633                1.0,
6634            );
6635            unsafe {
6636                ink.setFill();
6637                objc2_app_kit::NSRectFillUsingOperation(
6638                    rect,
6639                    objc2_app_kit::NSCompositingOperation::SourceIn,
6640                );
6641            }
6642            objc2::runtime::Bool::YES
6643        });
6644        objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(size, false, &draw)
6645    });
6646    unsafe {
6647        let position = btn.imagePosition();
6648        // Beside a title, the glyph gets a clear gap: AppKit draws a leading image flush
6649        // against the text, so the image carries the space itself (a template stays one, so
6650        // the label color still tints it). The cell centers the image in its slot, so half
6651        // the extra width lands on each side.
6652        let image = image.map(|source| {
6653            // The position is set after this on a fresh button, so an unset one counts as
6654            // "beside a title"; only an icon-only button keeps the glyph as drawn.
6655            if position == objc2_app_kit::NSCellImagePosition::ImageOnly {
6656                return source;
6657            }
6658            let size = source.size();
6659            let template = source.isTemplate();
6660            let padded = NSSize::new(size.width + 8.0, size.height);
6661            let draw = block2::RcBlock::new(move |_rect: NSRect| {
6662                source.drawInRect_fromRect_operation_fraction(
6663                    NSRect::new(NSPoint::new(0.0, 0.0), size),
6664                    NSRect::ZERO,
6665                    objc2_app_kit::NSCompositingOperation::SourceOver,
6666                    1.0,
6667                );
6668                objc2::runtime::Bool::YES
6669            });
6670            let out =
6671                objc2_app_kit::NSImage::imageWithSize_flipped_drawingHandler(padded, false, &draw);
6672            out.setTemplate(template);
6673            out
6674        });
6675        btn.setImage(image.as_deref());
6676        btn.setImagePosition(position);
6677        btn.setImageHugsTitle(true);
6678    }
6679}
6680
6681/// Put `ButtonProps::selected` on an `NSButton`, keeping it an NSButton. A momentary button
6682/// shows no state, so the first `true` makes it push-on/push-off, whose on state AppKit draws
6683/// as the bezel's highlighted fill and VoiceOver reads as selected; a button that never
6684/// selects keeps its momentary type. A click toggles the state natively before the action
6685/// runs, so the `action:` handler restores the value recorded here.
6686fn set_button_selected(btn: &objc2_app_kit::NSButton, on: bool) {
6687    BUTTON_SELECTED.with(|m| m.borrow_mut().insert(ptr_of(btn), on));
6688    unsafe {
6689        if on {
6690            btn.setButtonType(objc2_app_kit::NSButtonType::PushOnPushOff);
6691        }
6692        btn.setState(if on {
6693            NSControlStateValueOn
6694        } else {
6695            NSControlStateValueOff
6696        });
6697    }
6698}
6699
6700/// The corner radius of the tint painted behind a tinted button's bezel: the rounded push
6701/// bezel's own, so the fill reads as the bezel rather than as a box around it.
6702const TINT_CORNER_RADIUS: f64 = 6.0;
6703
6704/// Put a [`day_spec::props::ButtonStyleSpec`] on an `NSButton`, keeping it an NSButton.
6705///
6706/// Prominent = the return-key default button. Tinted = `bezelColor`, which AppKit composites
6707/// through the button's own bezel — so the pressed darkening, the focus ring and the disabled
6708/// look all still come from the control rather than from us painting a rectangle. macOS 26
6709/// composites the push bezel as a system material that ignores `bezelColor` on screen (an
6710/// offscreen `cacheDisplay` still honors it), so the tint is also painted on the control's
6711/// backing layer, where the translucent material lets it through; on older systems the opaque
6712/// tinted bezel covers that layer, so nothing changes there.
6713fn apply_button_style(btn: &objc2_app_kit::NSButton, style: day_spec::props::ButtonStyleSpec) {
6714    use day_spec::props::ButtonStyleSpec as S;
6715    let title = unsafe { btn.title() }.to_string();
6716    unsafe {
6717        // Reset first, so a patch from one style to another leaves nothing of the old one.
6718        btn.setKeyEquivalent(&NSString::from_str(""));
6719        btn.setBezelColor(None);
6720        btn.setBordered(!matches!(style, S::Plain));
6721        match style {
6722            S::Prominent => btn.setKeyEquivalent(&NSString::from_str("\r")),
6723            S::Tinted(c) => btn.setBezelColor(Some(&nscolor(c))),
6724            // Bordered is the stock NSButton look already; Automatic asks for nothing, and an
6725            // NSButton hugs a one-glyph title already, so Compact asks for nothing either.
6726            S::Bordered | S::Automatic | S::Compact | S::Plain => {}
6727        }
6728        btn.setWantsLayer(true);
6729        if let Some(layer) = btn.layer() {
6730            match style {
6731                S::Tinted(c) => {
6732                    layer.setBackgroundColor(Some(&nscolor(c).CGColor()));
6733                    layer.setCornerRadius(TINT_CORNER_RADIUS);
6734                }
6735                _ => layer.setBackgroundColor(None),
6736            }
6737        }
6738    }
6739    BUTTON_STYLES.with(|m| m.borrow_mut().insert(ptr_of(btn), style));
6740    let ink = match style {
6741        S::Tinted(c) => Some(nscolor(S::on_tint(c))),
6742        _ => None,
6743    };
6744    unsafe {
6745        btn.setContentTintColor(ink.as_deref());
6746    }
6747    set_button_title(btn, &title, style);
6748    set_button_image(btn, style);
6749}
6750
6751/// Set a button's title, coloring it for the tint where there is one.
6752///
6753/// `contentTintColor` is NOT the seam for this: on a bordered `NSButton`,
6754/// AppKit keeps drawing the title in its own control text color — which is how a
6755/// white-on-rust button came out black-on-rust. An ATTRIBUTED title is the documented way to
6756/// control the text color, so that is what a tinted button gets.
6757///
6758/// The button's own font is carried into the attributes: an attributed title supplies the whole
6759/// run, so leaving the font out would drop the control font and render at the system default.
6760fn set_button_title(
6761    btn: &objc2_app_kit::NSButton,
6762    title: &str,
6763    style: day_spec::props::ButtonStyleSpec,
6764) {
6765    use day_spec::props::ButtonStyleSpec as S;
6766    // Changing an attributed title can reset NSButton's image placement. A reactive
6767    // tint must keep an icon-only button icon-only, including its native template tint.
6768    let position = unsafe { btn.imagePosition() };
6769    let S::Tinted(fill) = style else {
6770        // Plain title: AppKit picks the label color that suits the bezel it is drawing.
6771        unsafe {
6772            btn.setTitle(&NSString::from_str(title));
6773            btn.setImagePosition(position);
6774        }
6775        return;
6776    };
6777    unsafe {
6778        let col = nscolor(S::on_tint(fill));
6779        let font = btn
6780            .font()
6781            .unwrap_or_else(|| NSFont::systemFontOfSize(NSFont::systemFontSize()));
6782        // Centered, matching a plain NSButton title: an attributed title carries its own
6783        // paragraph style, and the default is left-aligned.
6784        let para = objc2_app_kit::NSMutableParagraphStyle::new();
6785        para.setAlignment(objc2_app_kit::NSTextAlignment::Center);
6786        let keys: [&NSString; 3] = [
6787            objc2_app_kit::NSFontAttributeName,
6788            objc2_app_kit::NSForegroundColorAttributeName,
6789            objc2_app_kit::NSParagraphStyleAttributeName,
6790        ];
6791        let objs: [&objc2::runtime::AnyObject; 3] = [
6792            font.as_ref() as &objc2::runtime::AnyObject,
6793            col.as_ref() as &objc2::runtime::AnyObject,
6794            para.as_ref() as &objc2::runtime::AnyObject,
6795        ];
6796        let attrs = objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs);
6797        let s = objc2_foundation::NSAttributedString::initWithString_attributes(
6798            objc2_foundation::NSAttributedString::alloc(),
6799            &NSString::from_str(title),
6800            Some(&attrs),
6801        );
6802        btn.setAttributedTitle(&s);
6803        btn.setImagePosition(position);
6804    }
6805}
6806
6807// NSImageView supports aspect-fit but not aspect-fill. Expand its native drawing about
6808// the center and clip to the view; this retains vector rendering and template tinting.
6809define_class!(
6810    #[unsafe(super(objc2_app_kit::NSImageView))]
6811    #[thread_kind = MainThreadOnly]
6812    #[name = "DayFillImageView"]
6813    struct FillImageView;
6814
6815    impl FillImageView {
6816        #[unsafe(method(drawRect:))]
6817        fn draw_rect(&self, dirty: NSRect) {
6818            let bounds = self.bounds();
6819            let image = unsafe { self.image() };
6820            let Some(size) = image.map(|image| image.size()).filter(|size| {
6821                size.width > 0.0 && size.height > 0.0
6822                    && bounds.size.width > 0.0 && bounds.size.height > 0.0
6823            }) else {
6824                let _: () = unsafe { msg_send![super(self), drawRect: dirty] };
6825                return;
6826            };
6827            let x = bounds.size.width / size.width;
6828            let y = bounds.size.height / size.height;
6829            let scale = x.max(y) / x.min(y);
6830            let cx = bounds.origin.x + bounds.size.width / 2.0;
6831            let cy = bounds.origin.y + bounds.size.height / 2.0;
6832            NSGraphicsContext::saveGraphicsState_class();
6833            objc2_app_kit::NSBezierPath::bezierPathWithRect(bounds).addClip();
6834            let transform = NSAffineTransform::transform();
6835            transform.translateXBy_yBy(cx, cy);
6836            transform.scaleBy(scale);
6837            transform.translateXBy_yBy(-cx, -cy);
6838            transform.concat();
6839            let _: () = unsafe { msg_send![super(self), drawRect: bounds] };
6840            NSGraphicsContext::restoreGraphicsState_class();
6841        }
6842
6843        #[unsafe(method(setFrameSize:))]
6844        fn set_frame_size(&self, size: NSSize) {
6845            let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
6846            NSView::setNeedsDisplay(self, true);
6847        }
6848    }
6849);
6850
6851fn bezier(shape: &day_spec::Shape) -> Option<objc2::rc::Retained<objc2_app_kit::NSBezierPath>> {
6852    use day_spec::Shape;
6853    use objc2_app_kit::NSBezierPath;
6854    unsafe {
6855        Some(match shape {
6856            Shape::Rect(r) => NSBezierPath::bezierPathWithRect(ns_rect(*r)),
6857            Shape::RoundedRect(r, rad) => {
6858                NSBezierPath::bezierPathWithRoundedRect_xRadius_yRadius(ns_rect(*r), *rad, *rad)
6859            }
6860            Shape::Ellipse(r) => NSBezierPath::bezierPathWithOvalInRect(ns_rect(*r)),
6861            Shape::Arc {
6862                rect,
6863                start_deg,
6864                sweep_deg,
6865            } => {
6866                let p = NSBezierPath::new();
6867                let center = NSPoint::new(
6868                    rect.origin.x + rect.size.width / 2.0,
6869                    rect.origin.y + rect.size.height / 2.0,
6870                );
6871                let radius = rect.size.width.min(rect.size.height) / 2.0;
6872                // Flipped view: increasing angle is visually clockwise, matching the spec.
6873                p.appendBezierPathWithArcWithCenter_radius_startAngle_endAngle(
6874                    center,
6875                    radius,
6876                    *start_deg,
6877                    *start_deg + *sweep_deg,
6878                );
6879                p
6880            }
6881            Shape::Line(a, b) => {
6882                let p = NSBezierPath::new();
6883                p.moveToPoint(NSPoint::new(a.x, a.y));
6884                p.lineToPoint(NSPoint::new(b.x, b.y));
6885                p
6886            }
6887            Shape::Polygon(pts) => {
6888                if pts.len() < 2 {
6889                    return None;
6890                }
6891                let p = NSBezierPath::new();
6892                p.moveToPoint(NSPoint::new(pts[0].x, pts[0].y));
6893                for pt in &pts[1..] {
6894                    p.lineToPoint(NSPoint::new(pt.x, pt.y));
6895                }
6896                p.closePath();
6897                p
6898            }
6899            Shape::Path(path) => {
6900                use day_spec::PathSeg;
6901                if path.segs.is_empty() {
6902                    return None;
6903                }
6904                let p = NSBezierPath::new();
6905                // NSBezierPath's own quadratic API is macOS 14+, so quads are ELEVATED to
6906                // cubics with the standard formula (c1 = p0 + 2/3(c - p0), c2 = p1 + 2/3(c -
6907                // p1)), which is exact rather than an approximation.
6908                let mut cur = NSPoint::new(0.0, 0.0);
6909                for seg in &path.segs {
6910                    match seg {
6911                        PathSeg::Move(a) => {
6912                            cur = NSPoint::new(a.x, a.y);
6913                            p.moveToPoint(cur);
6914                        }
6915                        PathSeg::Line(a) => {
6916                            cur = NSPoint::new(a.x, a.y);
6917                            p.lineToPoint(cur);
6918                        }
6919                        PathSeg::Quad(c, a) => {
6920                            let (end, ctl) = (NSPoint::new(a.x, a.y), NSPoint::new(c.x, c.y));
6921                            let c1 = NSPoint::new(
6922                                cur.x + 2.0 / 3.0 * (ctl.x - cur.x),
6923                                cur.y + 2.0 / 3.0 * (ctl.y - cur.y),
6924                            );
6925                            let c2 = NSPoint::new(
6926                                end.x + 2.0 / 3.0 * (ctl.x - end.x),
6927                                end.y + 2.0 / 3.0 * (ctl.y - end.y),
6928                            );
6929                            p.curveToPoint_controlPoint1_controlPoint2(end, c1, c2);
6930                            cur = end;
6931                        }
6932                        PathSeg::Cubic(c1, c2, a) => {
6933                            cur = NSPoint::new(a.x, a.y);
6934                            p.curveToPoint_controlPoint1_controlPoint2(
6935                                cur,
6936                                NSPoint::new(c1.x, c1.y),
6937                                NSPoint::new(c2.x, c2.y),
6938                            );
6939                        }
6940                        PathSeg::Close => p.closePath(),
6941                    }
6942                }
6943                p.setWindingRule(match path.rule {
6944                    day_spec::FillRule::NonZero => objc2_app_kit::NSWindingRule::NonZero,
6945                    day_spec::FillRule::EvenOdd => objc2_app_kit::NSWindingRule::EvenOdd,
6946                });
6947                p
6948            }
6949        })
6950    }
6951}
6952
6953// ---------------------------------------------------------------------------
6954// DayUndoManager — the native FRONT of the app's one undo stack (docs/model.md)
6955// ---------------------------------------------------------------------------
6956
6957/// The mirrored [`day_spec::UndoState`]: what the stock Edit menu reads through the standard
6958/// `undo:`/`redo:` validation. The stack itself lives in day-model; this object only answers
6959/// questions and forwards invocations — two histories can never fork.
6960struct UndoIvars {
6961    state: std::cell::RefCell<day_spec::UndoState>,
6962}
6963
6964define_class!(
6965    #[unsafe(super(objc2_foundation::NSUndoManager))]
6966    #[thread_kind = MainThreadOnly]
6967    #[name = "DayUndoManager"]
6968    #[ivars = UndoIvars]
6969    struct DayUndoManager;
6970
6971    /// Overrides of the questions AppKit's menu validation asks, answered from the mirrored
6972    /// state — and of the two verbs, forwarded as `Event::Undo` (enqueue-only, like every
6973    /// other event). Registration/grouping machinery of the superclass is never used.
6974    impl DayUndoManager {
6975        #[unsafe(method(canUndo))]
6976        fn can_undo(&self) -> bool {
6977            self.ivars().state.borrow().can_undo
6978        }
6979
6980        #[unsafe(method(canRedo))]
6981        fn can_redo(&self) -> bool {
6982            self.ivars().state.borrow().can_redo
6983        }
6984
6985        #[unsafe(method(undo))]
6986        fn do_undo(&self) {
6987            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: false }))
6988        }
6989
6990        #[unsafe(method(redo))]
6991        fn do_redo(&self) {
6992            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Undo { redo: true }))
6993        }
6994
6995        #[unsafe(method_id(undoMenuItemTitle))]
6996        fn undo_menu_item_title(&self) -> Retained<NSString> {
6997            // Route through the superclass's own title former, so "Undo" itself comes out in
6998            // the system language; the action label arrived already localized from the app.
6999            let label = self.ivars().state.borrow().undo_label.clone();
7000            unsafe { self.undoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
7001        }
7002
7003        #[unsafe(method_id(redoMenuItemTitle))]
7004        fn redo_menu_item_title(&self) -> Retained<NSString> {
7005            let label = self.ivars().state.borrow().redo_label.clone();
7006            unsafe { self.redoMenuTitleForUndoActionName(&NSString::from_str(&label)) }
7007        }
7008    }
7009);
7010
7011fn undo_front(mtm: MainThreadMarker) -> Retained<DayUndoManager> {
7012    UNDO_FRONT.with(|u| {
7013        u.borrow_mut()
7014            .get_or_insert_with(|| {
7015                let this = DayUndoManager::alloc(mtm).set_ivars(UndoIvars {
7016                    state: std::cell::RefCell::new(day_spec::UndoState::default()),
7017                });
7018                unsafe { msg_send![super(this), init] }
7019            })
7020            .clone()
7021    })
7022}
7023
7024// ---------------------------------------------------------------------------
7025// DayWinDelegate — resize + close + key tracking, per window
7026// ---------------------------------------------------------------------------
7027
7028/// `node`: the day window-root id this delegate's window reports to. `None` = the PRIMARY
7029/// window — resize goes to `WINDOW_NODE` and close terminates the app; a secondary window
7030/// (docs/windows.md) reports to its own root and close tears down just that window.
7031struct WinIvars {
7032    node: Option<NodeId>,
7033    /// The tab group this window was opened in (`WindowTabbing::Group`/`Preferred`): the
7034    /// tab bar's "+" opens another window of the same group.
7035    group: Option<String>,
7036    /// The last display state reported (`WindowState::code`), so a resize that does not change
7037    /// the zoom state reports nothing.
7038    last_state: Cell<i32>,
7039}
7040
7041define_class!(
7042    #[unsafe(super(NSObject))]
7043    #[thread_kind = MainThreadOnly]
7044    #[name = "DayWinDelegate"]
7045    #[ivars = WinIvars]
7046    struct DayWinDelegate;
7047
7048    unsafe impl NSObjectProtocol for DayWinDelegate {}
7049
7050    /// The responder chain's last stop for the standard edit nav hosts: a focused text view
7051    /// answered `cut:`/`copy:`/`paste:` long before the window asked its delegate, so what
7052    /// arrives here is the app's to handle — the same precedence the undo manager route uses.
7053    impl DayWinDelegate {
7054        /// Edit ▸ Undo. The stock item's nil-target `undo:` finds no implementor among Day's
7055        /// plain views, so the delegate is where the chain lands — resolving through the
7056        /// acting manager keeps a focused field's typing undo ahead of the document stack.
7057        #[unsafe(method(undo:))]
7058        fn edit_undo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7059            ffi_guard::contain((), || {
7060                if let Some(m) = self.acting_undo_manager() {
7061                    unsafe { m.undo() };
7062                }
7063            });
7064        }
7065
7066        /// Edit ▸ Redo.
7067        #[unsafe(method(redo:))]
7068        fn edit_redo(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7069            ffi_guard::contain((), || {
7070                if let Some(m) = self.acting_undo_manager() {
7071                    unsafe { m.redo() };
7072                }
7073            });
7074        }
7075
7076        #[unsafe(method(cut:))]
7077        fn edit_cut(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7078            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Cut)));
7079        }
7080
7081        #[unsafe(method(copy:))]
7082        fn edit_copy(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7083            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Copy)));
7084        }
7085
7086        #[unsafe(method(paste:))]
7087        fn edit_paste(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7088            ffi_guard::contain((), || emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::Paste)));
7089        }
7090
7091        #[unsafe(method(selectAll:))]
7092        fn edit_select_all(&self, _sender: Option<&objc2::runtime::AnyObject>) {
7093            ffi_guard::contain((), || {
7094                emit(WINDOW_NODE, Event::Edit(day_spec::EditOp::SelectAll));
7095            });
7096        }
7097
7098        /// AppKit's menu validation, the same machinery that greys Edit items for text views:
7099        /// the bridge state answers for cut/copy, and paste additionally requires the
7100        /// pasteboard to actually hold text.
7101        #[unsafe(method(validateMenuItem:))]
7102        fn validate_menu_item(&self, item: &NSMenuItem) -> bool {
7103            ffi_guard::contain(false, || {
7104                let state = EDIT_STATE.with(|s| s.get());
7105                match unsafe { item.action() } {
7106                    // The undo pair enables from the acting manager and takes its titles
7107                    // ("Undo Move Shape"), exactly as AppKit's own windows do.
7108                    Some(a) if a == sel!(undo:) => match self.acting_undo_manager() {
7109                        Some(m) => {
7110                            item.setTitle(unsafe { m.undoMenuItemTitle() }.as_ref());
7111                            unsafe { m.canUndo() }
7112                        }
7113                        None => false,
7114                    },
7115                    Some(a) if a == sel!(redo:) => match self.acting_undo_manager() {
7116                        Some(m) => {
7117                            item.setTitle(unsafe { m.redoMenuItemTitle() }.as_ref());
7118                            unsafe { m.canRedo() }
7119                        }
7120                        None => false,
7121                    },
7122                    Some(a) if a == sel!(selectAll:) => state.can_select_all,
7123                    Some(a) if a == sel!(cut:) => state.can_cut,
7124                    Some(a) if a == sel!(copy:) => state.can_copy,
7125                    Some(a) if a == sel!(paste:) => {
7126                        state.can_paste && {
7127                            let pb = unsafe { NSPasteboard::generalPasteboard() };
7128                            pb.types().is_some_and(|types| !types.is_empty())
7129                        }
7130                    }
7131                    _ => true,
7132                }
7133            })
7134        }
7135    }
7136
7137    unsafe impl NSWindowDelegate for DayWinDelegate {
7138        #[unsafe(method(windowDidResize:))]
7139        fn window_did_resize(&self, notification: &NSNotification) {
7140            ffi_guard::contain((), || {
7141                if let Some(obj) = unsafe { notification.object() }
7142                    && let Ok(win) = obj.downcast::<NSWindow>()
7143                    && let Some(size) = pin_below_title_bar(&win)
7144                {
7145                    let target = self.ivars().node.unwrap_or(WINDOW_NODE);
7146                    emit(target, Event::WindowResized(size));
7147                }
7148                // Zooming is a resize with no notification of its own.
7149                self.report_state_of(notification);
7150            })
7151        }
7152
7153        #[unsafe(method(windowShouldClose:))]
7154        fn window_should_close(&self, _window: &NSWindow) -> bool {
7155            ffi_guard::contain(false, || day_core::windows::native_close_requested(self.ivars().node.unwrap_or(WINDOW_NODE)))
7156        }
7157
7158        #[unsafe(method(windowWillClose:))]
7159        fn window_will_close(&self, _notification: &NSNotification) {
7160            ffi_guard::contain((), || {
7161                match self.ivars().node {
7162                    // Secondary window: confirm the close to day-core, which tears the
7163                    // subtree down on a DEFERRED hop (never inside this AppKit close frame).
7164                    Some(node) => emit(node, Event::WindowClosed),
7165                    // Primary window: closing it quits, taking secondaries with it
7166                    // (docs/windows.md close policy), unless the app keeps running without a
7167                    // window (a status item, `KeepRunning::Always`): then it closes like any
7168                    // other window and day-core decides.
7169                    None if status_item::keeps_running() => emit(WINDOW_NODE, Event::WindowClosed),
7170                    None => {
7171                        let app = NSApplication::sharedApplication(self.mtm());
7172                        unsafe { app.terminate(None) };
7173                    }
7174                }
7175            })
7176        }
7177
7178        #[unsafe(method_id(windowWillReturnUndoManager:))]
7179        fn window_will_return_undo_manager(
7180            &self,
7181            _window: &NSWindow,
7182        ) -> Option<Retained<objc2_foundation::NSUndoManager>> {
7183            // The responder chain already gave a focused text field its OWN manager before
7184            // asking the window — typing undo stays the field's, the model stack gets the
7185            // rest, exactly the precedence the plan's typing rule wants.
7186            ffi_guard::contain(None, || {
7187                UNDO_FRONT.with(|u| {
7188                    u.borrow()
7189                        .as_ref()
7190                        .map(|m| Retained::into_super(m.clone()))
7191                })
7192            })
7193        }
7194
7195        #[unsafe(method(windowDidBecomeKey:))]
7196        fn window_did_become_key(&self, _notification: &NSNotification) {
7197            ffi_guard::contain((), || {
7198                if let Some(node) = self.ivars().node {
7199                    emit(node, Event::WindowFocused(true));
7200                }
7201            })
7202        }
7203
7204        #[unsafe(method(windowDidResignKey:))]
7205        fn window_did_resign_key(&self, _notification: &NSNotification) {
7206            ffi_guard::contain((), || {
7207                if let Some(node) = self.ivars().node {
7208                    emit(node, Event::WindowFocused(false));
7209                }
7210            })
7211        }
7212
7213        #[unsafe(method(windowDidMiniaturize:))]
7214        fn window_did_miniaturize(&self, notification: &NSNotification) {
7215            ffi_guard::contain((), || self.report_state_of(notification))
7216        }
7217
7218        #[unsafe(method(windowDidDeminiaturize:))]
7219        fn window_did_deminiaturize(&self, notification: &NSNotification) {
7220            ffi_guard::contain((), || self.report_state_of(notification))
7221        }
7222
7223        #[unsafe(method(windowDidEnterFullScreen:))]
7224        fn window_did_enter_full_screen(&self, notification: &NSNotification) {
7225            ffi_guard::contain((), || self.report_state_of(notification))
7226        }
7227
7228        #[unsafe(method(windowDidExitFullScreen:))]
7229        fn window_did_exit_full_screen(&self, notification: &NSNotification) {
7230            ffi_guard::contain((), || self.report_state_of(notification))
7231        }
7232    }
7233
7234    // The tab bar's "+" button walks the responder chain (window → delegate) for
7235    // `newWindowForTab:` — present only when the app registered a new-window builder
7236    // (otherwise automatic tabbing is off and no "+" exists).
7237    impl DayWinDelegate {
7238        #[unsafe(method(newWindowForTab:))]
7239        fn new_window_for_tab(&self, _sender: Option<&NSObject>) {
7240            ffi_guard::contain((), || {
7241                // A window in a tab group of its own gets another window of that group
7242                // (`register_new_window_for`); everything else gets File ▸ New Window's.
7243                let _ = match self.ivars().group.as_deref() {
7244                    Some(group) => day_core::windows::open_new_window_for_group(group),
7245                    None => day_core::windows::open_new_window(),
7246                };
7247            })
7248        }
7249    }
7250);
7251
7252impl DayWinDelegate {
7253    fn report_state_of(&self, notification: &NSNotification) {
7254        if let Some(obj) = unsafe { notification.object() }
7255            && let Ok(win) = obj.downcast::<NSWindow>()
7256        {
7257            self.report_state(&win);
7258        }
7259    }
7260}
7261
7262/// The day name for a key press, or `None` for every key the route does not carry — the
7263/// [`day_spec::KeyEvent`] names (docs/menus.md).
7264fn key_name(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
7265    match unsafe { event.keyCode() } {
7266        123 => Some("ArrowLeft"),
7267        124 => Some("ArrowRight"),
7268        125 => Some("ArrowDown"),
7269        126 => Some("ArrowUp"),
7270        // Not the delete keys. This backend draws a menu bar, so a Delete accelerator on a
7271        // menu item owns them (docs/menus.md) — and a focused piece that CLAIMS a key stops
7272        // that accelerator from ever seeing it, which is how a canvas ends up swallowing the
7273        // Delete its own Edit menu was going to act on.
7274        //
7275        // A digit, main row or keypad, named by what it types. Never under ⌘, ⌥ or ⌃: those
7276        // combinations are accelerators, and claiming one would starve the menu the same way.
7277        _ => {
7278            let held = NSEventModifierFlags::Command
7279                | NSEventModifierFlags::Option
7280                | NSEventModifierFlags::Control;
7281            if event.modifierFlags().intersects(held) {
7282                return None;
7283            }
7284            let typed = event.characters()?.to_string();
7285            let mut chars = typed.chars();
7286            match (chars.next(), chars.next()) {
7287                (Some(c), None) => day_spec::KeyEvent::digit_name(c),
7288                _ => None,
7289            }
7290        }
7291    }
7292}
7293
7294/// The web name for a key that types nothing, by its virtual key code, or `None` for a key
7295/// that types (docs/menus.md "The full route").
7296fn named_key(event: &objc2_app_kit::NSEvent) -> Option<&'static str> {
7297    Some(match unsafe { event.keyCode() } {
7298        123 => "ArrowLeft",
7299        124 => "ArrowRight",
7300        125 => "ArrowDown",
7301        126 => "ArrowUp",
7302        36 | 76 => "Enter",
7303        48 => "Tab",
7304        53 => "Escape",
7305        51 => "Backspace",
7306        117 => "Delete",
7307        115 => "Home",
7308        119 => "End",
7309        116 => "PageUp",
7310        121 => "PageDown",
7311        114 => "Insert",
7312        122 => "F1",
7313        120 => "F2",
7314        99 => "F3",
7315        118 => "F4",
7316        96 => "F5",
7317        97 => "F6",
7318        98 => "F7",
7319        100 => "F8",
7320        101 => "F9",
7321        109 => "F10",
7322        103 => "F11",
7323        111 => "F12",
7324        _ => return None,
7325    })
7326}
7327
7328/// A key press on the full route (`Decorate::keyboard`, docs/menus.md "The full route"), for
7329/// a canvas that took the whole keyboard. Answers whether the press was claimed.
7330///
7331/// The order is the policy: a ⌘ chord is the menu's and goes back to AppKit first, whatever
7332/// the key; a composition in progress owns every key until the input method commits or
7333/// cancels it; a key that types nothing is named; a ⌃ chord names its key and types nothing;
7334/// everything else is handed to the text input system, which turns a dead key into marked
7335/// text, an input method's keys into a composition, and a plain or ⌥ key into `insertText:`
7336/// with what it typed (⌥ types on a Mac: ⌥8 is "{" on a German layout; the piece still sees
7337/// [`day_spec::KeyEvent::ALT`] and decides).
7338fn full_route_key_down(view: &DayCanvas, node: NodeId, event: &objc2_app_kit::NSEvent) -> bool {
7339    let ptr = (view as *const DayCanvas).cast::<NSView>() as usize;
7340    let flags = event.modifierFlags();
7341    let mods = key_modifiers(flags);
7342    if flags.contains(NSEventModifierFlags::Command) {
7343        return false;
7344    }
7345    let composing = MARKED.with(|t| t.contains(ptr));
7346    if !composing && let Some(named) = named_key(event) {
7347        emit(node, Event::Key(day_spec::KeyEvent::named(named, mods)));
7348        return true;
7349    }
7350    let unmodified = unsafe { event.charactersIgnoringModifiers() }
7351        .map(|s| s.to_string())
7352        .unwrap_or_default();
7353    // A function or editing key the vocabulary lacks types a private-use glyph.
7354    let typeable = !unmodified.is_empty()
7355        && !unmodified
7356            .chars()
7357            .any(|c| c.is_control() || ('\u{f700}'..='\u{f8ff}').contains(&c));
7358    if !composing && flags.contains(NSEventModifierFlags::Control) {
7359        if typeable {
7360            emit(
7361                node,
7362                Event::Key(day_spec::KeyEvent::named(unmodified, mods)),
7363            );
7364        }
7365        return true;
7366    }
7367    if !composing && !typeable {
7368        return true;
7369    }
7370    INTERPRETING.with(|i| *i.borrow_mut() = Some((unmodified, mods)));
7371    view.interpretKeyEvents(&NSArray::from_slice(&[event]));
7372    INTERPRETING.with(|i| *i.borrow_mut() = None);
7373    true
7374}
7375
7376/// The text of an `NSString` or `NSAttributedString` the text input system hands over.
7377fn text_of_input_string(string: &AnyObject) -> String {
7378    if let Some(s) = string.downcast_ref::<NSString>() {
7379        s.to_string()
7380    } else if let Some(s) = string.downcast_ref::<objc2_foundation::NSAttributedString>() {
7381        s.string().to_string()
7382    } else {
7383        String::new()
7384    }
7385}
7386
7387/// AppKit's modifier flags as day's mask.
7388fn key_modifiers(f: NSEventModifierFlags) -> u8 {
7389    let mut modifiers = 0u8;
7390    if f.contains(NSEventModifierFlags::Shift) {
7391        modifiers |= day_spec::KeyEvent::SHIFT;
7392    }
7393    if f.contains(NSEventModifierFlags::Command) {
7394        modifiers |= day_spec::KeyEvent::PRIMARY;
7395    }
7396    if f.contains(NSEventModifierFlags::Option) {
7397        modifiers |= day_spec::KeyEvent::ALT;
7398    }
7399    if f.contains(NSEventModifierFlags::Control) {
7400        modifiers |= day_spec::KeyEvent::CONTROL;
7401    }
7402    modifiers
7403}
7404
7405impl DayWinDelegate {
7406    /// The manager AppKit's own undo mechanics act on: ask the FIRST RESPONDER, whose
7407    /// `undoManager` walks the chain itself — a field editor answers with its typing
7408    /// history, everything else falls through to `windowWillReturnUndoManager` and lands on
7409    /// the app's front. Falls back to the front when no window is key yet.
7410    fn acting_undo_manager(&self) -> Option<Retained<objc2_foundation::NSUndoManager>> {
7411        let responder = NSApplication::sharedApplication(self.mtm())
7412            .keyWindow()
7413            .and_then(|w| w.firstResponder());
7414        responder
7415            .and_then(|r| unsafe { r.undoManager() })
7416            .or_else(|| {
7417                UNDO_FRONT.with(|u| u.borrow().as_ref().map(|m| Retained::into_super(m.clone())))
7418            })
7419    }
7420}
7421
7422impl DayWinDelegate {
7423    fn new(mtm: MainThreadMarker, node: Option<NodeId>, group: Option<String>) -> Retained<Self> {
7424        let this = Self::alloc(mtm).set_ivars(WinIvars {
7425            node,
7426            group,
7427            last_state: Cell::new(day_spec::WindowState::Normal.code()),
7428        });
7429        unsafe { msg_send![super(this), init] }
7430    }
7431
7432    /// Report the window's display state if it changed since the last report
7433    /// (docs/windows.md "Window properties"): to the window's root node, or `WINDOW_NODE` for the
7434    /// primary, the same routing as `WindowResized`.
7435    fn report_state(&self, window: &NSWindow) {
7436        let state = ns_window_state(window);
7437        if self.ivars().last_state.replace(state.code()) != state.code() {
7438            log::debug!("appkit: window state now {state:?}");
7439            let target = self.ivars().node.unwrap_or(WINDOW_NODE);
7440            emit(target, Event::WindowStateChanged(state));
7441        }
7442    }
7443}
7444
7445/// What AppKit says a window is showing as: miniaturized wins (a fullscreen window can be
7446/// neither), then fullscreen (whose frame also reads as zoomed), then zoomed.
7447fn ns_window_state(window: &NSWindow) -> day_spec::WindowState {
7448    if window.isMiniaturized() {
7449        day_spec::WindowState::Minimized
7450    } else if window
7451        .styleMask()
7452        .contains(objc2_app_kit::NSWindowStyleMask::FullScreen)
7453    {
7454        day_spec::WindowState::Fullscreen
7455    } else if window.isZoomed() {
7456        day_spec::WindowState::Maximized
7457    } else {
7458        day_spec::WindowState::Normal
7459    }
7460}
7461
7462/// Ask AppKit for `state`, undoing whatever the window is in first: fullscreen and miniaturized
7463/// have to be left before a window can zoom, and each is its own toggle.
7464fn set_ns_window_state(window: &NSWindow, state: day_spec::WindowState) {
7465    use day_spec::WindowState as S;
7466    let current = ns_window_state(window);
7467    if current == state {
7468        return;
7469    }
7470    unsafe {
7471        match current {
7472            S::Minimized => window.deminiaturize(None),
7473            // Leaving fullscreen animates; asking for another state in the same turn would be
7474            // dropped by AppKit mid-transition, so the request stops at leaving it. The state
7475            // signal reads back `Normal`, and a second request takes it from there.
7476            S::Fullscreen => {
7477                window.toggleFullScreen(None);
7478                return;
7479            }
7480            S::Maximized if state != S::Minimized => window.zoom(None),
7481            _ => {}
7482        }
7483        match state {
7484            S::Normal => {}
7485            S::Minimized => window.miniaturize(None),
7486            S::Maximized => {
7487                if !window.isZoomed() {
7488                    window.zoom(None)
7489                }
7490            }
7491            S::Fullscreen => window.toggleFullScreen(None),
7492        }
7493    }
7494}
7495
7496// ---------------------------------------------------------------------------
7497// The backend
7498// ---------------------------------------------------------------------------
7499
7500/// Renderers registered by external Day Piece crates (§8.2 layer 3 — linkme convenience).
7501#[distributed_slice]
7502pub static RENDERERS: [fn() -> Renderer<AppKit>];
7503
7504/// A live secondary window (docs/windows.md). The delegate is RETAINED here —
7505/// `setDelegate:` holds it weakly, and unlike the primary's (kept alive because `run`
7506/// never returns) a secondary's delegate would die at the end of `open_window` otherwise.
7507struct SecondaryWin {
7508    window: Retained<NSWindow>,
7509    #[allow(dead_code)] // held for lifetime only; AppKit talks to it via the weak delegate ref
7510    delegate: Retained<DayWinDelegate>,
7511    content: Handle,
7512}
7513
7514/// Deliver an explicitly registered Escape accelerator before a field editor swallows it.
7515/// The monitor is local to this process and removed with the backend.
7516struct MenuEscapeMonitor(Retained<objc2::runtime::AnyObject>);
7517impl Drop for MenuEscapeMonitor {
7518    fn drop(&mut self) {
7519        unsafe { NSEvent::removeMonitor(&self.0) };
7520    }
7521}
7522
7523pub struct AppKit {
7524    menu_escape_monitor: Option<MenuEscapeMonitor>,
7525    sharing: Option<objc2::rc::Retained<objc2::runtime::AnyObject>>,
7526    /// The picker's delegate, which the picker holds only weakly.
7527    sharing_delegate: Option<Retained<DaySharePickerDelegate>>,
7528
7529    mtm: MainThreadMarker,
7530    registry: Registry<AppKit>,
7531    window: Option<Retained<NSWindow>>,
7532    content: Option<Handle>,
7533    secondary: Vec<SecondaryWin>,
7534    app_name: String,
7535    /// Where the next secondary window's top-left goes (docs/windows.md). macOS staggers new
7536    /// windows rather than stacking them: `cascadeTopLeftFromPoint:` places the window and
7537    /// answers the point after it, so threading that answer through here is the whole
7538    /// mechanism. `None` until the primary exists — the cascade starts from its corner.
7539    cascade: Option<NSPoint>,
7540    /// One tracking-area owner per view carrying a `.cursor()` (docs/cursor.md), keyed by the
7541    /// view pointer. Removed when the cursor goes back to `Default`.
7542    cursors: HashMap<usize, (Retained<DayCursorOwner>, Retained<NSTrackingArea>)>,
7543}
7544
7545impl AppKit {
7546    /// Rebuild a `text_field` as the other class (plain ⇄ secure) and put the replacement
7547    /// where the old view was: same text, look and place among its siblings, same focus and
7548    /// selection, and every view-keyed entry moved to it. day-core drops the old handle
7549    /// without a `release`, so nothing keyed by it may stay behind.
7550    fn swap_text_field(
7551        &mut self,
7552        h: &Handle,
7553        old: &NSTextField,
7554        node: NodeId,
7555        secure: bool,
7556    ) -> Retained<NSTextField> {
7557        let new = new_text_field(self.mtm, node, secure);
7558        let (old_key, new_key) = (ptr_of(h), ptr_of(&new));
7559        // Focus and selection first: reading them is only meaningful while the old field
7560        // still edits. `stringValue` below answers the field editor's live text.
7561        let window = h.window();
7562        let focused = window
7563            .as_deref()
7564            .is_some_and(|w| owns_first_responder(w, h));
7565        let selection = old.currentEditor().map(|e| e.selectedRange());
7566        unsafe {
7567            new.setStringValue(&old.stringValue());
7568            new.setPlaceholderString(old.placeholderString().as_deref());
7569            new.setEnabled(old.isEnabled());
7570            new.setFont(old.font().as_deref());
7571            new.setFrame(h.frame());
7572            new.setHidden(h.isHidden());
7573            new.setMenu(h.menu().as_deref());
7574            new.setToolTip(h.toolTip().as_deref());
7575            // Opacity and transform ride the layer (`set_opacity` / `set_transform`).
7576            if h.wantsLayer() {
7577                new.setWantsLayer(true);
7578                new.setAlphaValue(h.alphaValue());
7579                let from: *mut objc2::runtime::AnyObject = msg_send![h, layer];
7580                let to: *mut objc2::runtime::AnyObject = msg_send![&*new, layer];
7581                if !from.is_null() && !to.is_null() {
7582                    let t: CGAffineTransform = msg_send![from, affineTransform];
7583                    let _: () = msg_send![to, setAffineTransform: t];
7584                }
7585            }
7586            // Accessibility (`set_a11y`): only what was set explicitly, so the new class
7587            // keeps its own defaults (a secure field's role and hidden value) for the rest.
7588            if let Some(id) = h.accessibilityIdentifier().filter(|s| !s.is_empty()) {
7589                new.setAccessibilityIdentifier(Some(&id));
7590            }
7591            if let Some(label) = h.accessibilityLabel().filter(|s| !s.is_empty()) {
7592                new.setAccessibilityLabel(Some(&label));
7593            }
7594            if let Some(help) = h.accessibilityHelp().filter(|s| !s.is_empty()) {
7595                new.setAccessibilityHelp(Some(&help));
7596            }
7597            if !h.isAccessibilityElement() {
7598                new.setAccessibilityElement(false);
7599            }
7600        }
7601        // Recognizers and the cursor's tracking area move as objects, keeping their targets.
7602        for r in unsafe { h.gestureRecognizers() }.iter() {
7603            unsafe {
7604                h.removeGestureRecognizer(&r);
7605                new.addGestureRecognizer(&r);
7606            }
7607        }
7608        GESTURES.with(|m| {
7609            let mut m = m.borrow_mut();
7610            if let Some(targets) = m.remove(&old_key) {
7611                m.insert(new_key, targets);
7612            }
7613        });
7614        if let Some((owner, area)) = self.cursors.remove(&old_key) {
7615            unsafe {
7616                h.removeTrackingArea(&area);
7617                new.addTrackingArea(&area);
7618            }
7619            self.cursors.insert(new_key, (owner, area));
7620        }
7621        PAN_NODES.with(|t| rekey(t, old_key, new_key));
7622        HOVER_NODES.with(|t| rekey(t, old_key, new_key));
7623        ROTATE_NODES.with(|t| rekey(t, old_key, new_key));
7624        ROTATE_ANGLE.with(|t| rekey(t, old_key, new_key));
7625        KEY_NODES.with(|t| rekey(t, old_key, new_key));
7626        FOCUSABLE_NODES.with(|t| rekey(t, old_key, new_key));
7627        CTX_MENU_FNS.with(|t| rekey(t, old_key, new_key));
7628        transfer::moved(h, &new);
7629        // The old field goes silent before it leaves: ending its editing session would
7630        // otherwise report a focus loss for a node that keeps its focus.
7631        unsafe { old.setDelegate(None) };
7632        TARGETS.with(|m| {
7633            m.borrow_mut().remove(&old_key);
7634        });
7635        if let Some(parent) = unsafe { h.superview() } {
7636            unsafe {
7637                parent.addSubview_positioned_relativeTo(
7638                    &new,
7639                    objc2_app_kit::NSWindowOrderingMode::Above,
7640                    Some(h),
7641                );
7642                h.removeFromSuperview();
7643            }
7644        }
7645        if focused && let Some(window) = window {
7646            FIELD_SWAP.with(|s| s.set(true));
7647            let taken = window.makeFirstResponder(Some(&new));
7648            FIELD_SWAP.with(|s| s.set(false));
7649            // Taking focus selects the whole text; put back what was selected (the caret,
7650            // usually). Both classes count in UTF-16 units, so the range carries over.
7651            if taken && let Some(editor) = new.currentEditor() {
7652                let len = unsafe { new.stringValue() }.length();
7653                let range = selection
7654                    .filter(|r| r.location.saturating_add(r.length) <= len)
7655                    .unwrap_or(objc2_foundation::NSRange::new(len, 0));
7656                editor.setSelectedRange(range);
7657            }
7658        }
7659        // Whatever else was keyed by the old view goes with it.
7660        day_spec::sidetable::sweep(old_key);
7661        new
7662    }
7663
7664    pub fn new() -> Self {
7665        let mtm =
7666            MainThreadMarker::new().expect("day-toolkit-appkit must start on the main thread");
7667        let mut registry = Registry::default();
7668        for f in RENDERERS {
7669            registry.register(f());
7670        }
7671        AppKit {
7672            menu_escape_monitor: None,
7673            mtm,
7674            registry,
7675            window: None,
7676            sharing: None,
7677            sharing_delegate: None,
7678            content: None,
7679            secondary: Vec::new(),
7680            app_name: "Day".into(),
7681            cascade: None,
7682            cursors: HashMap::new(),
7683        }
7684    }
7685
7686    /// Public helper for external renderers.
7687    pub fn mtm(&self) -> MainThreadMarker {
7688        self.mtm
7689    }
7690
7691    /// The `NSWindow` whose content container is `host`: a secondary window, or the primary.
7692    /// What the main window's capture should show when the main window itself is hidden.
7693    ///
7694    /// Native document tabs (`group_windows`) move every document into its own window of an
7695    /// `NSWindowTabGroup` and leave the primary window an off-screen host. A capture of that
7696    /// host is an empty frame (or no frame at all), while the user sees the group's selected
7697    /// tab: that window's content is the stand-in, preferring the group of the app's main
7698    /// window. `None` while the primary window is on screen, or when no document window is.
7699    fn shown_document_content(&self, content: &NSView) -> Option<Handle> {
7700        if content.window().is_none_or(|w| w.isVisible()) {
7701            return None;
7702        }
7703        let main = NSApplication::sharedApplication(self.mtm).mainWindow();
7704        let anchor = main
7705            .filter(|m| {
7706                self.secondary
7707                    .iter()
7708                    .any(|w| std::ptr::eq(&*w.window, &**m))
7709            })
7710            .or_else(|| {
7711                self.secondary
7712                    .iter()
7713                    .find(|w| w.window.isVisible())
7714                    .map(|w| w.window.clone())
7715            })?;
7716        let shown = anchor
7717            .tabGroup()
7718            .and_then(|g| g.selectedWindow())
7719            .unwrap_or(anchor);
7720        self.secondary
7721            .iter()
7722            .find(|w| std::ptr::eq(&*w.window, &*shown) && w.window.isVisible())
7723            .map(|w| w.content.clone())
7724    }
7725
7726    fn ns_window_for(&self, host: &Handle) -> Option<Retained<NSWindow>> {
7727        if let Some(w) = self
7728            .secondary
7729            .iter()
7730            .find(|w| ptr_of(&w.content) == ptr_of(host))
7731        {
7732            return Some(w.window.clone());
7733        }
7734        self.content
7735            .as_ref()
7736            .filter(|c| ptr_of(c) == ptr_of(host))
7737            .and(self.window.clone())
7738    }
7739
7740    /// Build a Day window: titled + closable (Preferences kind drops resize/minimize and
7741    /// disallows tabbing per macOS convention; Normal windows share the `day.normal`
7742    /// tabbing group), a flipped content view, and a per-window delegate (`node`: `None` =
7743    /// primary). The window is NOT released-when-closed — Rust's `Retained` owns it, and
7744    /// the AppKit default would double-release under us on close.
7745    fn make_window(
7746        &self,
7747        options: &WindowOptions,
7748        prefs_style: bool,
7749        node: Option<NodeId>,
7750    ) -> (Retained<NSWindow>, Retained<DayWinDelegate>, Handle) {
7751        let mtm = self.mtm;
7752        let (title, size, min_size, tabbing) = (
7753            options.title.as_str(),
7754            options.size,
7755            options.min_size,
7756            &options.tabbing,
7757        );
7758        let content_rect =
7759            NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(size.width, size.height));
7760        // The kind decides the controls, the chrome decides the frame (docs/window-chrome.md).
7761        let style = window_chrome::style_mask(options, prefs_style);
7762        let window = window_chrome::alloc_window(
7763            mtm,
7764            content_rect,
7765            style,
7766            options.chrome == day_spec::WindowChrome::Frameless,
7767        );
7768        unsafe { window.setReleasedWhenClosed(false) };
7769        window.setTitle(&NSString::from_str(title));
7770        if let Some(min) = min_size {
7771            unsafe { window.setContentMinSize(NSSize::new(min.width, min.height)) };
7772        }
7773        if let Some(max) = options.max_size {
7774            unsafe { window.setContentMaxSize(NSSize::new(max.width, max.height)) };
7775        }
7776        use day_spec::WindowTabbing as T;
7777        use objc2_app_kit::NSWindowTabbingMode as M;
7778        let group = match tabbing {
7779            T::Group(g) | T::Preferred(g) => Some(g.clone()),
7780            T::Automatic | T::Disallowed => None,
7781        };
7782        match tabbing {
7783            _ if prefs_style => window.setTabbingMode(M::Disallowed),
7784            T::Disallowed => window.setTabbingMode(M::Disallowed),
7785            // Same-kind Day windows group as native tabs (System Settings "prefer tabs",
7786            // View ▸ Show Tab Bar, Merge All Windows) — meaningful once a second Normal
7787            // window can exist; inert while automatic tabbing is globally off (see `run`).
7788            T::Automatic => unsafe {
7789                window.setTabbingIdentifier(&NSString::from_str("day.normal"))
7790            },
7791            T::Group(g) => unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) },
7792            T::Preferred(g) => {
7793                unsafe { window.setTabbingIdentifier(&NSString::from_str(g)) };
7794                window.setTabbingMode(M::Preferred);
7795            }
7796        }
7797        if group.is_some() {
7798            // A named group is the app asking for tabs, so the class-wide switch `run` may have
7799            // turned off (no New Window builder) goes back on for it.
7800            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(true, mtm) };
7801        }
7802        let delegate = DayWinDelegate::new(mtm, node, group);
7803        window.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
7804        let content = view_of(DayFlipped::new(mtm));
7805        window.setContentView(Some(&content));
7806        window_chrome::apply(&window, &content, options);
7807        // Tab / Shift-Tab (docs/focus.md). AppKit does NOT derive the key view loop from the view
7808        // hierarchy: `nextKeyView` is nil on a programmatically built window and the loop stays
7809        // empty, so Tab moves focus OUT of a text field and onto nothing — measured on the
7810        // showcase's Focus page, where three Tabs in a row left every field unfocused. Every other
7811        // Day backend gets traversal from its widget order for free; this is the one that has to
7812        // ask. Autorecalculation rather than a call at the end of each layout because Day's tree
7813        // is reactive: fields appear, move, and vanish between passes, and AppKit rebuilding the
7814        // loop on hierarchy changes is the same rule expressed once.
7815        window.setAutorecalculatesKeyViewLoop(true);
7816        (window, delegate, content)
7817    }
7818}
7819
7820impl Default for AppKit {
7821    fn default() -> Self {
7822        Self::new()
7823    }
7824}
7825
7826fn view_of<T: AsRef<NSView>>(x: Retained<T>) -> Handle {
7827    Retained::from(x.as_ref())
7828}
7829
7830fn nscolor(c: day_spec::Color) -> Retained<NSColor> {
7831    unsafe { NSColor::colorWithSRGBRed_green_blue_alpha(c.r, c.g, c.b, c.a) }
7832}
7833
7834/// The macOS native semantic text style for a logical [`Font`] (`None` for a custom size).
7835/// `NSFont.preferredFont(forTextStyle:)` gives the OS's own typography, tracking the system settings.
7836fn ns_text_style(f: Font) -> Option<&'static objc2_app_kit::NSFontTextStyle> {
7837    use objc2_app_kit::*;
7838    unsafe {
7839        Some(match f {
7840            Font::LargeTitle => NSFontTextStyleLargeTitle,
7841            Font::Title => NSFontTextStyleTitle1,
7842            Font::Title2 => NSFontTextStyleTitle2,
7843            Font::Title3 => NSFontTextStyleTitle3,
7844            Font::Headline => NSFontTextStyleHeadline,
7845            Font::Subheadline => NSFontTextStyleSubheadline,
7846            Font::Body => NSFontTextStyleBody,
7847            Font::Callout => NSFontTextStyleCallout,
7848            Font::Footnote => NSFontTextStyleFootnote,
7849            Font::Caption => NSFontTextStyleCaption1,
7850            Font::Caption2 => NSFontTextStyleCaption2,
7851            Font::System(_) | Font::Custom(..) => return None,
7852        })
7853    }
7854}
7855
7856fn ns_weight(w: day_spec::FontWeight) -> objc2_app_kit::NSFontWeight {
7857    use day_spec::FontWeight as W;
7858    use objc2_app_kit::*;
7859    unsafe {
7860        match w {
7861            W::UltraLight => NSFontWeightUltraLight,
7862            W::Thin => NSFontWeightThin,
7863            W::Light => NSFontWeightLight,
7864            W::Regular => NSFontWeightRegular,
7865            W::Medium => NSFontWeightMedium,
7866            W::Semibold => NSFontWeightSemibold,
7867            W::Bold => NSFontWeightBold,
7868            W::Heavy => NSFontWeightHeavy,
7869            W::Black => NSFontWeightBlack,
7870        }
7871    }
7872}
7873
7874/// The `NSFontManager` weight rung (0 … 15) for a Day weight — the scale
7875/// `fontWithFamily:traits:weight:size:` matches faces on (5 = regular, 9 = bold).
7876fn nsfm_weight(w: day_spec::FontWeight) -> isize {
7877    use day_spec::FontWeight as W;
7878    match w {
7879        W::UltraLight => 2,
7880        W::Thin => 3,
7881        W::Light => 4,
7882        W::Regular => 5,
7883        W::Medium => 6,
7884        W::Semibold => 8,
7885        W::Bold => 9,
7886        W::Heavy => 10,
7887        W::Black => 12,
7888    }
7889}
7890
7891/// Resolve a canvas font (docs/fonts.md) at an absolute size: the system face for `None`,
7892/// else the family's nearest member through `NSFontManager` (which also synthesizes a bold or
7893/// italic the family lacks), falling back to a PostScript/full-name lookup (a bundled font
7894/// registered in `run`) and then to the system font with one warning.
7895fn canvas_nsfont(size: f64, font: &day_spec::CanvasFont) -> Retained<NSFont> {
7896    use objc2_app_kit::*;
7897    let weight = font.weight.unwrap_or(day_spec::FontWeight::Regular);
7898    // A painting thread draws with the fonts the UI thread resolved for this export
7899    // (`OffscreenResources`); on the UI thread the table is empty and the lookup falls through.
7900    let prepared = OFFSCREEN_FONTS.with(|t| {
7901        t.borrow()
7902            .iter()
7903            .find(|(key, _)| key.0 == size.to_bits() && key.1 == *font)
7904            .map(|(_, f)| f.clone())
7905    });
7906    if let Some(f) = prepared {
7907        return f;
7908    }
7909    let Some(mtm) = objc2::MainThreadMarker::new() else {
7910        // Off the UI thread with a font the collector never saw (it walks every text op, so
7911        // this is a guard, not a path): the system face, since `NSFontManager` is not ours to
7912        // call here. `NSFont` itself is usable from any thread.
7913        return unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7914    };
7915    let manager = unsafe { NSFontManager::sharedFontManager(mtm) };
7916    let mut traits = NSFontTraitMask::empty();
7917    if weight >= day_spec::FontWeight::Semibold {
7918        traits |= NSFontTraitMask::BoldFontMask;
7919    }
7920    if font.italic {
7921        traits |= NSFontTraitMask::ItalicFontMask;
7922    }
7923    let Some(family) = font.family.as_deref() else {
7924        let base = unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) };
7925        return if font.italic {
7926            unsafe { manager.convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask) }
7927        } else {
7928            base
7929        };
7930    };
7931    let ns_family = NSString::from_str(family);
7932    if let Some(f) = unsafe {
7933        manager.fontWithFamily_traits_weight_size(&ns_family, traits, nsfm_weight(weight), size)
7934    } {
7935        return f;
7936    }
7937    if let Some(f) = unsafe { NSFont::fontWithName_size(&ns_family, size) } {
7938        return if traits.is_empty() {
7939            f
7940        } else {
7941            unsafe { manager.convertFont_toHaveTrait(&f, traits) }
7942        };
7943    }
7944    log::warn!("unknown font family {family:?} — drawing canvas text in the system font");
7945    unsafe { NSFont::systemFontOfSize_weight(size, ns_weight(weight)) }
7946}
7947
7948/// The attribute dictionary canvas text draws and measures with (the same one, so
7949/// `measure_text` and `replay` agree on the line box).
7950fn canvas_text_attrs(
7951    font: &NSFont,
7952    color: day_spec::Color,
7953) -> Retained<objc2_foundation::NSDictionary<NSString, objc2::runtime::AnyObject>> {
7954    let col = nscolor(color);
7955    // SAFETY: both are AppKit's own attribute-name constants, valid for the process lifetime.
7956    let keys: [&NSString; 2] = unsafe {
7957        [
7958            objc2_app_kit::NSFontAttributeName,
7959            objc2_app_kit::NSForegroundColorAttributeName,
7960        ]
7961    };
7962    let objs: [&objc2::runtime::AnyObject; 2] = [
7963        font as &objc2::runtime::AnyObject,
7964        col.as_ref() as &objc2::runtime::AnyObject,
7965    ];
7966    objc2_foundation::NSDictionary::from_slices::<NSString>(&keys, &objs)
7967}
7968
7969/// Resolve a [`FontSpec`] to a native `NSFont`: a semantic style via `preferredFont(forTextStyle:)`
7970/// (or a custom system size), then an optional weight override (at the same size) and italic trait.
7971fn nsfont(spec: day_spec::FontSpec) -> Retained<NSFont> {
7972    use objc2_app_kit::*;
7973    let base: Retained<NSFont> = match spec.style {
7974        Font::System(pt) => {
7975            let w = spec
7976                .weight
7977                .map(ns_weight)
7978                .unwrap_or(unsafe { NSFontWeightRegular });
7979            unsafe { NSFont::systemFontOfSize_weight(pt, w) }
7980        }
7981        // A bundled family (§18.4), registered with CoreText in run(). fontWithName resolves
7982        // family, full, and PostScript names. A weight override maps to the bold trait (the
7983        // family decides what it can supply); unknown families fall back to the system font.
7984        Font::Custom(name, pt) => {
7985            match unsafe { NSFont::fontWithName_size(&NSString::from_str(name), pt) } {
7986                Some(f) => {
7987                    if spec
7988                        .weight
7989                        .is_some_and(|w| w >= day_spec::FontWeight::Semibold)
7990                    {
7991                        let mtm = objc2::MainThreadMarker::new()
7992                            .expect("labels realize on the main thread");
7993                        unsafe {
7994                            NSFontManager::sharedFontManager(mtm)
7995                                .convertFont_toHaveTrait(&f, NSFontTraitMask::BoldFontMask)
7996                        }
7997                    } else {
7998                        f
7999                    }
8000                }
8001                None => {
8002                    log::warn!(
8003                        "unknown font family {name:?} — falling back to the system font \
8004                         (is the file in the project's fonts/ directory?)"
8005                    );
8006                    let w = spec
8007                        .weight
8008                        .map(ns_weight)
8009                        .unwrap_or(unsafe { NSFontWeightRegular });
8010                    unsafe { NSFont::systemFontOfSize_weight(pt, w) }
8011                }
8012            }
8013        }
8014        style => {
8015            // Invariant: System/Custom matched above, so only the semantic styles — which
8016            // `ns_text_style` maps exhaustively — can reach this arm.
8017            let ts = ns_text_style(style).expect("semantic style");
8018            let opts = objc2_foundation::NSDictionary::new();
8019            let f = unsafe { NSFont::preferredFontForTextStyle_options(ts, &opts) };
8020            match spec.weight {
8021                // A weight override keeps the style's (system-resolved) size but re-picks the weight.
8022                Some(w) => unsafe { NSFont::systemFontOfSize_weight(f.pointSize(), ns_weight(w)) },
8023                None => f,
8024            }
8025        }
8026    };
8027    // Tabular figures. Cocoa exposes them as a whole font, not a trait, so this re-picks the
8028    // system font at the resolved size/weight rather than converting — which is why it only
8029    // applies to the system styles: a bundled `Font::Custom` family keeps its own figures (asking
8030    // for the system's monospaced-digit face there would silently swap the typeface).
8031    let base = if spec.tabular && !matches!(spec.style, Font::Custom(..)) {
8032        let w = spec
8033            .weight
8034            .map(ns_weight)
8035            .unwrap_or(unsafe { NSFontWeightRegular });
8036        unsafe { NSFont::monospacedDigitSystemFontOfSize_weight(base.pointSize(), w) }
8037    } else {
8038        base
8039    };
8040    // Monospace, by the same rule as tabular: Cocoa ships it as a whole font, so this re-picks
8041    // the system's monospaced face at the resolved size and weight. Skipped for a bundled family
8042    // — swapping a chosen typeface for the system mono would be a surprise, not a refinement.
8043    let base = if spec.monospace && !matches!(spec.style, Font::Custom(..)) {
8044        let w = spec
8045            .weight
8046            .map(ns_weight)
8047            .unwrap_or(unsafe { NSFontWeightRegular });
8048        unsafe { NSFont::monospacedSystemFontOfSize_weight(base.pointSize(), w) }
8049    } else {
8050        base
8051    };
8052    // Relative size (`FontSpec::scale`). Applied last, over whatever face the traits above
8053    // settled on, and through `convertFont_toSize` so a bundled family keeps its typeface —
8054    // re-picking the system font here would undo the Custom/monospace/tabular work above.
8055    let base = if spec.scale != 1.0 {
8056        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
8057        let pts = spec.resolved_points(base.pointSize());
8058        unsafe { NSFontManager::sharedFontManager(mtm).convertFont_toSize(&base, pts) }
8059    } else {
8060        base
8061    };
8062    if spec.italic {
8063        let mtm = objc2::MainThreadMarker::new().expect("labels realize on the main thread");
8064        unsafe {
8065            NSFontManager::sharedFontManager(mtm)
8066                .convertFont_toHaveTrait(&base, NSFontTraitMask::ItalicFontMask)
8067        }
8068    } else {
8069        base
8070    }
8071}
8072
8073/// Build an `NSAttributedString` for a label's text + runs (docs/text-runs.md).
8074///
8075/// Ranges arrive as BYTE offsets into a Rust `str`; `NSAttributedString` indexes UTF-16. The
8076/// conversion is per-run rather than a blanket assumption: any text with an emoji or a CJK
8077/// character makes the two disagree, and an off-by-N range there styles the wrong words.
8078/// Stamp a paragraph alignment across a label's whole attributed string.
8079///
8080/// Separate from `setAlignment:` because the two live in different places: the cell has a
8081/// paragraph style, the attributed string carries its own, and the string's wins.
8082fn set_paragraph_alignment(tf: &NSTextField, align: objc2_app_kit::NSTextAlignment) {
8083    use objc2_foundation::{NSMutableAttributedString, NSRange};
8084    unsafe {
8085        let cur = tf.attributedStringValue();
8086        let m = NSMutableAttributedString::initWithAttributedString(
8087            NSMutableAttributedString::alloc(),
8088            &cur,
8089        );
8090        let style = objc2_app_kit::NSMutableParagraphStyle::new();
8091        style.setAlignment(align);
8092        // Wrapping is what makes alignment observable at all, and the default paragraph style a
8093        // fresh NSMutableParagraphStyle carries would otherwise reset it to clipping.
8094        style.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByWordWrapping);
8095        m.addAttribute_value_range(
8096            objc2_app_kit::NSParagraphStyleAttributeName,
8097            &style,
8098            NSRange::new(0, cur.length()),
8099        );
8100        tf.setAttributedStringValue(&m);
8101    }
8102}
8103
8104fn attributed_label(
8105    text: &str,
8106    base_font: &NSFont,
8107    color: Option<day_spec::Color>,
8108    role: day_spec::props::TextRole,
8109    runs: &[day_spec::TextRun],
8110) -> Retained<objc2_foundation::NSAttributedString> {
8111    use objc2_foundation::{NSMutableAttributedString, NSRange};
8112    let ns = NSString::from_str(text);
8113    let s = unsafe {
8114        NSMutableAttributedString::initWithString(NSMutableAttributedString::alloc(), &ns)
8115    };
8116    let whole = NSRange::new(0, ns.length());
8117    unsafe {
8118        s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, base_font, whole);
8119        // Always a foreground: an attributed range with no color attribute draws in black,
8120        // which is unreadable in dark mode. `labelColor` is the adaptive default the field
8121        // would have used on its own.
8122        // An explicit color wins; otherwise the ROLE picks which adaptive system color to use.
8123        // Both are adaptive, which is the point of asking for a role instead of a grey: the
8124        // secondary label is legible against either appearance's background, and a literal one
8125        // cannot be.
8126        let fg = color.map(nscolor).unwrap_or_else(|| match role {
8127            day_spec::props::TextRole::Secondary => objc2_app_kit::NSColor::secondaryLabelColor(),
8128            day_spec::props::TextRole::Primary => objc2_app_kit::NSColor::labelColor(),
8129        });
8130        s.addAttribute_value_range(objc2_app_kit::NSForegroundColorAttributeName, &fg, whole);
8131    }
8132    for r in runs {
8133        let Some(range) = utf16_range(text, &r.range) else {
8134            continue;
8135        };
8136        unsafe {
8137            s.addAttribute_value_range(objc2_app_kit::NSFontAttributeName, &nsfont(r.font), range);
8138            if let Some(c) = r.color {
8139                s.addAttribute_value_range(
8140                    objc2_app_kit::NSForegroundColorAttributeName,
8141                    &nscolor(c),
8142                    range,
8143                );
8144            }
8145            if let Some(c) = r.background {
8146                s.addAttribute_value_range(
8147                    objc2_app_kit::NSBackgroundColorAttributeName,
8148                    &nscolor(c),
8149                    range,
8150                );
8151            }
8152            if r.underline.is_on() {
8153                let style = objc2_foundation::NSNumber::new_i64(ns_underline(r.underline));
8154                s.addAttribute_value_range(
8155                    objc2_app_kit::NSUnderlineStyleAttributeName,
8156                    &style,
8157                    range,
8158                );
8159            }
8160            if r.strikethrough {
8161                let one = objc2_foundation::NSNumber::new_i64(1);
8162                s.addAttribute_value_range(
8163                    objc2_app_kit::NSStrikethroughStyleAttributeName,
8164                    &one,
8165                    range,
8166                );
8167            }
8168            if let Some(url) = r.link.as_deref() {
8169                // The native field editor hit-tests this attribute; DayLabel handles its
8170                // delegate callback and reports LinkActivated without opening the URL itself.
8171                let value = NSString::from_str(url);
8172                s.addAttribute_value_range(objc2_app_kit::NSLinkAttributeName, &value, range);
8173            }
8174        }
8175    }
8176    s.into_super()
8177}
8178
8179/// [`Underline`](day_spec::Underline) as an `NSUnderlineStyle` bitmask: the line style in the low
8180/// byte, the pattern in the second. `Dotted`/`Wavy` are patterns over a single line, which is
8181/// exactly how AppKit spells them.
8182fn ns_underline(u: day_spec::Underline) -> i64 {
8183    use day_spec::Underline as U;
8184    match u {
8185        U::None => 0,
8186        U::Single => 0x01,
8187        U::Double => 0x09,
8188        U::Dotted => 0x01 | 0x0100,
8189        U::Wavy => 0x01 | 0x0400,
8190    }
8191}
8192
8193/// A byte range in `text` as an `NSRange` in UTF-16 units, or `None` if it is out of bounds.
8194fn utf16_range(text: &str, r: &std::ops::Range<usize>) -> Option<objc2_foundation::NSRange> {
8195    let start = text.get(..r.start)?.encode_utf16().count();
8196    let len = text.get(r.clone())?.encode_utf16().count();
8197    Some(objc2_foundation::NSRange::new(start, len))
8198}
8199
8200/// Register every bundled font file (the project's `fonts/`, staged per §18.4) with CoreText for
8201/// this process, so `Font::Custom` family names resolve through `NSFont::fontWithName`. Called
8202/// once from `run()`; a failure (already registered on a hot relaunch, or a broken file) only
8203/// means that family won't resolve, so it logs and moves on.
8204fn register_bundled_fonts() {
8205    // CFURLRef is toll-free bridged with NSURL, so the NSURL pointer passes straight through.
8206    #[link(name = "CoreText", kind = "framework")]
8207    unsafe extern "C" {
8208        fn CTFontManagerRegisterFontsForURL(
8209            font_url: *const std::ffi::c_void,
8210            scope: u32, // kCTFontManagerScopeProcess = 1
8211            error: *mut *const std::ffi::c_void,
8212        ) -> bool;
8213    }
8214    for path in day_spec::fonts::bundled_fonts() {
8215        let url = unsafe {
8216            objc2_foundation::NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()))
8217        };
8218        let ok = unsafe {
8219            CTFontManagerRegisterFontsForURL(
8220                Retained::as_ptr(&url) as *const std::ffi::c_void,
8221                1,
8222                std::ptr::null_mut(),
8223            )
8224        };
8225        if !ok {
8226            log::warn!("could not register bundled font {}", path.display());
8227        }
8228    }
8229}
8230
8231/// `TextAlign` → AppKit. `Natural` rather than `Left` for the leading case: it follows the
8232/// writing direction, so an RTL locale aligns right without the app asking (docs/localization.md).
8233fn nstextalign(a: day_spec::props::TextAlign) -> objc2_app_kit::NSTextAlignment {
8234    match a {
8235        day_spec::props::TextAlign::Leading => objc2_app_kit::NSTextAlignment::Natural,
8236        day_spec::props::TextAlign::Center => objc2_app_kit::NSTextAlignment::Center,
8237        day_spec::props::TextAlign::Trailing => objc2_app_kit::NSTextAlignment::Right,
8238    }
8239}
8240
8241fn configure_label_cell(tf: &NSTextField) {
8242    if let Some(cell) = unsafe { tf.cell() } {
8243        unsafe {
8244            cell.setWraps(true);
8245            cell.setUsesSingleLineMode(false);
8246            cell.setLineBreakMode(NSLineBreakMode::ByWordWrapping);
8247        }
8248    }
8249}
8250
8251/// If `parent` is a scroll view, children go into its (flipped) document view.
8252fn content_of(parent: &Handle) -> Retained<NSView> {
8253    if let Some(sv) = parent.downcast_ref::<NSScrollView>()
8254        && let Some(doc) = unsafe { sv.documentView() }
8255    {
8256        return doc;
8257    }
8258    parent.clone()
8259}
8260
8261/// Run `body` (which sets animatable properties on a layer-backed view) inside an
8262/// `NSAnimationContext` group so AppKit interpolates the change on the render server with the
8263/// curve's timing function, or immediately when `anim` is `None` (§8.4). `allowsImplicitAnimation`
8264/// makes direct property changes on layer-backed views animate. A spring maps to an overshooting
8265/// cubic-bezier timing function (a visible bounce without an explicit `CASpringAnimation`).
8266fn with_appkit_anim(anim: Option<&AnimSpec>, body: impl FnOnce()) {
8267    let Some(a) = anim else {
8268        body();
8269        return;
8270    };
8271    let (dur, timing) = appkit_timing(a);
8272    unsafe {
8273        NSAnimationContext::beginGrouping();
8274        let ctx = NSAnimationContext::currentContext();
8275        ctx.setDuration(dur);
8276        ctx.setTimingFunction(Some(&timing));
8277        ctx.setAllowsImplicitAnimation(true);
8278        body();
8279        NSAnimationContext::endGrouping();
8280    }
8281}
8282
8283/// The `(duration_secs, timing function)` for a curve. Springs render as an overshooting bezier
8284/// (control point y > 1) whose overshoot grows as damping falls, over a response-derived duration.
8285fn appkit_timing(a: &AnimSpec) -> (f64, Retained<CAMediaTimingFunction>) {
8286    unsafe {
8287        let named = |n| {
8288            (
8289                a.duration_secs().max(0.01),
8290                CAMediaTimingFunction::functionWithName(n),
8291            )
8292        };
8293        match a.curve {
8294            Curve::Linear => named(kCAMediaTimingFunctionLinear),
8295            Curve::EaseIn => named(kCAMediaTimingFunctionEaseIn),
8296            Curve::EaseOut => named(kCAMediaTimingFunctionEaseOut),
8297            Curve::EaseInOut => named(kCAMediaTimingFunctionEaseInEaseOut),
8298            Curve::Spring { damping, .. } => {
8299                // Overshoot bezier over exactly the specified duration (authoritative timing).
8300                let overshoot = 1.0 + (1.0 - damping.clamp(0.0, 1.0)) as f32 * 0.55;
8301                (
8302                    a.duration_secs().max(0.05),
8303                    CAMediaTimingFunction::functionWithControlPoints(0.34, overshoot, 0.5, 1.0),
8304                )
8305            }
8306        }
8307    }
8308}
8309
8310/// Warn once per kind that this backend has no registered renderer for `kind`, before falling back to
8311/// a visible placeholder. A missing renderer usually means the piece's `appkit` feature wasn't enabled
8312/// (Tier A.2 derives it automatically under `day build`; a bare `cargo` build may miss it). Deduped
8313/// per kind so a placeholder rendered every frame doesn't spam the log.
8314fn warn_missing_renderer(kind: PieceKind) {
8315    day_spec::placeholder::report(kind, "appkit");
8316}
8317
8318/// The visible-but-harmless placeholder label the unregistered-kind arm renders. Shared with
8319/// the [`props_of`] mismatch fallback, so a wrong props payload degrades to the same surface
8320/// (the warning is already reported by `props_of` itself).
8321pub(crate) fn placeholder_view(mtm: MainThreadMarker, kind: PieceKind) -> Handle {
8322    view_of(unsafe {
8323        NSTextField::labelWithString(&NSString::from_str(&format!("⟨{kind}⟩")), mtm)
8324    })
8325}
8326
8327impl Toolkit for AppKit {
8328    /// Settled unless a toolbar edit is still painting (toolbar.rs `CHROME_SETTLE`); AppKit's
8329    /// own transitions (sheets, nav pushes) complete within the turn that starts them.
8330    fn ui_idle(&mut self) -> bool {
8331        toolbar::chrome_settled()
8332    }
8333
8334    type Handle = Handle;
8335
8336    fn system_color(&mut self, role: day_spec::SystemColor) -> day_spec::Color {
8337        use day_spec::SystemColor;
8338        let result = std::cell::Cell::new(role.fallback(self.dark_mode()));
8339        let block = block2::StackBlock::new(|| {
8340            let color = match role {
8341                SystemColor::Accent => NSColor::controlAccentColor(),
8342                SystemColor::Text => NSColor::labelColor(),
8343                SystemColor::SecondaryText => NSColor::secondaryLabelColor(),
8344                SystemColor::Background => NSColor::windowBackgroundColor(),
8345                SystemColor::Surface => NSColor::controlBackgroundColor(),
8346            };
8347            if let Some(rgb) =
8348                color.colorUsingColorSpace(&objc2_app_kit::NSColorSpace::sRGBColorSpace())
8349            {
8350                result.set(day_spec::Color::rgba(
8351                    rgb.redComponent(),
8352                    rgb.greenComponent(),
8353                    rgb.blueComponent(),
8354                    rgb.alphaComponent(),
8355                ));
8356            }
8357        });
8358        NSApplication::sharedApplication(self.mtm())
8359            .effectiveAppearance()
8360            .performAsCurrentDrawingAppearance(&block);
8361        result.get()
8362    }
8363
8364    fn dark_mode(&mut self) -> bool {
8365        // The app's EFFECTIVE appearance — one source for the system setting, the DAY_THEME
8366        // launch force (applied as an NSApp override at startup), and a set_appearance call.
8367        let app = NSApplication::sharedApplication(self.mtm());
8368        app.effectiveAppearance()
8369            .name()
8370            .to_string()
8371            .contains("Dark")
8372    }
8373
8374    /// System Settings › Accessibility › Display › "Reduce motion", as NSWorkspace reports it
8375    /// (docs/accessibility.md). `install_reduce_motion_observer` re-reads it on a flip.
8376    fn reduce_motion(&mut self) -> bool {
8377        objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()
8378    }
8379
8380    /// macOS is the one platform whose badge takes arbitrary text: `NSDockTile.badgeLabel` is a
8381    /// `String`, so `Text` renders literally and a count is just its decimal form. A nil label
8382    /// clears it (docs/badge.md).
8383    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
8384        use day_spec::AppBadge;
8385        let label = match badge {
8386            AppBadge::None => None,
8387            // Zero clears, matching the platform convention the doc states.
8388            AppBadge::Count(0) => None,
8389            AppBadge::Count(n) => Some(n.to_string()),
8390            AppBadge::Text(t) if t.is_empty() => None,
8391            AppBadge::Text(t) => Some(t.clone()),
8392            // No dedicated dot on the Dock; the smallest honest mark is a single bullet.
8393            AppBadge::Dot => Some("\u{2022}".to_string()),
8394        };
8395        let tile = NSApplication::sharedApplication(self.mtm()).dockTile();
8396        let ns = label.map(|l| objc2_foundation::NSString::from_str(&l));
8397        unsafe { tile.setBadgeLabel(ns.as_deref()) };
8398        tile.display();
8399    }
8400
8401    fn set_appearance(&mut self, dark: Option<bool>) {
8402        let app = NSApplication::sharedApplication(self.mtm());
8403        let appearance = dark.and_then(|d| {
8404            objc2_app_kit::NSAppearance::appearanceNamed(unsafe {
8405                if d {
8406                    objc2_app_kit::NSAppearanceNameDarkAqua
8407                } else {
8408                    objc2_app_kit::NSAppearanceNameAqua
8409                }
8410            })
8411        });
8412        // `None` clears the override — back to the system appearance.
8413        unsafe { app.setAppearance(appearance.as_deref()) };
8414    }
8415
8416    fn attach_refresh(&mut self, handle: &Self::Handle, host: NodeId) {
8417        controls::refresh_gesture::attach(handle, host);
8418    }
8419
8420    fn set_presented(&mut self, handle: &Self::Handle, visible: bool) {
8421        unsafe {
8422            handle.setHidden(!visible);
8423        }
8424    }
8425
8426    fn capability(&self, cap: Cap) -> Support {
8427        match cap {
8428            // An `NSSharingService` per app action, from the picker's delegate.
8429            Cap::ShareActions => Support::Native,
8430            Cap::SearchField => Support::Native,
8431            Cap::ComboBox => Support::Native,
8432            Cap::Stepper => Support::Native,
8433            Cap::DateTimePicker => Support::Native,
8434            Cap::ColorPicker => Support::Native,
8435            Cap::PullRefresh => Support::Emulated,
8436            Cap::Pager => Support::Emulated,
8437            Cap::PullRefreshGesture => Support::Emulated,
8438            // A tracking-area owner sets an `NSCursor` per view (docs/cursor.md). Wait, progress,
8439            // help, and move take the arrow — AppKit draws no such shapes — and the zoom and
8440            // diagonal-resize cursors need macOS 15.
8441            Cap::Cursor => Support::Native,
8442            // `NSFontManager` enumerates every family and member (docs/fonts.md).
8443            Cap::FontList => Support::Native,
8444            // An image-and-text table cell's content (docs/list.md "List items").
8445            Cap::ListItem => Support::Native,
8446            // ImageIO behind `NSBitmapImageRep` reads every container macOS knows and writes
8447            // back PNG/JPEG/TIFF/BMP/GIF, and carries the container's own metadata dictionary
8448            // (docs/images.md).
8449            Cap::ImageDecode | Cap::ImageEncode | Cap::ImageProperties => Support::Native,
8450            // Canvas export (docs/canvas.md "Exporting"): the canvas painter replayed into a
8451            // CGBitmapContext, or a CGPDFContext that keeps shapes and text vector.
8452            Cap::CanvasBitmap | Cap::CanvasPdf => Support::Native,
8453            // The announcement-requested notification, posted from the primary window
8454            // (docs/accessibility.md).
8455            Cap::Announce => Support::Native,
8456            // `NSWorkspace.accessibilityDisplayShouldReduceMotion`, re-read when the workspace
8457            // posts its display-options change (docs/accessibility.md).
8458            Cap::ReduceMotion => Support::Native,
8459            Cap::Snapshot
8460            | Cap::NativeSymbols
8461            // The rows as chrome: `Rail` is the same source list pinned narrow, `Tabs` an
8462            // NSSegmentedControl docked below the pages. AppKit has no app-level tab bar —
8463            // NSTabView owns its own page content, the opposite of Day's model — so the bar
8464            // is composed from the control a Mac uses for a one-of-N switch this size.
8465            //
8466            // `Cap::NavTabsAdaptive` is deliberately NOT here: a Mac app may PIN a tab bar, but
8467            // a narrow Mac window hides its sidebar and pushes rather than growing one. It falls
8468            // through to the `Unsupported` arm below.
8469            | Cap::NavTabs
8470            | Cap::NavSplit
8471            // Both presentations are the same NSSplitViewController — a stack is that split with
8472            // its sidebar item collapsed — so re-presenting is a collapse plus one `addSubview`
8473            // that re-parents the sidebar page (docs/size-classes.md).
8474            | Cap::NavRepresent
8475            // A REAL `contentList` NSSplitViewItem between sidebar and detail; the pane
8476            // persists through every presentation (docs/navigation.md).
8477            | Cap::NavContentList
8478            | Cap::Dialogs
8479            | Cap::FileDialogs
8480            // NSOpenPanel with `canChooseDirectories` (docs/files.md).
8481            | Cap::FolderDialog
8482            | Cap::Animation
8483            // NSTextView natively honors all three text-area attributes.
8484            | Cap::TextEditable
8485            | Cap::TextSelectable
8486            | Cap::TextSpellCheck
8487            // NSTableView's own drag pipeline, with the `.gap` placeholder (docs/list.md), in
8488            // lists and in the source-list sidebar itself (docs/navigation.md).
8489            | Cap::NavReorder | Cap::ListReorder
8490            // NSTableView's view-based reuse queue (`makeViewWithIdentifier`) hands Day's cells
8491            // back for new rows; `didRemoveRowView` recycles them (docs/list.md).
8492            | Cap::ListRecycling
8493            // NSTableView row actions: reveal-as-you-swipe buttons with the native full-slide
8494            // activation (docs/list.md).
8495            | Cap::ListSwipeActions
8496            // NSTableView group rows with `floatsGroupRows` (docs/list.md "Sections").
8497            | Cap::ListSections
8498            // NSOutlineView hosts Day-built rows natively, drag-reparent included
8499            // (docs/tree.md).
8500            | Cap::Tree
8501            | Cap::TreeSections
8502            | Cap::TreeMove
8503            // Real NSWindows with native tabbing + the Windows menu (docs/windows.md).
8504            | Cap::MultiWindow
8505            // `miniaturize:` / `zoom:` / `toggleFullScreen:`, reported back through the window
8506            // delegate's notifications (docs/windows.md "Window properties").
8507            | Cap::WindowStates
8508            | Cap::WindowFullscreen
8509            // `NSWindowSharingNone`: captures, recordings and screen sharing see an empty window.
8510            | Cap::ContentProtection
8511            // Per-window `tabbingIdentifier` / `tabbingMode`, with the "+" opening the group's
8512            // own builder.
8513            | Cap::WindowTabbing
8514            // `applicationDockMenu:` on the app delegate (docs/menus.md).
8515            | Cap::DockMenu
8516            // Borderless windows that still take key, a transparent title bar over the
8517            // content, a clear window background, and `NSVisualEffectView` materials behind the
8518            // content (docs/window-chrome.md).
8519            | Cap::FramelessWindow
8520            | Cap::OverlayTitleBar
8521            | Cap::TransparentWindow
8522            | Cap::WindowMaterial
8523            // `performWindowDragWithEvent:` from a press on the region's own background.
8524            | Cap::DragRegion
8525            // `NSStatusItem`s in the menu bar, a progress bar drawn on the Dock tile, and the
8526            // accessory activation policy (docs/status-item.md).
8527            | Cap::StatusItem
8528            | Cap::AppProgress
8529            | Cap::DockVisibility
8530            // Frame, limits, level, Spaces, style-mask controls, per-window appearance, Dock
8531            // bounces, and `NSScreen` (docs/windows.md "Window properties").
8532            | Cap::WindowGeometry
8533            | Cap::WindowPosition
8534            | Cap::WindowLevel
8535            | Cap::WindowAppearance
8536            | Cap::RequestAttention
8537            | Cap::Monitors
8538            // Run-time shortcuts appear in the Dock menu beside the declared ones.
8539            | Cap::DynamicShortcuts
8540            // A real NSToolbar in the title bar (docs/toolbars.md).
8541            | Cap::Toolbar
8542            // The bar holds a native search field (docs/search.md).
8543            | Cap::ToolbarSearch
8544            | Cap::AppMenu
8545            // NSDockTile.badgeLabel is an arbitrary String, so all three payloads render — the
8546            // only backend where Text is real (docs/badge.md).
8547            | Cap::AppBadgeCount
8548            | Cap::AppBadgeText
8549            // NSUndoManager fronted by DayUndoManager: the stock Edit menu retitles and
8550            // enables itself, ⌘Z/⇧⌘Z land through the responder chain (docs/model.md).
8551            | Cap::UndoBridge
8552            | Cap::DragDrop | Cap::DragExternalImport | Cap::DragExternalExport | Cap::DragMultipleItems | Cap::DragFileReferences | Cap::EditBridge
8553            | Cap::AppBadgeDot
8554            | Cap::Appearance
8555            // firstBaselineOffsetFromTop — the platform's own answer (docs/baseline.md).
8556            | Cap::BaselineAlignment
8557            // A REAL inspector NSSplitViewItem (`inspectorWithViewController:`): the system
8558            // trailing-pane material and full-height layout (docs/inspector.md).
8559            | Cap::Inspector
8560            // A plain NSSplitView with two arranged panes (docs/split.md).
8561            | Cap::Split
8562            | Cap::TextRuns
8563            | Cap::TextLinks => Support::Native,
8564            // A topmost autoresizing child of the content view — not a system modal
8565            // (docs/cover.md's ArkUI tier).
8566            Cap::Cover => Support::Emulated,
8567            // `.sheet()` is a window sheet on the primary window (docs/cover.md "Modal sheet").
8568            Cap::CoverSheet => Support::Native,
8569            _ => Support::Unsupported,
8570        }
8571    }
8572
8573    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Handle {
8574        let mtm = self.mtm;
8575        match Builtin::from_key(kind) {
8576            Some(Builtin::Container) => {
8577                let v = DayFlipped::new(mtm);
8578                if let Some(p) = props.downcast_ref::<ContainerProps>() {
8579                    if p.role == Some(day_spec::SurfaceRole::SectionCard) {
8580                        v.set_section_card(p.corner_radius);
8581                    } else if p.background.is_some() || p.corner_radius > 0.0 || p.clips {
8582                        v.set_surface(p.background, p.corner_radius, p.clips);
8583                    }
8584                }
8585                view_of(v)
8586            }
8587            Some(Builtin::Scroll) => {
8588                let horizontal = props
8589                    .downcast_ref::<day_spec::props::ScrollProps>()
8590                    .map(|p| p.horizontal)
8591                    .unwrap_or(false);
8592                let sv = unsafe { NSScrollView::new(mtm) };
8593                unsafe {
8594                    sv.setHasVerticalScroller(!horizontal);
8595                    sv.setHasHorizontalScroller(horizontal);
8596                    sv.setDrawsBackground(false);
8597                    // Overlay scrollers ALWAYS: day lays content out at the scroll's full frame
8598                    // width, and a legacy scroller (the "always show scroll bars" system
8599                    // setting, or a mouse attached) would reserve ~15pt and clip trailing
8600                    // content. Overlay floats above content instead — and matches the GTK/Qt
8601                    // backends.
8602                    sv.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
8603                }
8604                let doc = DayFlipped::new(mtm);
8605                unsafe { sv.setDocumentView(Some(doc.as_ref())) };
8606                view_of(sv)
8607            }
8608            Some(Builtin::Label) => {
8609                // `props_of`, not a panicking downcast, for every typed-props arm: a mismatch
8610                // (a piece registered under a builtin key, or a day-core regression) warns once
8611                // per kind and degrades to the placeholder — realize runs inside native
8612                // up-calls, where a panic is a process kill.
8613                let Some(p) = props_of::<LabelProps>(kind, "appkit", props) else {
8614                    return placeholder_view(mtm, kind);
8615                };
8616                let tf = DayLabel::new(mtm, id, &p.text);
8617                configure_label_cell(&tf);
8618                if !p.wraps || p.max_lines > 0 {
8619                    unsafe {
8620                        tf.setMaximumNumberOfLines(if p.wraps { p.max_lines as isize } else { 1 });
8621                        if !p.wraps || p.max_lines == 1 {
8622                            tf.setUsesSingleLineMode(true);
8623                            tf.setLineBreakMode(objc2_app_kit::NSLineBreakMode::ByTruncatingTail);
8624                        }
8625                    }
8626                }
8627                unsafe { tf.setFont(Some(&nsfont(p.font))) };
8628                // The PLAIN path needs the role as much as the attributed one below: a label
8629                // with no runs never reaches `attributed_label`, and reading the role only there
8630                // left every ordinary `.secondary()` label rendering in the primary color.
8631                match (p.color, p.role) {
8632                    (Some(c), _) => unsafe { tf.setTextColor(Some(&nscolor(c))) },
8633                    (None, day_spec::props::TextRole::Secondary) => unsafe {
8634                        tf.setTextColor(Some(&objc2_app_kit::NSColor::secondaryLabelColor()))
8635                    },
8636                    (None, day_spec::props::TextRole::Primary) => {}
8637                }
8638                if !p.runs.is_empty() {
8639                    let s = attributed_label(&p.text, &nsfont(p.font), p.color, p.role, &p.runs);
8640                    unsafe { tf.setAttributedStringValue(&s) };
8641                }
8642                tf.ivars().has_runs.set(!p.runs.is_empty());
8643                tf.set_links(p.runs.iter().any(|r| r.link.is_some()));
8644                // Alignment goes on last and, for a runs label, has to reach inside the
8645                // attributed string. `setAlignment:` writes the cell's paragraph style, which an
8646                // attributed string then overrides wholesale with its own — so a markdown label
8647                // set only through the cell comes out leading-aligned no matter what was asked.
8648                if p.align != day_spec::props::TextAlign::Leading {
8649                    unsafe { tf.setAlignment(nstextalign(p.align)) };
8650                    if !p.runs.is_empty() {
8651                        set_paragraph_alignment(&tf, nstextalign(p.align));
8652                    }
8653                }
8654                view_of(Retained::into_super(tf))
8655            }
8656            Some(Builtin::Button) => {
8657                let Some(p) = props_of::<ButtonProps>(kind, "appkit", props) else {
8658                    return placeholder_view(mtm, kind);
8659                };
8660                let target = DayTarget::new(mtm, id);
8661                let btn = unsafe {
8662                    NSButton::buttonWithTitle_target_action(
8663                        &NSString::from_str(&p.title),
8664                        Some(&*target),
8665                        Some(sel!(action:)),
8666                        mtm,
8667                    )
8668                };
8669                apply_button_style(&btn, p.style);
8670                if p.icon.is_some() {
8671                    apply_button_content(&btn, &p.title, p.icon.as_ref(), p.icon_only);
8672                }
8673                unsafe { btn.setEnabled(p.enabled) };
8674                set_button_selected(&btn, p.selected);
8675                let view = view_of(btn);
8676                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8677                view
8678            }
8679            Some(Builtin::Toggle) => {
8680                let Some(p) = props_of::<ToggleProps>(kind, "appkit", props) else {
8681                    return placeholder_view(mtm, kind);
8682                };
8683                let target = DayTarget::new(mtm, id);
8684                let sw = unsafe { NSSwitch::new(mtm) };
8685                unsafe {
8686                    sw.setState(if p.on { 1 } else { 0 });
8687                    sw.setEnabled(p.enabled);
8688                    sw.setTarget(Some(&*target));
8689                    sw.setAction(Some(sel!(action:)));
8690                }
8691                let view = view_of(sw);
8692                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8693                view
8694            }
8695            Some(Builtin::Slider) => {
8696                let Some(p) = props_of::<SliderProps>(kind, "appkit", props) else {
8697                    return placeholder_view(mtm, kind);
8698                };
8699                let target = DayTarget::new(mtm, id);
8700                let sl = unsafe {
8701                    NSSlider::sliderWithValue_minValue_maxValue_target_action(
8702                        p.value,
8703                        p.min,
8704                        p.max,
8705                        Some(&*target),
8706                        Some(sel!(action:)),
8707                        mtm,
8708                    )
8709                };
8710                unsafe { sl.setContinuous(true) };
8711                let view = view_of(sl);
8712                TARGETS.with(|m| m.borrow_mut().insert(ptr_of(&view), target));
8713                view
8714            }
8715            Some(Builtin::Picker) => picker::realize_any(self, props, id),
8716            Some(Builtin::TextArea) => textarea::realize_any(self, props, id),
8717            Some(Builtin::TextField) => {
8718                let Some(p) = props_of::<TextFieldProps>(kind, "appkit", props) else {
8719                    return placeholder_view(mtm, kind);
8720                };
8721                let tf = new_text_field(mtm, id, false);
8722                unsafe {
8723                    tf.setStringValue(&NSString::from_str(&p.text));
8724                    tf.setPlaceholderString(Some(&NSString::from_str(&p.placeholder)));
8725                }
8726                view_of(tf)
8727            }
8728            Some(Builtin::Divider) => {
8729                let b = unsafe { NSBox::new(mtm) };
8730                unsafe { b.setBoxType(NSBoxType::Separator) };
8731                view_of(b)
8732            }
8733            Some(Builtin::Progress) => {
8734                let Some(p) = props_of::<ProgressProps>(kind, "appkit", props) else {
8735                    return placeholder_view(mtm, kind);
8736                };
8737                if p.value.is_none() {
8738                    return crate::controls::spinner::make(self, p, id);
8739                }
8740                let pi = unsafe { NSProgressIndicator::new(mtm) };
8741                unsafe {
8742                    match p.value {
8743                        Some(v) => {
8744                            pi.setStyle(NSProgressIndicatorStyle::Bar);
8745                            pi.setIndeterminate(false);
8746                            pi.setMinValue(0.0);
8747                            pi.setMaxValue(1.0);
8748                            pi.setDoubleValue(v);
8749                        }
8750                        None => {
8751                            pi.setStyle(NSProgressIndicatorStyle::Spinning);
8752                            pi.setIndeterminate(true);
8753                            pi.startAnimation(None);
8754                        }
8755                    }
8756                }
8757                view_of(pi)
8758            }
8759            Some(Builtin::Canvas) => {
8760                let canvas = DayCanvas::new(mtm);
8761                KEY_NODES.with(|t| t.insert(Retained::as_ptr(&canvas) as usize, id));
8762                view_of(canvas)
8763            }
8764            Some(Builtin::Inspector) => {
8765                let (visible, width, leading) = props
8766                    .downcast_ref::<InspectorProps>()
8767                    .map(|p| {
8768                        (
8769                            p.visible,
8770                            p.width,
8771                            p.edge == day_spec::props::PaneEdge::Leading,
8772                        )
8773                    })
8774                    .unwrap_or((false, 280.0, false));
8775                let content_wrap = view_of(DayFlipped::new(mtm));
8776                let panel_flipped = DayFlipped::new(mtm);
8777                // The panel draws an opaque window-background backdrop over the item's
8778                // vibrancy material — without it the section cards' thin quaternary fill
8779                // composites into near-black in dark mode (see `FlippedIvars`).
8780                panel_flipped.set_pane_backdrop();
8781                let panel_wrap = view_of(panel_flipped);
8782                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8783                // Force loadView before the items go in — the same lifecycle rule the nav
8784                // host below documents.
8785                let _ = unsafe { split_vc.view() };
8786                let content_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8787                let panel_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8788                unsafe {
8789                    content_vc.setView(&content_wrap);
8790                    panel_vc.setView(&panel_wrap);
8791                }
8792                let content_item = unsafe {
8793                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&content_vc)
8794                };
8795                // A TRAILING pane is a real inspector item (the system treatment). A LEADING
8796                // one is a plain item placed first: `sidebarWithViewController:` would bring
8797                // sidebar material, which captures black offscreen (docs/navigation.md), and
8798                // the panel wrap already paints its own backdrop.
8799                let panel_item = unsafe {
8800                    if leading {
8801                        objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&panel_vc)
8802                    } else {
8803                        objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&panel_vc)
8804                    }
8805                };
8806                unsafe {
8807                    // Day's signal is the only visibility driver: with the pinned width the
8808                    // divider has nothing to drag and the pane cannot be user-collapsed, so
8809                    // there is no native-initiated change to report back.
8810                    panel_item.setCanCollapse(false);
8811                    panel_item.setCollapsed(!visible);
8812                    panel_item.setMinimumThickness(width);
8813                    panel_item.setMaximumThickness(width);
8814                    panel_item.setAllowsFullHeightLayout(true);
8815                    if leading {
8816                        split_vc.addSplitViewItem(&panel_item);
8817                        split_vc.addSplitViewItem(&content_item);
8818                    } else {
8819                        split_vc.addSplitViewItem(&content_item);
8820                        split_vc.addSplitViewItem(&panel_item);
8821                    }
8822                }
8823                let split = unsafe { split_vc.splitView() };
8824                unsafe {
8825                    split.setVertical(true);
8826                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8827                    // The same Auto Layout hand-back as the nav host below: Day owns this
8828                    // view's frame outside the split; the controller's own constraints keep
8829                    // doing the pane sizing inside it.
8830                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
8831                }
8832                let view = view_of(split);
8833                INSPECTOR_STATE.with(|m| {
8834                    m.borrow_mut().insert(
8835                        ptr_of(&view),
8836                        InspectorState {
8837                            content_wrap,
8838                            panel_wrap,
8839                            _split_vc: split_vc,
8840                            panel_item,
8841                        },
8842                    )
8843                });
8844                view
8845            }
8846            Some(Builtin::InspectorPane) => {
8847                // A DayNavPage for its `setFrameSize:` → `FrameChanged` report: the pane's
8848                // frame is native-owned (the split sizes it), exactly like a nav page —
8849                // NAV_PAGES membership is what makes `set_frame` skip it.
8850                let pane = view_of(DayNavPage::new(mtm, id));
8851                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8852                let panel = props
8853                    .downcast_ref::<InspectorPaneProps>()
8854                    .map(|p| p.panel)
8855                    .unwrap_or(false);
8856                INSPECTOR_PANES.with(|t| t.insert(ptr_of(&pane), panel));
8857                pane
8858            }
8859            Some(Builtin::Split) => {
8860                let (axis, fraction, min_pane) = props
8861                    .downcast_ref::<SplitProps>()
8862                    .map(|p| (p.axis, p.fraction, p.min_pane))
8863                    .unwrap_or((day_spec::props::SplitAxis::Horizontal, 0.5, 80.0));
8864                let wrap = view_of(DayFlipped::new(mtm));
8865                let split = unsafe { objc2_app_kit::NSSplitView::new(mtm) };
8866                let first_wrap = view_of(DayFlipped::new(mtm));
8867                let second_wrap = view_of(DayFlipped::new(mtm));
8868                unsafe {
8869                    // AppKit's "vertical" is the divider's orientation: panes side by side.
8870                    split.setVertical(axis == day_spec::props::SplitAxis::Horizontal);
8871                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
8872                    split.addArrangedSubview(&first_wrap);
8873                    split.addArrangedSubview(&second_wrap);
8874                    split.setFrame(wrap.bounds());
8875                    split.setAutoresizingMask(
8876                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
8877                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
8878                    );
8879                    wrap.addSubview(&split);
8880                }
8881                let delegate = DaySplitDelegate::new(mtm, id, min_pane, fraction);
8882                split.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
8883                SPLIT_STATE.with(|m| {
8884                    m.borrow_mut().insert(
8885                        ptr_of(&wrap),
8886                        SplitState {
8887                            split,
8888                            first_wrap,
8889                            second_wrap,
8890                            delegate,
8891                        },
8892                    )
8893                });
8894                wrap
8895            }
8896            Some(Builtin::SplitPane) => {
8897                // A DayNavPage, as an inspector pane: the splitter owns its frame, and its
8898                // `setFrameSize:` reports `FrameChanged`.
8899                let pane = view_of(DayNavPage::new(mtm, id));
8900                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&pane)));
8901                let second = props
8902                    .downcast_ref::<SplitPaneProps>()
8903                    .map(|p| p.second)
8904                    .unwrap_or(false);
8905                SPLIT_PANES.with(|t| t.insert(ptr_of(&pane), second));
8906                pane
8907            }
8908            Some(Builtin::Nav) => {
8909                let presentation = props
8910                    .downcast_ref::<NavProps>()
8911                    .map(|p| p.presentation)
8912                    .unwrap_or(NavPresentation::Split);
8913                let is_split = presentation.is_split();
8914                // The host is an NSSplitViewController, not a bare NSSplitView. Handing the
8915                // sidebar pane to `NSSplitViewItem::sidebarWithViewController:` is what buys
8916                // the system treatment: AppKit installs its own backing material and vibrancy
8917                // (so no hand-rolled NSVisualEffectView), pins the thickness with a sidebar
8918                // holding priority, animates collapse/expand, and drives the window's titlebar
8919                // separator. Day still owns the CONTENT of each pane — the two wraps below are
8920                // the item view controllers' views, so `insert`/`remove`/the NAV patches are
8921                // unchanged.
8922                let sidebar_wrap = view_of(DayFlipped::new(mtm));
8923                let detail_wrap = view_of(DayFlipped::new(mtm));
8924                let split_vc = unsafe { objc2_app_kit::NSSplitViewController::new(mtm) };
8925                // Force loadView/viewDidLoad before the items go in. NSSplitViewController
8926                // installs an item's view into the split as the item is added, which it can
8927                // only do once its own view exists — and reading `splitView` does not trigger
8928                // the lifecycle the way reading `view` does. Skipping this leaves a split view
8929                // with zero subviews: correct frame, nothing in it.
8930                let _ = unsafe { split_vc.view() };
8931                // Plain NSViewControllers with their view set explicitly: setting `view` up
8932                // front is what stops NSViewController looking for a nib named after itself.
8933                let sidebar_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8934                let detail_vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8935                unsafe {
8936                    sidebar_vc.setView(&pane_under_title_bar(mtm, &sidebar_wrap));
8937                    detail_vc.setView(&pane_under_title_bar(mtm, &detail_wrap));
8938                }
8939                let sidebar_item = unsafe {
8940                    objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&sidebar_vc)
8941                };
8942                let detail_item = unsafe {
8943                    objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&detail_vc)
8944                };
8945                // The content-list pane (docs/navigation.md): a REAL `contentList`
8946                // NSSplitViewItem between the sidebar and the detail — Mail's own machinery,
8947                // holding priorities included. Its `Pane::List` page fills `list_wrap` exactly
8948                // as the sidebar page fills its own wrap, and the pane persists through every
8949                // presentation (only `NavPatch::ListVisible` collapses it).
8950                let list_width = props.downcast_ref::<NavProps>().and_then(|p| p.list_width);
8951                // Set before the item joins the split, exactly as the sidebar's is below. A
8952                // collapsed state applied afterwards — by `NavPatch::ListVisible`, on a window
8953                // that has not been displayed — reports as collapsed and is then laid back out
8954                // from the item's holding priorities, which is how an app whose first
8955                // destination has no list opened with one beside it anyway.
8956                let list_visible = props
8957                    .downcast_ref::<NavProps>()
8958                    .is_none_or(|p| p.list_visible);
8959                let (list_wrap, list_item) = match list_width {
8960                    Some(w) => {
8961                        let wrap = view_of(DayFlipped::new(mtm));
8962                        let vc = unsafe { objc2_app_kit::NSViewController::new(mtm) };
8963                        unsafe { vc.setView(&pane_under_title_bar(mtm, &wrap)) };
8964                        let item = unsafe {
8965                            objc2_app_kit::NSSplitViewItem::contentListWithViewController(&vc)
8966                        };
8967                        unsafe {
8968                            item.setCanCollapse(true);
8969                            item.setMinimumThickness(NAV_LIST_MIN_W.min(w));
8970                            item.setMaximumThickness(NAV_LIST_MAX_W.max(w));
8971                            item.setCollapsed(!list_visible);
8972                        }
8973                        (Some(wrap), Some(item))
8974                    }
8975                    None => (None, None),
8976                };
8977                unsafe {
8978                    // A stack presentation has no sidebar to show: collapse the (empty) pane
8979                    // and refuse the drag, so the detail owns the full width.
8980                    sidebar_item.setCanCollapse(is_split);
8981                    sidebar_item.setCollapsed(!is_split);
8982                    if is_split {
8983                        // Run the sidebar's material to the top of the window, under the
8984                        // titlebar, the way Mail and Finder do. Pairs with the unified toolbar
8985                        // style the window already uses (toolbar.rs).
8986                        sidebar_item.setAllowsFullHeightLayout(true);
8987                        sidebar_item.setMinimumThickness(NAV_SIDEBAR_MIN_W);
8988                        sidebar_item.setMaximumThickness(NAV_SIDEBAR_MAX_W);
8989                    } else {
8990                        sidebar_item.setMinimumThickness(0.0);
8991                        sidebar_item.setMaximumThickness(0.0);
8992                    }
8993                    split_vc.addSplitViewItem(&sidebar_item);
8994                    if let Some(item) = list_item.as_ref() {
8995                        split_vc.addSplitViewItem(item);
8996                    }
8997                    split_vc.addSplitViewItem(&detail_item);
8998                }
8999                let split = unsafe { split_vc.splitView() };
9000                // NSToolbarToggleSidebarItem sends `toggleSidebar:` down the RESPONDER chain,
9001                // and NSSplitViewController implements it — but a view controller only patches
9002                // itself into that chain when it is parented (a window's contentViewController
9003                // or another controller's child), and Day's tree is view-based all the way to
9004                // the window. Insert it by hand, directly after the split view, so a first
9005                // responder anywhere inside either pane walks up through it.
9006                unsafe {
9007                    let after = split.nextResponder();
9008                    split.setNextResponder(Some(&split_vc));
9009                    // The controller must never end up aiming at itself or at its OWN view,
9010                    // or its dealloc aborts the process: `-[NSViewController dealloc]`
9011                    // splices itself out with `view.nextResponder = self.nextResponder`, and
9012                    // if that lands the view on itself AppKit raises "The next responder
9013                    // should never be yourself!" — an NSException that unwinds into Rust and
9014                    // aborts. Both shapes occur here naturally: before macOS 15 the freshly
9015                    // loaded split view's next IS the controller, and on 15+ `view` is a
9016                    // WRAPPER above `splitView` whose auto-wiring makes the split's next
9017                    // that wrapper. Neither is a real upstream hop, so drop them.
9018                    let own_view = split_vc.view();
9019                    let vc_resp: *const objc2_app_kit::NSResponder = {
9020                        let r: &objc2_app_kit::NSResponder = &split_vc;
9021                        r
9022                    };
9023                    let view_resp: *const objc2_app_kit::NSResponder = {
9024                        let r: &objc2_app_kit::NSResponder = &own_view;
9025                        r
9026                    };
9027                    let upstream = after.filter(|a| {
9028                        let p: *const objc2_app_kit::NSResponder = &**a;
9029                        p != vc_resp && p != view_resp
9030                    });
9031                    split_vc.setNextResponder(upstream.as_deref());
9032                }
9033                unsafe {
9034                    split.setVertical(true);
9035                    split.setDividerStyle(objc2_app_kit::NSSplitViewDividerStyle::Thin);
9036                    // Day owns this view's frame (`set_frame`). A split view vended by
9037                    // NSSplitViewController arrives switched over to Auto Layout, which
9038                    // ignores that frame and lays the split out at zero — a window with
9039                    // chrome and nothing under it. Hand it back to autoresizing translation
9040                    // so Day stays the layout owner outside the split; the constraints the
9041                    // controller installs BETWEEN the split and its panes are untouched and
9042                    // keep doing the pane sizing.
9043                    split.setTranslatesAutoresizingMaskIntoConstraints(true);
9044                }
9045                let root_title = props
9046                    .downcast_ref::<NavProps>()
9047                    .map(|p| p.title.clone())
9048                    .unwrap_or_default();
9049                // Stack presentation: a back header (hidden at root) — desktop has no system
9050                // back affordance, so a pushed page needs its own way out (docs/navigation.md).
9051                let header = if presentation == NavPresentation::Stack {
9052                    Some(build_nav_header(mtm, id, &detail_wrap, &root_title))
9053                } else {
9054                    None
9055                };
9056                // A tabs host: the Mac's own tab control fills the detail pane and takes the
9057                // detail pages as its items (`TabHost`).
9058                let tabs = (presentation == NavPresentation::Tabs).then(|| {
9059                    let tv = unsafe { objc2_app_kit::NSTabView::new(mtm) };
9060                    let documents = props
9061                        .downcast_ref::<NavProps>()
9062                        .is_some_and(|p| p.documents.is_some());
9063                    // Inset from the pane, the way a tab view sits in any Mac window: its
9064                    // tabs stand above the bezel, so flush to the top they run into the
9065                    // toolbar's edge, and flush to the sides the bezel hugs the sidebar. The
9066                    // autoresizing mask keeps the margins as the pane resizes. A document host
9067                    // draws no tabs and no bezel, so its pages fill the pane edge to edge.
9068                    let (inset, inset_top) = if documents {
9069                        (0.0, 0.0)
9070                    } else {
9071                        (NAV_TABVIEW_INSET, NAV_TABVIEW_INSET_TOP)
9072                    };
9073                    let b = detail_wrap.bounds();
9074                    let frame = NSRect::new(
9075                        NSPoint::new(inset, inset_top),
9076                        NSSize::new(
9077                            (b.size.width - 2.0 * inset).max(0.0),
9078                            (b.size.height - inset_top - inset).max(0.0),
9079                        ),
9080                    );
9081                    unsafe {
9082                        tv.setTabViewType(if documents {
9083                            objc2_app_kit::NSTabViewType::NoTabsNoBorder
9084                        } else {
9085                            objc2_app_kit::NSTabViewType::TopTabsBezelBorder
9086                        });
9087                        tv.setFrame(frame);
9088                        tv.setAutoresizingMask(
9089                            objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
9090                                | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
9091                        );
9092                        detail_wrap.addSubview(&tv);
9093                    }
9094                    TabHost {
9095                        view: tv,
9096                        target: None,
9097                    }
9098                });
9099                let view = view_of(split);
9100                NAV_STATE.with(|m| {
9101                    m.borrow_mut().insert(
9102                        ptr_of(&view),
9103                        NavState {
9104                            sidebar_wrap,
9105                            detail_wrap,
9106                            _split_vc: split_vc,
9107                            sidebar_item,
9108                            list_wrap,
9109                            list_item,
9110                            pages: Vec::new(),
9111                            list_page: None,
9112                            sidebar_page: None,
9113                            list_width,
9114                            list_visible,
9115                            list_positioned: false,
9116                            positioned: false,
9117                            presentation,
9118                            selected: 0,
9119                            tabs,
9120                            header,
9121                            root_title,
9122                            node: id,
9123                            title_strip: 0.0,
9124                        },
9125                    )
9126                });
9127                view
9128            }
9129            Some(Builtin::NavPage) => {
9130                let page = view_of(DayNavPage::new(mtm, id));
9131                NAV_PAGES.with(|set| set.borrow_mut().insert(ptr_of(&page)));
9132                if let Some(p) = props.downcast_ref::<day_spec::props::NavPageProps>() {
9133                    PAGE_PANE.with(|t| t.insert(ptr_of(&page), p.pane));
9134                }
9135                page
9136            }
9137            // Emulated fullscreen cover (docs/cover.md, the ArkUI tier): a DayNavPage — its
9138            // setFrameSize: override reports FrameChanged, so a window resize re-lays the cover
9139            // content for free — parked hidden until CoverPatch::Present re-homes it on top.
9140            Some(Builtin::Cover) => {
9141                let page = DayNavPage::new(mtm, id);
9142                let cover_props = props.downcast_ref::<CoverProps>();
9143                // A half sheet is a sheet here: macOS has no half-height presentation of its
9144                // own, so the window sheet stands in, at half the parent's height.
9145                page.ivars()
9146                    .sheet
9147                    .set(cover_props.is_some_and(|p| p.sheet || p.half));
9148                page.ivars().half.set(cover_props.is_some_and(|p| p.half));
9149                page.ivars().large.set(cover_props.is_some_and(|p| p.large));
9150                unsafe { page.setHidden(true) };
9151                view_of(page)
9152            }
9153            Some(Builtin::NavMenu) => {
9154                let Some(p) = props_of::<NavMenuProps>(kind, "appkit", props) else {
9155                    return placeholder_view(mtm, kind);
9156                };
9157                let data = DayNavMenuData::new(
9158                    mtm,
9159                    id,
9160                    &p.items,
9161                    &p.icons,
9162                    &p.badges,
9163                    &p.badge_icons,
9164                    &p.badge_tints,
9165                    &p.sections,
9166                    &p.tints,
9167                    &p.menus,
9168                );
9169                *data.ivars().movable.borrow_mut() = p.movable.clone();
9170                data.ivars().regroup.set(p.regroup);
9171                *data.ivars().sorted.borrow_mut() = p.sorted.clone();
9172                // The Day subclass serves per-row context menus via menuForEvent:.
9173                let outline: Retained<objc2_app_kit::NSOutlineView> = {
9174                    let o: Retained<DayNavOutlineView> =
9175                        unsafe { msg_send![DayNavOutlineView::alloc(mtm), init] };
9176                    NAV_OUTLINE_MENUS
9177                        .with(|t| t.insert(Retained::as_ptr(&o) as usize, data.clone()));
9178                    unsafe { msg_send![&*o, self] }
9179                };
9180                let col = unsafe {
9181                    objc2_app_kit::NSTableColumn::initWithIdentifier(
9182                        objc2_app_kit::NSTableColumn::alloc(mtm),
9183                        &NSString::from_str("item"),
9184                    )
9185                };
9186                unsafe {
9187                    outline.addTableColumn(&col);
9188                    outline.setOutlineTableColumn(Some(&col));
9189                    outline.setHeaderView(None);
9190                    // SourceList: the real sidebar treatment (Finder/Mail). The outline now
9191                    // lives inside a sidebar NSSplitViewItem, so AppKit supplies the backing
9192                    // material and the vibrancy the source-list selection composites through.
9193                    // This was Inset until 2026-08 because the earlier hand-rolled
9194                    // NSVisualEffectView blended behind the window, and an offscreen capture
9195                    // (`cacheDisplayInRect`) has no backdrop to sample — the selection came out
9196                    // a black pill that swallowed the row label. The material is AppKit's own
9197                    // now, and captures go through the window server (`snapshot_view`), which
9198                    // composites the material for real instead of guessing at it.
9199                    // `style = SourceList` is the whole switch: the matching
9200                    // `selectionHighlightStyle` constant is deprecated precisely because the
9201                    // style property now implies it.
9202                    outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
9203                    // The default row size style follows the system's Sidebar icon size
9204                    // (Small, Medium, Large), live, as Finder's and Mail's sidebars do: AppKit
9205                    // sets the row height, the label's font and the icon's size. A table made
9206                    // in code starts at Custom, which ignores the setting.
9207                    outline.setRowSizeStyle(objc2_app_kit::NSTableViewRowSizeStyle::Default);
9208                    // Section headers pin to the top of the scroll as their group passes under
9209                    // it, the way Finder's sidebar groups do.
9210                    outline.setFloatsGroupRows(true);
9211                    outline.setIndentationPerLevel(0.0);
9212                    // Drag-to-reorder within this sidebar only (docs/navigation.md): rows that
9213                    // cannot move offer no drag, so registering costs a plain sidebar nothing.
9214                    outline.registerForDraggedTypes(
9215                        &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9216                            DAY_NAV_PASTEBOARD_TYPE,
9217                        )]),
9218                    );
9219                    outline.setDraggingSourceOperationMask_forLocal(
9220                        objc2_app_kit::NSDragOperation::Move,
9221                        true,
9222                    );
9223                    outline.setDraggingSourceOperationMask_forLocal(
9224                        objc2_app_kit::NSDragOperation::None,
9225                        false,
9226                    );
9227                    outline.setDraggingDestinationFeedbackStyle(
9228                        objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
9229                    );
9230                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9231                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9232                    outline.reloadData();
9233                }
9234                let scroll = unsafe { NSScrollView::new(mtm) };
9235                unsafe {
9236                    scroll.setDrawsBackground(false);
9237                    scroll.setHasVerticalScroller(true);
9238                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
9239                    // clip the trailing edge of rows laid out at the full frame width (see
9240                    // the SCROLL realize).
9241                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9242                    // One column, sized to the pane: a sidebar never scrolls sideways.
9243                    scroll.setHasHorizontalScroller(false);
9244                    outline.setAutoresizingMask(
9245                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
9246                    );
9247                    outline.setColumnAutoresizingStyle(
9248                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9249                    );
9250                    scroll.setDocumentView(Some(&outline));
9251                }
9252                let view = view_of(scroll);
9253                // Day selects by ITEM index; section headers make that differ from the
9254                // outline's row index, so every programmatic selection maps through `rows`.
9255                if let Some(row) = p.selected.and_then(|sel| data.row_of_item(sel)) {
9256                    data.ivars().suppress.set(true);
9257                    unsafe {
9258                        outline.selectRowIndexes_byExtendingSelection(
9259                            &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9260                            false,
9261                        )
9262                    };
9263                    data.ivars().suppress.set(false);
9264                }
9265                NAV_MENUS.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
9266                view
9267            }
9268            Some(Builtin::List) => {
9269                let Some(p) = props_of::<ListProps>(kind, "appkit", props) else {
9270                    return placeholder_view(mtm, kind);
9271                };
9272                // Every list reports responder changes, even without an activation handler.
9273                let table: Retained<DayListView> =
9274                    unsafe { msg_send![DayListView::alloc(mtm), init] };
9275                let table = Retained::into_super(table);
9276                if p.inset_grouped {
9277                    // macOS 11's inset style: rows set in from the edges with rounded selection,
9278                    // the grouped look `ListProps::inset_grouped` asks for.
9279                    unsafe { table.setStyle(objc2_app_kit::NSTableViewStyle::Inset) };
9280                }
9281                let col = unsafe {
9282                    NSTableColumn::initWithIdentifier(
9283                        NSTableColumn::alloc(mtm),
9284                        &NSString::from_str("day.list.col"),
9285                    )
9286                };
9287                let data = DayListData::new(
9288                    mtm,
9289                    id,
9290                    p.selectable,
9291                    p.multi_select,
9292                    p.row_height == RowHeight::Automatic,
9293                    p.sections,
9294                );
9295                unsafe {
9296                    if p.multi_select {
9297                        table.setAllowsMultipleSelection(true);
9298                    }
9299                    table.addTableColumn(&col);
9300                    table.setHeaderView(None);
9301                    // PLAIN, the classic edge-to-edge style: the macOS 11+ decorated styles
9302                    // (automatic ~14pt, FullWidth ~6pt) inset every cell view, clipping day
9303                    // row content laid out at the host's full frame width. This table ran
9304                    // FullWidth with a custom NSTableRowView pinning cells back to the row
9305                    // bounds until 2026-08 — and that pin also clobbered the cell-frame slide
9306                    // AppKit performs for row-action swipes, so the actions revealed behind a
9307                    // row whose CONTENT never moved. Plain has no inset to fight: standard
9308                    // row views, standard cell frames, and the swipe slide works untouched.
9309                    table.setStyle(objc2_app_kit::NSTableViewStyle::Plain);
9310                    // ...and the default intercell spacing (3pt × 2pt) shaves the column the
9311                    // same way — the last few points of a trailing control. Day rows own all
9312                    // of their spacing.
9313                    table.setIntercellSpacing(NSSize::new(0.0, 0.0));
9314                    // Host-drawn row separators (docs/list.md): the native horizontal grid
9315                    // line, which sits exactly at the row boundary — aligned with the
9316                    // selection, stationary under a row-action swipe, the Mail look.
9317                    if p.separators == Some(true) {
9318                        table.setGridStyleMask(
9319                            objc2_app_kit::NSTableViewGridLineStyle::SolidHorizontalGridLineMask,
9320                        );
9321                        table.setGridColor(&objc2_app_kit::NSColor::separatorColor());
9322                    }
9323                    table.setColumnAutoresizingStyle(
9324                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9325                    );
9326                    // Section headers pin to the top while their section scrolls under them,
9327                    // the way Mail's and Finder's group rows do (docs/list.md "Sections").
9328                    table.setFloatsGroupRows(p.sections);
9329                    match p.row_height {
9330                        RowHeight::Uniform(h) => table.setRowHeight(h),
9331                        RowHeight::Automatic => table.setRowHeight(44.0),
9332                    }
9333                    if !p.selectable {
9334                        table.setSelectionHighlightStyle(
9335                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
9336                        );
9337                    }
9338                    // Transparent: day panes own their backgrounds — the stock
9339                    // controlBackgroundColor would paint an appearance-colored slab that
9340                    // fights a themed app (visible whenever rows don't fill the viewport).
9341                    table.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
9342                    table.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9343                    table.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9344                    table.setTarget(Some(&*data));
9345                    if p.activatable {
9346                        table.setDoubleAction(Some(sel!(doubleClickRow:)));
9347                    }
9348                    if p.reorderable {
9349                        // Native drag-to-reorder (docs/list.md): rows drag within this table
9350                        // only (move locally, nothing leaves the app), and the drop target shows
9351                        // macOS's temporary placeholder GAP while the drag is over the table.
9352                        table.registerForDraggedTypes(
9353                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9354                                DAY_ROW_PASTEBOARD_TYPE,
9355                            )]),
9356                        );
9357                        table.setDraggingSourceOperationMask_forLocal(
9358                            objc2_app_kit::NSDragOperation::Move,
9359                            true,
9360                        );
9361                        table.setDraggingSourceOperationMask_forLocal(
9362                            objc2_app_kit::NSDragOperation::None,
9363                            false,
9364                        );
9365                        table.setDraggingDestinationFeedbackStyle(
9366                            objc2_app_kit::NSTableViewDraggingDestinationFeedbackStyle::Gap,
9367                        );
9368                    }
9369                }
9370                let scroll = unsafe { NSScrollView::new(mtm) };
9371                unsafe {
9372                    scroll.setDrawsBackground(false);
9373                    scroll.setHasVerticalScroller(true);
9374                    // Overlay scrollers always — a legacy scroller would reserve ~15pt and
9375                    // clip the trailing edge of rows laid out at the full frame width (see
9376                    // the SCROLL realize).
9377                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9378                    scroll.setDocumentView(Some(&table));
9379                    let clip = scroll.contentView();
9380                    clip.setPostsBoundsChangedNotifications(true);
9381                    objc2_foundation::NSNotificationCenter::defaultCenter()
9382                        .addObserver_selector_name_object(
9383                            &data,
9384                            sel!(listViewportChanged:),
9385                            Some(objc2_app_kit::NSViewBoundsDidChangeNotification),
9386                            Some(&clip),
9387                        );
9388                }
9389                let view = view_of(scroll);
9390                LIST_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (table, data)));
9391                view
9392            }
9393            Some(Builtin::Tree) => {
9394                let Some(p) = props_of::<TreeProps>(kind, "appkit", props) else {
9395                    return placeholder_view(mtm, kind);
9396                };
9397                // The width-pinning subclass (see DayOutlineView).
9398                let outline: Retained<objc2_app_kit::NSOutlineView> = {
9399                    let o: Retained<DayOutlineView> =
9400                        unsafe { msg_send![DayOutlineView::alloc(mtm), init] };
9401                    unsafe { msg_send![&*o, self] }
9402                };
9403                let col = unsafe {
9404                    NSTableColumn::initWithIdentifier(
9405                        NSTableColumn::alloc(mtm),
9406                        &NSString::from_str("day.tree.col"),
9407                    )
9408                };
9409                let data = DayTreeData::new(mtm, id, p.selectable);
9410                unsafe {
9411                    if p.multi_select {
9412                        outline.setAllowsMultipleSelection(true);
9413                    }
9414                    outline.addTableColumn(&col);
9415                    outline.setOutlineTableColumn(Some(&col));
9416                    outline.setHeaderView(None);
9417                    if p.section_headers {
9418                        // Real source-list groups use AppKit's trailing, hover-revealed
9419                        // show/hide button and float over their children while scrolling.
9420                        outline.setStyle(objc2_app_kit::NSTableViewStyle::SourceList);
9421                        outline.setFloatsGroupRows(true);
9422                    } else {
9423                        // Generic trees keep their existing full-width cells and rounded
9424                        // DayTreeRowView selection. Source lists use native row drawing.
9425                        outline.setStyle(objc2_app_kit::NSTableViewStyle::FullWidth);
9426                        outline.setIntercellSpacing(NSSize::new(0.0, 0.0));
9427                    }
9428                    outline.setColumnAutoresizingStyle(
9429                        objc2_app_kit::NSTableViewColumnAutoresizingStyle::UniformColumnAutoresizingStyle,
9430                    );
9431                    outline.setAutoresizesOutlineColumn(true);
9432                    if let Some(indent) = p.indent {
9433                        outline.setIndentationPerLevel(indent);
9434                    }
9435                    match p.row_height {
9436                        RowHeight::Uniform(h) => outline.setRowHeight(h),
9437                        RowHeight::Automatic if !p.section_headers => outline.setRowHeight(24.0),
9438                        RowHeight::Automatic => {}
9439                    }
9440                    if !p.selectable {
9441                        outline.setSelectionHighlightStyle(
9442                            objc2_app_kit::NSTableViewSelectionHighlightStyle::None,
9443                        );
9444                    }
9445                    outline.setBackgroundColor(&objc2_app_kit::NSColor::clearColor());
9446                    outline.setDataSource(Some(ProtocolObject::from_ref(&*data)));
9447                    outline.setDelegate(Some(ProtocolObject::from_ref(&*data)));
9448                    if p.movable {
9449                        // Native drag-to-move (docs/tree.md): nodes drag within this outline
9450                        // only. The REGULAR feedback style (not the list's Gap): a tree drop
9451                        // must distinguish "between rows" (insertion line) from "ONTO a row"
9452                        // (the highlighted-parent drop), and Gap has no onto affordance.
9453                        outline.registerForDraggedTypes(
9454                            &objc2_foundation::NSArray::from_retained_slice(&[NSString::from_str(
9455                                DAY_TREE_PASTEBOARD_TYPE,
9456                            )]),
9457                        );
9458                        outline.setDraggingSourceOperationMask_forLocal(
9459                            objc2_app_kit::NSDragOperation::Move,
9460                            true,
9461                        );
9462                        outline.setDraggingSourceOperationMask_forLocal(
9463                            objc2_app_kit::NSDragOperation::None,
9464                            false,
9465                        );
9466                    }
9467                }
9468                let scroll = unsafe { NSScrollView::new(mtm) };
9469                unsafe {
9470                    scroll.setDrawsBackground(false);
9471                    scroll.setHasVerticalScroller(true);
9472                    scroll.setHasHorizontalScroller(false);
9473                    scroll.setScrollerStyle(objc2_app_kit::NSScrollerStyle::Overlay);
9474                    outline.setAutoresizingMask(
9475                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable,
9476                    );
9477                    scroll.setDocumentView(Some(&outline));
9478                }
9479                let view = view_of(scroll);
9480                TREE_STATE.with(|m| m.borrow_mut().insert(ptr_of(&view), (outline, data)));
9481                view
9482            }
9483            Some(Builtin::Image) => {
9484                let Some(p) = props_of::<ImageProps>(kind, "appkit", props) else {
9485                    return placeholder_view(mtm, kind);
9486                };
9487                let iv: Retained<objc2_app_kit::NSImageView> =
9488                    if p.content_mode == ContentMode::Fill {
9489                        let view: Retained<FillImageView> =
9490                            unsafe { msg_send![FillImageView::alloc(mtm), init] };
9491                        Retained::from(
9492                            <FillImageView as AsRef<objc2_app_kit::NSImageView>>::as_ref(&view),
9493                        )
9494                    } else {
9495                        unsafe { objc2_app_kit::NSImageView::new(mtm) }
9496                    };
9497                // Fill expands the native aspect-fit drawing in FillImageView; Stretch
9498                // scales each axis independently, and Fit keeps the stock image view.
9499                let scaling = match p.content_mode {
9500                    ContentMode::Stretch => objc2_app_kit::NSImageScaling::ScaleAxesIndependently,
9501                    _ => objc2_app_kit::NSImageScaling::ScaleProportionallyUpOrDown,
9502                };
9503                unsafe { iv.setImageScaling(scaling) };
9504                if let Some(img) = appkit_image_for(&p.source) {
9505                    // Vector-glyph tint (docs/vectors.md): template rendering + the view's
9506                    // content tint — AppKit recolors the alpha mask natively. A template with
9507                    // no tint keeps the view's nil tint: the neutral template color the nav
9508                    // menu's own rows draw with, light in dark mode, dark in light.
9509                    if p.tint.is_some() || p.template {
9510                        unsafe { img.setTemplate(true) };
9511                    }
9512                    unsafe { iv.setImage(Some(&img)) };
9513                }
9514                if let Some(t) = p.tint {
9515                    unsafe { iv.setContentTintColor(Some(&nscolor(t))) };
9516                }
9517                IMAGE_MODES.with(|t| {
9518                    t.insert(
9519                        ptr_of(&iv),
9520                        ImageMode {
9521                            template: p.template,
9522                            tinted: p.tint.is_some(),
9523                        },
9524                    )
9525                });
9526                view_of(iv)
9527            }
9528            Some(Builtin::ListItem) => {
9529                let Some(p) = props_of::<day_spec::props::ListItemProps>(kind, "appkit", props)
9530                else {
9531                    return placeholder_view(mtm, kind);
9532                };
9533                make_list_item(p, mtm)
9534            }
9535            // A recycled list cell is ADOPTED from the native list, never realized
9536            // through this path; anything else is an extension piece.
9537            Some(Builtin::ListCell) | None => {
9538                if let Some(make) = self.registry.get(kind).map(|r| r.make) {
9539                    return make(self, props, id);
9540                }
9541                // Unregistered kind: LOUD once-per-kind warning, then a visible-but-harmless
9542                // placeholder (§8.2's debug check will panic first in debug builds once the
9543                // required-kinds set lands).
9544                warn_missing_renderer(kind);
9545                placeholder_view(mtm, kind)
9546            }
9547        }
9548    }
9549
9550    fn update(&mut self, h: &Handle, kind: PieceKind, patch: &dyn Any, _anim: Option<&AnimSpec>) {
9551        match kind {
9552            kinds::LIST_ITEM => {
9553                let Some(p) = patch.downcast_ref::<day_spec::props::ListItemPatch>() else {
9554                    return;
9555                };
9556                let props = LIST_ITEMS.with(|m| {
9557                    let mut m = m.borrow_mut();
9558                    let props = m.get_mut(&ptr_of(h))?;
9559                    use day_spec::props::ListItemPatch as P;
9560                    match p {
9561                        P::Title(t) => props.title = t.clone(),
9562                        P::Subtitle(t) => props.subtitle = t.clone(),
9563                        P::Detail(t) => props.detail = t.clone(),
9564                        P::Icon(i) => props.icon = i.clone(),
9565                        P::IconTint(c) => props.icon_tint = *c,
9566                        P::Checked(on) => props.checked = *on,
9567                    }
9568                    Some(props.clone())
9569                });
9570                if let Some(props) = props {
9571                    dress_list_item(h, &props, self.mtm());
9572                }
9573            }
9574            kinds::IMAGE => {
9575                if let Some(p) = patch.downcast_ref::<day_spec::props::ImagePatch>() {
9576                    match p {
9577                        day_spec::props::ImagePatch::Tint(c) => {
9578                            // Template rendering + the view's content tint, exactly as at realize
9579                            // — the glyph repaints in place rather than being rebuilt
9580                            // (docs/vectors.md). A template glyph stays one when the tint goes.
9581                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
9582                                let key = ptr_of(&iv);
9583                                let template = IMAGE_MODES
9584                                    .with(|t| {
9585                                        t.with(key, |m| {
9586                                            m.tinted = c.is_some();
9587                                            m.renders_template()
9588                                        })
9589                                    })
9590                                    .unwrap_or(c.is_some());
9591                                if let Some(img) = unsafe { iv.image() } {
9592                                    unsafe { img.setTemplate(template) };
9593                                }
9594                                unsafe { iv.setContentTintColor(c.map(nscolor).as_deref()) };
9595                            }
9596                        }
9597                        // A source swap repaints the same view (docs/images.md), so an `image()`
9598                        // bound to a signal shows new pixels without rebuilding its subtree —
9599                        // which is what makes a decode-then-show flow a patch and not a rebuild.
9600                        day_spec::props::ImagePatch::Source(source) => {
9601                            if let Ok(iv) = h.clone().downcast::<objc2_app_kit::NSImageView>() {
9602                                // A source that will not load leaves the view showing what it
9603                                // was — the patch's contract, and what GTK, Qt and Android do.
9604                                // The new image renders the way the view does: a tinted or
9605                                // template glyph stays one, so a recycled sidebar row shows the
9606                                // icon it was rebound to in the same color.
9607                                if let Some(img) = appkit_image_for(source) {
9608                                    let template = IMAGE_MODES
9609                                        .with(|t| t.get(ptr_of(&iv)))
9610                                        .is_some_and(|m| m.renders_template());
9611                                    unsafe {
9612                                        img.setTemplate(template);
9613                                        iv.setImage(Some(&img));
9614                                    }
9615                                }
9616                            }
9617                        }
9618                    }
9619                }
9620            }
9621            kinds::CONTAINER => {
9622                if let (Some(ContainerPatch::Background(c)), Ok(v)) = (
9623                    patch.downcast_ref::<ContainerPatch>(),
9624                    h.clone().downcast::<DayFlipped>(),
9625                ) {
9626                    // A background patch only targets a background container (corner radius 0).
9627                    // The AnimSpec is not honored: the fill is drawRect content
9628                    // (rasterized by our own drawing code so dynamic system colors re-resolve
9629                    // per appearance), not a CALayer property, and Core Animation only
9630                    // interpolates layer properties, so there is nothing for the render server
9631                    // to tween. Day animates only what the toolkit's animator can execute
9632                    // (§8.4), so an animated background change applies at commit here.
9633                    v.set_surface(*c, 0.0, false);
9634                }
9635            }
9636            kinds::LABEL => {
9637                if let (Some(p), Ok(tf)) = (
9638                    patch.downcast_ref::<LabelPatch>(),
9639                    h.clone().downcast::<NSTextField>(),
9640                ) {
9641                    match p {
9642                        LabelPatch::Text(t) => {
9643                            unsafe { tf.setStringValue(&NSString::from_str(t)) };
9644                            if let Some(label) = h.downcast_ref::<DayLabel>() {
9645                                label.ivars().has_runs.set(false);
9646                                label.set_links(false);
9647                            }
9648                        }
9649                        LabelPatch::Color(c) => unsafe {
9650                            tf.setTextColor(c.map(nscolor).as_deref())
9651                        },
9652                        LabelPatch::Font(f) => unsafe { tf.setFont(Some(&nsfont(*f))) },
9653                        LabelPatch::Runs(text, runs) => {
9654                            // The field's current font is the base the runs sit on, taken as the
9655                            // live object rather than rebuilt from a `FontSpec`, which would lose
9656                            // the semantic style behind the resolved size.
9657                            let base = unsafe { tf.font() };
9658                            let s = match base.as_deref() {
9659                                Some(f) => {
9660                                    attributed_label(text, f, None, Default::default(), runs)
9661                                }
9662                                None => attributed_label(
9663                                    text,
9664                                    &nsfont(day_spec::FontSpec::default()),
9665                                    None,
9666                                    Default::default(),
9667                                    runs,
9668                                ),
9669                            };
9670                            unsafe { tf.setAttributedStringValue(&s) };
9671                            // Preserve paragraph alignment and activate links introduced by a
9672                            // reactive markdown update without replacing the native label.
9673                            set_paragraph_alignment(&tf, unsafe { tf.alignment() });
9674                            if let Some(label) = h.downcast_ref::<DayLabel>() {
9675                                label.ivars().has_runs.set(!runs.is_empty());
9676                                label.set_links(runs.iter().any(|r| r.link.is_some()));
9677                            }
9678                        }
9679                    }
9680                }
9681            }
9682            kinds::BUTTON => {
9683                if let (Some(p), Ok(btn)) = (
9684                    patch.downcast_ref::<ButtonPatch>(),
9685                    h.clone().downcast::<NSButton>(),
9686                ) {
9687                    match p {
9688                        ButtonPatch::Content(c) => {
9689                            apply_button_content(&btn, &c.title, c.icon.as_ref(), c.icon_only)
9690                        }
9691                        ButtonPatch::Title(t) => {
9692                            let style = BUTTON_STYLES
9693                                .with(|m| m.borrow().get(&ptr_of(&btn)).copied())
9694                                .unwrap_or_default();
9695                            set_button_title(&btn, t, style);
9696                        }
9697                        ButtonPatch::Enabled(e) => unsafe { btn.setEnabled(*e) },
9698                        ButtonPatch::Selected(on) => set_button_selected(&btn, *on),
9699                        ButtonPatch::Style(s) => apply_button_style(&btn, *s),
9700                    }
9701                }
9702            }
9703            kinds::TOGGLE => {
9704                if let (Some(p), Ok(sw)) = (
9705                    patch.downcast_ref::<TogglePatch>(),
9706                    h.clone().downcast::<NSSwitch>(),
9707                ) {
9708                    match p {
9709                        TogglePatch::On(on) => {
9710                            let want = if *on { 1 } else { 0 };
9711                            if unsafe { sw.state() } != want {
9712                                unsafe { sw.setState(want) };
9713                            }
9714                        }
9715                        TogglePatch::Enabled(e) => unsafe { sw.setEnabled(*e) },
9716                    }
9717                }
9718            }
9719            kinds::SLIDER => {
9720                if let (Some(p), Ok(sl)) = (
9721                    patch.downcast_ref::<SliderPatch>(),
9722                    h.clone().downcast::<NSSlider>(),
9723                ) {
9724                    match p {
9725                        SliderPatch::Value(v) => {
9726                            if (unsafe { sl.doubleValue() } - v).abs() > 0.001 {
9727                                unsafe { sl.setDoubleValue(*v) };
9728                            }
9729                        }
9730                        SliderPatch::Enabled(e) => unsafe { sl.setEnabled(*e) },
9731                    }
9732                }
9733            }
9734            kinds::PROGRESS => {
9735                if let Some(p @ ProgressPatch::Animating(_)) = patch.downcast_ref::<ProgressPatch>()
9736                {
9737                    crate::controls::spinner::update(self, h, p);
9738                    return;
9739                }
9740
9741                if let (Some(ProgressPatch::Value(v)), Ok(pi)) = (
9742                    patch.downcast_ref::<ProgressPatch>(),
9743                    h.clone().downcast::<NSProgressIndicator>(),
9744                ) {
9745                    unsafe {
9746                        match v {
9747                            Some(val) => {
9748                                if pi.isIndeterminate() {
9749                                    pi.stopAnimation(None);
9750                                    pi.setIndeterminate(false);
9751                                    pi.setStyle(NSProgressIndicatorStyle::Bar);
9752                                    pi.setMinValue(0.0);
9753                                    pi.setMaxValue(1.0);
9754                                }
9755                                if (pi.doubleValue() - val).abs() > 0.0001 {
9756                                    pi.setDoubleValue(*val);
9757                                }
9758                            }
9759                            None => {
9760                                pi.setIndeterminate(true);
9761                                pi.setStyle(NSProgressIndicatorStyle::Spinning);
9762                                pi.startAnimation(None);
9763                            }
9764                        }
9765                    }
9766                }
9767            }
9768            kinds::NAV_MENU => {
9769                if let Some(NavMenuPatch::Items {
9770                    items,
9771                    icons,
9772                    badges,
9773                    badge_icons,
9774                    badge_tints,
9775                    sections,
9776                    tints,
9777                    menus,
9778                    movable,
9779                    sorted,
9780                    selected,
9781                    rows_changed,
9782                    ..
9783                }) = patch.downcast_ref::<NavMenuPatch>()
9784                {
9785                    NAV_MENUS.with(|m| {
9786                        let m = m.borrow();
9787                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
9788                            return;
9789                        };
9790                        *data.ivars().movable.borrow_mut() = movable.clone();
9791                        *data.ivars().sorted.borrow_mut() = sorted.clone();
9792                        data.set_items(
9793                            items,
9794                            icons,
9795                            badges,
9796                            badge_icons,
9797                            badge_tints,
9798                            sections,
9799                            tints,
9800                            menus,
9801                        );
9802                        data.ivars().suppress.set(true);
9803                        // The same rows with new words or counts: reload just those rows, which
9804                        // keeps the selection and every other row's view.
9805                        if let Some(rows) = rows_changed {
9806                            let set = objc2_foundation::NSMutableIndexSet::new();
9807                            for row in rows.iter().filter_map(|i| data.row_of_item(*i)) {
9808                                unsafe { set.addIndex(row) };
9809                            }
9810                            unsafe {
9811                                outline.reloadDataForRowIndexes_columnIndexes(
9812                                    &set,
9813                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(0),
9814                                )
9815                            };
9816                            data.ivars().suppress.set(false);
9817                            return;
9818                        }
9819                        unsafe {
9820                            outline.reloadData();
9821                            match selected.and_then(|i| data.row_of_item(i)) {
9822                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
9823                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9824                                    false,
9825                                ),
9826                                None => outline.deselectAll(None),
9827                            }
9828                        }
9829                        data.ivars().suppress.set(false);
9830                    });
9831                    // The rows are a tabs host's labels where the menu sits in one.
9832                    adopt_menu_for_tabs(self.mtm(), h);
9833                } else if let Some(NavMenuPatch::IconProgress(progress)) =
9834                    patch.downcast_ref::<NavMenuPatch>()
9835                {
9836                    NAV_MENUS.with(|menus| {
9837                        let menus = menus.borrow();
9838                        let Some((outline, data)) = menus.get(&ptr_of(h)) else {
9839                            return;
9840                        };
9841                        let previous = data.ivars().icon_progress.replace(progress.clone());
9842                        for (row, item) in data.ivars().rows.borrow().iter().enumerate() {
9843                            let Some(index) = item else {
9844                                continue;
9845                            };
9846                            let value = progress.iter().find(|(i, _)| i == index).map(|(_, v)| *v);
9847                            if previous.iter().find(|(i, _)| i == index).map(|(_, v)| *v) == value {
9848                                continue;
9849                            }
9850                            if let Some(view) = unsafe {
9851                                outline.viewAtColumn_row_makeIfNecessary(0, row as isize, false)
9852                            } && let Some(cell) =
9853                                view.downcast_ref::<objc2_app_kit::NSTableCellView>()
9854                                && let Some(icon) = unsafe { cell.imageView() }
9855                            {
9856                                nav_progress::update(&icon, value);
9857                            }
9858                        }
9859                    });
9860                } else if let Some(NavMenuPatch::Selected(sel)) =
9861                    patch.downcast_ref::<NavMenuPatch>()
9862                {
9863                    NAV_MENUS.with(|m| {
9864                        let m = m.borrow();
9865                        let Some((outline, data)) = m.get(&ptr_of(h)) else {
9866                            return;
9867                        };
9868                        data.ivars().suppress.set(true);
9869                        unsafe {
9870                            match sel.and_then(|i| data.row_of_item(i)) {
9871                                Some(row) => outline.selectRowIndexes_byExtendingSelection(
9872                                    &objc2_foundation::NSIndexSet::indexSetWithIndex(row),
9873                                    false,
9874                                ),
9875                                None => outline.deselectAll(None),
9876                            }
9877                        }
9878                        data.ivars().suppress.set(false);
9879                    });
9880                }
9881            }
9882            kinds::INSPECTOR => {
9883                if let Some(InspectorPatch::Visible(v)) = patch.downcast_ref::<InspectorPatch>() {
9884                    INSPECTOR_STATE.with(|m| {
9885                        if let Some(state) = m.borrow().get(&ptr_of(h)) {
9886                            // Directly, not through the animator proxy: a screenshot must not
9887                            // catch a mid-animation pane (the sidebar-toggle rule).
9888                            state.panel_item.setCollapsed(!*v);
9889                        }
9890                    });
9891                }
9892            }
9893            kinds::SPLIT => {
9894                if let Some(p) = patch.downcast_ref::<SplitPatch>() {
9895                    SPLIT_STATE.with(|m| {
9896                        let m = m.borrow();
9897                        let Some(state) = m.get(&ptr_of(h)) else {
9898                            return;
9899                        };
9900                        let iv = state.delegate.ivars();
9901                        match p {
9902                            SplitPatch::Fraction(f) => {
9903                                iv.share.set(f.clamp(0.0, 1.0));
9904                                if iv.positioned.get() {
9905                                    split_place(&state.split, iv);
9906                                }
9907                            }
9908                            SplitPatch::Axis(axis) => unsafe {
9909                                state
9910                                    .split
9911                                    .setVertical(*axis == day_spec::props::SplitAxis::Horizontal);
9912                                state.split.adjustSubviews();
9913                                if iv.positioned.get() {
9914                                    split_place(&state.split, iv);
9915                                }
9916                            },
9917                        }
9918                    });
9919                }
9920            }
9921            kinds::NAV => {
9922                if let Some(NavPatch::Presentation(next)) = patch.downcast_ref::<NavPatch>() {
9923                    nav_present(self.mtm(), h, *next);
9924                    return;
9925                }
9926                if let Some(p) = patch.downcast_ref::<NavPatch>() {
9927                    NAV_STATE.with(|m| {
9928                        let mut m = m.borrow_mut();
9929                        let Some(state) = m.get_mut(&ptr_of(h)) else {
9930                            return;
9931                        };
9932                        match p {
9933                            NavPatch::Pushed { title, .. } => {
9934                                // Only the new top detail page stays visible.
9935                                let last = state.pages.len().saturating_sub(1);
9936                                state.selected = last;
9937                                for (i, page) in state.pages.iter().enumerate() {
9938                                    page.setHidden(i != last);
9939                                }
9940                                if let Some(hdr) = state.header.as_mut() {
9941                                    hdr.titles.push(title.clone());
9942                                    sync_nav_header(hdr, &state.detail_wrap, &state.pages);
9943                                }
9944                            }
9945                            NavPatch::Popped => {
9946                                // Hide the outgoing top; reveal its predecessor (Day
9947                                // removes the popped page right after this patch).
9948                                let n = state.pages.len();
9949                                if let Some(top) = state.pages.last() {
9950                                    top.setHidden(true);
9951                                }
9952                                if n >= 2 {
9953                                    state.pages[n - 2].setHidden(false);
9954                                }
9955                                state.selected = n.saturating_sub(2);
9956                                if let Some(hdr) = state.header.as_mut() {
9957                                    if hdr.titles.len() > 1 {
9958                                        hdr.titles.pop();
9959                                    }
9960                                    // The popped page is still in `pages` here (Day removes
9961                                    // it right after this patch), so frame for depth-after-pop.
9962                                    let after: Vec<Retained<NSView>> = state
9963                                        .pages
9964                                        .iter()
9965                                        .take(n.saturating_sub(1))
9966                                        .cloned()
9967                                        .collect();
9968                                    sync_nav_header(hdr, &state.detail_wrap, &after);
9969                                }
9970                            }
9971                            NavPatch::Title(t) => {
9972                                if let Some(hdr) = state.header.as_mut() {
9973                                    if let Some(last) = hdr.titles.last_mut() {
9974                                        *last = t.clone();
9975                                    }
9976                                    unsafe {
9977                                        hdr.title.setStringValue(&NSString::from_str(t));
9978                                    }
9979                                }
9980                            }
9981                            // The custom back header always routes back through Day
9982                            // (NavBack{already_popped:false}), so there is no native auto-pop to
9983                            // suppress; the guard runs in the pieces layer (docs/navigation.md).
9984                            NavPatch::GuardTop(_) => {}
9985                            NavPatch::Reorder(order) => {
9986                                let old = state.pages.clone();
9987                                state.pages =
9988                                    order.iter().filter_map(|i| old.get(*i).cloned()).collect();
9989                                if let Some(tabs) = &state.tabs {
9990                                    TAB_PICK_SUPPRESS.with(|s| s.set(true));
9991                                    unsafe {
9992                                        let items = tabs.view.tabViewItems();
9993                                        for item in items.iter() {
9994                                            tabs.view.removeTabViewItem(&item);
9995                                        }
9996                                        for i in order {
9997                                            if let Some(item) = items.iter().nth(*i) {
9998                                                tabs.view.addTabViewItem(&item);
9999                                            }
10000                                        }
10001                                    }
10002                                    TAB_PICK_SUPPRESS.with(|s| s.set(false));
10003                                }
10004                            }
10005                            // Handled outside this borrow (it re-homes views and builds chrome).
10006                            NavPatch::Presentation(_) => {}
10007                            // Resident-page switch (docs/navigation.md): every page stays in the
10008                            // view hierarchy and only one is unhidden, so switching tabs keeps
10009                            // each page's scroll position and first responder exactly as left.
10010                            NavPatch::Select(i) => {
10011                                state.selected = *i;
10012                                match state.tabs.as_ref() {
10013                                    // The tab view shows exactly its selected item's page.
10014                                    Some(tabs) => {
10015                                        let n = unsafe { tabs.view.numberOfTabViewItems() };
10016                                        if (*i as isize) < n {
10017                                            TAB_PICK_SUPPRESS.with(|s| s.set(true));
10018                                            unsafe {
10019                                                tabs.view.selectTabViewItemAtIndex(*i as isize)
10020                                            };
10021                                            TAB_PICK_SUPPRESS.with(|s| s.set(false));
10022                                        }
10023                                    }
10024                                    None => {
10025                                        for (n, page) in state.pages.iter().enumerate() {
10026                                            page.setHidden(n != *i);
10027                                        }
10028                                    }
10029                                }
10030                            }
10031                            // Per-destination pane visibility (docs/navigation.md). Directly,
10032                            // not through the animator proxy: a screenshot must not catch a
10033                            // mid-animation pane (the sidebar-toggle rule), and settled now,
10034                            // like a re-present, so the detail's frame is right the instant
10035                            // the patch returns rather than one layout pass later.
10036                            NavPatch::ListVisible(v) => {
10037                                state.list_visible = *v;
10038                                if let Some(item) = state.list_item.as_ref() {
10039                                    item.setCollapsed(!*v);
10040                                    let split = unsafe { state._split_vc.splitView() };
10041                                    unsafe { split.layoutSubtreeIfNeeded() };
10042                                    // First time this pane is actually on screen: give it the
10043                                    // width the app asked for. The frame pass that would
10044                                    // otherwise do it has already run, back when there was no
10045                                    // pane to size.
10046                                    if let Some(w) = take_list_placement(state) {
10047                                        unsafe {
10048                                            split.setPosition_ofDividerAtIndex(
10049                                                day_spec::NAV_SIDEBAR_WIDTH + w,
10050                                                1,
10051                                            );
10052                                        }
10053                                    }
10054                                    // Re-frame the pane's page to the wrap it fills. A page
10055                                    // inserted while the pane was collapsed got a zero-width
10056                                    // frame, and `ViewWidthSizable` scales zero to zero however
10057                                    // wide the wrap becomes, so the list stayed invisible while
10058                                    // its rows were still there to click. An app opening on a
10059                                    // full-page section hits this on the first reveal.
10060                                    if *v
10061                                        && let Some(wrap) = state.list_wrap.as_ref()
10062                                        && let Some(page) = state.list_page.as_ref()
10063                                    {
10064                                        unsafe {
10065                                            wrap.layoutSubtreeIfNeeded();
10066                                            page.setFrame(wrap.bounds());
10067                                        }
10068                                    }
10069                                }
10070                            }
10071                            // Never arrives here: the pane persists through every presentation
10072                            // (`Cap::NavContentList` = Native), so the pieces layer never asks
10073                            // for the merged-stack shape.
10074                            NavPatch::ListInStack(_) => {}
10075                        }
10076                    });
10077                }
10078            }
10079            // Emulated cover (docs/cover.md): present = re-home onto the window's content view
10080            // at full bounds, topmost, autoresized with the window (the DayNavPage handle
10081            // reports FrameChanged on every resize). Dismiss = hide + report `CoverHidden`
10082            // immediately (no transition on this tier). Interactive dismissal doesn't exist on
10083            // this backend, so DismissDisabled has nothing to disable.
10084            kinds::COVER => {
10085                if let (Some(p), Ok(page)) = (
10086                    patch.downcast_ref::<CoverPatch>(),
10087                    h.clone().downcast::<DayNavPage>(),
10088                ) {
10089                    let node = page.ivars().node;
10090                    match p {
10091                        CoverPatch::Present { background, .. } => {
10092                            if page.ivars().sheet.get() {
10093                                if let Some(parent) =
10094                                    primary_content().and_then(|v| unsafe { v.window() })
10095                                {
10096                                    let bounds = parent.frame().size;
10097                                    let max = if page.ivars().large.get() {
10098                                        day_spec::props::LARGE_SHEET_MAX
10099                                    } else {
10100                                        day_spec::props::SHEET_MAX
10101                                    };
10102                                    let height = if page.ivars().half.get() {
10103                                        (bounds.height * 0.5).clamp(160.0, max.height)
10104                                    } else {
10105                                        (bounds.height - 80.0).clamp(300.0, max.height)
10106                                    };
10107                                    let size = NSSize::new(
10108                                        (bounds.width - 40.0).clamp(320.0, max.width),
10109                                        height,
10110                                    );
10111                                    let window = unsafe {
10112                                        NSWindow::initWithContentRect_styleMask_backing_defer(
10113                                            NSWindow::alloc(MainThreadMarker::new().unwrap()),
10114                                            NSRect::new(NSPoint::new(0.0, 0.0), size),
10115                                            NSWindowStyleMask::Titled,
10116                                            NSBackingStoreType::Buffered,
10117                                            false,
10118                                        )
10119                                    };
10120                                    unsafe {
10121                                        window.setReleasedWhenClosed(false);
10122                                        page.removeFromSuperview();
10123                                        page.setHidden(false);
10124                                        page.setFrame(NSRect::new(NSPoint::new(0.0, 0.0), size));
10125                                        window.setContentView(Some(&page));
10126                                    }
10127                                    let key = ptr_of(h);
10128                                    SHEET_NODES.with(|t| {
10129                                        t.insert(Retained::as_ptr(&window) as usize, node)
10130                                    });
10131                                    install_sheet_escape_monitor();
10132                                    COVER_SHEETS.with(|t| t.insert(key, CoverSheet(window)));
10133                                    dispatch2::DispatchQueue::main().exec_async(move || {
10134                                        ffi_guard::contain((), || {
10135                                            let window =
10136                                                COVER_SHEETS.with(|t| t.with(key, |s| s.0.clone()));
10137                                            if let (Some(window), Some(parent)) = (
10138                                                window,
10139                                                primary_content()
10140                                                    .and_then(|v| unsafe { v.window() }),
10141                                            ) {
10142                                                unsafe {
10143                                                    parent.beginSheet_completionHandler(
10144                                                        &window, None,
10145                                                    );
10146                                                }
10147                                            }
10148                                        });
10149                                    });
10150                                    emit(
10151                                        node,
10152                                        Event::FrameChanged(Size::new(size.width, size.height)),
10153                                    );
10154                                }
10155                                return;
10156                            }
10157                            // A cover must occlude the window (the native tiers' modal surfaces
10158                            // are opaque): default to the window background when the app sets
10159                            // no explicit color.
10160                            unsafe {
10161                                page.setWantsLayer(true);
10162                                if let Some(layer) = page.layer() {
10163                                    let color = match background {
10164                                        Some(bg) => nscolor(*bg),
10165                                        None => NSColor::windowBackgroundColor(),
10166                                    };
10167                                    layer.setBackgroundColor(Some(&color.CGColor()));
10168                                }
10169                            }
10170                            // The primary window's content, specifically: firstObject()
10171                            // is arbitrary once secondary windows exist (docs/windows.md).
10172                            if let Some(content) = primary_content() {
10173                                if let Some(window) = unsafe { content.window() } {
10174                                    toolbar::cover_presented(ptr_of(h), &window);
10175                                }
10176                                // Edge to edge like the root's own background, laid out below
10177                                // the title bar like the root's content: the page starts at the
10178                                // top of the window (above the pinned content origin) and
10179                                // keeps the same strip above its own layout origin.
10180                                let top = title_bar_inset(&content);
10181                                let full = content.frame().size;
10182                                page.ivars().top_inset.set(top);
10183                                unsafe {
10184                                    page.removeFromSuperview();
10185                                    content.addSubview(&page);
10186                                    page.setFrame(NSRect::new(
10187                                        NSPoint::new(0.0, -top),
10188                                        NSSize::new(full.width, full.height),
10189                                    ));
10190                                    page.setBoundsOrigin(NSPoint::new(0.0, -top));
10191                                    page.setAutoresizingMask(
10192                                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10193                                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10194                                    );
10195                                    page.setHidden(false);
10196                                }
10197                                emit(
10198                                    node,
10199                                    Event::FrameChanged(Size::new(
10200                                        full.width,
10201                                        (full.height - top).max(0.0),
10202                                    )),
10203                                );
10204                            }
10205                        }
10206                        CoverPatch::DismissDisabled(_) => {}
10207                        CoverPatch::Dismiss => {
10208                            COVER_SHEETS.with(|t| drop(t.remove(ptr_of(h))));
10209                            toolbar::cover_dismissed(ptr_of(h));
10210                            unsafe {
10211                                page.setHidden(true);
10212                                page.removeFromSuperview();
10213                            }
10214                            emit(node, Event::CoverHidden);
10215                        }
10216                    }
10217                }
10218            }
10219            kinds::PICKER => picker::update_any(self, h, patch),
10220            kinds::TEXT_AREA => textarea::update_any(self, h, patch),
10221            kinds::TEXT_FIELD => {
10222                if let (Some(p), Ok(tf)) = (
10223                    patch.downcast_ref::<TextFieldPatch>(),
10224                    h.clone().downcast::<NSTextField>(),
10225                ) {
10226                    match p {
10227                        TextFieldPatch::Text { text, from_native } => {
10228                            // Origin-tagged echo suppression (§4.4).
10229                            if !*from_native && unsafe { tf.stringValue() }.to_string() != *text {
10230                                unsafe { tf.setStringValue(&NSString::from_str(text)) };
10231                            }
10232                        }
10233                        TextFieldPatch::Placeholder(t) => unsafe {
10234                            tf.setPlaceholderString(Some(&NSString::from_str(t)))
10235                        },
10236                        TextFieldPatch::Enabled(e) => unsafe { tf.setEnabled(*e) },
10237                        // A selection lives in the field editor, which a field has only while
10238                        // it edits (docs/textfield.md "Selection"): an unfocused field has none
10239                        // to set, and taking focus selects the whole text anyway.
10240                        TextFieldPatch::Select(sel) => {
10241                            if let Some(editor) = tf.currentEditor() {
10242                                let (start, end) = sel.utf16(&editor.string().to_string());
10243                                editor.setSelectedRange(objc2_foundation::NSRange::new(
10244                                    start,
10245                                    end - start,
10246                                ));
10247                            }
10248                        }
10249                    }
10250                }
10251            }
10252            kinds::LIST => match patch.downcast_ref::<ListPatch>() {
10253                Some(ListPatch::Splice(deltas)) => {
10254                    // The set changed by exactly these deltas: animate each row in, out, or
10255                    // across, the thing a reload cannot express. Indexes are sequential, so
10256                    // each delta gets its own begin/endUpdates batch (NSTableView's combined
10257                    // batch semantics re-interpret indexes; one-at-a-time stays literal).
10258                    // Row realization stays deferred, as with Reload.
10259                    if let Some((table, data)) = list_entry(ptr_of(h)) {
10260                        use objc2_app_kit::NSTableViewAnimationOptions;
10261                        for d in deltas {
10262                            unsafe {
10263                                table.beginUpdates();
10264                                match d {
10265                                    day_spec::props::RowDelta::Insert(i) => table
10266                                        .insertRowsAtIndexes_withAnimation(
10267                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
10268                                            NSTableViewAnimationOptions::SlideDown,
10269                                        ),
10270                                    day_spec::props::RowDelta::Remove(i) => table
10271                                        .removeRowsAtIndexes_withAnimation(
10272                                            &objc2_foundation::NSIndexSet::indexSetWithIndex(*i),
10273                                            NSTableViewAnimationOptions::SlideUp,
10274                                        ),
10275                                    day_spec::props::RowDelta::Move(from, to) => {
10276                                        table.moveRowAtIndex_toIndex(*from as isize, *to as isize)
10277                                    }
10278                                }
10279                                table.endUpdates();
10280                            }
10281                        }
10282                        // The displayed order matches the source again: refresh the cache a
10283                        // committed drag keeps in step and `permutation_moves` compares, or the
10284                        // next Reload finds a stale length and reloads flat instead of animating.
10285                        if let Some(source) = data.ivars().source.borrow().as_ref() {
10286                            let n = (source.len)();
10287                            *data.ivars().tokens.borrow_mut() =
10288                                (0..n).map(|i| (source.token_at)(i)).collect();
10289                        }
10290                    }
10291                    post_realize_visible_rows(ptr_of(h));
10292                }
10293                Some(ListPatch::Reload) => {
10294                    if let Some((table, data)) = list_entry(ptr_of(h)) {
10295                        // NSTableView reloadData clears selection for this view-based source.
10296                        // Preserve identities, not indexes, across refreshes/reorders; removed
10297                        // items disappear from the selection without selecting their successor.
10298                        let selected = unsafe { table.selectedRowIndexes() };
10299                        let tokens: Vec<u64> = data
10300                            .ivars()
10301                            .tokens
10302                            .borrow()
10303                            .iter()
10304                            .enumerate()
10305                            .filter(|(row, _)| selected.containsIndex(*row))
10306                            .map(|(_, token)| *token)
10307                            .collect();
10308                        data.ivars().suppress.set(true);
10309                        // A reload whose rows are the same set in a new order (a shuffle,
10310                        // a programmatic sort) animates as native row moves instead of a
10311                        // blink: a `moveRowAtIndex` batch, the same animation a drag commit
10312                        // gets. Anything else (insert/remove/content change) reloads flat.
10313                        // reloadData queries numberOfRows synchronously (snapshot only, no
10314                        // tree) and defers viewForRow, so both paths are safe in with_tree.
10315                        if let Some(moves) = data.permutation_moves(&table) {
10316                            unsafe {
10317                                table.beginUpdates();
10318                                for (from, to) in moves {
10319                                    table.moveRowAtIndex_toIndex(from as isize, to as isize);
10320                                }
10321                                table.endUpdates();
10322                            }
10323                        } else {
10324                            unsafe { table.reloadData() };
10325                        }
10326                        let restored = objc2_foundation::NSMutableIndexSet::new();
10327                        for (row, token) in data.ivars().tokens.borrow().iter().enumerate() {
10328                            if tokens.contains(token) {
10329                                restored.addIndex(row);
10330                            }
10331                        }
10332                        unsafe { table.selectRowIndexes_byExtendingSelection(&restored, false) };
10333                        data.ivars().suppress.set(false);
10334                    }
10335                    // Realize the visible rows on the next main-loop turn, outside this borrow.
10336                    // An occluded window (locked screen, covered, headless CI) gets no normal
10337                    // draw pass; NSTableView would first realize these rows inside a snapshot's
10338                    // `cacheDisplayInRect`, where `bind_row` must skip the held borrow and the
10339                    // table would cache permanently blank cells.
10340                    post_realize_visible_rows(ptr_of(h));
10341                }
10342                Some(ListPatch::ScrollToRow(row)) => {
10343                    // Same deferral discipline as ScrollToEnd: the scroll tiles target rows
10344                    // synchronously, which must happen outside this `with_tree` borrow.
10345                    let (key, row) = (ptr_of(h), *row);
10346                    <AppKit as Platform>::post(Box::new(move || {
10347                        if let Some((table, _)) = list_entry(key) {
10348                            let rows = unsafe { table.numberOfRows() };
10349                            if rows > 0 {
10350                                unsafe { table.scrollRowToVisible((row as isize).min(rows - 1)) };
10351                            }
10352                        }
10353                    }));
10354                    post_realize_visible_rows(ptr_of(h));
10355                }
10356                Some(ListPatch::ScrollToEnd) => {
10357                    // Deferred to the next main-loop turn: an actual scroll forces NSTableView
10358                    // to tile (realize) the target rows synchronously, and this patch arrives
10359                    // inside a `with_tree` borrow where `bind_row` must skip; the table would
10360                    // cache blank cells for every newly exposed row (see Reload above).
10361                    let key = ptr_of(h);
10362                    <AppKit as Platform>::post(Box::new(move || {
10363                        if let Some((table, _)) = list_entry(key) {
10364                            let rows = unsafe { table.numberOfRows() };
10365                            if rows > 0 {
10366                                unsafe { table.scrollRowToVisible(rows - 1) };
10367                            }
10368                        }
10369                    }));
10370                    // ...and realize whatever the scroll exposed, still outside the borrow.
10371                    post_realize_visible_rows(ptr_of(h));
10372                }
10373                Some(ListPatch::Selected(rows)) => {
10374                    // Programmatic selection sync (empty = clear), suppressed so the
10375                    // delegate does not echo it back as a selection event.
10376                    if let Some((table, data)) = list_entry(ptr_of(h)) {
10377                        data.ivars().suppress.set(true);
10378                        unsafe {
10379                            if rows.is_empty() {
10380                                table.deselectAll(None);
10381                            } else {
10382                                let set = objc2_foundation::NSMutableIndexSet::new();
10383                                let count = table.numberOfRows().max(0) as usize;
10384                                for r in rows.iter().copied().filter(|r| *r < count) {
10385                                    set.addIndex(r);
10386                                }
10387                                table.selectRowIndexes_byExtendingSelection(&set, false);
10388                            }
10389                        }
10390                        data.ivars().suppress.set(false);
10391                    }
10392                }
10393                Some(ListPatch::RowSizeInvalidated { cell, height }) => {
10394                    if let Some((table, data)) = list_entry(ptr_of(h)) {
10395                        data.row_resized(&table, *cell, *height);
10396                    }
10397                }
10398                // `None` = a patch for another kind's enum. A desktop table has no editing mode
10399                // (Cap::ListEditing is Unsupported).
10400                Some(ListPatch::Editing(_)) | None => {}
10401            },
10402            kinds::TREE => match patch.downcast_ref::<TreePatch>() {
10403                Some(TreePatch::Reload) => {
10404                    // Interned items keep their identity across reloadData, so NSOutlineView
10405                    // itself preserves expansion; the piece re-asserts it (and the selection)
10406                    // by token right after, belt and braces. reloadData queries the child
10407                    // counts synchronously (snapshot only, no tree) and defers viewForItem.
10408                    if let Some((outline, _)) = tree_entry(ptr_of(h)) {
10409                        unsafe { outline.reloadData() };
10410                    }
10411                    post_realize_visible_tree_rows(ptr_of(h));
10412                }
10413                Some(TreePatch::Expand(token, on)) => {
10414                    // Deferred: expandItem/collapseItem realize (or remove) the disclosed
10415                    // rows synchronously, and this patch arrives inside a `with_tree` borrow
10416                    // where `bind_row` must skip; the outline would cache permanently blank,
10417                    // id-less rows (the ScrollToEnd rule, one arm over).
10418                    let (key, token, on) = (ptr_of(h), *token, *on);
10419                    <AppKit as Platform>::post(Box::new(move || {
10420                        if let Some((outline, data)) = tree_entry(key) {
10421                            let item = data.intern(token);
10422                            // Suppressed: a programmatic disclosure must not echo back as
10423                            // `Event::TreeExpanded`. Redundant applications are AppKit no-ops.
10424                            data.ivars().suppress.set(true);
10425                            unsafe {
10426                                if on {
10427                                    outline.expandItem(Some(&item));
10428                                } else {
10429                                    outline.collapseItem(Some(&item));
10430                                }
10431                            }
10432                            data.ivars().suppress.set(false);
10433                        }
10434                        day_core::pump_events();
10435                    }));
10436                    post_realize_visible_tree_rows(ptr_of(h));
10437                }
10438                Some(TreePatch::Selected(tokens)) => {
10439                    if let Some((outline, data)) = tree_entry(ptr_of(h)) {
10440                        data.ivars().suppress.set(true);
10441                        unsafe {
10442                            if tokens.is_empty() {
10443                                outline.deselectAll(None);
10444                            } else {
10445                                let set = objc2_foundation::NSMutableIndexSet::new();
10446                                for t in tokens {
10447                                    // A token under a collapsed ancestor has no row, so it is
10448                                    // skipped; the piece re-applies after expansion changes.
10449                                    let row = outline.rowForItem(Some(&data.intern(*t)));
10450                                    if row >= 0 {
10451                                        set.addIndex(row as usize);
10452                                    }
10453                                }
10454                                outline.selectRowIndexes_byExtendingSelection(&set, false);
10455                            }
10456                        }
10457                        data.ivars().suppress.set(false);
10458                    }
10459                }
10460                Some(TreePatch::Reveal(token)) => {
10461                    // Deferred: the scroll tiles target rows synchronously, which must
10462                    // happen outside this `with_tree` borrow (the ScrollToRow rule).
10463                    let (key, token) = (ptr_of(h), *token);
10464                    <AppKit as Platform>::post(Box::new(move || {
10465                        if let Some((outline, data)) = tree_entry(key) {
10466                            let row = unsafe { outline.rowForItem(Some(&data.intern(token))) };
10467                            if row >= 0 {
10468                                unsafe { outline.scrollRowToVisible(row) };
10469                            }
10470                        }
10471                    }));
10472                    post_realize_visible_tree_rows(ptr_of(h));
10473                }
10474                None => {}
10475            },
10476            _ => {
10477                if let Some(update) = self.registry.get(kind).map(|r| r.update) {
10478                    update(self, h, patch);
10479                }
10480            }
10481        }
10482    }
10483
10484    /// Offer a satellite piece its teardown hook before `release` frees the handle (§15.2).
10485    fn release_piece(&mut self, kind: day_spec::PieceKind, h: &Self::Handle) {
10486        // Copy the fn pointer out first: the registry lookup borrows `self` immutably and
10487        // the hook needs it mutably.
10488        let f = self.registry.get(kind).and_then(|r| r.release);
10489        if let Some(f) = f {
10490            f(self, h);
10491        }
10492    }
10493    fn release(&mut self, h: Handle) {
10494        LIST_ITEMS.with(|m| m.borrow_mut().remove(&ptr_of(&h)));
10495        // A released window content = that window is gone (docs/windows.md teardown):
10496        // drop the SecondaryWin (closing a straggler NSWindow) and its delegate with it.
10497        // (A re-fired windowWillClose emits to a torn-down node: dropped, harmless.)
10498        self.secondary.retain(|w| {
10499            if ptr_of(&w.content) == ptr_of(&h) {
10500                w.window.close();
10501                // The window's keyed state goes with it: its toolbar (toolbar.rs BARS,
10502                // keyed by the window pointer) used to survive a secondary close, and its
10503                // items, targets, retained NSToolbar and delegate all leaked.
10504                day_spec::sidetable::sweep(Retained::as_ptr(&w.window) as usize);
10505                false
10506            } else {
10507                true
10508            }
10509        });
10510        TARGETS.with(|m| {
10511            m.borrow_mut().remove(&ptr_of(&h));
10512        });
10513        LIST_STATE.with(|m| {
10514            m.borrow_mut().remove(&ptr_of(&h));
10515        });
10516        TREE_STATE.with(|m| {
10517            m.borrow_mut().remove(&ptr_of(&h));
10518        });
10519        GESTURES.with(|m| {
10520            m.borrow_mut().remove(&ptr_of(&h));
10521        });
10522        NAV_STATE.with(|m| {
10523            if let Some(nav) = m.borrow_mut().remove(&ptr_of(&h)) {
10524                // Unhook the split view controller from the responder chain before the drop
10525                // deallocs it. AppKit rewires these pointers behind day's back (mounting the
10526                // split resets its next to the superview; the controller's own view keeps
10527                // aiming at the controller), and a controller whose next responder is its own
10528                // view dies in dealloc's chain splice with the "next responder should never
10529                // be yourself" NSException, foreign to Rust, so it aborts the process
10530                // instead of unwinding (the Stack-page teardown crash, 2026-08).
10531                unsafe {
10532                    nav._split_vc.setNextResponder(None);
10533                    let split = nav._split_vc.splitView();
10534                    if split.nextResponder().is_some_and(|r| {
10535                        core::ptr::eq::<objc2::runtime::AnyObject>(
10536                            r.as_ref(),
10537                            nav._split_vc.as_ref(),
10538                        )
10539                    }) {
10540                        split.setNextResponder(None);
10541                    }
10542                }
10543            }
10544        });
10545        NAV_PAGES.with(|set| {
10546            set.borrow_mut().remove(&ptr_of(&h));
10547        });
10548        SPLIT_STATE.with(|m| {
10549            if let Some(state) = m.borrow_mut().remove(&ptr_of(&h)) {
10550                state.split.setDelegate(None);
10551            }
10552        });
10553        INSPECTOR_STATE.with(|m| {
10554            if let Some(insp) = m.borrow_mut().remove(&ptr_of(&h)) {
10555                // The same dealloc-splice guard as the nav host above: never let the
10556                // controller (or its split) dealloc aiming at itself.
10557                unsafe {
10558                    insp._split_vc.setNextResponder(None);
10559                    let split = insp._split_vc.splitView();
10560                    if split.nextResponder().is_some_and(|r| {
10561                        core::ptr::eq::<objc2::runtime::AnyObject>(
10562                            r.as_ref(),
10563                            insp._split_vc.as_ref(),
10564                        )
10565                    }) {
10566                        split.setNextResponder(None);
10567                    }
10568                }
10569            }
10570        });
10571        NAV_MENUS.with(|m| {
10572            if let Some((outline, _)) = m.borrow_mut().remove(&ptr_of(&h)) {
10573                // The outline registers under its pointer (`menuForEvent:` resolves by
10574                // outline, not by this scroll handle): sweep that auxiliary key too, so
10575                // NAV_OUTLINE_MENUS, and any future outline-keyed table, drops it. A
10576                // surviving entry served the dead menu's rows once the address was recycled.
10577                day_spec::sidetable::sweep(Retained::as_ptr(&outline) as usize);
10578            }
10579        });
10580        // One call reclaims this handle's entry from every SideTable on this thread (canvas
10581        // OPS, PAGE_PANE, the picker/textarea state, and whatever lands later), running each
10582        // table's teardown hook (day-spec sidetable). The explicit removals above are the
10583        // older per-map checklist; new per-view maps should be SideTables so this sweep covers
10584        // them without another line here.
10585        day_spec::sidetable::sweep(ptr_of(&h));
10586        unsafe { h.removeFromSuperview() };
10587    }
10588
10589    fn insert(&mut self, parent: &Handle, child: &Handle, _index: usize) {
10590        // A nav menu that has just gained ancestors: if one of them is a tabs host, its rows
10591        // Are that host's tab labels (`adopt_menu_for_tabs`). The menu is built after its rows
10592        // page joined the host, so this is the first moment the host can see its rows.
10593        if NAV_MENUS.with(|m| m.borrow().contains_key(&ptr_of(child))) {
10594            unsafe { content_of(parent).addSubview(child) };
10595            adopt_menu_for_tabs(self.mtm(), child);
10596            return;
10597        }
10598        // Nav host: pages land by their pane, not their position (docs/size-classes.md). Pages
10599        // fill their pane via autoresizing; the pane, not Day, owns their frames.
10600        let page_pane = PAGE_PANE.with(|t| t.get(ptr_of(child)));
10601        let is_sidebar_page = page_pane == Some(day_spec::props::Pane::Sidebar);
10602        let handled = NAV_STATE.with(|m| {
10603            let mut m = m.borrow_mut();
10604            let Some(state) = m.get_mut(&ptr_of(parent)) else {
10605                return false;
10606            };
10607            // The content-list page fills its pane at every presentation
10608            // (docs/navigation.md), never a member of the detail stack.
10609            if page_pane == Some(day_spec::props::Pane::List)
10610                && let Some(wrap) = state.list_wrap.as_ref()
10611            {
10612                state.list_page = Some(child.clone());
10613                unsafe {
10614                    child.setFrame(wrap.bounds());
10615                    child.setAutoresizingMask(
10616                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10617                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10618                    );
10619                    wrap.addSubview(child);
10620                }
10621                return true;
10622            }
10623            if is_sidebar_page {
10624                state.sidebar_page = Some(child.clone());
10625            }
10626            // Split (nav host Sidebar): the sidebar pane's page goes in the sidebar; the rest are
10627            // detail pages. Stack: every page, including the sidebar's, which is the stack's
10628            // root, lives in the detail pane so push/pop visibility covers them all.
10629            // The rows page goes to the sidebar pane in every presentation but `Stack`, where
10630            // it is the stack root and joins the detail pages instead.
10631            let to_pane = is_sidebar_page && state.presentation != NavPresentation::Stack;
10632            // A tabs host's detail page becomes an item of its tab view, which frames it (the
10633            // page's `setFrameSize:` reports the size to Day). Its label comes with the
10634            // menu's rows: already here when a page joins a live host, otherwise when the
10635            // menu is inserted (`adopt_menu_for_tabs`).
10636            if !to_pane && let Some(tabs) = state.tabs.as_ref() {
10637                state.pages.push(child.clone());
10638                let item = unsafe { objc2_app_kit::NSTabViewItem::new() };
10639                unsafe {
10640                    child.setAutoresizingMask(
10641                        objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10642                            | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10643                    );
10644                    item.setView(Some(child));
10645                    tabs.view.addTabViewItem(&item);
10646                }
10647                if let Some((titles, _)) = state.sidebar_page.as_deref().and_then(nav_menu_rows) {
10648                    sync_tab_labels(tabs, &titles, state.selected);
10649                }
10650                return true;
10651            }
10652            let (wrap, frame) = if to_pane {
10653                (&state.sidebar_wrap, state.sidebar_wrap.bounds())
10654            } else {
10655                state.pages.push(child.clone());
10656                let visible = state.header.as_ref().is_some_and(|h| !h.bar.isHidden());
10657                (
10658                    &state.detail_wrap,
10659                    nav_page_frame(&state.detail_wrap, visible),
10660                )
10661            };
10662            unsafe {
10663                child.setFrame(frame);
10664                child.setAutoresizingMask(
10665                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10666                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10667                );
10668                wrap.addSubview(child);
10669            }
10670            true
10671        });
10672        if handled {
10673            return;
10674        }
10675        // Split host (docs/split.md): each pane fills its wrap, an arranged subview the
10676        // splitter sizes; the pane's own `setFrameSize:` reports the size to Day.
10677        let split_pane = SPLIT_STATE.with(|m| {
10678            let m = m.borrow();
10679            let Some(state) = m.get(&ptr_of(parent)) else {
10680                return false;
10681            };
10682            let second = SPLIT_PANES.with(|t| t.get(ptr_of(child))).unwrap_or(false);
10683            let wrap = if second {
10684                &state.second_wrap
10685            } else {
10686                &state.first_wrap
10687            };
10688            unsafe {
10689                child.setFrame(wrap.bounds());
10690                child.setAutoresizingMask(
10691                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10692                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10693                );
10694                wrap.addSubview(child);
10695            }
10696            true
10697        });
10698        if split_pane {
10699            return;
10700        }
10701        // Inspector host: each pane fills its wrap via autoresizing, the nav-page contract;
10702        // the split, not Day, owns the pane frames (docs/inspector.md).
10703        let inspected = INSPECTOR_STATE.with(|m| {
10704            let m = m.borrow();
10705            let Some(state) = m.get(&ptr_of(parent)) else {
10706                return false;
10707            };
10708            let panel = INSPECTOR_PANES
10709                .with(|t| t.get(ptr_of(child)))
10710                .unwrap_or(false);
10711            let wrap = if panel {
10712                &state.panel_wrap
10713            } else {
10714                &state.content_wrap
10715            };
10716            unsafe {
10717                child.setFrame(wrap.bounds());
10718                child.setAutoresizingMask(
10719                    objc2_app_kit::NSAutoresizingMaskOptions::ViewWidthSizable
10720                        | objc2_app_kit::NSAutoresizingMaskOptions::ViewHeightSizable,
10721                );
10722                wrap.addSubview(child);
10723            }
10724            true
10725        });
10726        if !inspected {
10727            // Absolute positioning: z-order is build order; index is irrelevant for
10728            // non-overlapping frames (stack_z will need ordered insertion later).
10729            unsafe { content_of(parent).addSubview(child) };
10730        }
10731    }
10732
10733    fn remove(&mut self, parent: &Handle, child: &Handle) {
10734        PAGE_PANE.with(|t| t.remove(ptr_of(child)));
10735        let mtm = self.mtm();
10736        NAV_STATE.with(|m| {
10737            if let Some(state) = m.borrow_mut().get_mut(&ptr_of(parent)) {
10738                // A tabs host: the page leaves with its tab item.
10739                if let Some(tabs) = state.tabs.as_ref() {
10740                    unsafe {
10741                        let n = tabs.view.numberOfTabViewItems();
10742                        for i in 0..n {
10743                            let item = tabs.view.tabViewItemAtIndex(i);
10744                            if item.view(mtm).is_some_and(|v| ptr_of(&v) == ptr_of(child)) {
10745                                tabs.view.removeTabViewItem(&item);
10746                                break;
10747                            }
10748                        }
10749                    }
10750                }
10751                state.pages.retain(|p| ptr_of(p) != ptr_of(child));
10752                if state.sidebar_page.as_deref().map(ptr_of) == Some(ptr_of(child)) {
10753                    state.sidebar_page = None;
10754                }
10755            }
10756        });
10757        unsafe { child.removeFromSuperview() };
10758    }
10759
10760    fn move_child(&mut self, parent: &Handle, child: &Handle, _to: usize) {
10761        unsafe { content_of(parent).addSubview(child) };
10762    }
10763
10764    fn measure(&mut self, h: &Handle, kind: PieceKind, p: Proposal) -> Size {
10765        match kind {
10766            kinds::LABEL => {
10767                if let Some(tf) = h.downcast_ref::<NSTextField>() {
10768                    let w = p.width.unwrap_or(1.0e6);
10769                    // The field owns maximumNumberOfLines; measuring its cell bypasses it.
10770                    let s = tf.sizeThatFits(NSSize::new(w, 1.0e6));
10771                    let mut height = s.height.ceil();
10772                    // AppKit's truncating single-line mode still measures explicit newlines
10773                    // as multiple lines. Bound that case using AppKit's own font metrics.
10774                    if tf.maximumNumberOfLines() == 1 {
10775                        thread_local! {
10776                            static METRICS: Retained<objc2_app_kit::NSLayoutManager> = objc2_app_kit::NSLayoutManager::new();
10777                        }
10778                        if let Some(font) = unsafe { tf.font() } {
10779                            height = height.min(
10780                                METRICS
10781                                    .with(|metrics| metrics.defaultLineHeightForFont(&font))
10782                                    .ceil(),
10783                            );
10784                        }
10785                    }
10786                    return Size::new(s.width.ceil().min(w), height);
10787                }
10788                Size::ZERO
10789            }
10790            kinds::BUTTON | kinds::TOGGLE => {
10791                let s = unsafe { h.fittingSize() };
10792                Size::new(s.width.ceil(), s.height.ceil())
10793            }
10794            kinds::SLIDER => {
10795                let s = unsafe { h.fittingSize() };
10796                Size::new(p.width.unwrap_or(180.0), s.height.max(21.0).ceil())
10797            }
10798            kinds::PICKER => picker::measure_any(self, h, p),
10799            kinds::TEXT_AREA => textarea::measure_any(self, h, p),
10800            kinds::TEXT_FIELD => {
10801                let s = unsafe { h.fittingSize() };
10802                Size::new(
10803                    p.width.unwrap_or(s.width.max(160.0)),
10804                    s.height.max(22.0).ceil(),
10805                )
10806            }
10807            kinds::DIVIDER => Size::new(p.width.unwrap_or(0.0), 5.0),
10808            // The stack's own fitting size, at least a table row's 28pt; the words truncate to
10809            // the row's width.
10810            kinds::LIST_ITEM => {
10811                let s = h.fittingSize();
10812                Size::new(p.width.unwrap_or(s.width.ceil()), s.height.ceil().max(28.0))
10813            }
10814            kinds::PROGRESS => {
10815                // Indeterminate spinner is a fixed square; determinate bar fills width.
10816                let indeterminate = h
10817                    .clone()
10818                    .downcast::<NSProgressIndicator>()
10819                    .map(|pi| unsafe { pi.isIndeterminate() })
10820                    .unwrap_or(false);
10821                if indeterminate {
10822                    let large = h
10823                        .downcast_ref::<NSProgressIndicator>()
10824                        .is_some_and(|pi| pi.controlSize() == objc2_app_kit::NSControlSize::Large);
10825                    let side = if large { 32.0 } else { 20.0 };
10826                    Size::new(side, side)
10827                } else {
10828                    Size::new(p.width.unwrap_or(180.0), 20.0)
10829                }
10830            }
10831            kinds::NAV_MENU => {
10832                let rows = NAV_MENUS.with(|m| {
10833                    m.borrow()
10834                        .get(&ptr_of(h))
10835                        .map(|(_, d)| d.ivars().items.borrow().len())
10836                        .unwrap_or(0)
10837                });
10838                Size::new(
10839                    p.width.unwrap_or(220.0),
10840                    p.height.unwrap_or(rows as f64 * 32.0 + 12.0),
10841                )
10842            }
10843            // The recycling list fills the space it is offered (its native scroll owns overflow).
10844            kinds::LIST | kinds::TREE => Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0)),
10845            _ => {
10846                if let Some(measure) = self.registry.get(kind).and_then(|r| r.measure) {
10847                    measure(self, h, p)
10848                } else {
10849                    let s = unsafe { h.fittingSize() };
10850                    Size::new(p.width.unwrap_or(s.width), p.height.unwrap_or(s.height))
10851                }
10852            }
10853        }
10854    }
10855
10856    fn set_opacity(&mut self, h: &Handle, opacity: f64, anim: Option<&AnimSpec>) {
10857        unsafe {
10858            h.setWantsLayer(true);
10859        }
10860        let v = h.clone();
10861        with_appkit_anim(anim, move || unsafe { v.setAlphaValue(opacity) });
10862    }
10863
10864    fn set_transform(&mut self, h: &Handle, t: Transform, _size: Size, anim: Option<&AnimSpec>) {
10865        // Expressed in the view's own geometry (see `TRANSFORMS`), so hit-testing follows the
10866        // drawing, as UIKit's does. Without a laid-out frame yet, `set_frame` applies it.
10867        TRANSFORMS.with(|m| m.insert(ptr_of(h), t));
10868        let base = BASE_FRAMES.with(|m| m.get(ptr_of(h)));
10869        let v = h.clone();
10870        with_appkit_anim(anim, move || {
10871            if let Some(base) = base {
10872                apply_geometry(&v, base, t);
10873            }
10874        });
10875    }
10876
10877    fn set_selectable(&mut self, h: &Handle, selectable: bool) -> Option<Handle> {
10878        if let Some(label) = h.downcast_ref::<DayLabel>() {
10879            label.ivars().selectable.set(selectable);
10880            label.set_links(label.ivars().has_links.get());
10881        } else if let Some(tf) = h.downcast_ref::<NSTextField>() {
10882            unsafe { tf.setSelectable(selectable) };
10883        }
10884        None
10885    }
10886
10887    fn set_input_traits(&mut self, h: &Handle, traits: &InputTraits) -> Option<Handle> {
10888        let node = text_field_node(h)?;
10889        let old = h.downcast_ref::<NSTextField>()?;
10890        // Hidden characters are a class on AppKit. A field already of the right class is
10891        // dressed in place; otherwise its replacement is, and the node moves to it.
10892        let swapped = (h.downcast_ref::<DaySecureTextField>().is_some() != traits.secure)
10893            .then(|| self.swap_text_field(h, old, node, traits.secure));
10894        let tf = swapped.as_deref().unwrap_or(old);
10895        unsafe {
10896            // Read-only keeps the bezel and the ordinary text color; the text stays
10897            // selectable, so it can still be copied.
10898            tf.setEditable(!traits.read_only);
10899            tf.setSelectable(true);
10900        }
10901        // The purpose is AutoFill's hint on the desktop: which saved credential or contact
10902        // detail the system offers. `Number` and `Decimal` have no content type. A constant
10903        // newer than the running system leaves the field untyped.
10904        let content_type = match traits.purpose {
10905            InputPurpose::Text | InputPurpose::Number | InputPurpose::Decimal => None,
10906            InputPurpose::Name => text_content_type(c"NSTextContentTypeName"),
10907            InputPurpose::Email => text_content_type(c"NSTextContentTypeEmailAddress"),
10908            InputPurpose::Url => text_content_type(c"NSTextContentTypeURL"),
10909            InputPurpose::Phone => text_content_type(c"NSTextContentTypeTelephoneNumber"),
10910            InputPurpose::Username => text_content_type(c"NSTextContentTypeUsername"),
10911            InputPurpose::Password => text_content_type(c"NSTextContentTypePassword"),
10912            InputPurpose::NewPassword => text_content_type(c"NSTextContentTypeNewPassword"),
10913            InputPurpose::OneTimeCode => text_content_type(c"NSTextContentTypeOneTimeCode"),
10914        };
10915        unsafe {
10916            tf.setContentType(content_type);
10917            // Only free text wants the system finishing words; a name, an address or a code
10918            // is typed exactly.
10919            tf.setAutomaticTextCompletionEnabled(traits.purpose == InputPurpose::Text);
10920        }
10921        // No on-screen keyboard, so no action key to label; and no native length limit:
10922        // day-pieces holds `max_length`.
10923        swapped.map(view_of)
10924    }
10925
10926    fn set_cursor(&mut self, h: &Handle, cursor: Cursor) {
10927        let key = Retained::as_ptr(h) as usize;
10928        if cursor == Cursor::Default {
10929            // Release: drop the tracking area, and the hide if this owner holds one.
10930            if let Some((owner, area)) = self.cursors.remove(&key) {
10931                unsafe { h.removeTrackingArea(&area) };
10932                if owner.ivars().hiding.replace(false) {
10933                    NSCursor::unhide();
10934                }
10935            }
10936            return;
10937        }
10938        let hidden = cursor == Cursor::None;
10939        let shape = if hidden { None } else { ns_cursor(&cursor) };
10940        let mtm = self.mtm;
10941        let (owner, _) = self.cursors.entry(key).or_insert_with(|| {
10942            let owner = DayCursorOwner::new(mtm);
10943            // InVisibleRect: the area follows the view's bounds, so no rect to keep in step
10944            // with layout. ActiveInKeyWindow: the shape belongs to the window taking input.
10945            let opts = NSTrackingAreaOptions::CursorUpdate
10946                | NSTrackingAreaOptions::MouseEnteredAndExited
10947                | NSTrackingAreaOptions::ActiveInKeyWindow
10948                | NSTrackingAreaOptions::InVisibleRect;
10949            let any: &objc2::runtime::AnyObject = &owner;
10950            let area = unsafe {
10951                NSTrackingArea::initWithRect_options_owner_userInfo(
10952                    NSTrackingArea::alloc(),
10953                    NSRect::ZERO,
10954                    opts,
10955                    Some(any),
10956                    None,
10957                )
10958            };
10959            unsafe { h.addTrackingArea(&area) };
10960            (owner, area)
10961        });
10962        let changed = {
10963            let iv = owner.ivars();
10964            let same = match (iv.cursor.borrow().as_ref(), shape.as_ref()) {
10965                (Some(a), Some(b)) => Retained::as_ptr(a) == Retained::as_ptr(b),
10966                (None, None) => true,
10967                _ => false,
10968            };
10969            *iv.cursor.borrow_mut() = shape;
10970            let was_hidden = iv.hidden.replace(hidden);
10971            !same || was_hidden != hidden
10972        };
10973        // A reactive change while the pointer is already inside: AppKit only asks on entry,
10974        // so ask it to re-evaluate now.
10975        if changed && let Some(w) = h.window() {
10976            unsafe { w.invalidateCursorRectsForView(h) };
10977        }
10978    }
10979
10980    /// Where the control actually draws its first line of text (docs/baseline.md).
10981    ///
10982    /// AppKit publishes `firstBaselineOffsetFromTop`, but it is measured from the top of the
10983    /// view's alignment rect and it is rounded to whole points, and that rounding is visible.
10984    /// An `NSDatePicker` in a 26pt frame insets its alignment rect 4pt and answers 15, i.e. 19
10985    /// in frame terms, while it paints at 19.9; a label beside it then sits a point high, which
10986    /// is exactly the drift baseline alignment exists to remove.
10987    ///
10988    /// So derive it from the metrics AppKit rounded: a single line of the control's own font,
10989    /// centered in its alignment rect, with the baseline an ascender below the line's top. That
10990    /// reproduces AppKit's own numbers for a plain label and a bezeled field (12.91 → its 13,
10991    /// 19.91 → its 20) while keeping the fractional part that makes a picker land on the line.
10992    /// Controls with no font of their own keep AppKit's answer.
10993    fn first_baseline(&mut self, h: &Handle, kind: PieceKind, size: Size) -> Option<f64> {
10994        if !day_spec::kind_has_baseline(kind) {
10995            return None;
10996        }
10997        // The view has to be at the height the row settled on before it answers: a control
10998        // that centers its text vertically moves its baseline with its box.
10999        let current = unsafe { h.frame() };
11000        if (current.size.height - size.height).abs() > 0.5 {
11001            unsafe { h.setFrameSize(NSSize::new(current.size.width.max(size.width), size.height)) };
11002        }
11003        let insets = unsafe { h.alignmentRectInsets() };
11004        let reported = unsafe { h.firstBaselineOffsetFromTop() } + insets.top;
11005        let font = h
11006            .downcast_ref::<NSControl>()
11007            .and_then(|c| unsafe { c.font() });
11008        let offset = match font {
11009            // A multi-line editor's first line sits at the top of its text container, not
11010            // centered in it, so the centering model would put its baseline half a box too low.
11011            Some(_) if kind == kinds::TEXT_AREA => reported,
11012            Some(f) => {
11013                let (ascender, descender) = unsafe { (f.ascender(), f.descender()) };
11014                let line = ascender - descender;
11015                let align_h = (size.height - insets.top - insets.bottom).max(0.0);
11016                insets.top + ((align_h - line) / 2.0).max(0.0) + ascender
11017            }
11018            None => reported,
11019        };
11020        // AppKit's documented "no baseline" answer is the view's own height.
11021        (offset > 0.0 && offset < size.height).then_some(offset)
11022    }
11023
11024    fn set_frame(&mut self, h: &Handle, frame: Rect, _anim: Option<&AnimSpec>) {
11025        // Nav pages: the splitter pane / nav container owns the frame (autoresized).
11026        if NAV_PAGES.with(|set| set.borrow().contains(&ptr_of(h))) {
11027            return;
11028        }
11029        // Every Day parent is flipped (DayFlipped containers, flipped scroll document views),
11030        // so top-left frames apply directly.
11031        let r = NSRect::new(
11032            NSPoint::new(frame.origin.x, frame.origin.y),
11033            NSSize::new(frame.size.width, frame.size.height),
11034        );
11035        // Nav host: the sidebar holds its width when the window resizes and the detail pane
11036        // absorbs the change. That is now the sidebar NSSplitViewItem's behavior, so the
11037        // only thing left to do here is give the split its frame and place the divider once;
11038        // re-placing it on every resize would fight the item and undo a user's drag.
11039        if let Some(split) = h.downcast_ref::<objc2_app_kit::NSSplitView>() {
11040            // A host at the top of a window's pinned content reaches up under the title bar,
11041            // where its controller expects to be (see `pane_under_title_bar`); its panes keep
11042            // their content below the strip, so nothing Day laid out moves.
11043            let strip = unsafe { split.superview() }
11044                .and_then(|sup| {
11045                    let content = unsafe { sup.window() }?.contentView()?;
11046                    // Layout wrappers (for example zstack with a reader cover) may sit
11047                    // between the window root and its navigation host. A direct-parent
11048                    // check misses them and puts AppKit's frosted pocket over page text.
11049                    let mut ancestor = Some(sup.clone());
11050                    while let Some(view) = ancestor {
11051                        if std::ptr::eq(&*view, &*content) {
11052                            break;
11053                        }
11054                        if view.downcast_ref::<objc2_app_kit::NSSplitView>().is_some() {
11055                            return None; // nested navigation belongs to the outer pane
11056                        }
11057                        ancestor = unsafe { view.superview() };
11058                    }
11059                    let point = unsafe {
11060                        sup.convertPoint_toView(
11061                            NSPoint::new(frame.origin.x, frame.origin.y),
11062                            Some(&content),
11063                        )
11064                    };
11065                    (point.y.abs() <= 0.5).then(|| title_bar_inset(&content))
11066                })
11067                .unwrap_or(0.0);
11068            let r = NSRect::new(
11069                NSPoint::new(r.origin.x, r.origin.y - strip),
11070                NSSize::new(r.size.width, r.size.height + strip),
11071            );
11072            let wraps = NAV_STATE.with(|m| {
11073                m.borrow_mut().get_mut(&ptr_of(h)).and_then(|s| {
11074                    (s.title_strip != strip).then(|| {
11075                        s.title_strip = strip;
11076                        let mut w = vec![s.sidebar_wrap.clone(), s.detail_wrap.clone()];
11077                        w.extend(s.list_wrap.clone());
11078                        w
11079                    })
11080                })
11081            });
11082            let first = NAV_STATE.with(|m| {
11083                m.borrow_mut()
11084                    .get_mut(&ptr_of(h))
11085                    .map(|s| {
11086                        if !s.presentation.is_split() {
11087                            return (false, None);
11088                        }
11089                        let sidebar = !std::mem::replace(&mut s.positioned, true);
11090                        // The list's divider waits for the pane to be showing. Placing it while
11091                        // the pane is collapsed re-opens it (which is how an app whose first
11092                        // destination has no list opened with one beside it) and spends the one
11093                        // placement the pane gets, leaving it at the solver's width later on.
11094                        (sidebar, take_list_placement(s))
11095                    })
11096                    .unwrap_or((false, None))
11097            });
11098            unsafe {
11099                split.setFrame(r);
11100                split.layoutSubtreeIfNeeded();
11101            }
11102            // After the panes have their new size, so each wrap is placed in the final pane;
11103            // autoresizing keeps the strip from then on.
11104            for wrap in wraps.iter().flatten() {
11105                place_below_strip(wrap, strip);
11106            }
11107            unsafe {
11108                if first.0 {
11109                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH, 0);
11110                }
11111                // A triple split has a second divider, and nothing else places it: left alone,
11112                // the controller's initial constraint pass lands it wherever the solver liked, so
11113                // the content list opens at an arbitrary width and the detail pane gets the
11114                // leftovers until the first manual drag re-settles them.
11115                if let Some(w) = first.1 {
11116                    split.setPosition_ofDividerAtIndex(day_spec::NAV_SIDEBAR_WIDTH + w, 1);
11117                }
11118            }
11119        } else {
11120            BASE_FRAMES.with(|m| {
11121                m.insert(
11122                    ptr_of(h),
11123                    [
11124                        frame.origin.x,
11125                        frame.origin.y,
11126                        frame.size.width,
11127                        frame.size.height,
11128                    ],
11129                )
11130            });
11131            // A transform (`set_transform`) is applied to the frame Day laid out.
11132            match TRANSFORMS.with(|m| m.get(ptr_of(h))) {
11133                Some(t) => apply_geometry(
11134                    h,
11135                    [
11136                        frame.origin.x,
11137                        frame.origin.y,
11138                        frame.size.width,
11139                        frame.size.height,
11140                    ],
11141                    t,
11142                ),
11143                None => unsafe { h.setFrame(r) },
11144            }
11145        }
11146    }
11147
11148    fn set_scroll_content(&mut self, h: &Handle, content: Size) {
11149        if let Some(sv) = h.downcast_ref::<NSScrollView>()
11150            && let Some(doc) = unsafe { sv.documentView() }
11151        {
11152            unsafe { doc.setFrameSize(NSSize::new(content.width, content.height)) };
11153        }
11154    }
11155
11156    /// A macOS table row: the dense rows of a Finder or Mail list, 28pt for an icon and a line of body text.
11157    fn list_row_metrics(&mut self, _h: &Handle) -> day_spec::RowMetrics {
11158        day_spec::RowMetrics {
11159            insets: day_spec::Insets {
11160                top: 4.0,
11161                leading: 8.0,
11162                bottom: 4.0,
11163                trailing: 8.0,
11164            },
11165            min_height: 28.0,
11166        }
11167    }
11168
11169    fn scroll_to(&mut self, h: &Handle, target: Rect, _animated: bool) {
11170        if let Some(sv) = h.downcast_ref::<NSScrollView>()
11171            && let Some(doc) = unsafe { sv.documentView() }
11172        {
11173            unsafe {
11174                doc.scrollRectToVisible(NSRect::new(
11175                    NSPoint::new(target.origin.x, target.origin.y),
11176                    NSSize::new(target.size.width, target.size.height),
11177                ))
11178            };
11179        }
11180    }
11181
11182    fn focus(&mut self, h: &Handle, _node: NodeId, focused: bool) {
11183        let Some(window) = h.window() else { return };
11184        // A list's public handle is its scroll view; keyboard focus belongs to the table.
11185        let list = list_entry(ptr_of(h));
11186        let responder: &NSResponder = match &list {
11187            Some((table, _)) => table,
11188            None => h,
11189        };
11190        let responder_ptr = responder as *const NSResponder as usize;
11191        if focused {
11192            window.makeFirstResponder(Some(responder));
11193            return;
11194        }
11195        // Resign only while this view still owns focus, so a stale release can't blur a
11196        // sibling.
11197        let owns = window
11198            .firstResponder()
11199            .is_some_and(|fr| Retained::as_ptr(&fr) as usize == responder_ptr)
11200            || owns_first_responder(&window, h);
11201        if owns {
11202            window.makeFirstResponder(None);
11203        }
11204    }
11205
11206    fn set_focusable(&mut self, h: &Handle, node: NodeId, focusable: bool) {
11207        // The overrides live on `DayFlipped` (the container view); registering any other
11208        // view is harmless but inert, the graceful silence the duty documents.
11209        if focusable {
11210            FOCUSABLE_NODES.with(|t| t.insert(ptr_of(h), node));
11211        } else {
11212            FOCUSABLE_NODES.with(|t| t.remove(ptr_of(h)));
11213        }
11214    }
11215
11216    fn set_event_sink(&mut self, sink: EventSink) {
11217        SINK.with(|s| *s.borrow_mut() = Some(Rc::from(sink)));
11218    }
11219
11220    fn set_edit_state(&mut self, state: &day_spec::EditState) {
11221        EDIT_STATE.with(|s| s.set(*state));
11222    }
11223
11224    fn modifiers(&mut self) -> day_spec::Modifiers {
11225        let f = NSEvent::modifierFlags_class();
11226        day_spec::Modifiers {
11227            shift: f.contains(NSEventModifierFlags::Shift),
11228            primary: f.contains(NSEventModifierFlags::Command),
11229            alt: f.contains(NSEventModifierFlags::Option),
11230        }
11231    }
11232
11233    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
11234        let front = undo_front(self.mtm);
11235        *front.ivars().state.borrow_mut() = state.clone();
11236    }
11237
11238    fn attach_list(&mut self, host: &Handle, source: ListSource) {
11239        let key = ptr_of(host);
11240        if let Some((table, data)) = list_entry(key) {
11241            data.ivars().source.replace(Some(source));
11242            // Initial fill: numberOfRows reads the snapshot only; viewForRow is deferred.
11243            unsafe { table.reloadData() };
11244        }
11245        // Force the table to realize its visible row views on the next main-loop turn, outside
11246        // any `with_tree` borrow, so `viewForRow`/`bind_row` build the cells then. Otherwise a
11247        // headless CI window never lays the table out until a snapshot's `cacheDisplayInRect`
11248        // forces it *inside* the snapshot borrow, where `bind_row` must skip (blank rows).
11249        post_realize_visible_rows(key);
11250    }
11251
11252    fn attach_tree(&mut self, host: &Handle, source: TreeSource) {
11253        let key = ptr_of(host);
11254        if let Some((outline, data)) = tree_entry(key) {
11255            data.ivars().source.replace(Some(source));
11256            // Initial fill: child counts read the snapshot only; viewForItem is deferred.
11257            unsafe { outline.reloadData() };
11258        }
11259        // Realize visible rows on the next main-loop turn, outside any borrow (the
11260        // attach_list comment has the occluded-window story).
11261        <AppKit as Platform>::post(Box::new(move || {
11262            if let Some((outline, _)) = tree_entry(key) {
11263                unsafe { outline.layoutSubtreeIfNeeded() };
11264            }
11265        }));
11266    }
11267
11268    fn adopt(&mut self, raw: RawHandle) -> Handle {
11269        // A recycling NSTableView cell view; Day builds/rebinds its row content in place.
11270        // Invariant, not app input: day-core only passes back the cell pointer this backend
11271        // itself vended through `bind_row`, so a null here is a framework bug worth stopping on.
11272        let ptr = raw as *mut NSView;
11273        unsafe { Retained::retain(ptr) }.expect("adopt: null list cell handle")
11274    }
11275
11276    fn edit_toolbar(&mut self, h: &Handle, ops: &[day_spec::ToolbarOp]) -> bool {
11277        self.edit_toolbar(h, ops)
11278    }
11279
11280    fn update_toolbar(&mut self, h: &Handle, patch: &day_spec::ToolbarPatch) {
11281        self.patch_toolbar(h, patch);
11282    }
11283
11284    fn set_app_menu(&mut self, items: &[day_spec::MenuItem]) {
11285        let mtm = self.mtm;
11286        if self.menu_escape_monitor.is_none() {
11287            let block = block2::RcBlock::new(move |event: std::ptr::NonNull<NSEvent>| {
11288                ffi_guard::contain(event.as_ptr(), || {
11289                    let event_ref = unsafe { event.as_ref() };
11290                    let app = NSApplication::sharedApplication(mtm);
11291                    // Native dialogs retain their cancellation behavior. Only an enabled
11292                    // menu key equivalent can consume Escape, never the general key stream.
11293                    if app.modalWindow().is_none()
11294                        && app.keyWindow().is_some_and(|w| w.attachedSheet().is_none())
11295                        && unsafe { event_ref.charactersIgnoringModifiers() }
11296                            .is_some_and(|s| s.to_string() == "\u{1b}")
11297                        && app
11298                            .mainMenu()
11299                            .is_some_and(|menu| menu.performKeyEquivalent(event_ref))
11300                    {
11301                        std::ptr::null_mut()
11302                    } else {
11303                        event.as_ptr()
11304                    }
11305                })
11306            });
11307            self.menu_escape_monitor = unsafe {
11308                NSEvent::addLocalMonitorForEventsMatchingMask_handler(
11309                    objc2_app_kit::NSEventMask::KeyDown,
11310                    &block,
11311                )
11312            }
11313            .map(MenuEscapeMonitor);
11314        }
11315        let app = NSApplication::sharedApplication(mtm);
11316        let menubar = NSMenu::new(mtm);
11317        // macOS owns the application menu; relocate app-level roles while preserving
11318        // their callbacks, shortcuts, and enabled state.
11319        let mut items = items.to_vec();
11320        let about = extract_app_role(&mut items, day_spec::MenuRole::About);
11321        let updates = extract_app_role(&mut items, day_spec::MenuRole::CheckForUpdates);
11322        let prefs = extract_app_role(&mut items, day_spec::MenuRole::Preferences);
11323        let quit = extract_app_role(&mut items, day_spec::MenuRole::Quit);
11324        let services =
11325            install_application_menu(mtm, &menubar, &self.app_name, about, updates, prefs, quit);
11326        // Fill the standard slots the app did not claim, in the platform's bar order
11327        // (day-core owns that policy so every backend arranges its bar the same way).
11328        // Fill the standard slots the app left open, in macOS's bar order. The Window menu is
11329        // installed natively below, so the style deliberately supplies none.
11330        let items =
11331            day_core::menu::standard_menu_bar_for(day_core::menu::MenuBarStyle::Macos, items);
11332        let mut help_menu: Option<(String, Retained<NSMenu>)> = None;
11333        // Each top-level entry becomes a menu-bar menu.
11334        for item in &items {
11335            match item {
11336                day_spec::MenuItem::Submenu { label, items, role } => {
11337                    let sub = build_ns_menu(mtm, label, items);
11338                    let it = NSMenuItem::new(mtm);
11339                    // Help is held back: the Window menu is installed natively after this loop
11340                    // (AppKit owns it so it can append the live window list), and Help sits
11341                    // last on every Mac menu bar.
11342                    if *role == Some(day_spec::MenuBarRole::Help)
11343                        || *label == day_localization::t(day_localization::key::day_help)
11344                    {
11345                        help_menu = Some((label.clone(), sub));
11346                        continue;
11347                    }
11348                    it.setTitle(&NSString::from_str(label));
11349                    it.setSubmenu(Some(&sub));
11350                    menubar.addItem(&it);
11351                }
11352                other => {
11353                    // A bare top-level action → wrap in a one-item menu so it has a submenu.
11354                    let sub = build_ns_menu(mtm, "", std::slice::from_ref(other));
11355                    let it = NSMenuItem::new(mtm);
11356                    it.setSubmenu(Some(&sub));
11357                    menubar.addItem(&it);
11358                }
11359            }
11360        }
11361        // The Window menu (docs/windows.md): auto-installed unless the app's model owns
11362        // `MenuRole::Minimize` (then the app is composing its own window management).
11363        if !model_has_role(&items, day_spec::MenuRole::Minimize) {
11364            install_windows_menu(mtm, &app, &menubar);
11365        }
11366        if let Some((label, help)) = help_menu {
11367            let it = NSMenuItem::new(mtm);
11368            it.setTitle(&NSString::from_str(&label));
11369            it.setSubmenu(Some(&help));
11370            menubar.addItem(&it);
11371            // Registering it makes AppKit add the Help search field and index the help book —
11372            // behavior no hand-built menu reproduces.
11373            unsafe { app.setHelpMenu(Some(&help)) };
11374        }
11375        app.setMainMenu(Some(&menubar));
11376        unsafe { app.setServicesMenu(Some(&services)) };
11377    }
11378
11379    fn set_context_menu(&mut self, h: &Handle, _node: NodeId, items: &[day_spec::MenuItem]) {
11380        let Some(view) = h.downcast_ref::<NSView>() else {
11381            return;
11382        };
11383        if items.is_empty() {
11384            unsafe { view.setMenu(None) };
11385            return;
11386        }
11387        let menu = build_ns_menu(self.mtm, "", items);
11388        // Attach to the view AND its current subviews: a right-click that hit-tests a child
11389        // control (the label inside a padded target) must find the menu on the view it hit —
11390        // AppKit does not walk ancestors for `.menu`, and controls swallow the event.
11391        // DayFlipped's `rightMouseDown:` pops the menu explicitly; native controls (labels)
11392        // show their `.menu` through their own default path.
11393        unsafe { view.setMenu(Some(&menu)) };
11394        fn apply_to_subviews(v: &NSView, menu: &NSMenu) {
11395            for sub in v.subviews() {
11396                unsafe { sub.setMenu(Some(menu)) };
11397                apply_to_subviews(&sub, menu);
11398            }
11399        }
11400        apply_to_subviews(view, &menu);
11401    }
11402
11403    fn set_drag_source(&mut self, h: &Handle, source: day_spec::transfer::Source) {
11404        transfer::source(h, source);
11405    }
11406    fn set_drop_target(&mut self, h: &Handle, target: day_spec::transfer::Target) {
11407        transfer::target(h, target);
11408    }
11409    fn set_context_menu_fn(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
11410        // Consulted by the classes that override `menuForEvent:` (the canvas; docs/menus.md
11411        // "Dynamic context menus" lists the covered surfaces per backend).
11412        CTX_MENU_FNS.with(|t| t.insert(ptr_of(h), f));
11413    }
11414
11415    fn set_button_menu(&mut self, h: &Handle, _node: NodeId, f: day_spec::ContextMenuFn) {
11416        let Some(btn) = h.downcast_ref::<NSButton>() else {
11417            return;
11418        };
11419        // A pull-down opens on the mouse going down, as `NSPopUpButton` does, so a press can
11420        // drag straight onto an item and release there. Space and the accessibility press
11421        // still arrive through `performClick:`, which sends the same action.
11422        unsafe { btn.sendActionOn(objc2_app_kit::NSEventMask::LeftMouseDown) };
11423        BUTTON_MENUS.with(|t| t.insert(ptr_of(h), f));
11424    }
11425
11426    fn enable_gesture(&mut self, h: &Handle, node: NodeId, kind: day_spec::GestureKind) {
11427        let key = ptr_of(h);
11428        // Pan is not a recognizer on macOS: the two-finger idiom is the trackpad SCROLL, so
11429        // the canvas view's own `scrollWheel:` override reports it for registered nodes.
11430        // Containers use a horizontal-only monitor so nested vertical scrolling still works.
11431        if kind == day_spec::GestureKind::Pan {
11432            PAN_NODES.with(|t| t.insert(key, node));
11433            install_container_pan_monitor();
11434            return;
11435        }
11436        // Nor is rotation: `DayCanvas::rotateWithEvent:` reads the trackpad's rotate events, so
11437        // it runs alongside the magnification recognizer a pinch attaches. Like Pan and Hover,
11438        // a rotation enabled on another view emits nothing.
11439        if kind == day_spec::GestureKind::Rotate {
11440            ROTATE_NODES.with(|t| t.insert(key, node));
11441            return;
11442        }
11443        // Nor is hover: it is a tracking area plus `mouseEntered:`/`mouseMoved:`/`mouseExited:`,
11444        // which only `DayCanvas` overrides — a hover enabled on another view emits nothing, the
11445        // same limitation Pan has.
11446        if kind == day_spec::GestureKind::Hover {
11447            // Idempotent, and it has to be checked here rather than falling through to the
11448            // recognizer guard below: day-core re-enables a gesture on rebuild, and a second
11449            // tracking area on the same view means a second copy of every hover event.
11450            let first = HOVER_NODES.with(|t| t.get(key)).is_none();
11451            HOVER_NODES.with(|t| t.insert(key, node));
11452            if first {
11453                install_tracking_area(h);
11454            }
11455            return;
11456        }
11457        // Idempotent: attach each kind at most once per view.
11458        let already = GESTURES.with(|m| {
11459            m.borrow()
11460                .get(&key)
11461                .is_some_and(|v| v.iter().any(|t| t.ivars().kind == kind))
11462        });
11463        if already {
11464            return;
11465        }
11466        let mtm = self.mtm;
11467        let target = DayGesture::new(mtm, node, kind);
11468        let recognizer: Retained<NSGestureRecognizer> = unsafe {
11469            match kind {
11470                day_spec::GestureKind::Drag => {
11471                    Retained::into_super(NSPanGestureRecognizer::initWithTarget_action(
11472                        NSPanGestureRecognizer::alloc(mtm),
11473                        Some(&target),
11474                        Some(sel!(fire:)),
11475                    ))
11476                }
11477                day_spec::GestureKind::Pinch => Retained::into_super(
11478                    objc2_app_kit::NSMagnificationGestureRecognizer::initWithTarget_action(
11479                        objc2_app_kit::NSMagnificationGestureRecognizer::alloc(mtm),
11480                        Some(&target),
11481                        Some(sel!(fire:)),
11482                    ),
11483                ),
11484                _ => Retained::into_super(NSClickGestureRecognizer::initWithTarget_action(
11485                    NSClickGestureRecognizer::alloc(mtm),
11486                    Some(&target),
11487                    Some(sel!(fire:)),
11488                )),
11489            }
11490        };
11491        unsafe { h.addGestureRecognizer(&recognizer) };
11492        GESTURES.with(|m| m.borrow_mut().entry(key).or_default().push(target));
11493    }
11494
11495    fn set_a11y(&mut self, h: &Handle, a11y: &A11yProps) {
11496        unsafe {
11497            if let Some(id) = &a11y.identifier {
11498                h.setAccessibilityIdentifier(Some(&NSString::from_str(id)));
11499            }
11500            if let Some(label) = &a11y.label {
11501                h.setAccessibilityLabel(Some(&NSString::from_str(label)));
11502                APP_LABELED.with(|t| t.insert(ptr_of(h), ()));
11503            } else {
11504                APP_LABELED.with(|t| t.remove(ptr_of(h)));
11505            }
11506            if let Some(hint) = &a11y.hint {
11507                h.setAccessibilityHelp(Some(&NSString::from_str(hint)));
11508            }
11509            if let Some(value) = &a11y.value {
11510                let ns = NSString::from_str(value);
11511                h.setAccessibilityValue(Some(ns.as_ref() as &objc2::runtime::AnyObject));
11512            }
11513            // Only apply an EXPLICIT role (canvas/custom pieces, e.g. a Meter): native controls
11514            // already report the right role, so Day records but doesn't override theirs (§13).
11515            if let Some(role) = ns_role(a11y.role) {
11516                h.setAccessibilityRole(Some(role));
11517            }
11518            if a11y.role == day_spec::Role::Tab {
11519                h.setAccessibilitySubrole(Some(objc2_app_kit::NSAccessibilityTabButtonSubrole));
11520            }
11521            if let Some(on) = a11y.selected {
11522                h.setAccessibilitySelected(on);
11523            }
11524            // Decorative / hidden: drop from the AX tree entirely. An ignored view alone is
11525            // not enough — AppKit promotes an ignored element's children into its parent's
11526            // list — so the subtree is cut off too, which also covers subviews added later
11527            // (list rows, re-created children). Hidden never flips back, so the override is
11528            // never lifted.
11529            if a11y.hidden {
11530                h.setAccessibilityElement(false);
11531                h.setAccessibilityChildren(Some(&NSArray::new()));
11532            }
11533        }
11534    }
11535
11536    /// The announcement request goes out from the primary window (any live element will
11537    /// do; the app object stands in before the window exists). Without VoiceOver nothing
11538    /// observes the notification, so posting is free.
11539    fn announce(&mut self, text: &str, urgent: bool) {
11540        use objc2_app_kit::{
11541            NSAccessibilityAnnouncementKey, NSAccessibilityAnnouncementRequestedNotification,
11542            NSAccessibilityPostNotificationWithUserInfo, NSAccessibilityPriorityKey,
11543            NSAccessibilityPriorityLevel,
11544        };
11545        let app = NSApplication::sharedApplication(self.mtm());
11546        let window = primary_content().and_then(|content| content.window());
11547        let element: &objc2::runtime::AnyObject = match &window {
11548            Some(window) => window,
11549            None => &app,
11550        };
11551        // High priority interrupts the current sentence; medium waits its turn.
11552        let priority = if urgent {
11553            NSAccessibilityPriorityLevel::High
11554        } else {
11555            NSAccessibilityPriorityLevel::Medium
11556        };
11557        let announcement = NSString::from_str(text);
11558        let priority = NSNumber::new_isize(priority.0);
11559        let values: [&objc2::runtime::AnyObject; 2] = [&announcement, &priority];
11560        // SAFETY: the keys are AppKit's constants and both values are the types the
11561        // announcement notification documents (an NSString and an NSNumber).
11562        unsafe {
11563            let user_info = NSDictionary::from_slices::<NSString>(
11564                &[NSAccessibilityAnnouncementKey, NSAccessibilityPriorityKey],
11565                &values,
11566            );
11567            NSAccessibilityPostNotificationWithUserInfo(
11568                element,
11569                NSAccessibilityAnnouncementRequestedNotification,
11570                Some(&user_info),
11571            );
11572        }
11573    }
11574
11575    fn read_native(&self, h: &Handle) -> day_spec::NativeSnapshot {
11576        unsafe {
11577            let role = h
11578                .accessibilityRole()
11579                .map(|r| day_role_from_ns(&r.to_string()))
11580                .unwrap_or(day_spec::Role::None);
11581            // A picker answers its displayed selection and its enabled state itself: the
11582            // inline style is a stack of radios, not one control.
11583            let picker = picker::read_native(h);
11584            day_spec::NativeSnapshot {
11585                found: true,
11586                role,
11587                label: h.accessibilityLabel().map(|s| s.to_string()),
11588                value: h
11589                    .accessibilityValue()
11590                    .and_then(|v| v.downcast_ref::<NSString>().map(|s| s.to_string())),
11591                identifier: h
11592                    .accessibilityIdentifier()
11593                    .map(|s| s.to_string())
11594                    .filter(|s| !s.is_empty()),
11595                text: match &picker {
11596                    Some((text, _)) => text.clone(),
11597                    None => native_text(h),
11598                },
11599                number: native_number(h),
11600                checked: if let Some(sw) = h.downcast_ref::<NSSwitch>() {
11601                    match sw.state() {
11602                        s if s == NSControlStateValueOn => Some(true),
11603                        s if s == NSControlStateValueOff => Some(false),
11604                        // Mixed is neither on nor off.
11605                        _ => None,
11606                    }
11607                } else if let Some(btn) = h.downcast_ref::<NSButton>() {
11608                    // A Day button's selected state (`ButtonProps::selected`): its own
11609                    // `state`, which a momentary button holds off at rest.
11610                    BUTTON_SELECTED
11611                        .with(|m| m.borrow().contains_key(&ptr_of(h)))
11612                        .then(|| btn.state() == NSControlStateValueOn)
11613                } else {
11614                    None
11615                },
11616                // A label is a non-editable NSTextField whose `isEnabled` says nothing about
11617                // input; every other control answers for itself.
11618                enabled: match (&picker, h.downcast_ref::<NSControl>()) {
11619                    (Some((_, on)), _) => *on,
11620                    (None, Some(_)) if h.downcast_ref::<DayLabel>().is_some() => None,
11621                    (None, Some(c)) => Some(c.isEnabled()),
11622                    (None, None) => None,
11623                },
11624                // Off-window counts as not shown: nothing of it reaches the screen.
11625                visible: Some(h.window().is_some() && !h.isHiddenOrHasHiddenAncestor()),
11626                frame: native_frame(h),
11627            }
11628        }
11629    }
11630
11631    fn request_frame(
11632        &mut self,
11633        host: &Handle,
11634        cb: day_spec::FrameCallback,
11635    ) -> day_spec::CancelFrame {
11636        frame::request(host, cb)
11637    }
11638
11639    fn replay(&mut self, h: &Handle, ops: &[DrawOp], _size: Size) {
11640        OPS.with(|t| t.insert(ptr_of(h), ops.to_vec()));
11641        unsafe { h.setNeedsDisplay(true) };
11642    }
11643    fn toggle_sidebar(&mut self, host: &Self::Handle) -> bool {
11644        NAV_STATE.with(|m| {
11645            let m = m.borrow();
11646            let Some(st) = m.get(&ptr_of(host)) else {
11647                return false;
11648            };
11649            // A pane to toggle exists in `Split` and `Rail`; a stack has none and a tab bar
11650            // keeps its rows in the chrome, where hiding them would strand the user.
11651            if !matches!(
11652                st.presentation,
11653                NavPresentation::Split | NavPresentation::Rail
11654            ) {
11655                return false;
11656            }
11657            let item = &st.sidebar_item;
11658            // Set directly, not through the `animator` proxy. The proxy defers the change to
11659            // an animation the dayscript screenshot step does not wait on, so a scripted
11660            // toggle captured a sidebar that had not moved yet. AppKit's own
11661            // NSToolbarToggleSidebarItem still animates — it runs `toggleSidebar:` on the
11662            // controller and never comes through here.
11663            let collapsed = unsafe { item.isCollapsed() };
11664            unsafe { item.setCollapsed(!collapsed) };
11665            true
11666        })
11667    }
11668
11669    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
11670        let content = self.content.as_ref().ok_or("no window content")?;
11671        match self.shown_document_content(content) {
11672            Some(shown) => snapshot_view(&shown),
11673            None => snapshot_view(content),
11674        }
11675    }
11676
11677    /// Decode bytes into an `NSImage` (docs/images.md).
11678    ///
11679    /// `NSBitmapImageRep` is asked first and kept: it is what actually reads the container, it
11680    /// answers in PIXELS (`NSImage.size` is in points and reports a 144-DPI photo at
11681    /// two-thirds its real width), and it is the only thing here that can re-encode later.
11682    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
11683        use objc2::AllocAnyThread as _;
11684        let data = NSData::with_bytes(bytes);
11685        let Some(rep) = (unsafe { objc2_app_kit::NSBitmapImageRep::imageRepWithData(&data) })
11686        else {
11687            emit(
11688                WINDOW_NODE,
11689                Event::ImageDecoded {
11690                    req,
11691                    result: Err(day_spec::ImageError::Decode),
11692                },
11693            );
11694            return;
11695        };
11696        let (w, h) = unsafe { (rep.pixelsWide() as f64, rep.pixelsHigh() as f64) };
11697        let info = day_spec::BitmapInfo {
11698            pixels: Size::new(w, h),
11699            // Decoded bytes carry no density — a PNG is simply its pixels. Only a staged @2x
11700            // asset has a scale, and that arrives through the named path instead.
11701            scale: 1.0,
11702            format: day_spec::ImageFormat::sniff(bytes),
11703            has_alpha: unsafe { rep.hasAlpha() },
11704        };
11705        // Built AT the rep's pixel size so it draws 1:1 by default: an NSImage otherwise adopts
11706        // the rep's own `size`, which ImageIO derives from the file's DPI — that is what shrinks
11707        // a 144-DPI photo for no reason the app asked for.
11708        let image = unsafe {
11709            objc2_app_kit::NSImage::initWithSize(objc2_app_kit::NSImage::alloc(), NSSize::new(w, h))
11710        };
11711        unsafe { image.addRepresentation(&rep) };
11712        BITMAPS.with(|m| {
11713            m.borrow_mut().insert(
11714                id.0,
11715                AppKitBitmap {
11716                    image,
11717                    rep: Some(rep),
11718                    info,
11719                },
11720            )
11721        });
11722        emit(
11723            WINDOW_NODE,
11724            Event::ImageDecoded {
11725                req,
11726                result: Ok(info),
11727            },
11728        );
11729    }
11730
11731    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
11732        BITMAPS.with(|m| m.borrow().get(&id.0).map(|b| b.info))
11733    }
11734
11735    /// The container's own metadata (docs/images.md).
11736    ///
11737    /// DPI is DERIVED rather than read from a tag: AppKit has already resolved the file's
11738    /// resolution into the rep's point size, so pixels-per-point × 72 is the number the platform
11739    /// itself believes — and it is right for containers that record resolution in ways EXIF
11740    /// does not.
11741    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
11742        let rep = BITMAPS.with(|m| m.borrow().get(&id.0).and_then(|b| b.rep.clone()))?;
11743        let mut out = day_spec::ImageProperties::default();
11744        let size = unsafe { rep.size() };
11745        if size.width > 0.0 {
11746            let dpi = unsafe { rep.pixelsWide() } as f64 / size.width * 72.0;
11747            // 72 is "no resolution recorded" wearing a number; reporting it would read as a fact
11748            // the file never stated.
11749            if (dpi - 72.0).abs() > 0.5 {
11750                out.dpi = Some(dpi);
11751            }
11752        }
11753        // EXIF arrives as a dictionary of the format's own keys. It is walked through
11754        // `msg_send!` rather than a downcast because a generic `NSDictionary` is not a
11755        // `DowncastTarget`.
11756        if let Some(exif) = rep.valueForProperty(unsafe { objc2_app_kit::NSImageEXIFData }) {
11757            let keys: Retained<NSArray<NSString>> = unsafe { msg_send![&*exif, allKeys] };
11758            for key in keys.iter() {
11759                let value: Option<Retained<objc2::runtime::AnyObject>> =
11760                    unsafe { msg_send![&*exif, objectForKey: &*key] };
11761                let Some(value) = value else { continue };
11762                let text: Retained<NSString> = unsafe { msg_send![&*value, description] };
11763                let (k, v) = (key.to_string(), text.to_string());
11764                match k.as_str() {
11765                    "Orientation" => out.orientation = v.parse().ok(),
11766                    "DateTimeOriginal" => out.created = Some(v.clone()),
11767                    _ => {}
11768                }
11769                // Keys stay in EXIF's own vocabulary, passed through rather than translated —
11770                // the doc for `extra` promises exactly that.
11771                out.extra.push((k, v));
11772            }
11773        }
11774        Some(out)
11775    }
11776
11777    /// What `NSBitmapImageRep` WRITES. It reads more than this — WebP and HEIF among them — and
11778    /// the asymmetry is the platform's own, which is exactly why this duty exists instead of
11779    /// letting `Cap::ImageEncode` imply every format round-trips.
11780    fn encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
11781        use day_spec::ImageFormat::{Bmp, Gif, Jpeg, Png, Tiff};
11782        vec![Png, Jpeg, Tiff, Bmp, Gif]
11783    }
11784
11785    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
11786        let result = encode_bitmap(id, spec);
11787        emit(WINDOW_NODE, Event::ImageEncoded { req, result });
11788    }
11789
11790    fn release_image(&mut self, id: day_spec::BitmapId) {
11791        release_bitmap(id);
11792    }
11793
11794    /// Replay `ops` offscreen through the canvas's own painter (docs/canvas.md "Exporting") and
11795    /// keep the result in the decode table, so `image`, `encode_image` and `DrawOp::Image` take
11796    /// it like any decoded bitmap.
11797    ///
11798    /// The paint runs on a `day_spec::offscreen` thread: CoreGraphics draws into a bitmap
11799    /// context from any thread, so a long replay (a map tile of a thousand paths) no longer
11800    /// holds a frame. The images and fonts the ops need are resolved here first, the painted
11801    /// `CGImage` comes back on the main queue, and the table insert and the answer happen
11802    /// there, in that order.
11803    fn render_bitmap(
11804        &mut self,
11805        req: u64,
11806        id: day_spec::BitmapId,
11807        ops: &[DrawOp],
11808        size: Size,
11809        scale: f64,
11810    ) {
11811        let resources = Sendable(OffscreenResources::collect(ops));
11812        let ops = ops.to_vec();
11813        day_spec::offscreen::spawn(move || {
11814            // Bound whole so the closure captures the `Send` wrapper, not its field.
11815            let resources = resources;
11816            let painted = day_spec::ffi_guard::contain(
11817                Err(day_spec::ExportError::Failed(
11818                    "the offscreen painter panicked".into(),
11819                )),
11820                || {
11821                    let started = std::time::Instant::now();
11822                    let painted = resources
11823                        .0
11824                        .with_installed(|| render_bitmap_cgimage(&ops, size, scale));
11825                    // The painter's own cost, apart from the queuing a caller's clock sees.
11826                    log::debug!(
11827                        "day-toolkit-appkit: bitmap {}x{} painted in {:.1} ms ({} ops)",
11828                        size.width * scale,
11829                        size.height * scale,
11830                        started.elapsed().as_secs_f64() * 1000.0,
11831                        ops.len()
11832                    );
11833                    painted
11834                },
11835            );
11836            let painted = Sendable(painted);
11837            <AppKit as Platform>::post(Box::new(move || {
11838                let painted = painted;
11839                let result = painted.0.map(|cg_image| {
11840                    let bitmap = bitmap_from_cgimage(&cg_image, scale);
11841                    let info = bitmap.info;
11842                    BITMAPS.with(|m| m.borrow_mut().insert(id.0, bitmap));
11843                    info
11844                });
11845                emit(WINDOW_NODE, Event::BitmapRendered { req, result });
11846            }));
11847        });
11848    }
11849
11850    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
11851        let result = render_pdf_bytes(pages, info);
11852        emit(WINDOW_NODE, Event::PdfRendered { req, result });
11853    }
11854
11855    /// `NSFontManager.availableFontFamilies` + `availableMembersOfFontFamily:`, whose members
11856    /// are `[postscriptName, styleName, weight 0 … 15, traits]` (docs/fonts.md). The `.`-prefixed
11857    /// families are the system's private UI faces and are skipped, as Font Book skips them.
11858    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
11859        use day_spec::FontWeight as W;
11860        let mtm =
11861            objc2::MainThreadMarker::new().expect("day-toolkit-appkit runs on the main thread");
11862        let manager = unsafe { objc2_app_kit::NSFontManager::sharedFontManager(mtm) };
11863        let mut out = Vec::new();
11864        for family in unsafe { manager.availableFontFamilies() }.iter() {
11865            let name = family.to_string();
11866            if name.starts_with('.') {
11867                continue;
11868            }
11869            let mut faces = Vec::new();
11870            if let Some(members) = unsafe { manager.availableMembersOfFontFamily(&family) } {
11871                for member in members.iter() {
11872                    if member.count() < 4 {
11873                        continue;
11874                    }
11875                    let style = member
11876                        .objectAtIndex(1)
11877                        .downcast_ref::<NSString>()
11878                        .map(|s| s.to_string())
11879                        .unwrap_or_default();
11880                    let weight = member
11881                        .objectAtIndex(2)
11882                        .downcast_ref::<objc2_foundation::NSNumber>()
11883                        .map(|n| n.integerValue())
11884                        .unwrap_or(5);
11885                    let traits = member
11886                        .objectAtIndex(3)
11887                        .downcast_ref::<objc2_foundation::NSNumber>()
11888                        .map(|n| n.integerValue())
11889                        .unwrap_or(0);
11890                    let weight = match weight {
11891                        ..=2 => W::UltraLight,
11892                        3 => W::Thin,
11893                        4 => W::Light,
11894                        5 => W::Regular,
11895                        6 => W::Medium,
11896                        7 | 8 => W::Semibold,
11897                        9 => W::Bold,
11898                        10 | 11 => W::Heavy,
11899                        _ => W::Black,
11900                    };
11901                    let italic = traits & 0x1 != 0; // NSItalicFontMask
11902                    faces.push(day_spec::FontFace {
11903                        name: if style.is_empty() {
11904                            day_spec::FontFace::synthesized_name(weight, italic)
11905                        } else {
11906                            style
11907                        },
11908                        weight,
11909                        italic,
11910                    });
11911                }
11912            }
11913            out.push(day_spec::FontFamilyInfo {
11914                family: name,
11915                faces,
11916            });
11917        }
11918        out
11919    }
11920
11921    /// `sizeWithAttributes:` with the attributes `replay` draws with; the ascent is the
11922    /// font's own, so `at.y + ascent` is where the glyphs' baseline lands.
11923    fn measure_text(
11924        &mut self,
11925        text: &str,
11926        size: f64,
11927        font: &day_spec::CanvasFont,
11928    ) -> Option<day_spec::TextMetrics> {
11929        let nsfont = canvas_nsfont(size, font);
11930        let attrs = canvas_text_attrs(&nsfont, day_spec::Color::BLACK);
11931        let ns = NSString::from_str(text);
11932        let sz: NSSize = unsafe { msg_send![&ns, sizeWithAttributes: &*attrs] };
11933        // The INK box: `NSStringDrawingUsesDeviceMetrics` is what turns `boundingRectWithSize:`
11934        // from the layout box into the glyphs' own bounds, and it comes back baseline-relative
11935        // with y up — hence the flip. An unbounded size so nothing wraps: this measures one line.
11936        let unbounded = NSSize::new(f64::MAX, f64::MAX);
11937        let ink: NSRect = unsafe {
11938            msg_send![
11939                &ns,
11940                boundingRectWithSize: unbounded,
11941                options: objc2_app_kit::NSStringDrawingOptions::UsesDeviceMetrics,
11942                attributes: &*attrs,
11943            ]
11944        };
11945        Some(day_spec::TextMetrics::from_baseline(
11946            sz.width,
11947            nsfont.ascender(),
11948            sz.height - nsfont.ascender(),
11949            nsfont.capHeight(),
11950            day_spec::Rect::new(
11951                ink.origin.x,
11952                -(ink.origin.y + ink.size.height),
11953                ink.size.width,
11954                ink.size.height,
11955            ),
11956        ))
11957    }
11958
11959    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
11960        let content = self.content.as_ref().ok_or("no window content")?;
11961        match self.shown_document_content(content) {
11962            Some(shown) => snapshot_view_chrome(&shown),
11963            None => snapshot_view_chrome(content),
11964        }
11965    }
11966
11967    fn snapshot_window_of(&mut self, host: &Handle) -> Result<Vec<u8>, String> {
11968        snapshot_view(host)
11969    }
11970
11971    fn open_window(
11972        &mut self,
11973        id: NodeId,
11974        options: &WindowOptions,
11975        kind: day_spec::WindowKind,
11976    ) -> day_spec::WindowOpenReply<Handle> {
11977        let prefs = kind.is_panel();
11978        let (window, delegate, content) = self.make_window(options, prefs, Some(id));
11979        if prefs {
11980            // A settings panel is one-of-a-kind and centered, and it stays OUT of the Window
11981            // menu — the macOS convention every stock app follows (docs/windows.md).
11982            window.center();
11983            unsafe { window.setExcludedFromWindowsMenu(true) };
11984        } else {
11985            // Stagger, don't stack. Without this every window opens at the same centered frame
11986            // and the one underneath is invisible — which is exactly what two Day windows did.
11987            //
11988            // `cascadeTopLeftFromPoint:` puts the window AT the point it is given and answers
11989            // the point for the one after, so the series has to be primed from the primary
11990            // rather than seeded with its corner — seeding lands the first new window exactly
11991            // on top of the primary, which is the bug this replaces.
11992            let from = match self.cascade {
11993                Some(p) => p,
11994                None => self
11995                    .window
11996                    .as_ref()
11997                    .map(|w| {
11998                        let f = w.frame();
11999                        let top_left = NSPoint::new(f.origin.x, f.origin.y + f.size.height);
12000                        // Asking the primary to cascade from where it already is leaves it
12001                        // there and answers the next slot — the offset the first new window wants.
12002                        unsafe { w.cascadeTopLeftFromPoint(top_left) }
12003                    })
12004                    .unwrap_or(NSPoint::new(0.0, 0.0)),
12005            };
12006            self.cascade = Some(unsafe { window.cascadeTopLeftFromPoint(from) });
12007        }
12008        window_chrome::place(&window, options.placement);
12009        // `center` (a settings panel's, or a `Centered` placement's) uses the main screen, the
12010        // one with the keyboard focus, which on a Mac with several displays need not be the
12011        // app's: such a window goes to the primary's screen instead. A scripted run on the
12012        // capture display relies on this to keep the window in its captures.
12013        if prefs || matches!(options.placement, day_spec::WindowPlacement::Centered) {
12014            center_on_screen_of(&window, self.window.as_deref());
12015        }
12016        // Secondary windows need the same initial client-coordinate pinning as the
12017        // primary. Native document pages may move here before any resize notification.
12018        let _ = pin_below_title_bar(&window);
12019        if !options.start_hidden {
12020            window.makeKeyAndOrderFront(None);
12021        }
12022        // Same macOS 26 quirk as the primary (`run`): a window ordered front before its
12023        // first turn drops pre-run layer displays — nudge every layer once.
12024        mark_tree_needs_display(&content);
12025        self.secondary.push(SecondaryWin {
12026            window,
12027            delegate,
12028            content: content.clone(),
12029        });
12030        day_spec::WindowOpenReply::Open(content)
12031    }
12032
12033    fn native_window_tabs(&self) -> bool {
12034        true
12035    }
12036    fn group_windows(&mut self, hosts: &[Handle]) {
12037        let windows: Vec<_> = hosts.iter().filter_map(|h| self.ns_window_for(h)).collect();
12038        let Some(first) = windows.first() else {
12039            return;
12040        };
12041        unsafe {
12042            NSWindow::setAllowsAutomaticWindowTabbing(true, self.mtm);
12043        }
12044        // Explicit insertion respects the model even when system automatic tabbing is off.
12045        for window in windows.iter().skip(1) {
12046            unsafe {
12047                first.addTabbedWindow_ordered(window, objc2_app_kit::NSWindowOrderingMode::Above);
12048            }
12049        }
12050        if let Some(group) = first.tabGroup() {
12051            if !group.isTabBarVisible() {
12052                unsafe {
12053                    first.toggleTabBar(None);
12054                }
12055            }
12056            for (i, window) in windows.iter().enumerate() {
12057                group.insertWindow_atIndex(window, i as isize);
12058            }
12059        }
12060        // Adding/showing a native tab strip changes contentLayoutRect without necessarily
12061        // resizing the window. Re-pin every member and tell the layout tree its usable size.
12062        for window in &windows {
12063            if let Some(size) = pin_below_title_bar(window) {
12064                let node = window
12065                    .delegate()
12066                    .and_then(|d| d.downcast::<DayWinDelegate>().ok())
12067                    .and_then(|d| d.ivars().node)
12068                    .unwrap_or(WINDOW_NODE);
12069                emit(node, Event::WindowResized(size));
12070            }
12071        }
12072    }
12073    fn window_tab_order(&self, host: &Handle) -> Vec<NodeId> {
12074        let Some(window) = self.ns_window_for(host) else {
12075            return Vec::new();
12076        };
12077        let windows = window.tabGroup().map(|g| g.windows());
12078        let Some(windows) = windows else {
12079            return Vec::new();
12080        };
12081        windows
12082            .iter()
12083            .filter_map(|window| {
12084                self.secondary
12085                    .iter()
12086                    .find(|w| std::ptr::eq(&*w.window, &*window))
12087                    .and_then(|w| w.delegate.ivars().node)
12088            })
12089            .collect()
12090    }
12091
12092    fn close_window(&mut self, host: &Handle) {
12093        // `close()` runs the full native path — windowWillClose → `WindowClosed` →
12094        // day-core teardown — so programmatic and title-bar closes are one code path.
12095        if let Some(w) = self
12096            .secondary
12097            .iter()
12098            .find(|w| ptr_of(&w.content) == ptr_of(host))
12099        {
12100            w.window.close();
12101        }
12102    }
12103
12104    fn focus_window(&mut self, host: &Handle) {
12105        if let Some(w) = self
12106            .secondary
12107            .iter()
12108            .find(|w| ptr_of(&w.content) == ptr_of(host))
12109        {
12110            w.window.makeKeyAndOrderFront(None);
12111        }
12112    }
12113
12114    fn fit_window(&mut self, host: &Handle, size: Size) {
12115        let Some(w) = self
12116            .secondary
12117            .iter()
12118            .find(|w| ptr_of(&w.content) == ptr_of(host))
12119        else {
12120            return;
12121        };
12122        unsafe {
12123            // `setContentSize:` rather than `setFrame:`: Day measured the CONTENT, and AppKit
12124            // adds the title bar itself. Sizing the frame instead would eat the bar's height out
12125            // of the panel and clip the last row by exactly that much.
12126            w.window
12127                .setContentSize(NSSize::new(size.width, size.height));
12128            // A settings panel that fits its content has no reason to be resizable, and macOS
12129            // panels are not — dropping the mask also stops the user dragging it back to a size
12130            // the content does not fill.
12131            let mask = w.window.styleMask();
12132            w.window
12133                .setStyleMask(mask & !objc2_app_kit::NSWindowStyleMask::Resizable);
12134            w.window.center();
12135        }
12136        center_on_screen_of(&w.window, self.window.as_deref());
12137    }
12138
12139    fn set_window_title(&mut self, host: &Handle, title: &str) {
12140        if let Some(w) = self
12141            .secondary
12142            .iter()
12143            .find(|w| ptr_of(&w.content) == ptr_of(host))
12144        {
12145            w.window.setTitle(&NSString::from_str(title));
12146            return;
12147        }
12148        // The PRIMARY window is retitlable too. It is an ordinary window (docs/windows.md), so
12149        // `window_title` in the first window's shell and `set_title` on `initial_window()` both
12150        // arrive here — and searching only the secondary list silently dropped them.
12151        if self
12152            .content
12153            .as_ref()
12154            .is_some_and(|c| ptr_of(c) == ptr_of(host))
12155            && let Some(w) = self.window.as_ref()
12156        {
12157            w.setTitle(&NSString::from_str(title));
12158        }
12159    }
12160
12161    fn apply_window(&mut self, host: &Handle, change: &day_spec::WindowChange) {
12162        use day_spec::WindowChange as C;
12163        let Some(window) = self.ns_window_for(host) else {
12164            return;
12165        };
12166        match change {
12167            C::State(state) => set_ns_window_state(&window, *state),
12168            // Screen capture, recording and sharing see an empty window; the user still does.
12169            C::ContentProtected(on) => window.setSharingType(if *on {
12170                objc2_app_kit::NSWindowSharingType::None
12171            } else {
12172                objc2_app_kit::NSWindowSharingType::ReadOnly
12173            }),
12174            other => window_chrome::apply_property(&window, other),
12175        }
12176    }
12177
12178    fn window_frame(&self, host: &Handle) -> Option<day_spec::Rect> {
12179        self.ns_window_for(host)
12180            .map(|w| window_chrome::frame_of(&w))
12181    }
12182
12183    fn monitors(&self) -> Vec<day_spec::Monitor> {
12184        window_chrome::monitors(self.mtm)
12185    }
12186
12187    /// The Dock menu lists them: day-core folds the run-time shortcuts into the model it sends
12188    /// through `set_dock_menu`, so there is nothing more to install here.
12189    fn set_launcher_shortcuts(&mut self, _shortcuts: &[day_spec::LauncherShortcut]) {}
12190
12191    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
12192        dock::set_app_items(self.mtm, items);
12193    }
12194
12195    fn set_drag_region(&mut self, h: &Handle, drag: bool) {
12196        window_chrome::set_drag_region(h, drag);
12197    }
12198
12199    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
12200        status_item::set_items(self.mtm, items);
12201    }
12202
12203    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
12204        status_item::set_progress(self.mtm, progress);
12205    }
12206
12207    fn set_dock_visible(&mut self, visible: bool) {
12208        status_item::set_dock_visible(self.mtm, visible);
12209    }
12210
12211    fn set_keep_running(&mut self, keep: bool) {
12212        status_item::set_keep_running(keep);
12213    }
12214
12215    fn quit_app(&mut self) {
12216        let app = NSApplication::sharedApplication(self.mtm);
12217        unsafe { app.terminate(None) };
12218    }
12219
12220    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
12221        use present::PresentSpec;
12222        let mtm = self.mtm;
12223        // Sheets attach to the KEY window at present time (docs/windows.md) — a dialog
12224        // raised from a secondary/preferences window belongs on it; primary is the
12225        // fallback when no DAY window is key (a system panel may hold key status).
12226        let app = NSApplication::sharedApplication(mtm);
12227        let key = app.keyWindow().filter(|k| {
12228            let mut owner = k.clone();
12229            while let Some(parent) = owner.sheetParent() {
12230                owner = parent;
12231            }
12232            self.window
12233                .as_deref()
12234                .is_some_and(|w| std::ptr::eq(w, &*owner))
12235                || self
12236                    .secondary
12237                    .iter()
12238                    .any(|s| std::ptr::eq(&*s.window, &*owner))
12239        });
12240        let Some(mut window) = key.or_else(|| self.window.clone()) else {
12241            emit(
12242                WINDOW_NODE,
12243                Event::PresentResult {
12244                    req,
12245                    result: present::PresentResult::Dismissed,
12246                },
12247            );
12248            return;
12249        };
12250        // A dialog opened from a modal cover belongs on the active sheet, not behind it.
12251        while let Some(sheet) = window.attachedSheet() {
12252            window = sheet;
12253        }
12254        // File pickers use a different native object (NSOpen/NSSavePanel), not an NSAlert.
12255        match spec {
12256            PresentSpec::OpenFile {
12257                filters, multiple, ..
12258            } => {
12259                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
12260                unsafe {
12261                    panel.setCanChooseFiles(true);
12262                    panel.setCanChooseDirectories(false);
12263                    panel.setAllowsMultipleSelection(*multiple);
12264                    panel.setMessage(Some(&NSString::from_str(spec.title())));
12265                }
12266                apply_allowed_file_types(&panel, filters);
12267                let p = panel.clone();
12268                // Completion blocks run inside a C ABI frame, so their bodies are contained
12269                // like every other trampoline (§8.5) — this one and the four below.
12270                let handler: block2::RcBlock<dyn Fn(isize)> =
12271                    block2::RcBlock::new(move |resp: isize| {
12272                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
12273                    });
12274                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12275                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
12276                return;
12277            }
12278            // The folder chooser is the same NSOpenPanel with files and directories swapped.
12279            PresentSpec::OpenFolder { .. } => {
12280                let panel = unsafe { objc2_app_kit::NSOpenPanel::openPanel(mtm) };
12281                unsafe {
12282                    panel.setCanChooseFiles(false);
12283                    panel.setCanChooseDirectories(true);
12284                    panel.setCanCreateDirectories(true);
12285                    panel.setAllowsMultipleSelection(false);
12286                    panel.setMessage(Some(&NSString::from_str(spec.title())));
12287                }
12288                let p = panel.clone();
12289                let handler: block2::RcBlock<dyn Fn(isize)> =
12290                    block2::RcBlock::new(move |resp: isize| {
12291                        ffi_guard::contain((), || emit_open_panel_result(req, resp, &p));
12292                    });
12293                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12294                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, Retained::into_super(panel)));
12295                return;
12296            }
12297            PresentSpec::SaveFile { suggested_name, .. } => {
12298                let panel = unsafe { objc2_app_kit::NSSavePanel::savePanel(mtm) };
12299                unsafe {
12300                    panel.setMessage(Some(&NSString::from_str(spec.title())));
12301                    panel.setNameFieldStringValue(&NSString::from_str(suggested_name));
12302                }
12303                apply_allowed_file_types(&panel, spec.filters());
12304                let p = panel.clone();
12305                let handler: block2::RcBlock<dyn Fn(isize)> =
12306                    block2::RcBlock::new(move |resp: isize| {
12307                        // The pieces layer copies the staged bytes to the chosen local path.
12308                        ffi_guard::contain((), || emit_panel_result(req, resp, &p));
12309                    });
12310                unsafe { panel.beginSheetModalForWindow_completionHandler(&window, &handler) };
12311                PRESENT_PANELS.with(|m| m.borrow_mut().insert(req, panel));
12312                return;
12313            }
12314            _ => {}
12315        }
12316        let alert = unsafe { objc2_app_kit::NSAlert::new(mtm) };
12317        unsafe { alert.setMessageText(&NSString::from_str(spec.title())) };
12318        if let Some(msg) = spec.message() {
12319            unsafe { alert.setInformativeText(&NSString::from_str(msg)) };
12320        }
12321        // The completion handler must outlive this call, so it's a heap (Rc) block.
12322        let handler: block2::RcBlock<dyn Fn(isize)> = match spec {
12323            PresentSpec::Dialog { buttons, .. } => {
12324                if buttons
12325                    .iter()
12326                    .any(|b| b.role == present::ButtonRole::Destructive)
12327                {
12328                    unsafe { alert.setAlertStyle(objc2_app_kit::NSAlertStyle::Warning) };
12329                }
12330                for b in buttons {
12331                    unsafe { alert.addButtonWithTitle(&NSString::from_str(&b.label)) };
12332                }
12333                block2::RcBlock::new(move |resp: isize| {
12334                    ffi_guard::contain((), || {
12335                        // NSAlertFirstButtonReturn = 1000; add order == spec order.
12336                        let idx = resp - 1000;
12337                        emit(
12338                            WINDOW_NODE,
12339                            Event::PresentResult {
12340                                req,
12341                                result: present::PresentResult::Button(idx as i64),
12342                            },
12343                        );
12344                        PRESENT_ALERTS.with(|m| {
12345                            m.borrow_mut().remove(&req);
12346                        });
12347                    })
12348                })
12349            }
12350            PresentSpec::Prompt {
12351                placeholder,
12352                initial,
12353                ok,
12354                cancel,
12355                ..
12356            } => {
12357                let tf = unsafe { NSTextField::new(mtm) };
12358                unsafe {
12359                    tf.setFrame(NSRect::new(
12360                        NSPoint::new(0.0, 0.0),
12361                        NSSize::new(260.0, 24.0),
12362                    ));
12363                    tf.setEditable(true);
12364                    tf.setBezeled(true);
12365                    tf.setStringValue(&NSString::from_str(initial));
12366                    tf.setPlaceholderString(Some(&NSString::from_str(placeholder)));
12367                    alert.setAccessoryView(Some(&tf));
12368                    alert.addButtonWithTitle(&NSString::from_str(ok)); // resp 1000
12369                    alert.addButtonWithTitle(&NSString::from_str(cancel)); // resp 1001
12370                }
12371                block2::RcBlock::new(move |resp: isize| {
12372                    ffi_guard::contain((), || {
12373                        let result = if resp == 1000 {
12374                            present::PresentResult::Text(unsafe { tf.stringValue() }.to_string())
12375                        } else {
12376                            present::PresentResult::Dismissed
12377                        };
12378                        emit(WINDOW_NODE, Event::PresentResult { req, result });
12379                        PRESENT_ALERTS.with(|m| {
12380                            m.borrow_mut().remove(&req);
12381                        });
12382                    })
12383                })
12384            }
12385            // File pickers returned early above.
12386            PresentSpec::OpenFile { .. }
12387            | PresentSpec::OpenFolder { .. }
12388            | PresentSpec::SaveFile { .. } => unreachable!(),
12389        };
12390        unsafe {
12391            alert.beginSheetModalForWindow_completionHandler(&window, Some(&handler));
12392        }
12393        PRESENT_ALERTS.with(|m| m.borrow_mut().insert(req, alert));
12394    }
12395
12396    fn dismiss(&mut self, req: u64) {
12397        // Close the sheet; its completion handler fires but its (native) result is dropped
12398        // because day-core already removed the pending request when it resolved.
12399        let alert = PRESENT_ALERTS.with(|m| m.borrow_mut().remove(&req));
12400        if let Some(alert) = alert {
12401            let sheet = alert.window();
12402            if let Some(parent) = sheet.sheetParent() {
12403                unsafe { parent.endSheet(&sheet) };
12404            }
12405        }
12406        // File-picker sheets are their own NSWindow.
12407        let panel = PRESENT_PANELS.with(|m| m.borrow_mut().remove(&req));
12408        if let Some(panel) = panel
12409            && let Some(parent) = panel.sheetParent()
12410        {
12411            unsafe { parent.endSheet(&panel) };
12412        }
12413    }
12414
12415    fn application_handlers(
12416        &mut self,
12417        query: &day_spec::applications::HandlerQuery,
12418    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
12419    {
12420        applications::handlers(query)
12421    }
12422
12423    fn open_url_with_application(
12424        &mut self,
12425        url: &str,
12426        application: &str,
12427        completion: day_spec::applications::OpenApplicationCompletion,
12428    ) {
12429        applications::open(url, application, completion);
12430    }
12431
12432    fn share_support(&self) -> day_spec::Support {
12433        day_spec::Support::Native
12434    }
12435    fn share(&mut self, spec: &day_spec::share::ShareSpec, anchor: Option<&Self::Handle>) -> bool {
12436        use objc2::{msg_send, runtime::AnyObject};
12437        use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL};
12438        let Some(mtm) = objc2::MainThreadMarker::new() else {
12439            return false;
12440        };
12441        let Some(url) = NSURL::URLWithString(&NSString::from_str(&spec.url)) else {
12442            return false;
12443        };
12444        let app = objc2_app_kit::NSApplication::sharedApplication(mtm);
12445        let Some(window_view) = app.keyWindow().and_then(|w| w.contentView()) else {
12446            return false;
12447        };
12448        unsafe {
12449            let items = NSArray::from_retained_slice(&[url]);
12450            let picker: objc2::rc::Allocated<AnyObject> =
12451                msg_send![objc2::class!(NSSharingServicePicker), alloc];
12452            let picker: objc2::rc::Retained<AnyObject> = msg_send![picker, initWithItems: &*items];
12453            let delegate = DaySharePickerDelegate::alloc(mtm).set_ivars(SharePickerIvars {
12454                actions: spec.actions.clone(),
12455            });
12456            let delegate: Retained<DaySharePickerDelegate> = msg_send![super(delegate), init];
12457            let _: () = msg_send![&*picker, setDelegate: &*delegate];
12458            // Pointing at the control that asked, under it; without one, at the window's top
12459            // trailing corner.
12460            let (view, rect, edge) = match anchor {
12461                Some(view) => (view.clone(), view.bounds(), 1usize),
12462                None => {
12463                    let bounds = window_view.bounds();
12464                    let y = if window_view.isFlipped() {
12465                        30.0
12466                    } else {
12467                        bounds.size.height - 30.0
12468                    };
12469                    let rect = NSRect::new(
12470                        NSPoint::new(bounds.size.width - 30.0, y),
12471                        NSSize::new(1.0, 1.0),
12472                    );
12473                    (window_view, rect, 3usize)
12474                }
12475            };
12476            let _: () =
12477                msg_send![&*picker, showRelativeToRect: rect, ofView: &*view, preferredEdge: edge];
12478            // The picker holds its delegate weakly: keep both until the next share.
12479            self.sharing = Some(picker);
12480            self.sharing_delegate = Some(delegate);
12481        }
12482        true
12483    }
12484    fn open_url(&mut self, url: &str) {
12485        // NSWorkspace opens the URL in the user's default handler (Safari for http(s), Mail for
12486        // mailto:, …). An unparseable string yields no NSURL and is silently ignored.
12487        let nsurl = unsafe { objc2_foundation::NSURL::URLWithString(&NSString::from_str(url)) };
12488        if let Some(nsurl) = nsurl {
12489            unsafe { objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&nsurl) };
12490        }
12491    }
12492}
12493
12494/// Apply a file dialog's extension filters (`allowedFileTypes` — deprecated but still the simplest
12495/// extension-based API; `UTType` would pull in another framework crate for no benefit here).
12496#[allow(deprecated)]
12497fn apply_allowed_file_types(
12498    panel: &objc2_app_kit::NSSavePanel,
12499    filters: &[day_spec::present::FileFilter],
12500) {
12501    let exts: Vec<Retained<NSString>> = filters
12502        .iter()
12503        .flat_map(|f| f.extensions.iter())
12504        .map(|e| NSString::from_str(e))
12505        .collect();
12506    if !exts.is_empty() {
12507        let refs: Vec<&NSString> = exts.iter().map(|r| &**r).collect();
12508        let arr = objc2_foundation::NSArray::from_slice(&refs);
12509        unsafe { panel.setAllowedFileTypes(Some(&arr)) };
12510    }
12511}
12512
12513/// Turn an open panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1):
12514/// every chosen URL, so a multiple-selection pick reports all of its files (and a folder
12515/// chooser its one directory).
12516fn emit_open_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSOpenPanel) {
12517    let mut paths = Vec::new();
12518    if resp == 1 {
12519        for url in unsafe { panel.URLs() }.iter() {
12520            if let Some(p) = unsafe { url.path() } {
12521                paths.push(p.to_string());
12522            }
12523        }
12524    }
12525    let result = if paths.is_empty() {
12526        present::PresentResult::Dismissed
12527    } else {
12528        present::PresentResult::Files(paths)
12529    };
12530    emit(WINDOW_NODE, Event::PresentResult { req, result });
12531    PRESENT_PANELS.with(|m| {
12532        m.borrow_mut().remove(&req);
12533    });
12534}
12535
12536/// Turn a save panel completion into a `PresentResult` and enqueue it (NSModalResponseOK = 1).
12537fn emit_panel_result(req: u64, resp: isize, panel: &objc2_app_kit::NSSavePanel) {
12538    let result = if resp == 1 {
12539        unsafe { panel.URL() }
12540            .and_then(|url| unsafe { url.path() })
12541            .map(|p| present::PresentResult::Files(vec![p.to_string()]))
12542            .unwrap_or(present::PresentResult::Dismissed)
12543    } else {
12544        present::PresentResult::Dismissed
12545    };
12546    emit(WINDOW_NODE, Event::PresentResult { req, result });
12547    PRESENT_PANELS.with(|m| {
12548        m.borrow_mut().remove(&req);
12549    });
12550}
12551
12552impl Platform for AppKit {
12553    const TARGET: &'static str = "macos-appkit";
12554    const TOOLKIT: &'static str = "appkit";
12555
12556    fn run(mut self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Handle, Size)>) {
12557        let mtm = self.mtm;
12558        // The App menu / About use the app's display name. `app_name` overrides the (possibly
12559        // decorated) window title; setting the process name also makes the standard About panel and
12560        // the bold App-menu title show it (an unbundled binary otherwise shows the exe name).
12561        self.app_name = options
12562            .app_name
12563            .clone()
12564            .unwrap_or_else(|| options.title.clone());
12565        // The bold App-menu title, the About panel and Quit all show the app's NAME. Always set
12566        // it, not just when `app_name` was given explicitly — an app that only set `title` was
12567        // showing its kebab-case cargo target ("day-sheets") where its name belongs.
12568        //
12569        // Two sources, because AppKit consults them in order: the main bundle's CFBundleName
12570        // wins when there is one, and `day launch` runs the binary UNBUNDLED during development,
12571        // where the name falls back to the executable's file name. Writing the info dictionary
12572        // covers the bundled case; the process name covers the unbundled one.
12573        unsafe {
12574            objc2_foundation::NSProcessInfo::processInfo()
12575                .setProcessName(&NSString::from_str(&self.app_name));
12576            let bundle = objc2_foundation::NSBundle::mainBundle();
12577            let info: Option<Retained<objc2_foundation::NSDictionary>> =
12578                msg_send![&bundle, infoDictionary];
12579            if let Some(info) = info {
12580                let key = NSString::from_str("CFBundleName");
12581                let value = NSString::from_str(&self.app_name);
12582                // `infoDictionary` is documented immutable, but the instance backing an
12583                // unbundled process is a mutable dictionary; guard the send so a genuinely
12584                // immutable one is left alone instead of raising.
12585                if info.respondsToSelector(objc2::sel!(setObject:forKey:)) {
12586                    let _: () = msg_send![&info, setObject: &*value, forKey: &*key];
12587                }
12588            }
12589        }
12590        // RTL locales (docs/localization): AppleTextDirection flips AppKit's app-wide
12591        // userInterfaceLayoutDirection (label alignment, slider fill, control mirroring) —
12592        // read at NSApplication init, so register before sharedApplication. Registration
12593        // domain only: volatile, never persisted to the app's defaults.
12594        if day_core::layout_direction() == day_spec::LayoutDirection::Rtl {
12595            unsafe {
12596                use objc2_foundation::{NSDictionary, NSNumber, NSUserDefaults};
12597                let yes: objc2::rc::Retained<objc2::runtime::AnyObject> = NSNumber::new_bool(true)
12598                    .into_super()
12599                    .into_super()
12600                    .into_super();
12601                let dict = NSDictionary::from_retained_objects(
12602                    &[
12603                        &*NSString::from_str("AppleTextDirection"),
12604                        &*NSString::from_str("NSForceRightToLeftWritingDirection"),
12605                    ],
12606                    &[yes.clone(), yes],
12607                );
12608                NSUserDefaults::standardUserDefaults().registerDefaults(&dict);
12609            }
12610        }
12611        let app = NSApplication::sharedApplication(mtm);
12612        // A menu-bar app keeps out of the Dock from the first frame (docs/status-item.md): its
12613        // bundle carries LSUIElement, and an unbundled `day launch` run hears DAY_MACOS_DOCK=0.
12614        let menu_bar_app = std::env::var("DAY_MACOS_DOCK").is_ok_and(|v| v == "0")
12615            || unsafe {
12616                let bundle = objc2_foundation::NSBundle::mainBundle();
12617                let value: Option<Retained<objc2::runtime::AnyObject>> = msg_send![
12618                    &bundle,
12619                    objectForInfoDictionaryKey: &*NSString::from_str("LSUIElement")
12620                ];
12621                value.is_some_and(|v| {
12622                    let on: bool = msg_send![&v, boolValue];
12623                    on
12624                })
12625            };
12626        app.setActivationPolicy(if menu_bar_app {
12627            NSApplicationActivationPolicy::Accessory
12628        } else {
12629            NSApplicationActivationPolicy::Regular
12630        });
12631        let document_delegate = documents::delegate(mtm);
12632        app.setDelegate(Some(ProtocolObject::from_ref(&*document_delegate)));
12633        // DAY_THEME=light|dark forces the appearance app-wide (themed CI screenshot runs and
12634        // local theme checks); unset ⇒ follow the system.
12635        if let Ok(theme) = std::env::var("DAY_THEME") {
12636            let name = match theme.as_str() {
12637                "dark" => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
12638                "light" => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
12639                _ => None,
12640            };
12641            if let Some(name) = name {
12642                let appearance = objc2_app_kit::NSAppearance::appearanceNamed(name);
12643                unsafe { app.setAppearance(appearance.as_deref()) };
12644            }
12645        }
12646        // Bundled custom fonts (§18.4) must be registered before the first label realizes.
12647        register_bundled_fonts();
12648
12649        // Default menu bar (standard app menu + Edit) so ⌘Q / Cut-Copy-Paste work before the app
12650        // installs its own via `app_menu(...)`. Rebuilt after `ready` for the items that depend
12651        // on the app's registrations — see there.
12652        let app_name = self.app_name.clone();
12653        install_main_menu(mtm, &app, &app_name);
12654        // App activation / termination → day lifecycle events (docs/lifecycle.md).
12655        install_lifecycle_observers();
12656        install_appearance_observer();
12657        install_reduce_motion_observer();
12658
12659        let (window, delegate, content) = self.make_window(&options, false, None);
12660        // Optional window-appearance override (opt-in via env). An app with a fixed light/dark
12661        // palette sets `DAY_APPEARANCE=light|dark` so native controls (list, fields, editor) match
12662        // its own colors instead of following the system appearance. Unset = follow the system.
12663        let appearance_name = match std::env::var("DAY_APPEARANCE").ok().as_deref() {
12664            Some("light") => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
12665            Some("dark") => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
12666            _ => None,
12667        };
12668        if let Some(name) = appearance_name
12669            && let Some(appearance) = unsafe { objc2_app_kit::NSAppearance::appearanceNamed(name) }
12670        {
12671            window.setAppearance(Some(&appearance));
12672        }
12673        // The primary delegate lives for the process (this frame never returns); secondary
12674        // delegates are retained in `self.secondary`.
12675        std::mem::forget(delegate);
12676
12677        self.window = Some(window.clone());
12678        self.content = Some(content.clone());
12679        PRIMARY_CONTENT.with(|c| *c.borrow_mut() = Some(content.clone()));
12680
12681        // The root lays out below the title bar, not under it (§7.7).
12682        let layout = pin_below_title_bar(&window)
12683            .unwrap_or(Size::new(options.size.width, options.size.height));
12684        ready(self, content, layout);
12685
12686        // `ready` ran the app's root() — registrations are in. Without a new-window
12687        // builder only one Normal window can ever exist: turn automatic tabbing off so no
12688        // tab bar, "+" button, or dead tab menu items appear (docs/windows.md).
12689        if day_core::windows::new_window_action_id() == 0
12690            && options.tabbing == day_spec::WindowTabbing::Automatic
12691        {
12692            unsafe { NSWindow::setAllowsAutomaticWindowTabbing(false, mtm) };
12693        }
12694        // The DEFAULT menu bar was built before `root()` ran, so its registration-dependent
12695        // items — Settings…/⌘, and File ▸ New Window — could not exist yet. Rebuild it now that
12696        // they can. An app with its own `app_menu` model already replaced the whole bar and
12697        // gets its items through the injection path instead.
12698        if !day_core::has_app_menu() {
12699            install_main_menu(mtm, &app, &app_name);
12700        }
12701
12702        // Reopen where the user left it (docs/windows.md). AppKit persists the frame under an
12703        // autosave name and hands it back on request; `setFrameUsingName` answers false the
12704        // first time, which is when centering is the right answer.
12705        //
12706        // NOT while a dayscript is driving or `DAY_WINDOW` has forced a size: a restored frame
12707        // would make every captured screenshot's dimensions depend on where the developer last
12708        // dragged the window, and the capture suites compare those across machines.
12709        let deterministic =
12710            std::env::var_os("DAY_SCRIPT").is_some() || std::env::var_os("DAY_WINDOW").is_some();
12711        let autosave = NSString::from_str("day.main");
12712        if deterministic || !unsafe { window.setFrameUsingName(&autosave) } {
12713            window.center();
12714            // An explicit placement wins over centering, but not over the frame the user left.
12715            window_chrome::place(&window, options.placement);
12716        }
12717        // A scripted run whose capture needs a display scale this host's displays lack opens on
12718        // the one `day launch` made for it (`DAY_WINDOW_SCREEN`, a CGDirectDisplayID): a
12719        // capture is the window server's pixels, so it has the scale of the display under it.
12720        if let Some(screen) = capture_screen(mtm) {
12721            let (visible, frame) = (screen.visibleFrame(), window.frame());
12722            window.setFrameOrigin(NSPoint::new(
12723                visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
12724                visible.origin.y + ((visible.size.height - frame.size.height) / 2.0).max(0.0),
12725            ));
12726        }
12727        if !deterministic {
12728            unsafe { window.setFrameAutosaveName(&autosave) };
12729        }
12730        if !options.start_hidden {
12731            window.makeKeyAndOrderFront(None);
12732            app.activate();
12733        }
12734        // The root was mounted before the window was shown (ready() runs first), and on
12735        // macOS 26 layer displays requested pre-run are dropped for a window ordered front
12736        // before the app finishes launching — the window stays blank until the next real
12737        // event. Re-mark the whole tree so the first run-loop turn commits a full frame.
12738        if let Some(content) = window.contentView() {
12739            mark_tree_needs_display(&content);
12740        }
12741        if std::env::var_os("DAY_DUMP").is_some() {
12742            std::thread::spawn(|| {
12743                std::thread::sleep(std::time::Duration::from_millis(2000));
12744                Self::post(Box::new(|| {
12745                    // The primary's content specifically (docs/windows.md).
12746                    if let Some(content) = primary_content() {
12747                        let desc: Retained<NSString> =
12748                            unsafe { msg_send![&*content, _subtreeDescription] };
12749                        log::warn!("{desc}");
12750                    }
12751                }));
12752            });
12753        }
12754        app.run();
12755    }
12756
12757    fn post(f: Box<dyn FnOnce() + Send>) {
12758        // Posted-closure trampoline (§8.5): the closure runs inside dispatch's C frame, so a
12759        // panic is contained here rather than unwinding into libdispatch.
12760        dispatch2::DispatchQueue::main().exec_async(move || ffi_guard::contain((), f));
12761    }
12762
12763    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
12764        // The timer door behind `day::sleep` (docs/async.md): `dispatch_after` on the main
12765        // queue, so a sleep is a dispatch timer rather than a parked helper thread. Contained
12766        // like `post`. A delay too large for dispatch's clock runs at the far horizon instead.
12767        let when =
12768            dispatch2::DispatchTime::try_from(std::time::Duration::from_millis(u64::from(ms)))
12769                .unwrap_or(dispatch2::DispatchTime::FOREVER);
12770        if let Err(e) = dispatch2::DispatchQueue::main().after(when, move || {
12771            ffi_guard::contain((), f);
12772        }) {
12773            log::error!("day-toolkit-appkit: dispatch_after refused a timer: {e:?}");
12774        }
12775    }
12776
12777    fn locale_hints(&self) -> Vec<String> {
12778        // The user's ordered language preference from Settings ("fr-FR", "en-US", …), which is
12779        // the ambient locale Day negotiates its catalogs against (§12.2, docs/localization.md).
12780        objc2_foundation::NSLocale::preferredLanguages()
12781            .iter()
12782            .map(|s| s.to_string())
12783            .collect()
12784    }
12785}
12786
12787// `CGWindowListCreateImage` is obsoleted as of the macOS 15 SDK (ScreenCaptureKit is the
12788// sanctioned replacement) but still resolves and answers on macOS 26. It is declared here rather
12789// than taken from a binding because the availability attribute would refuse the call outright,
12790// and every use below treats a NULL return as "ask the offscreen path instead".
12791unsafe extern "C" {
12792    fn CGWindowListCreateImage(
12793        bounds: objc2_core_foundation::CGRect,
12794        list_option: u32,
12795        window_id: u32,
12796        image_option: u32,
12797    ) -> *mut objc2_core_graphics::CGImage;
12798}
12799
12800/// kCGWindowListOptionIncludingWindow — composite only this window, so whatever is stacked over
12801/// it (another app, a CI runner's stray window) cannot appear in the capture.
12802const CG_WINDOW_LIST_INCLUDING_WINDOW: u32 = 1 << 3;
12803/// kCGWindowImageBoundsIgnoreFraming — the window's own frame, without its drop shadow, which
12804/// makes the returned image exactly `window.frame()` at the backing scale.
12805const CG_WINDOW_IMAGE_IGNORE_FRAMING: u32 = 1 << 0;
12806
12807/// Encode a captured rep as PNG, in sRGB.
12808///
12809/// A capture arrives in the color space of the display it was composited for, and a PNG of it
12810/// embeds that display's ICC profile: the same color then has different sample values on every
12811/// machine, and on every other Day target, which all capture sRGB. Converting first makes a
12812/// macOS capture's samples comparable with theirs and independent of the capturing display.
12813fn png_of_rep(rep: &objc2_app_kit::NSBitmapImageRep) -> Result<Vec<u8>, String> {
12814    let srgb = rep.bitmapImageRepByConvertingToColorSpace_renderingIntent(
12815        &objc2_app_kit::NSColorSpace::sRGBColorSpace(),
12816        objc2_app_kit::NSColorRenderingIntent::Default,
12817    );
12818    let rep = srgb.as_deref().unwrap_or(rep);
12819    let data = unsafe {
12820        rep.representationUsingType_properties(NSBitmapImageFileType::PNG, &NSDictionary::new())
12821    }
12822    .ok_or("png encode failed")?;
12823    Ok(data.to_vec())
12824}
12825
12826/// Capture `content` by asking the WINDOW SERVER for the composited window and cropping to it.
12827///
12828/// This exists because an offscreen render cannot draw macOS's own materials. As of macOS 26 a
12829/// sidebar `NSSplitViewItem` is a Liquid Glass surface the window server composites from what is
12830/// behind it; `cacheDisplayInRect` has no backdrop to sample, so it renders the sidebar as an
12831/// opaque white slab with none of its rows in it — every macos-appkit gallery shot had a blank
12832/// sidebar. The window server has the real pixels, including the rows.
12833///
12834/// It answers only while the window is actually on screen. A hidden, minimized or
12835/// never-composited window has no image to hand back (verified: hiding the app makes this return
12836/// NULL while the offscreen path still produces a frame), so this returns `Err` and the caller
12837/// falls back rather than failing the capture.
12838fn snapshot_via_window_server(content: &NSView, chrome: bool) -> Result<Vec<u8>, String> {
12839    let window = content.window().ok_or("view is not in a window")?;
12840    // An attached sheet is the active modal surface and has its own composited window.
12841    // Capturing only the parent's window would show dimmed content without the modal UI.
12842    if let Some(sheet) = window.attachedSheet().and_then(|s| s.contentView()) {
12843        return snapshot_via_window_server(&sheet, chrome);
12844    }
12845    let number = window.windowNumber();
12846    if number <= 0 {
12847        return Err(format!("window {number} is not on screen"));
12848    }
12849    // The server hands back the frame it last COMPOSITED, which is the previous one whenever the
12850    // app has changed the view tree since. A capture taken right after a state change then shows
12851    // the state before it — a `when` whose outgoing arm is already gone from the tree and from the
12852    // view hierarchy still appears in the image, so a walkthrough asserting on pixels reads a
12853    // stale frame as "the change did not happen". Push the pending work out first: lay out, draw,
12854    // then commit the layer tree to the render server.
12855    unsafe { content.layoutSubtreeIfNeeded() };
12856    window.displayIfNeeded();
12857    CATransaction::flush();
12858    // CGRectNull asks for the window's own bounds rather than a screen region.
12859    let null_rect = objc2_core_foundation::CGRect::new(
12860        objc2_core_foundation::CGPoint::new(f64::INFINITY, f64::INFINITY),
12861        objc2_core_foundation::CGSize::new(0.0, 0.0),
12862    );
12863    let shot = unsafe {
12864        CGWindowListCreateImage(
12865            null_rect,
12866            CG_WINDOW_LIST_INCLUDING_WINDOW,
12867            number as u32,
12868            CG_WINDOW_IMAGE_IGNORE_FRAMING,
12869        )
12870    };
12871    if shot.is_null() {
12872        return Err("the window server has no image for this window".into());
12873    }
12874    // SAFETY: non-NULL CGImageRef owned by this call (Create rule); CFRetained takes that
12875    // ownership over, so it is released exactly once.
12876    let shot = unsafe {
12877        objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new_unchecked(shot))
12878    };
12879
12880    // A chrome capture is the window image as the server composited it — titlebar, toolbar and
12881    // rounded corners included — so it is done here, before the crop.
12882    if chrome {
12883        let rep = unsafe {
12884            objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12885                objc2_app_kit::NSBitmapImageRep::alloc(),
12886                &shot,
12887            )
12888        };
12889        return png_of_rep(&rep);
12890    }
12891
12892    // Crop the window frame down to the content view. Keeping the framing identical to the
12893    // offscreen path is the point: the titlebar has never been part of a Day capture, and every
12894    // published gallery shot would otherwise change size.
12895    let frame = window.frame();
12896    if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
12897        return Err("zero-size window".into());
12898    }
12899    let scale = objc2_core_graphics::CGImage::width(Some(&shot)) as f64 / frame.size.width;
12900    // Cocoa rects are bottom-left origin; a CGImage's are top-left, so the content's distance
12901    // from the window top is what the crop needs.
12902    let in_window = unsafe { content.convertRect_toView(content.bounds(), None) };
12903    let from_top = frame.size.height - (in_window.origin.y + in_window.size.height);
12904    let crop = objc2_core_foundation::CGRect::new(
12905        objc2_core_foundation::CGPoint::new(
12906            (in_window.origin.x * scale).round(),
12907            (from_top * scale).round(),
12908        ),
12909        objc2_core_foundation::CGSize::new(
12910            (in_window.size.width * scale).round(),
12911            (in_window.size.height * scale).round(),
12912        ),
12913    );
12914    let cropped = objc2_core_graphics::CGImage::with_image_in_rect(Some(&shot), crop)
12915        .ok_or("crop to the content view failed")?;
12916    let rep = unsafe {
12917        objc2_app_kit::NSBitmapImageRep::initWithCGImage(
12918            objc2_app_kit::NSBitmapImageRep::alloc(),
12919            &cropped,
12920        )
12921    };
12922    png_of_rep(&rep)
12923}
12924
12925/// Capture a window content view as PNG (the dayscript screenshot seam, §14).
12926///
12927/// The window server first, because it is the only one of the two that can show macOS's own
12928/// composited materials; the offscreen render when it declines, because it is the only one of the
12929/// two that works with no window on screen. See each for why.
12930/// Put a [`Transform`] on a view through its own geometry rather than its layer: the frame is
12931/// the laid-out `base` scaled about its center and moved by the translation, the bounds keep the
12932/// laid-out size (so the content draws at the scale), and the rotation is the frame's center
12933/// rotation (positive is clockwise on screen: Day's parents are flipped, y down).
12934fn apply_geometry(v: &NSView, base: [f64; 4], t: Transform) {
12935    let [x, y, w, h] = base;
12936    let (sw, sh) = (w * t.sx, h * t.sy);
12937    let frame = NSRect::new(
12938        NSPoint::new(x + (w - sw) / 2.0 + t.tx, y + (h - sh) / 2.0 + t.ty),
12939        NSSize::new(sw, sh),
12940    );
12941    unsafe {
12942        // The rotation goes first and comes back last: a rotated view's frame is its bounding
12943        // box, so setting the frame of a rotated view would scale it.
12944        v.setFrameCenterRotation(0.0);
12945        v.setFrame(frame);
12946        v.setBoundsSize(NSSize::new(w, h));
12947        if t.rotate_deg != 0.0 {
12948            v.setFrameCenterRotation(t.rotate_deg);
12949        }
12950    }
12951}
12952
12953fn snapshot_view(content: &NSView) -> Result<Vec<u8>, String> {
12954    let modal = content
12955        .window()
12956        .and_then(|w| w.attachedSheet())
12957        .and_then(|s| s.contentView());
12958    let content = modal.as_deref().unwrap_or(content);
12959    match snapshot_via_window_server(content, false) {
12960        Ok(bytes) => Ok(bytes),
12961        Err(_) => snapshot_view_cache(content),
12962    }
12963}
12964
12965/// Capture a window *with* its chrome — the titlebar and toolbar the content capture crops away
12966/// (`day::window_image().chrome()`, docs/window-image.md).
12967///
12968/// Only the window server can produce this: the offscreen path renders the content view's own
12969/// hierarchy, which the titlebar is not part of. When it declines (an offscreen or hidden window)
12970/// the content capture stands in — a smaller image beats no image, and it is what the caller
12971/// would have got from the plain duty.
12972fn snapshot_view_chrome(content: &NSView) -> Result<Vec<u8>, String> {
12973    let modal = content
12974        .window()
12975        .and_then(|w| w.attachedSheet())
12976        .and_then(|s| s.contentView());
12977    let content = modal.as_deref().unwrap_or(content);
12978    match snapshot_via_window_server(content, true) {
12979        Ok(bytes) => Ok(bytes),
12980        Err(_) => snapshot_view_cache(content),
12981    }
12982}
12983
12984/// The offscreen fallback: `cacheDisplayInRect` over a window-background pre-fill resolved for
12985/// the view's light/dark appearance. Renders the view hierarchy Day drew, and nothing the window
12986/// server composites (see `snapshot_via_window_server`).
12987fn snapshot_view_cache(content: &NSView) -> Result<Vec<u8>, String> {
12988    let bounds = content.bounds();
12989    let rep =
12990        unsafe { content.bitmapImageRepForCachingDisplayInRect(bounds) }.ok_or("no bitmap rep")?;
12991    // Day containers are transparent (the window server paints the backdrop), so pre-fill
12992    // the rep with the window background — resolved for the window's light/dark appearance —
12993    // before compositing the view hierarchy over it (§14).
12994    let ctx =
12995        NSGraphicsContext::graphicsContextWithBitmapImageRep(&rep).ok_or("no graphics context")?;
12996    NSGraphicsContext::saveGraphicsState_class();
12997    NSGraphicsContext::setCurrentContext(Some(&ctx));
12998    content
12999        .effectiveAppearance()
13000        .performAsCurrentDrawingAppearance(&block2::StackBlock::new(|| unsafe {
13001            NSColor::windowBackgroundColor().setFill();
13002            objc2_app_kit::NSRectFill(bounds);
13003        }));
13004    NSGraphicsContext::restoreGraphicsState_class();
13005    unsafe { content.cacheDisplayInRect_toBitmapImageRep(bounds, &rep) };
13006    png_of_rep(&rep)
13007}
13008
13009/// The screen a scripted run asked to open on: `DAY_WINDOW_SCREEN`, the CGDirectDisplayID of the
13010/// capture display `day launch --script` provides when no attached display has the capture's
13011/// scale. `None` when unset or when no screen has that id, which leaves the window where it was.
13012/// Center `window` on `primary`'s screen when `center` put it on another, as high as `center`
13013/// places a window (a third of the free height above it, two below).
13014fn center_on_screen_of(window: &NSWindow, primary: Option<&NSWindow>) {
13015    let Some(screen) = primary.and_then(|w| w.screen()) else {
13016        return;
13017    };
13018    if window.screen().is_some_and(|s| s.frame() == screen.frame()) {
13019        return;
13020    }
13021    let (visible, frame) = (screen.visibleFrame(), window.frame());
13022    window.setFrameOrigin(NSPoint::new(
13023        visible.origin.x + ((visible.size.width - frame.size.width) / 2.0).max(0.0),
13024        visible.origin.y + ((visible.size.height - frame.size.height) * 2.0 / 3.0).max(0.0),
13025    ));
13026}
13027
13028fn capture_screen(mtm: MainThreadMarker) -> Option<Retained<objc2_app_kit::NSScreen>> {
13029    let wanted: u32 = std::env::var("DAY_WINDOW_SCREEN")
13030        .ok()?
13031        .trim()
13032        .parse()
13033        .ok()?;
13034    let key = NSString::from_str("NSScreenNumber");
13035    objc2_app_kit::NSScreen::screens(mtm)
13036        .into_iter()
13037        .find(|screen| {
13038            let number: Option<Retained<objc2_foundation::NSNumber>> =
13039                unsafe { msg_send![&*screen.deviceDescription(), objectForKey: &*key] };
13040            number.is_some_and(|n| n.unsignedIntValue() == wanted)
13041        })
13042}
13043
13044/// Recursively mark a view tree as needing display (startup first-frame fix, see `run`).
13045fn mark_tree_needs_display(view: &NSView) {
13046    view.setNeedsDisplay(true);
13047    for sub in view.subviews() {
13048        mark_tree_needs_display(&sub);
13049    }
13050}
13051
13052/// Which lifecycle phases this desktop backend delivers (docs/lifecycle.md): the universal set.
13053/// macOS has no true background/foreground or memory-warning lifecycle. `const` so
13054/// `day::require_lifecycle!` can reject unsupported phases at compile time. Must agree with the
13055/// `Toolkit::supports_lifecycle` default (which also returns `is_universal`).
13056pub const fn lifecycle_supported(phase: day_spec::Lifecycle) -> bool {
13057    phase.is_universal()
13058}
13059
13060/// Follow the SYSTEM appearance while the app runs: macOS posts the distributed
13061/// "AppleInterfaceThemeChangedNotification" on a theme switch, and AppKit updates
13062/// `effectiveAppearance` just after — so re-read on the next main-queue turn and refresh
13063/// day-core's reactive dark-mode signal (palette closures recolor live instead of going
13064/// stale until the next rebuild). The token is leaked to observe for the app's lifetime.
13065fn install_appearance_observer() {
13066    use objc2_foundation::{NSDistributedNotificationCenter, NSNotification, NSString};
13067    let center = unsafe { NSDistributedNotificationCenter::defaultCenter() };
13068    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13069        dispatch2::DispatchQueue::main()
13070            .exec_async(|| ffi_guard::contain((), day_core::note_appearance_changed));
13071    });
13072    let name = NSString::from_str("AppleInterfaceThemeChangedNotification");
13073    let token = unsafe {
13074        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
13075    };
13076    std::mem::forget(token);
13077    // Accent and contrast changes can leave the appearance name unchanged.
13078    let center = objc2_foundation::NSNotificationCenter::defaultCenter();
13079    let name = NSString::from_str("NSSystemColorsDidChangeNotification");
13080    let token = unsafe {
13081        center.addObserverForName_object_queue_usingBlock(Some(&name), None, None, &block)
13082    };
13083    std::mem::forget(token);
13084}
13085
13086/// Follow the SYSTEM reduce-motion switch while the app runs: NSWorkspace posts
13087/// `NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification` on its own notification
13088/// center when any Accessibility › Display option flips, and
13089/// `accessibilityDisplayShouldReduceMotion` already answers the new value by then. The
13090/// notification arrives on the main thread; the main-queue hop keeps the re-read off the
13091/// poster's stack, as the appearance observer does. The token is leaked to observe for the
13092/// app's lifetime.
13093fn install_reduce_motion_observer() {
13094    use objc2_foundation::NSNotification;
13095    let center = objc2_app_kit::NSWorkspace::sharedWorkspace().notificationCenter();
13096    let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13097        dispatch2::DispatchQueue::main()
13098            .exec_async(|| ffi_guard::contain((), day_core::note_motion_changed));
13099    });
13100    let token = unsafe {
13101        center.addObserverForName_object_queue_usingBlock(
13102            Some(objc2_app_kit::NSWorkspaceAccessibilityDisplayOptionsDidChangeNotification),
13103            None,
13104            None,
13105            &block,
13106        )
13107    };
13108    std::mem::forget(token);
13109}
13110
13111/// Bridge the NSApplication activation/termination notifications to day lifecycle events
13112/// (docs/lifecycle.md). The observer tokens are leaked to live for the whole app.
13113fn install_lifecycle_observers() {
13114    use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName};
13115    let center = unsafe { NSNotificationCenter::defaultCenter() };
13116    let observe = |name: &NSNotificationName, phase: day_spec::Lifecycle| {
13117        let block = block2::RcBlock::new(move |_: std::ptr::NonNull<NSNotification>| {
13118            ffi_guard::contain((), || emit(day_spec::WINDOW_NODE, Event::Lifecycle(phase)));
13119        });
13120        let token = unsafe {
13121            center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block)
13122        };
13123        std::mem::forget(token); // observe for the app's lifetime
13124    };
13125    unsafe {
13126        observe(
13127            NSApplicationDidBecomeActiveNotification,
13128            day_spec::Lifecycle::DidBecomeActive,
13129        );
13130        observe(
13131            NSApplicationWillResignActiveNotification,
13132            day_spec::Lifecycle::WillResignActive,
13133        );
13134        observe(
13135            NSApplicationWillTerminateNotification,
13136            day_spec::Lifecycle::WillTerminate,
13137        );
13138        // `terminate:` exits the process from inside the run loop, so the loop never returns to
13139        // `launch_with`: the last Day code to run is this notification's second observer, which
13140        // NSNotificationCenter calls after the first (docs/lifecycle.md).
13141        observe(
13142            NSApplicationWillTerminateNotification,
13143            day_spec::Lifecycle::DidExit,
13144        );
13145    }
13146}
13147
13148day_localization_ui::locales!();
13149
13150/// Shared by the initial menu and every reactive replacement. AppKit owns Services
13151/// and the hide actions; these commands must not depend on a window or app callback.
13152fn install_application_menu(
13153    mtm: MainThreadMarker,
13154    menubar: &NSMenu,
13155    title: &str,
13156    about: Option<day_spec::MenuItem>,
13157    updates: Option<day_spec::MenuItem>,
13158    prefs: Option<day_spec::MenuItem>,
13159    quit: Option<day_spec::MenuItem>,
13160) -> Retained<NSMenu> {
13161    let app = NSApplication::sharedApplication(mtm);
13162    use day_spec::{MenuItem as M, MenuRole as R};
13163    let standard = |role, label| M::Action {
13164        id: None,
13165        action: 0,
13166        label,
13167        shortcut: None,
13168        enabled: true,
13169        checked: None,
13170        role: Some(role),
13171        icon: None,
13172    };
13173    let mut about =
13174        about.unwrap_or_else(|| standard(R::About, res::str::about_app(title).format()));
13175    let mut quit = quit.unwrap_or_else(|| standard(R::Quit, res::str::quit_app(title).format()));
13176    for (item, title) in [
13177        (&mut about, res::str::about_app(title).format()),
13178        (&mut quit, res::str::quit_app(title).format()),
13179    ] {
13180        if let M::Action { label, .. } = item {
13181            *label = title;
13182        }
13183    }
13184    // A registered Day About (docs/settings.md) replaces the stock Info.plist panel: the
13185    // item fires the dispatch action instead of `orderFrontStandardAboutPanel:`.
13186    if let M::Action { action, .. } = &mut about
13187        && *action == 0
13188    {
13189        *action = day_core::windows::about_action_id();
13190    }
13191    // Check for Updates… sits directly under About (the Sparkle convention), whether the app
13192    // placed the role itself or the updater only registered its action.
13193    let updates_id = day_core::windows::check_for_updates_action_id();
13194    let updates = updates.or_else(|| {
13195        (updates_id != 0).then(|| {
13196            standard(
13197                R::CheckForUpdates,
13198                day_localization::t(day_localization::key::day_check_for_updates),
13199            )
13200        })
13201    });
13202    let mut head = vec![about];
13203    if let Some(mut updates) = updates {
13204        if let M::Action { action, .. } = &mut updates
13205            && *action == 0
13206        {
13207            *action = updates_id;
13208        }
13209        head.push(updates);
13210    }
13211    head.push(M::Separator);
13212    let menu = build_ns_menu(mtm, title, &head);
13213    if let Some(mut prefs) = prefs {
13214        if let M::Action { label, .. } = &mut prefs {
13215            *label = res::str::settings().format();
13216        }
13217        let section = build_ns_menu(mtm, title, &[prefs, M::Separator]);
13218        for item in section.itemArray() {
13219            section.removeItem(&item);
13220            menu.addItem(&item);
13221        }
13222    }
13223    // AppKit keeps the registered Services menu across main-menu replacements.
13224    // Move that same menu to the new bar rather than abandoning its system-populated items.
13225    let services = app.servicesMenu().unwrap_or_else(|| NSMenu::new(mtm));
13226    if let Some(parent) = unsafe { services.supermenu() } {
13227        let index = parent.indexOfItemWithSubmenu(Some(&services));
13228        if index >= 0 {
13229            parent.itemAtIndex(index).unwrap().setSubmenu(None);
13230        }
13231    }
13232    let services_item = NSMenuItem::new(mtm);
13233    services_item.setTitle(&NSString::from_str(&res::str::services().format()));
13234    services_item.setSubmenu(Some(&services));
13235    menu.addItem(&services_item);
13236    menu.addItem(&NSMenuItem::separatorItem(mtm));
13237    for (label, selector, shortcut) in [
13238        (
13239            res::str::hide_app(title).format(),
13240            sel!(hide:),
13241            Some(day_spec::Shortcut::primary("h")),
13242        ),
13243        (
13244            res::str::hide_others().format(),
13245            sel!(hideOtherApplications:),
13246            Some(day_spec::Shortcut::primary("h").alt()),
13247        ),
13248        (
13249            res::str::show_all().format(),
13250            sel!(unhideAllApplications:),
13251            None,
13252        ),
13253    ] {
13254        let item = unsafe {
13255            NSMenuItem::initWithTitle_action_keyEquivalent(
13256                NSMenuItem::alloc(mtm),
13257                &NSString::from_str(&label),
13258                Some(selector),
13259                &NSString::from_str(shortcut.as_ref().map_or("", |s| s.key.as_str())),
13260            )
13261        };
13262        if let Some(shortcut) = shortcut {
13263            item.setKeyEquivalentModifierMask(ns_modifiers(&shortcut));
13264        }
13265        // Explicitly target the application so window responders cannot override Hide.
13266        unsafe { item.setTarget(Some(&app)) };
13267        menu.addItem(&item);
13268    }
13269    menu.addItem(&NSMenuItem::separatorItem(mtm));
13270    let section = build_ns_menu(mtm, title, &[quit]);
13271    let quit = section.itemAtIndex(0).unwrap();
13272    section.removeItem(&quit);
13273    menu.addItem(&quit);
13274    let item = NSMenuItem::new(mtm);
13275    item.setSubmenu(Some(&menu));
13276    menubar.addItem(&item);
13277    services
13278}
13279
13280/// The default main menu (§21.2 M2): standard application menu; Edit menu wired to the responder
13281/// chain so Cmd+C/V/X/A work in NSTextFields; Window menu basics.
13282fn install_main_menu(mtm: MainThreadMarker, app: &NSApplication, title: &str) {
13283    let menubar = NSMenu::new(mtm);
13284
13285    let prefs_id = day_core::windows::preferences_action_id();
13286    let prefs = (prefs_id != 0).then(|| day_spec::MenuItem::Action {
13287        id: None,
13288        action: prefs_id,
13289        label: res::str::settings().format(),
13290        shortcut: None,
13291        enabled: true,
13292        checked: None,
13293        role: Some(day_spec::MenuRole::Preferences),
13294        icon: None,
13295    });
13296    let services = install_application_menu(mtm, &menubar, title, None, None, prefs, None);
13297
13298    // File ▸ New Window / Close, when the app registered a new-window builder — the same
13299    // zero-menu-code rule as Settings…/⌘, above (docs/windows.md). Without this an app that
13300    // never calls `app_menu` gets the tab-bar "+" and the Window menu's tab commands but no
13301    // File ▸ New Window, because the default menu bar has no File menu to put it in.
13302    let new_window_id = day_core::windows::new_window_action_id();
13303    if new_window_id != 0 {
13304        let file_item = NSMenuItem::new(mtm);
13305        let file_menu = unsafe {
13306            NSMenu::initWithTitle(
13307                NSMenu::alloc(mtm),
13308                &NSString::from_str(&day_localization::t(day_localization::key::day_file)),
13309            )
13310        };
13311        let new_window = unsafe {
13312            NSMenuItem::initWithTitle_action_keyEquivalent(
13313                NSMenuItem::alloc(mtm),
13314                &NSString::from_str(&day_localization::t(day_localization::key::day_new_window)),
13315                Some(sel!(fire:)),
13316                &NSString::from_str("n"),
13317            )
13318        };
13319        let target = menu_target(mtm);
13320        let tobj: &objc2::runtime::AnyObject = target.as_ref();
13321        unsafe { new_window.setTarget(Some(tobj)) };
13322        new_window.setTag(new_window_id as isize);
13323        file_menu.addItem(&new_window);
13324        file_menu.addItem(&NSMenuItem::separatorItem(mtm));
13325        // Nil-targeted, so it closes whatever window is key — the standard responder route.
13326        let close = unsafe {
13327            NSMenuItem::initWithTitle_action_keyEquivalent(
13328                NSMenuItem::alloc(mtm),
13329                &NSString::from_str(&day_localization::t(day_localization::key::day_close)),
13330                Some(sel!(performClose:)),
13331                &NSString::from_str("w"),
13332            )
13333        };
13334        file_menu.addItem(&close);
13335        file_item.setSubmenu(Some(&file_menu));
13336        menubar.addItem(&file_item);
13337    }
13338
13339    let edit_item = NSMenuItem::new(mtm);
13340    let edit_menu = unsafe {
13341        NSMenu::initWithTitle(
13342            NSMenu::alloc(mtm),
13343            &NSString::from_str(&day_localization::t(day_localization::key::day_edit)),
13344        )
13345    };
13346    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
13347        let item = unsafe {
13348            NSMenuItem::initWithTitle_action_keyEquivalent(
13349                NSMenuItem::alloc(mtm),
13350                &NSString::from_str(&day_localization::t(key)),
13351                Some(action),
13352                &NSString::from_str(accel),
13353            )
13354        };
13355        edit_menu.addItem(&item);
13356    };
13357    add("day_undo", sel!(undo:), "z");
13358    add("day_redo", sel!(redo:), "Z");
13359    edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
13360    add("day_cut", sel!(cut:), "x");
13361    add("day_copy", sel!(copy:), "c");
13362    add("day_paste", sel!(paste:), "v");
13363    add("day_select_all", sel!(selectAll:), "a");
13364    edit_item.setSubmenu(Some(&edit_menu));
13365    menubar.addItem(&edit_item);
13366
13367    install_windows_menu(mtm, app, &menubar);
13368
13369    app.setMainMenu(Some(&menubar));
13370    unsafe { app.setServicesMenu(Some(&services)) };
13371}
13372
13373/// The standard Window menu (docs/windows.md): Minimize ⌘M / Zoom / Bring All to Front,
13374/// registered as `NSApp.windowsMenu` — AppKit then appends the open-window list and, with
13375/// tabbing live, the tab commands (Show Next/Previous Tab, Merge All Windows) itself. All
13376/// nav hosts are nil-targeted (responder chain), so they act on the key window.
13377fn install_windows_menu(mtm: MainThreadMarker, app: &NSApplication, menubar: &NSMenu) {
13378    let menu = unsafe {
13379        NSMenu::initWithTitle(
13380            NSMenu::alloc(mtm),
13381            &NSString::from_str(&day_localization::t(day_localization::key::day_window)),
13382        )
13383    };
13384    let add = |key: &str, action: objc2::runtime::Sel, accel: &str| {
13385        let item = unsafe {
13386            NSMenuItem::initWithTitle_action_keyEquivalent(
13387                NSMenuItem::alloc(mtm),
13388                &NSString::from_str(&day_localization::t(key)),
13389                Some(action),
13390                &NSString::from_str(accel),
13391            )
13392        };
13393        menu.addItem(&item);
13394    };
13395    add("day_minimize", sel!(performMiniaturize:), "m");
13396    add("day_zoom", sel!(performZoom:), "");
13397    menu.addItem(&NSMenuItem::separatorItem(mtm));
13398    add("day_bring_all_front", sel!(arrangeInFront:), "");
13399    let item = NSMenuItem::new(mtm);
13400    item.setTitle(&NSString::from_str(&day_localization::t(
13401        day_localization::key::day_window,
13402    )));
13403    item.setSubmenu(Some(&menu));
13404    menubar.addItem(&item);
13405    unsafe { app.setWindowsMenu(Some(&menu)) };
13406}
13407
13408/// Hoist application roles even from nested menus. First declaration wins; remove
13409/// duplicates and empty containers, then normalize separators left by the move.
13410fn extract_app_role(
13411    items: &mut Vec<day_spec::MenuItem>,
13412    role: day_spec::MenuRole,
13413) -> Option<day_spec::MenuItem> {
13414    use day_spec::MenuItem as M;
13415    let mut found = None;
13416    let mut remaining = Vec::new();
13417    for mut item in items.drain(..) {
13418        match &mut item {
13419            M::Action { role: Some(r), .. } if *r == role => {
13420                found.get_or_insert(item);
13421                continue;
13422            }
13423            M::Submenu { items, .. } => {
13424                let nested = extract_app_role(items, role);
13425                if found.is_none() {
13426                    found = nested;
13427                }
13428                if items.is_empty() {
13429                    continue;
13430                }
13431            }
13432            M::Separator
13433                if remaining.is_empty() || matches!(remaining.last(), Some(M::Separator)) =>
13434            {
13435                continue;
13436            }
13437            _ => {}
13438        }
13439        remaining.push(item);
13440    }
13441    while matches!(remaining.last(), Some(M::Separator)) {
13442        remaining.pop();
13443    }
13444    *items = remaining;
13445    found
13446}
13447
13448/// Whether any action in the model (recursively) carries `role`.
13449fn model_has_role(items: &[day_spec::MenuItem], role: day_spec::MenuRole) -> bool {
13450    items.iter().any(|it| match it {
13451        day_spec::MenuItem::Action { role: r, .. } => *r == Some(role),
13452        day_spec::MenuItem::Submenu { items, .. } => model_has_role(items, role),
13453        day_spec::MenuItem::Separator => false,
13454    })
13455}
13456
13457// ---------------------------------------------------------------------------
13458// Menus (§ menus): render day's MenuItem model with NSMenu. Custom items route to a shared
13459// DayMenuTarget (id in the item's tag → Event::MenuAction); role items use the native selector.
13460// ---------------------------------------------------------------------------
13461
13462define_class!(
13463    #[unsafe(super(NSObject))]
13464    #[thread_kind = MainThreadOnly]
13465    #[name = "DayMenuTarget"]
13466    #[ivars = ()]
13467    struct DayMenuTarget;
13468
13469    unsafe impl NSObjectProtocol for DayMenuTarget {}
13470
13471    impl DayMenuTarget {
13472        #[unsafe(method(fire:))]
13473        fn fire(&self, sender: &NSMenuItem) {
13474            ffi_guard::contain((), || {
13475                let id = sender.tag() as u64;
13476                if id != 0 {
13477                    emit(day_spec::WINDOW_NODE, Event::MenuAction(id));
13478                }
13479            })
13480        }
13481    }
13482);
13483
13484/// The primary window's content view (set once in `run`).
13485/// Pin the window's content coordinate space under its title bar and toolbar (§7.7). The
13486/// content view is full-size (`FullSizeContentView`, for the unified toolbar), so it runs
13487/// beneath the bar; moving its bounds origin up by that strip makes Day's root, laid out from
13488/// (0, 0), start below the bar — the way UIKit pins the root inside `safeAreaInsets` — while
13489/// the view's own background still paints edge to edge. Returns the size Day lays out at, the
13490/// window's `contentLayoutRect`. Called wherever that rect can change: window creation, every
13491/// resize, and a toolbar coming or going.
13492pub(crate) fn pin_below_title_bar(window: &NSWindow) -> Option<Size> {
13493    let content = window.contentView()?;
13494    let full = content.frame().size;
13495    let layout = unsafe { window.contentLayoutRect() }.size;
13496    let top = (full.height - layout.height).max(0.0);
13497    // An overlay title bar (docs/window-chrome.md) is the one place the content belongs under
13498    // the bar: it keeps the full height, and the bar's height goes to the app as a safe-area
13499    // inset so it can pad its own content.
13500    if window_chrome::is_overlay(window) {
13501        unsafe { content.setBoundsOrigin(NSPoint::new(0.0, 0.0)) };
13502        window_chrome::report_title_bar_inset(window, top);
13503        return Some(Size::new(full.width, full.height));
13504    }
13505    unsafe { content.setBoundsOrigin(NSPoint::new(0.0, -top)) };
13506    Some(Size::new(full.width, (full.height - top).max(0.0)))
13507}
13508
13509/// The text a widget displays, for `read_native`: a label's or text field's string, a
13510/// button's title, a text area's contents. `None` for a secure field (it masks its text), an
13511/// icon-only button (its title is a tooltip), and every other view.
13512fn native_text(h: &NSView) -> Option<String> {
13513    if h.downcast_ref::<NSSecureTextField>().is_some() {
13514        return None;
13515    }
13516    if let Some(tf) = h.downcast_ref::<NSTextField>() {
13517        // `stringValue` answers the field editor's live text while the field edits.
13518        return Some(tf.stringValue().to_string());
13519    }
13520    if let Some(btn) = h.downcast_ref::<NSButton>() {
13521        if unsafe { btn.imagePosition() } == objc2_app_kit::NSCellImagePosition::ImageOnly {
13522            return None;
13523        }
13524        return Some(btn.title().to_string());
13525    }
13526    // A text area is an NSTextView inside the scroll view its handle names (textarea.rs).
13527    let sv = h.downcast_ref::<NSScrollView>()?;
13528    let doc = sv.documentView()?;
13529    let tv = doc.downcast_ref::<NSTextView>()?;
13530    Some(tv.string().to_string())
13531}
13532
13533/// A slider's value or a determinate progress bar's fraction, for `read_native`. Both native
13534/// ranges are the ones Day gave: the slider is built with Day's min and max, the bar runs 0–1.
13535fn native_number(h: &NSView) -> Option<f64> {
13536    if let Some(sl) = h.downcast_ref::<NSSlider>() {
13537        return Some(sl.doubleValue());
13538    }
13539    let pi = h.downcast_ref::<NSProgressIndicator>()?;
13540    (!pi.isIndeterminate()).then(|| pi.doubleValue())
13541}
13542
13543/// The view's frame in its window's content coordinates, origin top left, for `read_native`.
13544/// The content view is flipped and pinned below the title bar (`pin_below_title_bar`), so
13545/// converting into it gives Day's layout space; an unflipped content view is flipped here.
13546fn native_frame(h: &NSView) -> Option<Rect> {
13547    let content = h.window()?.contentView()?;
13548    let r = h.convertRect_toView(h.bounds(), Some(&content));
13549    let y = if content.isFlipped() {
13550        r.origin.y
13551    } else {
13552        let b = content.bounds();
13553        b.origin.y + b.size.height - (r.origin.y + r.size.height)
13554    };
13555    Some(Rect::new(r.origin.x, y, r.size.width, r.size.height))
13556}
13557
13558/// The strip a pinned content view keeps above its layout origin (see `pin_below_title_bar`).
13559fn title_bar_inset(content: &NSView) -> f64 {
13560    (-content.bounds().origin.y).max(0.0)
13561}
13562
13563fn primary_content() -> Option<Retained<NSView>> {
13564    PRIMARY_CONTENT.with(|c| c.borrow().clone())
13565}
13566
13567fn menu_target(mtm: MainThreadMarker) -> Retained<DayMenuTarget> {
13568    MENU_TARGET.with(|t| {
13569        t.borrow_mut()
13570            .get_or_insert_with(|| {
13571                let this = DayMenuTarget::alloc(mtm).set_ivars(());
13572                let obj: Retained<DayMenuTarget> = unsafe { msg_send![super(this), init] };
13573                obj
13574            })
13575            .clone()
13576    })
13577}
13578
13579fn ns_modifiers(s: &day_spec::Shortcut) -> objc2_app_kit::NSEventModifierFlags {
13580    use objc2_app_kit::NSEventModifierFlags as F;
13581    let mut m = F::empty();
13582    if s.primary {
13583        m |= F::Command;
13584    }
13585    if s.shift {
13586        m |= F::Shift;
13587    }
13588    if s.alt {
13589        m |= F::Option;
13590    }
13591    if s.control {
13592        m |= F::Control;
13593    }
13594    m
13595}
13596
13597/// A shortcut's key-equivalent string. Single chars pass through (lowercased); a few named keys map
13598/// to their control characters. Modifiers ride separately via `setKeyEquivalentModifierMask`.
13599fn ns_key_equivalent(key: &str) -> String {
13600    match key {
13601        "Return" | "Enter" => "\r".into(),
13602        "Tab" => "\t".into(),
13603        "Delete" | "Backspace" => "\u{8}".into(),
13604        "Escape" => "\u{1b}".into(),
13605        "Space" => " ".into(),
13606        k if k.chars().count() == 1 => k.to_lowercase(),
13607        _ => String::new(), // named keys we don't map get no key-equivalent (still shown in menu)
13608    }
13609}
13610
13611/// A standard role → (default label, nav host, default shortcut). Nav host `None` = no native action
13612/// (the app should attach its own via a custom item); the role then only supplies label placement.
13613fn role_spec(
13614    role: day_spec::MenuRole,
13615) -> (
13616    &'static str,
13617    Option<objc2::runtime::Sel>,
13618    Option<day_spec::Shortcut>,
13619) {
13620    use day_spec::MenuRole as R;
13621    use day_spec::Shortcut as S;
13622    match role {
13623        R::Cut => ("Cut", Some(sel!(cut:)), Some(S::primary("x"))),
13624        R::Copy => ("Copy", Some(sel!(copy:)), Some(S::primary("c"))),
13625        R::Paste => ("Paste", Some(sel!(paste:)), Some(S::primary("v"))),
13626        R::SelectAll => ("Select All", Some(sel!(selectAll:)), Some(S::primary("a"))),
13627        R::Undo => ("Undo", Some(sel!(undo:)), Some(S::primary("z"))),
13628        R::Redo => ("Redo", Some(sel!(redo:)), Some(S::primary("z").shift())),
13629        R::Delete => ("Delete", Some(sel!(delete:)), None),
13630        R::About => ("About", Some(sel!(orderFrontStandardAboutPanel:)), None),
13631        R::Quit => ("Quit", Some(sel!(terminate:)), Some(S::primary("q"))),
13632        R::Preferences => ("Settings…", None, Some(S::primary(","))),
13633        R::Minimize => (
13634            "Minimize",
13635            Some(sel!(performMiniaturize:)),
13636            Some(S::primary("m")),
13637        ),
13638        R::CloseWindow => ("Close", Some(sel!(performClose:)), Some(S::primary("w"))),
13639        R::Fullscreen => (
13640            "Enter Full Screen",
13641            Some(sel!(toggleFullScreen:)),
13642            Some(S::primary("f").control()),
13643        ),
13644        // No native selector (docs/windows.md): the item dispatches the registered
13645        // new-window action through the ordinary custom-item path (`fire:`).
13646        R::NewWindow => ("New Window", None, Some(S::primary("n"))),
13647        // Likewise: no selector, the registered updater action fires through `fire:`.
13648        R::CheckForUpdates => ("Check for Updates…", None, None),
13649    }
13650}
13651
13652pub(crate) fn build_ns_menu(
13653    mtm: MainThreadMarker,
13654    title: &str,
13655    items: &[day_spec::MenuItem],
13656) -> Retained<NSMenu> {
13657    use day_spec::MenuItem as MI;
13658    let menu = unsafe { NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title)) };
13659    let target = menu_target(mtm);
13660    for item in items {
13661        match item {
13662            MI::Separator => menu.addItem(&NSMenuItem::separatorItem(mtm)),
13663            MI::Submenu { label, items, .. } => {
13664                let sub = build_ns_menu(mtm, label, items);
13665                let it = NSMenuItem::new(mtm);
13666                it.setTitle(&NSString::from_str(label));
13667                it.setSubmenu(Some(&sub));
13668                menu.addItem(&it);
13669            }
13670            MI::Action {
13671                action,
13672                label,
13673                shortcut,
13674                enabled,
13675                checked,
13676                role,
13677                icon,
13678                ..
13679            } => {
13680                // Resolve label/nav host/shortcut, folding in the role's native defaults.
13681                let (mut lbl, sel, mut sc) = match role {
13682                    Some(r) => {
13683                        let (dl, ds, dsc) = role_spec(*r);
13684                        (dl.to_string(), ds, dsc)
13685                    }
13686                    None => (String::new(), None, None),
13687                };
13688                if !label.is_empty() {
13689                    lbl = label.clone();
13690                }
13691                if shortcut.is_some() {
13692                    sc = shortcut.clone();
13693                }
13694                // Custom action (nonzero id) overrides any role nav host and targets our
13695                // trampoline — except the responder-routed set (undo pair, clipboard trio),
13696                // whose nonzero ids are only the other platforms' fallback dispatchers: here
13697                // the nil-target nav hosts must stay, so the responder chain resolves the
13698                // acting object (a focused text field before the app's bridge).
13699                let responder_role = matches!(
13700                    role,
13701                    Some(
13702                        day_spec::MenuRole::Undo
13703                            | day_spec::MenuRole::Redo
13704                            | day_spec::MenuRole::Cut
13705                            | day_spec::MenuRole::Copy
13706                            | day_spec::MenuRole::Paste
13707                            | day_spec::MenuRole::SelectAll
13708                    )
13709                );
13710                let custom = *action != 0 && !responder_role;
13711                let key = sc
13712                    .as_ref()
13713                    .map(|s| ns_key_equivalent(&s.key))
13714                    .unwrap_or_default();
13715                let it = unsafe {
13716                    NSMenuItem::initWithTitle_action_keyEquivalent(
13717                        NSMenuItem::alloc(mtm),
13718                        &NSString::from_str(&lbl),
13719                        if custom { Some(sel!(fire:)) } else { sel },
13720                        &NSString::from_str(&key),
13721                    )
13722                };
13723                if let Some(s) = &sc {
13724                    it.setKeyEquivalentModifierMask(ns_modifiers(s));
13725                    // AppKit's own per-layout/per-language adjustments (macOS 12+): remap a
13726                    // key equivalent the current keyboard layout cannot type, and MIRROR
13727                    // directional pairs (⌘[ / ⌘]) under RTL languages — the system half of
13728                    // shortcut localization; the catalog half is the `.key` attribute
13729                    // (docs/localization.md).
13730                    it.setAllowsAutomaticKeyEquivalentLocalization(true);
13731                    it.setAllowsAutomaticKeyEquivalentMirroring(true);
13732                }
13733                if custom {
13734                    let tobj: &objc2::runtime::AnyObject = target.as_ref();
13735                    unsafe { it.setTarget(Some(tobj)) };
13736                    it.setTag(*action as isize);
13737                }
13738                it.setEnabled(*enabled);
13739                // A checkable item takes NSMenuItem's own state, so macOS draws the ✓ it draws
13740                // everywhere else and reserves the mark's column when it is off (docs/menus.md).
13741                if let Some(on) = checked {
13742                    it.setState(if *on {
13743                        NSControlStateValueOn
13744                    } else {
13745                        NSControlStateValueOff
13746                    });
13747                }
13748                // The item's glyph, drawn the way NSMenuItem draws its own (docs/menus.md):
13749                // template-tinted, sized to the menu's text.
13750                if let Some(icon) = icon
13751                    && let Some(img) = crate::toolbar::image_for(icon, &lbl, mtm)
13752                {
13753                    img.setSize(NSSize::new(16.0, 16.0));
13754                    it.setImage(Some(&img));
13755                }
13756                menu.addItem(&it);
13757            }
13758        }
13759    }
13760    menu
13761}
13762
13763// AppKit's TLS may be destroyed before the reactive arena drops its last Bitmap.
13764// The registry already released the native images in that case.
13765fn release_bitmap(id: day_spec::BitmapId) {
13766    let _ = BITMAPS.try_with(|m| m.borrow_mut().remove(&id.0));
13767}
13768
13769#[cfg(test)]
13770mod bitmap_teardown_tests {
13771    use super::*;
13772
13773    #[test]
13774    fn releasing_after_bitmap_registry_teardown_does_not_abort() {
13775        // Isolate destructor panics: Rust aborts the process when a TLS destructor unwinds.
13776        const CHILD: &str = "DAY_APPKIT_BITMAP_TEARDOWN_CHILD";
13777        if std::env::var_os(CHILD).is_some() {
13778            struct LateRelease;
13779            impl Drop for LateRelease {
13780                fn drop(&mut self) {
13781                    assert!(BITMAPS.try_with(|_| ()).is_err());
13782                    // Same duty called by Bitmap::drop; no NSApplication is needed.
13783                    release_bitmap(day_spec::BitmapId(1));
13784                }
13785            }
13786            std::thread_local! {
13787                static LATE: RefCell<Option<LateRelease>> = const { RefCell::new(None) };
13788            }
13789            std::thread::spawn(|| {
13790                LATE.with(|slot| *slot.borrow_mut() = Some(LateRelease));
13791                BITMAPS.with(|_| ()); // initialized last, destroyed first
13792            })
13793            .join()
13794            .unwrap();
13795            return;
13796        }
13797        let output = std::process::Command::new(std::env::current_exe().unwrap())
13798            .args([
13799                "--exact",
13800                "bitmap_teardown_tests::releasing_after_bitmap_registry_teardown_does_not_abort",
13801                "--nocapture",
13802            ])
13803            .env(CHILD, "1")
13804            .output()
13805            .unwrap();
13806        assert!(
13807            output.status.success(),
13808            "{}",
13809            String::from_utf8_lossy(&output.stderr)
13810        );
13811    }
13812}