Skip to main content

day_core/
windows.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Secondary windows (docs/windows.md): the app-facing `open_window` API, the per-window
5//! registry, and the fallback that presents window content as a fullscreen cover where the
6//! toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`).
7//!
8//! Windows live in the one thread-local tree as additional boundary roots (the same
9//! "wrap an externally-owned handle" record as the primary root and the list cell
10//! anchors), so bindings, `find_by_id`, and dayscript work across windows unchanged.
11//! Close is asynchronous everywhere: the platform (or the cover's hide transition)
12//! confirms, and teardown runs then: one path for native and programmatic closes.
13
14use std::cell::{Cell, OnceCell, RefCell};
15use std::rc::Rc;
16
17use day_reactive::{Scope, Signal};
18use day_spec::props::{CoverPatch, CoverProps};
19use day_spec::{
20    Attention, Event, NodeId, Point, Rect, Size, WindowChange, WindowKind, WindowLevel,
21    WindowOptions, WindowRole, WindowState, WindowTabbing, kinds,
22};
23
24use crate::AnyPiece;
25use crate::build::{Boundary, BuildCx, Piece};
26use crate::tree::{RNode, WindowRootReply, id_to_rnode, rnode_to_id, with_tree};
27
28fn focus_revision() -> Signal<u64> {
29    FOCUS_REVISION.with(|revision| *revision.get_or_init(|| Signal::global(0)))
30}
31
32/// How a window record is realized.
33enum Tier {
34    /// A live native OS window; the root's handle is its content container.
35    Native { closing: Cell<bool> },
36    /// The toolkit answered `Pending`: native creation is in flight; the content builds
37    /// when the backend calls [`finish_window_open`].
38    PendingNative {
39        build: Option<Box<dyn FnOnce() -> AnyPiece>>,
40        title: String,
41    },
42    /// No native window: the content presents as a fullscreen cover in the primary
43    /// window; `cover` is the cover node, `closing` gates the dismiss transition.
44    Cover {
45        cover: RNode,
46        closing: Rc<Cell<bool>>,
47    },
48}
49
50/// Close callbacks, shared so they outlive the registry entry during teardown.
51type OnCloseList = Rc<RefCell<Vec<Box<dyn Fn()>>>>;
52
53struct WindowRecord {
54    root: RNode,
55    key: Option<String>,
56    kind: WindowKind,
57    /// Whether this window keeps the app alive (docs/windows.md close policy). Derived from
58    /// `kind` today; a per-window override is the natural next step.
59    role: WindowRole,
60    scope: Scope,
61    content_scope: Option<Scope>,
62    tier: Tier,
63    focused: bool,
64    on_close: OnCloseList,
65    close_request: Option<Rc<dyn Fn()>>,
66    /// What the window's `state()` signal holds: written by the app to ask, and by
67    /// `Event::WindowStateChanged` to report.
68    state: Signal<WindowState>,
69    /// The last state the platform reported, so a report written into `state` is not sent back
70    /// to the platform as a request.
71    reported: Rc<Cell<WindowState>>,
72    /// The `WindowOptions::remember_frame` key this window saves its frame under.
73    remember: Option<String>,
74}
75
76impl WindowRecord {
77    /// Whether dismissal has been requested and not yet confirmed by the platform.
78    fn closing(&self) -> bool {
79        match &self.tier {
80            Tier::Native { closing } => closing.get(),
81            Tier::Cover { closing, .. } => closing.get(),
82            Tier::PendingNative { .. } => false,
83        }
84    }
85}
86
87day_reactive::tls_slots! {
88    windows;
89    static WINDOWS: RefCell<Vec<WindowRecord>> = const { RefCell::new(Vec::new()) };
90
91    /// Invalidate reactive focused ambient lookups after command routing changes.
92    // Keep the core TLS initializer independent of the reactive runtime. Bitmap cleanup
93    // can touch an empty core root while reactive TLS is being destroyed (Windows GNU
94    // can even recreate the root after its destructor has finished).
95    static FOCUS_REVISION: OnceCell<Signal<u64>> = const { OnceCell::new() };
96
97    /// The app's first window, so [`initial_window`] can name it. Nothing about the close
98    /// policy consults this: that window is an ordinary registry record and counts exactly
99    /// like the ones opened after it.
100    static INITIAL_WINDOW: Cell<Option<RNode>> = const { Cell::new(None) };
101
102    /// Set while [`quit`] disposes the windows, so the last one closing does not start a second
103    /// quit.
104    static QUITTING: Cell<bool> = const { Cell::new(false) };
105
106    static PREFS: RefCell<Option<PrefsRegistration>> = const { RefCell::new(None) };
107    static PREFS_ACTION: Cell<u64> = const { Cell::new(0) };
108    /// What About does (docs/settings.md): opens a Day window, or the toolkit's own dialog.
109    static ABOUT: RefCell<Option<Rc<dyn Fn()>>> = const { RefCell::new(None) };
110    static ABOUT_ACTION: Cell<u64> = const { Cell::new(0) };
111    /// The updater's Check for Updates… command (docs/settings.md).
112    static UPDATES: RefCell<Option<Rc<dyn Fn()>>> = const { RefCell::new(None) };
113    static UPDATES_ACTION: Cell<u64> = const { Cell::new(0) };
114    static NEW_WINDOW: RefCell<Option<Rc<dyn Fn() -> AnyPiece>>> = const { RefCell::new(None) };
115    /// Builders behind the macOS tab bar's "+" for windows of one tab group
116    /// (`register_new_window_for`, docs/windows.md).
117    static TAB_NEW: RefCell<Vec<(String, Rc<dyn Fn()>)>> = const { RefCell::new(Vec::new()) };
118    static GROUP_WINDOWS: RefCell<Vec<(String, Rc<dyn Fn() -> AnyPiece>)>> = const { RefCell::new(Vec::new()) };
119    static NEW_WINDOW_ACTION: Cell<u64> = const { Cell::new(0) };
120
121    /// What the app asked `launch` for, so a window opened later can describe itself the same
122    /// way (docs/windows.md). Title above all: every platform's automatic window management
123    /// keys on it (the macOS Window menu and tab bar, the iPad app switcher, the Android
124    /// recents card), and an untitled window is absent from all of them.
125    static LAUNCH_OPTIONS: RefCell<Option<WindowOptions>> = const { RefCell::new(None) };
126}
127
128/// Record what the app handed `launch`, for [`open_new_window`] to inherit. Called once by
129/// `launch_with` with the options it is about to open the primary window with, already
130/// title-decorated, which is idempotent (`tag_title`).
131pub fn set_launch_options(options: &WindowOptions) {
132    LAUNCH_OPTIONS.with(|o| *o.borrow_mut() = Some(options.clone()));
133}
134
135/// What the app handed `launch` (title, app name, version), for surfaces that describe the
136/// app (an About page). `None` before launch.
137#[must_use]
138pub fn launch_options() -> Option<WindowOptions> {
139    LAUNCH_OPTIONS.with(|o| o.borrow().clone())
140}
141
142/// A live secondary window (docs/windows.md). Cheap to clone; inert after close.
143#[derive(Clone)]
144pub struct WindowHandle {
145    root: RNode,
146}
147
148impl WindowHandle {
149    /// Bind command/ambient lookup to retained document state without transferring scope ownership.
150    pub fn set_content_scope(&self, scope: Scope) {
151        WINDOWS.with(|w| {
152            if let Some(r) = w.borrow_mut().iter_mut().find(|r| r.root == self.root) {
153                r.content_scope = Some(scope);
154            }
155        });
156        focus_revision().update(|n| *n += 1);
157    }
158
159    /// Route native user close requests to the document owner. `close()` still closes
160    /// unconditionally after the owner has accepted and removed its content.
161    pub fn on_close_request(&self, f: impl Fn() + 'static) {
162        WINDOWS.with(|w| {
163            if let Some(r) = w.borrow_mut().iter_mut().find(|r| r.root == self.root) {
164                r.close_request = Some(Rc::new(f));
165            }
166        });
167    }
168    /// Observe native activation (including selection of an OS window tab).
169    pub fn on_focus(&self, f: impl Fn() + 'static) {
170        with_tree(|t| {
171            t.on_event(
172                self.root,
173                Rc::new(move |ev| {
174                    if matches!(ev, Event::WindowFocused(true)) {
175                        f();
176                    }
177                }),
178            );
179        });
180    }
181    /// Native order of this window's tab group. Empty where unsupported.
182    #[must_use]
183    pub fn tab_order(&self) -> Vec<NodeId> {
184        with_tree(|t| t.window_tab_order(self.root))
185    }
186
187    /// Close the window. Asynchronous: the platform (or the cover's hide transition)
188    /// confirms, then the content is disposed and `on_close` callbacks run. Focused-window
189    /// lookup stops targeting this window as soon as close is requested. Idempotent.
190    pub fn close(&self) {
191        let root = self.root;
192        let action = WINDOWS.with(|w| {
193            w.borrow()
194                .iter()
195                .find(|r| r.root == root)
196                .map(|r| match &r.tier {
197                    Tier::Native { closing } => {
198                        if closing.replace(true) {
199                            CloseAction::None
200                        } else {
201                            CloseAction::Native
202                        }
203                    }
204                    Tier::PendingNative { .. } => CloseAction::Immediate,
205                    Tier::Cover { cover, closing } => {
206                        if closing.get() {
207                            CloseAction::None
208                        } else {
209                            closing.set(true);
210                            CloseAction::Cover(*cover)
211                        }
212                    }
213                })
214        });
215        focus_revision().update(|n| *n += 1);
216        match action {
217            Some(CloseAction::Native) => with_tree(|t| t.close_native_window(root)),
218            // Parked pending: nothing native to wait for, so tear down now; the backend's
219            // later `finish_window_open` finds the record gone and drops its window.
220            Some(CloseAction::Immediate) => teardown(root),
221            Some(CloseAction::Cover(cover)) => {
222                with_tree(|t| t.patch(cover, Box::new(CoverPatch::Dismiss), false));
223            }
224            Some(CloseAction::None) | None => {}
225        }
226    }
227
228    /// Bring the window to front and make it key. No-op on the cover tier (the cover is
229    /// already frontmost in the primary window) and while a `Pending` open is in flight.
230    pub fn focus(&self) {
231        let root = self.root;
232        if WINDOWS.with(|w| {
233            w.borrow()
234                .iter()
235                .any(|r| r.root == root && !r.closing() && matches!(r.tier, Tier::Native { .. }))
236        }) {
237            // Record explicit activation as well as native notifications. An inactive
238            // AppKit application can accept makeKeyAndOrderFront without sending a key
239            // notification; commands must still follow the window we just selected.
240            WINDOWS.with(|windows| {
241                for window in windows.borrow_mut().iter_mut() {
242                    window.focused = window.root == root;
243                }
244            });
245            focus_revision().update(|n| *n += 1);
246            with_tree(|t| t.focus_native_window(root));
247        }
248    }
249
250    /// Retitle the window. Applies to live native windows; a `Pending` window picks the
251    /// new title up at completion; the cover tier has no title bar (no-op).
252    pub fn set_title(&self, title: &str) {
253        let root = self.root;
254        let title = &crate::decorate_window_title(title);
255        let live = WINDOWS.with(|w| {
256            let mut windows = w.borrow_mut();
257            match windows.iter_mut().find(|r| r.root == root) {
258                Some(r) => match &mut r.tier {
259                    Tier::Native { .. } => true,
260                    Tier::PendingNative { title: t, .. } => {
261                        t.clone_from(title);
262                        false
263                    }
264                    Tier::Cover { .. } => false,
265                },
266                None => false,
267            }
268        });
269        if live {
270            let title = title.clone();
271            with_tree(|t| t.set_native_window_title(root, &title));
272        }
273    }
274
275    /// A frame source tied to this window, usable outside a piece build.
276    #[must_use]
277    pub fn frame_clock(&self) -> crate::frame::FrameClock {
278        crate::frame::FrameClock::for_root(self.root)
279    }
280
281    /// Whether the window is still open (its record exists; a `Pending` open counts).
282    #[must_use]
283    pub fn is_open(&self) -> bool {
284        let root = self.root;
285        WINDOWS.with(|w| w.borrow().iter().any(|r| r.root == root))
286    }
287
288    /// Run `f` after the window has closed and its content is disposed, on any close path
289    /// (title-bar, platform gesture, [`WindowHandle::close`]). No-op if already closed.
290    pub fn on_close(&self, f: impl Fn() + 'static) {
291        let root = self.root;
292        WINDOWS.with(|w| {
293            if let Some(r) = w.borrow().iter().find(|r| r.root == root) {
294                r.on_close.borrow_mut().push(Box::new(f));
295            }
296        });
297    }
298
299    /// The window's display state, two ways (docs/windows.md "Window properties"): read it to
300    /// follow what the user does (minimize, zoom, fullscreen), write it to ask for a state.
301    ///
302    /// The platform has the last word. A write is a request; the signal settles on whatever the
303    /// window actually became once the platform reports it, so a request the platform declines
304    /// (a fullscreen the browser refuses outside a user gesture) reads back as the state the
305    /// window kept. Probe `Cap::WindowStates` and `Cap::WindowFullscreen` before offering the
306    /// controls. A cover-tier window (`Cap::MultiWindow` = `Unsupported`) stays `Normal`.
307    #[must_use]
308    pub fn state(&self) -> Signal<WindowState> {
309        let root = self.root;
310        WINDOWS
311            .with(|w| w.borrow().iter().find(|r| r.root == root).map(|r| r.state))
312            .unwrap_or_else(|| Signal::new(WindowState::Normal))
313    }
314
315    /// This window's safe-area insets, in points (tracked): what lies under the window's own
316    /// chrome. Nonzero for a [`WindowChrome::Overlay`] window, whose title bar sits over the
317    /// content (docs/window-chrome.md), and on a phone running edge-to-edge. Unlike
318    /// [`crate::safe_area`], which resolves the window being built and otherwise the primary,
319    /// this keeps answering for this window when a binding re-runs later.
320    ///
321    /// [`WindowChrome::Overlay`]: day_spec::WindowChrome::Overlay
322    #[must_use]
323    pub fn safe_area(&self) -> day_geometry::Insets {
324        crate::ambient::window_safe_area(self.root)
325    }
326
327    /// Ask for a display state: `state().set(s)`, spelled as an action.
328    pub fn set_state(&self, state: WindowState) {
329        self.state().set(state);
330    }
331
332    /// Keep this window's content out of screenshots, screen recordings and screen sharing
333    /// (`Cap::ContentProtection`, docs/windows.md): for passwords, payment details, private
334    /// messages. On iOS the content is covered while the screen is recorded or mirrored, but a
335    /// screenshot still captures it.
336    pub fn set_content_protected(&self, protected: bool) {
337        self.apply(&WindowChange::ContentProtected(protected));
338    }
339
340    /// Move and/or resize the window (docs/windows.md "Window properties"): `origin` is the outer
341    /// frame's top-left corner on the desktop (`Cap::WindowPosition`), `size` the content size
342    /// (`Cap::WindowGeometry`). `None` leaves that part alone.
343    pub fn set_frame(&self, origin: Option<Point>, size: Option<Size>) {
344        self.apply(&WindowChange::Frame { origin, size });
345    }
346
347    /// The window's outer frame on the desktop, in points, where the platform says
348    /// (`None` on a phone, under Wayland, and for a cover-tier window).
349    #[must_use]
350    pub fn frame(&self) -> Option<Rect> {
351        if !self.is_native() {
352            return None;
353        }
354        let root = self.root;
355        with_tree(|t| t.native_window_frame(root))
356    }
357
358    /// The content sizes the user can resize the window between (`Cap::WindowGeometry`).
359    pub fn set_limits(&self, min: Option<Size>, max: Option<Size>) {
360        self.apply(&WindowChange::Limits { min, max });
361    }
362
363    /// Whether the user can resize the window (`Cap::WindowGeometry`).
364    pub fn set_resizable(&self, resizable: bool) {
365        self.apply(&WindowChange::Resizable(resizable));
366    }
367
368    /// Keep the window above other apps' windows, or let it stack normally (`Cap::WindowLevel`).
369    pub fn set_level(&self, level: WindowLevel) {
370        self.apply(&WindowChange::Level(level));
371    }
372
373    /// Show the window on every virtual desktop / Space (`Cap::WindowLevel`).
374    pub fn set_on_all_workspaces(&self, on: bool) {
375        self.apply(&WindowChange::OnAllWorkspaces(on));
376    }
377
378    /// Leave the window out of the taskbar and the window switcher (`Cap::WindowLevel`).
379    pub fn set_skip_taskbar(&self, skip: bool) {
380        self.apply(&WindowChange::SkipTaskbar(skip));
381    }
382
383    /// Offer or withhold the window's minimize control (`Cap::WindowStates`).
384    pub fn set_minimizable(&self, on: bool) {
385        self.apply(&WindowChange::Minimizable(on));
386    }
387
388    /// Offer or withhold the window's maximize / zoom control (`Cap::WindowStates`).
389    pub fn set_maximizable(&self, on: bool) {
390        self.apply(&WindowChange::Maximizable(on));
391    }
392
393    /// Offer or withhold the window's close control (`Cap::WindowStates`). The app can still
394    /// close it with [`close`](Self::close).
395    pub fn set_closable(&self, on: bool) {
396        self.apply(&WindowChange::Closable(on));
397    }
398
399    /// Hide the window without closing it, or show it again (`Cap::WindowStates`): a palette
400    /// that comes and goes, a window a status item toggles.
401    pub fn set_visible(&self, visible: bool) {
402        self.apply(&WindowChange::Visible(visible));
403    }
404
405    /// Give this window its own light (`Some(false)`) or dark (`Some(true)`) appearance, or
406    /// follow the app's again (`None`). `Cap::WindowAppearance`; where unsupported the app-wide
407    /// `day::set_appearance` still applies.
408    pub fn set_appearance(&self, dark: Option<bool>) {
409        self.apply(&WindowChange::Appearance(dark));
410    }
411
412    /// Ask for the user's attention: a Dock bounce, a flashing taskbar button
413    /// (`Cap::RequestAttention`). The platform does nothing while the app is already in front.
414    pub fn request_attention(&self, attention: Attention) {
415        self.apply(&WindowChange::RequestAttention(attention));
416    }
417
418    /// Hand one change to the toolkit, for a window that has a native side. A cover-tier window
419    /// lives inside the primary one and has nothing of its own to change.
420    fn apply(&self, change: &WindowChange) {
421        if self.is_native() {
422            let root = self.root;
423            with_tree(|t| t.apply_window(root, change));
424        }
425    }
426
427    fn is_native(&self) -> bool {
428        let root = self.root;
429        WINDOWS.with(|w| {
430            w.borrow()
431                .iter()
432                .any(|r| r.root == root && matches!(r.tier, Tier::Native { .. }))
433        })
434    }
435}
436
437enum CloseAction {
438    Native,
439    Immediate,
440    Cover(RNode),
441    None,
442}
443
444/// Open a secondary window (docs/windows.md): `open_window(res::window_options().key("city").size(…), build)`.
445/// `options.key` names the logical window: when a window with this key is already open it is
446/// focused and returned instead of duplicated (the preferences pattern); no key always opens a
447/// new one. `options.kind` says whether it is a regular window or a preferences/About panel.
448/// Where the toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`; probe it to adapt
449/// chrome) the content presents as a fullscreen cover in the primary window instead, closable
450/// the same way.
451pub fn open_window<P: Piece>(
452    mut options: WindowOptions,
453    build: impl FnOnce() -> P + 'static,
454) -> WindowHandle {
455    let key = options.key.take();
456    let key = key.as_deref();
457    let kind = options.kind;
458    if let Some(k) = key
459        && let Some(existing) = window_by_key(k)
460    {
461        revive_if_dismissing(existing.root);
462        existing.focus();
463        return existing;
464    }
465    // A secondary window carries the same debug tag as the primary: with several windows of
466    // several builds open, that is what tells them apart.
467    options.title = crate::decorate_window_title(&options.title);
468
469    // The window's lifetime is app-owned, not caller-owned: a window opened from a button
470    // must survive that page popping, so its scope hangs off the root scope.
471    let scope = Scope::root().enter(Scope::child);
472
473    match with_tree(|t| t.open_window_root(&options, kind)) {
474        WindowRootReply::Open(root) => {
475            register(
476                root,
477                key,
478                kind,
479                scope,
480                Tier::Native {
481                    closing: Cell::new(false),
482                },
483            );
484            wire_window_events(root);
485            if let Some(k) = &options.remember_frame {
486                remember_frame(root, k);
487            }
488            scope.enter(|| {
489                // Name this window for the duration of its build, so a `toolbar(...)` inside a
490                // shared window builder installs on this window (docs/toolbars.md).
491                crate::toolbar::with_window(root, || {
492                    let piece = build();
493                    let mut cx = BuildCx::new(root);
494                    let _ = piece.build(&mut cx);
495                });
496            });
497            with_tree(|t| {
498                t.mark_layout_dirty();
499                t.layout_if_needed();
500            });
501            if options.size_to_fit {
502                // Measured after the first layout, because that is the only point where the
503                // content's real height is known; it depends on the user's text size, their
504                // language, and which rows the app decided to show.
505                //
506                // The content root has exactly one child (the piece the builder returned), and
507                // its laid-out frame is the content's natural height.
508                let fitted = with_tree(|t| {
509                    t.first_child(root)
510                        .and_then(|c| t.node_frame(c))
511                        .map_or(0.0, |f| f.origin.y + f.size.height)
512                });
513                // Never grow past what the caller asked for: `size` is the ceiling, so a panel
514                // with more content than fits scrolls rather than running off the screen.
515                if fitted > 0.0 && fitted < options.size.height {
516                    with_tree(|t| {
517                        t.fit_window(root, Size::new(options.size.width, fitted));
518                        t.mark_layout_dirty();
519                        t.layout_if_needed();
520                    });
521                }
522            }
523            focus_revision().update(|n| *n += 1);
524            WindowHandle { root }
525        }
526        WindowRootReply::Pending(root) => {
527            register(
528                root,
529                key,
530                kind,
531                scope,
532                Tier::PendingNative {
533                    build: Some(Box::new(move || AnyPiece::new(build()))),
534                    title: options.title.clone(),
535                },
536            );
537            wire_window_events(root);
538            WindowHandle { root }
539        }
540        WindowRootReply::Unsupported => {
541            open_as_cover(key, kind, scope, Box::new(move || AnyPiece::new(build())))
542        }
543    }
544}
545
546/// The open window registered under `key`, if any (the dayscript `screenshot` step's
547/// `window:` target resolves here). Native windows being closed are excluded; a dismissing
548/// fallback cover remains available so reopening its key can reverse the transition.
549#[must_use]
550pub fn window_by_key(key: &str) -> Option<WindowHandle> {
551    WINDOWS.with(|w| {
552        w.borrow()
553            .iter()
554            .find(|r| {
555                r.key.as_deref() == Some(key)
556                    && !matches!(&r.tier, Tier::Native { closing } if closing.get())
557            })
558            .map(|r| WindowHandle { root: r.root })
559    })
560}
561
562/// The most recently focused open secondary window, if any. `None` ⇒ the primary window
563/// is key (or no secondary window exists).
564#[must_use]
565pub fn focused_window() -> Option<WindowHandle> {
566    WINDOWS.with(|w| {
567        w.borrow()
568            .iter()
569            // The same rule as `focused_scope`: a dismissing window is already behind us.
570            .find(|r| r.focused && !r.closing())
571            .map(|r| WindowHandle { root: r.root })
572    })
573}
574
575pub(crate) fn focused_root() -> RNode {
576    focused_window().map_or_else(|| with_tree(|t| t.root_node()), |w| w.root)
577}
578
579/// The scope owning the content of the window that currently has focus: the scope an
580/// app-wide command should resolve per-window state through (docs/state.md).
581///
582/// Falls back to the app's primary window, which is the same rule [`focused_window`] states:
583/// a backend reports focus for the windows it opened, and "no record is focused" means the
584/// primary is key (on AppKit the primary's delegate carries no node and never emits
585/// `WindowFocused` at all, so that IS the primary's steady state). `None` only before boot
586/// and after the last window is gone.
587#[must_use]
588pub fn focused_scope() -> Option<Scope> {
589    focus_revision().track();
590    WINDOWS.with(|w| {
591        let windows = w.borrow();
592        // A dismissing window is no longer the command target, even while its content stays
593        // registered until native confirmation. GTK dialogs animate their close just as
594        // cover sheets do; resolving through Settings during that gap loses document state.
595        let focused = windows.iter().find(|r| r.focused && !r.closing());
596        let initial = INITIAL_WINDOW.with(std::cell::Cell::get);
597        focused
598            .or_else(|| windows.iter().find(|r| Some(r.root) == initial))
599            .map(|r| r.content_scope.unwrap_or(r.scope))
600    })
601}
602
603/// The scopes a focused-window lookup consults, in order: the focused window's own, then,
604/// when that window is a cover, the primary window's. A cover renders inside the primary
605/// window, so state the cover does not carry — an editor's per-window `Scene` while its
606/// settings cover is up — is still the primary's: a handler of the content underneath that
607/// fires during the presentation (a focus change, a redraw) resolves to the window it belongs
608/// to rather than to a sheet that never had one (docs/state.md).
609pub(crate) fn focused_scope_chain() -> Vec<Scope> {
610    focus_revision().track();
611    WINDOWS.with(|w| {
612        let windows = w.borrow();
613        let initial = INITIAL_WINDOW.with(std::cell::Cell::get);
614        let primary = || {
615            windows
616                .iter()
617                .find(|r| Some(r.root) == initial)
618                .map(|r| r.content_scope.unwrap_or(r.scope))
619        };
620        match windows.iter().find(|r| r.focused && !r.closing()) {
621            Some(front) => {
622                let own = front.content_scope.unwrap_or(front.scope);
623                let mut chain = vec![own];
624                if matches!(front.tier, Tier::Cover { .. }) {
625                    chain.extend(primary().filter(|scope| *scope != own));
626                }
627                chain
628            }
629            None => primary().into_iter().collect(),
630        }
631    })
632}
633
634/// The tree root of the window registered under `key`: day-script's snapshot target.
635#[must_use]
636pub fn window_root_by_key(key: &str) -> Option<RNode> {
637    WINDOWS.with(|w| {
638        w.borrow()
639            .iter()
640            .find(|r| {
641                r.key.as_deref() == Some(key)
642                    && !matches!(&r.tier, Tier::Native { closing } if closing.get())
643            })
644            .map(|r| match &r.tier {
645                // The cover renders inside the primary window: its pixels are the
646                // primary's pixels.
647                Tier::Cover { .. } => with_tree(|t| t.root_node()),
648                _ => r.root,
649            })
650    })
651}
652
653/// Backend-facing: complete a `Pending` window open (docs/windows.md). `id` is the node
654/// the backend's `open_window` received; `raw` is the new window's content container;
655/// `size` its content size in points. `false` ⇒ the window was closed before completion,
656/// and the backend should drop the native window it just created.
657pub fn finish_window_open(id: NodeId, raw: day_spec::RawHandle, size: Size) -> bool {
658    let root = id_to_rnode(id);
659    let pending = WINDOWS.with(|w| {
660        let mut windows = w.borrow_mut();
661        let r = windows.iter_mut().find(|r| r.root == root)?;
662        match &mut r.tier {
663            Tier::PendingNative { build, title } => {
664                let b = build.take();
665                let title = title.clone();
666                r.tier = Tier::Native {
667                    closing: Cell::new(false),
668                };
669                Some((b, title, r.scope))
670            }
671            _ => None,
672        }
673    });
674    let Some((build, title, scope)) = pending else {
675        return false;
676    };
677    if !with_tree(|t| t.adopt_window_root(root, raw, size)) {
678        return false;
679    }
680    with_tree(|t| t.set_native_window_title(root, &title));
681    // This window's size class, before its content builds (docs/size-classes.md): a second
682    // window can sit in a different class from the first, which is why the signal is per-window.
683    crate::ambient::set_window_size_class(
684        root,
685        day_spec::SizeClass::from_size(size.width, size.height),
686    );
687    if let Some(build) = build {
688        scope.enter(|| {
689            crate::toolbar::with_window(root, || {
690                let piece = build();
691                let mut cx = BuildCx::new(root);
692                let _ = piece.build(&mut cx);
693            });
694        });
695    }
696    with_tree(|t| {
697        t.mark_layout_dirty();
698        t.layout_if_needed();
699    });
700    // The window has a native root only now, so a toolbar edit composed before this could not
701    // reach it (docs/toolbars.md). Owe the windows a recompose: the bar goes out whole.
702    crate::toolbar::chrome_changed();
703    focus_revision().update(|n| *n += 1);
704    true
705}
706
707fn register(root: RNode, key: Option<&str>, kind: WindowKind, scope: Scope, tier: Tier) {
708    WINDOWS.with(|w| {
709        let mut windows = w.borrow_mut();
710        // A window that just opened is the key window; every platform orders it front. Seeding
711        // that here rather than waiting for `Event::WindowFocused` is what makes it true for the
712        // first one: the toolkit makes the window key while creating it, which on AppKit fires
713        // `windowDidBecomeKey` before `wire_window_events` has installed a handler to hear it.
714        // Without this, a window opened by File ▸ New Window is never marked focused, and
715        // `focused_scope` (how an app-wide menu command finds the front window's state,
716        // docs/state.md) resolves to the primary until the user clicks away and back.
717        for r in windows.iter_mut() {
718            r.focused = false;
719        }
720        let (state, reported) = state_rail(root, scope);
721        windows.push(WindowRecord {
722            root,
723            key: key.map(str::to_string),
724            kind,
725            role: WindowRole::from(kind),
726            scope,
727            content_scope: None,
728            tier,
729            focused: true,
730            on_close: Rc::default(),
731            close_request: None,
732            state,
733            reported,
734            remember: None,
735        });
736    });
737    focus_revision().update(|n| *n += 1);
738}
739
740/// Start remembering `root`'s frame under `key`, and put the window where it was last time
741/// (docs/windows.md "Remembered frames"). A saved position no attached display shows any more is
742/// dropped; the size is kept.
743fn remember_frame(root: RNode, key: &str) {
744    WINDOWS.with(|w| {
745        if let Some(r) = w.borrow_mut().iter_mut().find(|r| r.root == root) {
746            r.remember = Some(key.to_owned());
747        }
748    });
749    let Some(saved) = crate::frames::load(key) else {
750        return;
751    };
752    let areas: Vec<Rect> = monitors().iter().map(|m| m.work_area).collect();
753    let origin = crate::frames::on_screen(saved.frame, &areas).then_some(saved.frame.origin);
754    let handle = WindowHandle { root };
755    handle.set_frame(origin, Some(saved.frame.size));
756    if saved.maximized {
757        handle.set_state(WindowState::Maximized);
758    }
759}
760
761/// [`save_frame`] for a window already out of the registry (its state signal is still alive:
762/// the scope is disposed after this).
763fn save_frame_of_record(root: RNode, key: &str, state: WindowState) {
764    if matches!(state, WindowState::Minimized | WindowState::Fullscreen) {
765        return;
766    }
767    if let Some(frame) = remembered_frame(root) {
768        crate::frames::save(
769            key,
770            crate::frames::Remembered {
771                frame,
772                maximized: state == WindowState::Maximized,
773            },
774        );
775    }
776}
777
778/// Save the frame of every window that remembers one (window close, app quit).
779pub(crate) fn save_remembered_frames() {
780    let keyed: Vec<(RNode, String)> = WINDOWS
781        .try_with(|w| {
782            w.borrow()
783                .iter()
784                .filter(|r| matches!(r.tier, Tier::Native { .. }))
785                .filter_map(|r| r.remember.clone().map(|k| (r.root, k)))
786                .collect()
787        })
788        .unwrap_or_default();
789    for (root, key) in keyed {
790        save_frame(root, &key);
791    }
792}
793
794fn save_frame(root: RNode, key: &str) {
795    let handle = WindowHandle { root };
796    let state = handle.state().get_untracked();
797    // A minimized or fullscreen window's frame is not one to reopen at; keep the last normal
798    // one and only note the zoom.
799    if matches!(state, WindowState::Minimized | WindowState::Fullscreen) {
800        return;
801    }
802    if let Some(frame) = remembered_frame(root) {
803        crate::frames::save(
804            key,
805            crate::frames::Remembered {
806                frame,
807                maximized: state == WindowState::Maximized,
808            },
809        );
810    }
811}
812
813/// What a remembered frame records: the outer frame's position, and the size Day lays the
814/// content out at, which is the size `WindowChange::Frame` restores. Recording the outer size
815/// would grow the window by its title bar on every launch.
816fn remembered_frame(root: RNode) -> Option<Rect> {
817    let outer = with_tree(|t| t.native_window_frame(root))?;
818    let laid_out = with_tree(|t| t.node_frame(root)).map_or(outer.size, |f| f.size);
819    Some(Rect::new(
820        outer.origin.x,
821        outer.origin.y,
822        laid_out.width,
823        laid_out.height,
824    ))
825}
826
827/// The window's two-way state signal: an app write becomes a [`WindowChange::State`] request,
828/// a platform report (`Event::WindowStateChanged`, handled in `wire_window_events`) is written
829/// into the signal without being sent back. Owned by the window's scope, so it goes with the
830/// window.
831fn state_rail(root: RNode, scope: Scope) -> (Signal<WindowState>, Rc<Cell<WindowState>>) {
832    let reported: Rc<Cell<WindowState>> = Rc::default();
833    let state = scope.enter(|| {
834        let state = Signal::new(WindowState::Normal);
835        let rep = reported.clone();
836        day_reactive::bind_seeded(
837            WindowState::Normal,
838            move || state.get(),
839            move |s| {
840                if *s != rep.get() {
841                    WindowHandle { root }.apply(&WindowChange::State(*s));
842                }
843            },
844        );
845        state
846    });
847    (state, reported)
848}
849
850/// The per-window event rail (native + pending tiers): resize relayouts that window,
851/// focus updates the registry, close tears down, deferred one main-loop hop so the
852/// disposal never runs inside the platform's close callback (a released view inside
853/// `windowWillClose`/`close-request`/`closeEvent` is the top reentrancy hazard).
854fn wire_window_events(root: RNode) {
855    with_tree(|t| {
856        t.on_event(
857            root,
858            Rc::new(move |ev| match ev {
859                Event::WindowResized(size) => {
860                    let s = *size;
861                    with_tree(|t| t.set_root_size(root, s));
862                    // …and re-bucket this window (docs/size-classes.md). The primary's rail does
863                    // the same in `launch_with`; without it here a secondary window relayouts at
864                    // its new size but keeps the class it opened at, so dragging the second
865                    // window from narrow to wide never re-presented its navigation. Invisible
866                    // until a window could be resized at all, which on the phones it now can.
867                    crate::ambient::set_window_size_class(
868                        root,
869                        crate::ambient::resized_size_class(root, s),
870                    );
871                }
872                Event::WindowFocused(f) => {
873                    let f = *f;
874                    WINDOWS.with(|w| {
875                        for r in w.borrow_mut().iter_mut() {
876                            if r.root == root {
877                                r.focused = f;
878                            } else if f {
879                                r.focused = false;
880                            }
881                        }
882                    });
883                    focus_revision().update(|n| *n += 1);
884                }
885                Event::WindowClosed => {
886                    day_reactive::on_main(move || teardown(root));
887                }
888                Event::WindowStateChanged(s) => {
889                    let s = *s;
890                    let signal = WINDOWS.with(|w| {
891                        w.borrow().iter().find(|r| r.root == root).map(|r| {
892                            r.reported.set(s);
893                            r.state
894                        })
895                    });
896                    if let Some(signal) = signal {
897                        signal.set_if_changed(s);
898                    }
899                }
900                _ => {}
901            }),
902        );
903    });
904}
905
906/// How many non-closing primary windows keep the app alive (docs/windows.md close policy).
907/// This includes the initial window while it remains registered and open.
908#[must_use]
909pub fn primary_window_count() -> usize {
910    WINDOWS.with(|w| {
911        w.borrow()
912            .iter()
913            .filter(|r| r.role == WindowRole::Primary)
914            .count()
915    })
916}
917
918/// Whether any window is still holding the app open.
919fn app_has_primary_window() -> bool {
920    primary_window_count() > 0
921}
922
923/// Whether closing the last primary window ends the process on this platform.
924///
925/// macOS says no, and means it: an app with no windows stays running with its menu bar live,
926/// and ⌘N reopens one; `applicationShouldTerminateAfterLastWindowClosed` defaults to false
927/// for exactly this. Quitting there would be the framework overriding a platform convention
928/// its users rely on. Every other desktop treats the last window as the app.
929fn last_primary_close_quits() -> bool {
930    match crate::status::keep_running_policy() {
931        // A status item (Automatic) or the app's own choice keeps the process up.
932        _ if crate::status::keeps_running() => false,
933        crate::status::KeepRunning::Never => true,
934        _ => !cfg!(target_os = "macos"),
935    }
936}
937
938/// End the app now (docs/windows.md "Keeping the app running"): the Quit item of a status
939/// item's menu, a background helper's own decision. Every window is disposed and
940/// `Lifecycle::WillTerminate` delivered first, as when the last window closes.
941pub fn quit() {
942    let remaining: Vec<RNode> = WINDOWS.with(|w| w.borrow().iter().map(|r| r.root).collect());
943    for root in remaining {
944        teardown_quietly(root);
945    }
946    crate::lifecycle::dispatch_lifecycle(day_spec::Lifecycle::WillTerminate);
947    with_tree(|t| t.quit_app());
948}
949
950/// [`teardown`] without the "was that the last primary?" check: the caller is ending the app
951/// itself.
952fn teardown_quietly(root: RNode) {
953    QUITTING.with(|q| q.set(true));
954    teardown(root);
955    QUITTING.with(|q| q.set(false));
956}
957
958/// End the app because its last [`WindowRole::Primary`] window has closed.
959///
960/// One place, for every backend: dispose whatever is still open (a settings panel does not
961/// keep an app alive, however long it has been up), deliver `WillTerminate` once, and then
962/// ask the toolkit for the platform's exit.
963fn quit_after_last_primary() {
964    if !last_primary_close_quits() {
965        return;
966    }
967    // Secondary windows go with the app. Collected first: teardown mutates the registry.
968    let remaining: Vec<RNode> = WINDOWS.with(|w| w.borrow().iter().map(|r| r.root).collect());
969    for root in remaining {
970        teardown(root);
971    }
972    crate::lifecycle::dispatch_lifecycle(day_spec::Lifecycle::WillTerminate);
973    with_tree(|t| t.quit_app());
974}
975
976/// The single teardown path (any close route lands here). Idempotent via registry
977/// membership: registry-remove → scope dispose → content removal → root removal →
978/// `on_close` callbacks.
979fn teardown(root: RNode) {
980    let Some(record) = WINDOWS.with(|w| {
981        let mut windows = w.borrow_mut();
982        windows
983            .iter()
984            .position(|r| r.root == root)
985            .map(|i| windows.remove(i))
986    }) else {
987        return;
988    };
989    focus_revision().update(|n| *n += 1);
990    // The toolbar forgets the window FIRST: its contributions' cleanups run inside the
991    // dispose below and would otherwise re-compose a bar through gates whose signals the same
992    // dispose has already dropped (a contained panic that left the next New Window blank).
993    // The frame, while the native window still answers for it.
994    if let (Some(key), Tier::Native { .. }) = (&record.remember, &record.tier) {
995        save_frame_of_record(root, key, record.state.get_untracked());
996    }
997    crate::frame::forget_window(root);
998    crate::toolbar::forget_window(root);
999    record.scope.dispose();
1000    crate::ambient::forget_window(root);
1001    match record.tier {
1002        Tier::Native { .. } | Tier::PendingNative { .. } => {
1003            while let Some(c) = with_tree(|t| t.first_child(root)) {
1004                with_tree(|t| t.remove_subtree(c));
1005            }
1006            with_tree(|t| t.remove_window_root(root));
1007        }
1008        Tier::Cover { cover, .. } => {
1009            // The cover node lives under the primary root: drop its independent layout
1010            // entry, then the ordinary subtree removal takes its content with it.
1011            with_tree(|t| {
1012                t.drop_extra_layout_root(cover);
1013                t.remove_subtree(cover);
1014            });
1015        }
1016    }
1017    with_tree(|t| {
1018        t.mark_layout_dirty();
1019        t.layout_if_needed();
1020    });
1021    for f in record.on_close.borrow().iter() {
1022        f();
1023    }
1024    // The app's life is the life of its primary windows, not of the first one opened. Checked
1025    // after the callbacks so a handler that opens a replacement window is counted.
1026    if record.role == WindowRole::Primary
1027        && !app_has_primary_window()
1028        && !QUITTING.with(std::cell::Cell::get)
1029    {
1030        quit_after_last_primary();
1031    }
1032}
1033
1034/// Reverse a cover dismissal that has not yet been confirmed. Close is asynchronous on this
1035/// tier (the hide transition runs for a quarter second, and the record stays registered until
1036/// `CoverHidden` comes back), so a keyed window reopened inside that window is the same window
1037/// arriving again, not a second one. Without this the reopen returns a handle to content the
1038/// pending confirmation is about to dispose, and the surface the caller asked for goes blank
1039/// (docs/windows.md). Clearing `closing` is also what makes that confirmation a no-op when it
1040/// lands: the cover's handler already gates on it.
1041fn revive_if_dismissing(root: RNode) {
1042    let cover = WINDOWS.with(|w| {
1043        w.borrow()
1044            .iter()
1045            .find(|r| r.root == root)
1046            .and_then(|r| match &r.tier {
1047                Tier::Cover { cover, closing } if closing.get() => {
1048                    closing.set(false);
1049                    Some(*cover)
1050                }
1051                _ => None,
1052            })
1053    });
1054    let Some(cover) = cover else { return };
1055    with_tree(|t| {
1056        t.patch(
1057            cover,
1058            Box::new(CoverPatch::Present {
1059                background: None,
1060                dismiss_disabled: false,
1061            }),
1062            false,
1063        );
1064    });
1065}
1066
1067/// The fallback tier: present window content modally in the primary window. Preferences
1068/// prefer a sheet on regular-width windows and remain fullscreen on compact windows.
1069/// `NavBack` dismisses; `Event::CoverHidden` confirms (docs/cover.md).
1070fn open_as_cover(
1071    key: Option<&str>,
1072    kind: WindowKind,
1073    scope: Scope,
1074    build: Box<dyn FnOnce() -> AnyPiece>,
1075) -> WindowHandle {
1076    let size: Rc<RefCell<Option<Size>>> = Rc::default();
1077    let primary = with_tree(|t| t.root_node());
1078    // A settings or About panel is a sheet where there is room for one; content windows cover.
1079    let sheet = matches!(kind, WindowKind::Preferences | WindowKind::About)
1080        && crate::window_size_class_untracked(primary)
1081            .is_some_and(|size| size.width != day_spec::WidthClass::Compact);
1082    let composed_sheet =
1083        sheet && crate::capability(day_spec::Cap::CoverSheet) == day_spec::Support::Unsupported;
1084    let cover = {
1085        let mut cx = BuildCx::new(primary);
1086        cx.native(
1087            kinds::COVER,
1088            &CoverProps {
1089                sheet,
1090                ..Default::default()
1091            },
1092            Rc::new(crate::CoverLayout { size: size.clone() }),
1093            crate::Flex::default(),
1094            Boundary::Yes,
1095        )
1096    };
1097    with_tree(|t| t.add_extra_layout_root(cover, Size::new(0.0, 0.0)));
1098    let closing: Rc<Cell<bool>> = Rc::default();
1099    // The window root is the cover node on this tier: one id for close/teardown.
1100    register(
1101        cover,
1102        key,
1103        kind,
1104        scope,
1105        Tier::Cover {
1106            cover,
1107            closing: closing.clone(),
1108        },
1109    );
1110
1111    {
1112        let (size, closing) = (size.clone(), closing.clone());
1113        with_tree(|t| {
1114            t.on_event(
1115                cover,
1116                Rc::new(move |ev| match ev {
1117                    Event::FrameChanged(sz) => {
1118                        if *size.borrow() != Some(*sz) {
1119                            *size.borrow_mut() = Some(*sz);
1120                            with_tree(|t| {
1121                                t.set_root_size(cover, *sz);
1122                                t.mark_layout_dirty();
1123                                t.layout_if_needed();
1124                            });
1125                        }
1126                    }
1127                    // Native dismissal request (Android system back): a fallback "window"
1128                    // closes like a window, not like a page.
1129                    Event::NavBack { .. } => {
1130                        if !closing.get() {
1131                            closing.set(true);
1132                            with_tree(|t| t.patch(cover, Box::new(CoverPatch::Dismiss), false));
1133                        }
1134                    }
1135                    // The hide transition finished; now the content can go.
1136                    Event::CoverHidden if closing.get() => {
1137                        day_reactive::on_main(move || teardown(cover));
1138                    }
1139                    _ => {}
1140                }),
1141            );
1142        });
1143    }
1144
1145    scope.enter(|| {
1146        crate::toolbar::with_window(cover, || {
1147            let piece = build();
1148            let mut cx = BuildCx::new(cover);
1149            if composed_sheet {
1150                let _ = crate::ComposedSheet {
1151                    content: piece,
1152                    large: false,
1153                }
1154                .build(&mut cx);
1155            } else {
1156                let _ = piece.build(&mut cx);
1157            }
1158        });
1159    });
1160    with_tree(|t| {
1161        t.patch(
1162            cover,
1163            Box::new(CoverPatch::Present {
1164                background: composed_sheet.then_some(day_spec::Color::CLEAR),
1165                dismiss_disabled: false,
1166            }),
1167            false,
1168        );
1169        t.mark_needs_measure(cover);
1170        t.mark_layout_dirty();
1171        t.layout_if_needed();
1172    });
1173    focus_revision().update(|n| *n += 1);
1174    WindowHandle { root: cover }
1175}
1176
1177// ---------------------------------------------------------------------------
1178// Preferences + New Window registration (docs/windows.md)
1179// ---------------------------------------------------------------------------
1180
1181/// The registered preferences piece: its builder plus the window options it opens with.
1182type PrefsRegistration = (Rc<dyn Fn() -> AnyPiece>, WindowOptions);
1183
1184/// The singleton key every preferences window opens under.
1185pub const PREFERENCES_KEY: &str = "day.preferences";
1186
1187/// Declare the app's preferences piece (docs/windows.md): once, in `root()`, ideally
1188/// before `app_menu`. Enables the desktop Preferences window (singleton, primary+`,`),
1189/// the auto Settings…/Preferences menu item, and [`open_preferences`] everywhere (cover
1190/// fallback where the toolkit cannot open windows). The window titles itself with
1191/// `options.title`; use [`register_preferences_with`] to localize it or change the size.
1192pub fn register_preferences<P: Piece>(build: impl Fn() -> P + 'static) {
1193    register_preferences_with(
1194        WindowOptions {
1195            title: day_localization::t(day_localization::key::day_settings),
1196            version: None,
1197            // The width a settings panel wants, and a ceiling for the height rather than the
1198            // height itself: `size_to_fit` shrinks the window to whatever the rows actually
1199            // measure. A fixed 640 either clips the last row or leaves a band of empty panel
1200            // under it, and which one depends on the user's text size, so nobody can pick a
1201            // number that is right for everyone.
1202            size: Size::new(520.0, 640.0),
1203            min_size: None,
1204            size_to_fit: true,
1205            app_name: None,
1206            // Secondary windows: the app-launch ceremony belongs to `launch` alone.
1207            locales: None,
1208            title_fn: None,
1209            // A settings panel never becomes a tab; `WindowKind::Preferences` says so already.
1210            tabbing: WindowTabbing::Automatic,
1211            ..WindowOptions::default()
1212        },
1213        build,
1214    );
1215}
1216
1217/// [`register_preferences`] with explicit window options (localized title, size).
1218pub fn register_preferences_with<P: Piece>(
1219    options: WindowOptions,
1220    build: impl Fn() -> P + 'static,
1221) {
1222    PREFS.with(|p| *p.borrow_mut() = Some((Rc::new(move || AnyPiece::new(build())), options)));
1223    if PREFS_ACTION.with(std::cell::Cell::get) == 0 {
1224        PREFS_ACTION.with(|c| {
1225            c.set(crate::menu::register_menu_action(Rc::new(|| {
1226                open_preferences();
1227            })));
1228        });
1229    }
1230    // Self-heal for registration after `app_menu`: re-forward the retained model so the
1231    // injection pass sees the now-registered action.
1232    crate::menu::reinstall_app_menu();
1233}
1234
1235/// Open-or-focus the preferences surface (docs/windows.md): a `WindowKind::Preferences`
1236/// singleton window on desktop, the cover fallback elsewhere: one call for menu items and
1237/// toolbar gears alike. `false` = no preferences piece is registered (logged).
1238pub fn open_preferences() -> bool {
1239    let Some((build, options)) = PREFS.with(|p| p.borrow().clone()) else {
1240        log::warn!("open_preferences without register_preferences — ignored");
1241        return false;
1242    };
1243    open_window(
1244        options.key(PREFERENCES_KEY).kind(WindowKind::Preferences),
1245        move || build(),
1246    );
1247    true
1248}
1249
1250// ---------------------------------------------------------------------------
1251// About + Check for Updates registration (docs/settings.md)
1252// ---------------------------------------------------------------------------
1253
1254/// The singleton key the About window opens under.
1255pub const ABOUT_KEY: &str = "day.about";
1256
1257/// Declare what the app's About command does (docs/settings.md): once, in `root()`. Enables
1258/// the About menu item everywhere a desktop has one (the macOS App menu, Help elsewhere; both
1259/// the default menu and an installed `app_menu`) and [`open_about`]. The action is the whole
1260/// contract, so a toolkit-native About dialog (libadwaita's) and a Day window
1261/// ([`register_about_window`]) register the same way.
1262pub fn register_about(open: impl Fn() + 'static) {
1263    ABOUT.with(|a| *a.borrow_mut() = Some(Rc::new(open)));
1264    if ABOUT_ACTION.with(std::cell::Cell::get) == 0 {
1265        ABOUT_ACTION.with(|c| {
1266            c.set(crate::menu::register_menu_action(Rc::new(|| {
1267                open_about();
1268            })));
1269        });
1270    }
1271    crate::menu::reinstall_app_menu();
1272}
1273
1274/// [`register_about`] with a Day-rendered About window: opened under the singleton key
1275/// [`ABOUT_KEY`] as a `WindowKind::About` panel (fixed, centered, out of the Window menu),
1276/// the cover fallback where the toolkit cannot open windows. The window titles itself with
1277/// `options.title`.
1278pub fn register_about_window<P: Piece>(options: WindowOptions, build: impl Fn() -> P + 'static) {
1279    let build: Rc<dyn Fn() -> AnyPiece> = Rc::new(move || AnyPiece::new(build()));
1280    register_about(move || {
1281        let build = build.clone();
1282        open_window(
1283            options.clone().key(ABOUT_KEY).kind(WindowKind::About),
1284            move || build(),
1285        );
1286    });
1287}
1288
1289/// Run the registered About action (docs/settings.md): the menu item's dispatch, and what a
1290/// toolbar button or a settings row calls. `false` = nothing registered (logged).
1291pub fn open_about() -> bool {
1292    let Some(open) = ABOUT.with(|a| a.borrow().clone()) else {
1293        log::warn!("open_about without register_about — ignored");
1294        return false;
1295    };
1296    open();
1297    true
1298}
1299
1300/// The dispatch id of the About menu action (0 = unregistered). Backends wire their stock
1301/// About item to it; `MenuRole::About` lowering and the injection pass use it.
1302#[must_use]
1303pub fn about_action_id() -> u64 {
1304    ABOUT_ACTION.with(std::cell::Cell::get)
1305}
1306
1307/// Declare the updater's Check for Updates… command (docs/settings.md): the item appears
1308/// under About in the macOS App menu and in Help elsewhere, and `MenuRole::CheckForUpdates`
1309/// items lower to it. Registered by an update provider, not by the app.
1310pub fn register_check_for_updates(check: impl Fn() + 'static) {
1311    UPDATES.with(|u| *u.borrow_mut() = Some(Rc::new(check)));
1312    if UPDATES_ACTION.with(std::cell::Cell::get) == 0 {
1313        UPDATES_ACTION.with(|c| {
1314            c.set(crate::menu::register_menu_action(Rc::new(|| {
1315                check_for_updates();
1316            })));
1317        });
1318    }
1319    crate::menu::reinstall_app_menu();
1320}
1321
1322/// Run the registered Check for Updates… command. `false` = none registered.
1323pub fn check_for_updates() -> bool {
1324    let Some(check) = UPDATES.with(|u| u.borrow().clone()) else {
1325        return false;
1326    };
1327    check();
1328    true
1329}
1330
1331/// The dispatch id of the Check for Updates… action (0 = unregistered).
1332#[must_use]
1333pub fn check_for_updates_action_id() -> u64 {
1334    UPDATES_ACTION.with(std::cell::Cell::get)
1335}
1336
1337/// Register the builder behind File ▸ New Window and the macOS tab-bar "+" (docs/windows.md):
1338/// each call opens another `WindowKind::Normal` window. A `menu_role(MenuRole::NewWindow)`
1339/// item lowers to this action; without a registration it lowers disabled.
1340pub fn register_new_window<P: Piece>(build: impl Fn() -> P + 'static) {
1341    NEW_WINDOW.with(|p| *p.borrow_mut() = Some(Rc::new(move || AnyPiece::new(build()))));
1342    if NEW_WINDOW_ACTION.with(std::cell::Cell::get) == 0 {
1343        NEW_WINDOW_ACTION.with(|c| {
1344            c.set(crate::menu::register_menu_action(Rc::new(|| {
1345                open_new_window();
1346            })));
1347        });
1348    }
1349    crate::menu::reinstall_app_menu();
1350}
1351
1352/// Open a window through the registered new-window builder (the `newWindowForTab:` /
1353/// File ▸ New Window path). `None` = no builder registered.
1354pub fn open_new_window() -> Option<WindowHandle> {
1355    let build = NEW_WINDOW.with(|p| p.borrow().clone())?;
1356    // Another window of this app, so it describes itself the way the app described its first
1357    // one: same title, same minimum size, same display name. A window with no title is missing
1358    // from the macOS Window menu and shows a blank tab, so inheriting is what makes File ▸ New
1359    // Window produce something the platform can manage (docs/windows.md). Content that wants a
1360    // title of its own says so with `window_title` from inside the window.
1361    let launch = LAUNCH_OPTIONS.with(|o| o.borrow().clone());
1362    // Size mirrors the primary's current content size so a "duplicate window" lands familiar.
1363    let size = with_tree(|t| {
1364        let root = t.root_node();
1365        t.node_frame(root).map(|f| f.size)
1366    })
1367    .unwrap_or(Size::new(800.0, 600.0));
1368    Some(open_window(
1369        WindowOptions {
1370            title: launch.as_ref().map_or_default(|o| o.title.clone()),
1371            size,
1372            min_size: launch.as_ref().and_then(|o| o.min_size),
1373            size_to_fit: false,
1374            app_name: launch.as_ref().and_then(|o| o.app_name.clone()),
1375            version: launch.as_ref().and_then(|o| o.version.clone()),
1376            // Secondary windows: the app-launch ceremony belongs to `launch` alone.
1377            locales: None,
1378            // Already resolved into `title` above; calling it again would re-run app code
1379            // outside the launch sequence it was written for.
1380            title_fn: None,
1381            tabbing: WindowTabbing::Automatic,
1382            ..WindowOptions::default()
1383        },
1384        move || build(),
1385    ))
1386}
1387
1388/// Register the builder behind the macOS tab bar's "+" for windows whose
1389/// [`WindowOptions::tabbing`] names `group` (docs/windows.md): each call opens another window of
1390/// that group, as a tab of the window the user clicked "+" in. Groups without a registration
1391/// fall back to [`register_new_window`]'s builder.
1392pub fn register_new_window_for<P: Piece>(group: &str, build: impl Fn() -> P + 'static) {
1393    let build: Rc<dyn Fn() -> AnyPiece> = Rc::new(move || AnyPiece::new(build()));
1394    GROUP_WINDOWS.with(|g| {
1395        let mut groups = g.borrow_mut();
1396        groups.retain(|(name, _)| name != group);
1397        groups.push((group.to_string(), build));
1398    });
1399}
1400
1401/// Open another window of tab group `group` (the backend's `newWindowForTab:` path for a window
1402/// whose tabbing names a group). Uses the group's registered builder, else the app's New Window
1403/// builder; `None` when neither exists.
1404pub fn open_new_window_for_group(group: &str) -> Option<WindowHandle> {
1405    let action = TAB_NEW.with(|g| {
1406        g.borrow()
1407            .iter()
1408            .find(|(name, _)| name == group)
1409            .map(|(_, f)| f.clone())
1410    });
1411    if action.is_some() {
1412        let group = group.to_string();
1413        day_reactive::on_main(move || {
1414            let action = TAB_NEW.with(|g| {
1415                g.borrow()
1416                    .iter()
1417                    .find(|(name, _)| name == &group)
1418                    .map(|(_, f)| f.clone())
1419            });
1420            if let Some(f) = action {
1421                f();
1422            }
1423        });
1424        return None;
1425    }
1426
1427    let Some(build) = GROUP_WINDOWS.with(|g| {
1428        g.borrow()
1429            .iter()
1430            .find(|(name, _)| name == group)
1431            .map(|(_, b)| b.clone())
1432    }) else {
1433        return open_new_window();
1434    };
1435    let launch = LAUNCH_OPTIONS.with(|o| o.borrow().clone());
1436    let size = with_tree(|t| {
1437        let root = t.root_node();
1438        t.node_frame(root).map(|f| f.size)
1439    })
1440    .unwrap_or(Size::new(800.0, 600.0));
1441    Some(open_window(
1442        WindowOptions {
1443            title: launch.as_ref().map_or_default(|o| o.title.clone()),
1444            size,
1445            min_size: launch.as_ref().and_then(|o| o.min_size),
1446            app_name: launch.as_ref().and_then(|o| o.app_name.clone()),
1447            version: launch.as_ref().and_then(|o| o.version.clone()),
1448            tabbing: WindowTabbing::Group(group.to_string()),
1449            ..WindowOptions::default()
1450        },
1451        move || build(),
1452    ))
1453}
1454
1455/// The window the caller belongs to (docs/windows.md): the one whose content is being built
1456/// right now, else the focused window, else the app's first window. What a piece uses to change
1457/// "its" window (`current_window()?.set_content_protected(true)`) without threading a handle
1458/// through. `None` before boot.
1459pub fn current_window() -> Option<WindowHandle> {
1460    let building = crate::toolbar::window_being_built();
1461    let known = WINDOWS.with(|w| w.borrow().iter().any(|r| r.root == building));
1462    if known {
1463        return Some(WindowHandle { root: building });
1464    }
1465    focused_window().or_else(initial_window)
1466}
1467
1468/// Bind the title of the window this piece is building into to a reactive closure
1469/// (docs/windows.md). This is how a window comes to be named after what it shows.
1470///
1471/// The window-level counterpart to a navigation title. It matters more than it looks: the macOS
1472/// Window menu, the tab bar, Mission Control, the iPad app switcher and the Android recents card
1473/// all label a window by its title, so two windows that share one title are two windows the user
1474/// cannot tell apart anywhere the system lists them.
1475///
1476/// ```ignore
1477/// // inside a window's shell, so each window titles itself:
1478/// day::window_title(move || match scene.selected.get() {
1479///     Some(id) => scene.name_of(id),
1480///     None => app_title(),
1481/// });
1482/// ```
1483///
1484/// Reactive like any binding: the title follows what the closure reads. Which window it targets
1485/// is resolved once, here, for the same reason `toolbar_reactive` captures it: the binding
1486/// re-runs long after this build, when "the window being built" is no longer this one.
1487pub fn window_title(f: impl Fn() -> String + 'static) {
1488    let root = crate::toolbar::window_being_built();
1489    day_reactive::bind(f, move |title| {
1490        let title = crate::decorate_window_title(title);
1491        with_tree(|t| t.set_native_window_title(root, &title));
1492    });
1493}
1494
1495/// The dispatch id of the auto Preferences menu action (0 = unregistered). Backends use it
1496/// to wire their default-menu Settings item; the injection pass uses it for `app_menu`.
1497#[must_use]
1498pub fn preferences_action_id() -> u64 {
1499    PREFS_ACTION.with(std::cell::Cell::get)
1500}
1501
1502/// The dispatch id of the New Window action (0 = unregistered), used by `MenuRole::NewWindow`
1503/// lowering and the backends' tab-bar "+" wiring.
1504#[must_use]
1505pub fn new_window_action_id() -> u64 {
1506    NEW_WINDOW_ACTION.with(std::cell::Cell::get)
1507}
1508
1509/// Test/diagnostic surface: the number of open secondary windows.
1510#[must_use]
1511pub fn open_window_count() -> usize {
1512    WINDOWS.with(|w| w.borrow().len())
1513}
1514
1515/// The `WindowKind` of the open window at `root`, for backends and tests.
1516#[must_use]
1517pub fn window_kind_of(handle: &WindowHandle) -> Option<WindowKind> {
1518    WINDOWS.with(|w| {
1519        w.borrow()
1520            .iter()
1521            .find(|r| r.root == handle.root)
1522            .map(|r| r.kind)
1523    })
1524}
1525
1526/// Reset the registry + registrations (tests; pairs with `uninstall_tree`).
1527pub fn reset_windows() {
1528    // Does not dispose each record's content scope, which is a change that was
1529    // made and then reverted after it broke navigation (docs/settings.md "Appearance on Android").
1530    //
1531    // Disposing looks right: the reactive graph a window built otherwise outlives it, and on an
1532    // Android re-mount that showed up as the previous window's navigation host re-registering
1533    // over the new one's ("two routed one-of-N surfaces … at the same navigation level"). But
1534    // the disposal cascade runs app cleanup that reads signals the same cascade has already
1535    // disposed; the panic is contained, the disposal stops half-way, and the rebuild that
1536    // follows registers no routes at all. The symptom is an app whose tab bar draws and whose
1537    // tabs do nothing.
1538    //
1539    // Leaking the old graph is the lesser fault: it warns, and the app works. Disposing safely
1540    // needs the cascade to tear down in dependency order, which is its own piece of work.
1541    WINDOWS.with(|w| w.borrow_mut().clear());
1542    INITIAL_WINDOW.with(|c| c.set(None));
1543    crate::toolbar::reset_toolbars();
1544    PREFS.with(|p| *p.borrow_mut() = None);
1545    ABOUT.with(|a| *a.borrow_mut() = None);
1546    UPDATES.with(|u| *u.borrow_mut() = None);
1547    NEW_WINDOW.with(|p| *p.borrow_mut() = None);
1548    GROUP_WINDOWS.with(|g| g.borrow_mut().clear());
1549    // Action ids stay registered (the closures are inert without a builder); that is cheap, and
1550    // re-registration reuses them.
1551}
1552
1553/// Adopt the app's first window into the registry, so it is an ordinary primary window rather
1554/// than a privileged one (docs/windows.md close policy).
1555///
1556/// Called once at boot with the root container the backend handed back. `scope` owns the root
1557/// content, so closing this window disposes exactly its tree and nothing else, which is
1558/// why the caller builds that content in a child of the root scope rather than in the root
1559/// scope itself. State an app wants to outlive its windows still does: `Signal::global` lives
1560/// on the root scope, above this one.
1561pub fn adopt_initial_window(root: RNode, scope: Scope) {
1562    register(
1563        root,
1564        None,
1565        WindowKind::Normal,
1566        scope,
1567        Tier::Native {
1568            closing: Cell::new(false),
1569        },
1570    );
1571    wire_window_events(root);
1572    INITIAL_WINDOW.with(|c| c.set(Some(root)));
1573    let key = LAUNCH_OPTIONS.with(|o| o.borrow().as_ref().and_then(|o| o.remember_frame.clone()));
1574    if let Some(key) = key {
1575        remember_frame(root, &key);
1576    }
1577}
1578
1579/// The displays attached now (docs/windows.md "Monitors"). A toolkit that cannot list them
1580/// (`Cap::Monitors` unsupported) answers with one display the size of the primary window, so a
1581/// placement computed from the answer stays on screen.
1582#[must_use]
1583pub fn monitors() -> Vec<day_spec::Monitor> {
1584    let listed = with_tree(|t| t.monitors());
1585    if !listed.is_empty() {
1586        return listed;
1587    }
1588    let size = with_tree(|t| {
1589        let root = t.root_node();
1590        t.node_frame(root).map(|f| f.size)
1591    })
1592    .unwrap_or(Size::new(0.0, 0.0));
1593    let frame = Rect::new(0.0, 0.0, size.width, size.height);
1594    vec![day_spec::Monitor {
1595        id: "0".into(),
1596        name: String::new(),
1597        frame,
1598        work_area: frame,
1599        scale: 1.0,
1600        primary: true,
1601    }]
1602}
1603
1604/// A handle to the app's first window, once adopted. `None` before boot completes, and after
1605/// that window closes; it is an ordinary window and can be closed like any other.
1606#[must_use]
1607pub fn initial_window() -> Option<WindowHandle> {
1608    let root = INITIAL_WINDOW.with(std::cell::Cell::get)?;
1609    WINDOWS.with(|w| {
1610        w.borrow()
1611            .iter()
1612            .any(|r| r.root == root)
1613            .then_some(WindowHandle { root })
1614    })
1615}
1616
1617/// The window root's spec-boundary id (backends key their per-window maps by it).
1618#[must_use]
1619pub fn window_node_id(handle: &WindowHandle) -> NodeId {
1620    rnode_to_id(handle.root)
1621}
1622
1623/// Whether this backend can group actual OS windows as tabs.
1624#[must_use]
1625pub fn native_window_tabs() -> bool {
1626    with_tree(|t| t.native_window_tabs())
1627}
1628
1629/// Explicit grouping, independent of the user's automatic-tabbing preference.
1630pub fn group_windows(windows: &[WindowHandle]) {
1631    with_tree(|t| t.group_windows(&windows.iter().map(|w| w.root).collect::<Vec<_>>()));
1632}
1633
1634/// Native close delegate hook. Queue document code outside the toolkit callback.
1635/// Returns false when the owner will decide whether to close.
1636#[must_use]
1637pub fn native_close_requested(id: NodeId) -> bool {
1638    let handler = WINDOWS.with(|w| {
1639        w.borrow()
1640            .iter()
1641            .find(|r| r.root == id_to_rnode(id))
1642            .and_then(|r| r.close_request.clone())
1643    });
1644    if handler.is_some() {
1645        day_reactive::on_main(move || {
1646            let handler = WINDOWS.with(|w| {
1647                w.borrow()
1648                    .iter()
1649                    .find(|r| r.root == id_to_rnode(id))
1650                    .and_then(|r| r.close_request.clone())
1651            });
1652            if let Some(f) = handler {
1653                f();
1654            }
1655        });
1656        false
1657    } else {
1658        true
1659    }
1660}
1661
1662/// Route the native group add button to a document collection rather than a window builder.
1663/// Registration belongs to the current scope.
1664pub fn register_tab_new(group: String, action: Rc<dyn Fn()>) {
1665    TAB_NEW.with(|g| g.borrow_mut().push((group.clone(), action)));
1666    Scope::current()
1667        .on_cleanup(move || TAB_NEW.with(|g| g.borrow_mut().retain(|(name, _)| *name != group)));
1668}