Skip to main content

ferrokit/
lib.rs

1//! A native macOS GUI framework for Rust: every view is a real AppKit control
2//! (`NSTableView`, `NSOutlineView`, `NSTextView`…), built once and updated in
3//! place by fine-grained signals. No virtual DOM, no diffing, no web view.
4//!
5//! ```no_run
6//! use ferrokit::*;
7//!
8//! let count = Signal::new(0);
9//! App::new("Counter")
10//!     .window(Window::new("Counter").size(320.0, 140.0).view(
11//!         vstack((
12//!             text(move || format!("Clicked {} times", count.get())),
13//!             button("Click me", move || count.update(|n| *n += 1)),
14//!         ))
15//!         .padding(20.0),
16//!     ))
17//!     .run();
18//! ```
19//!
20//! - **State:** [`Signal`] and [`Memo`] (`Copy` handles, freed with the
21//!   window, row or document that made them), [`Effect`], [`batch`],
22//!   [`spawn`] and [`Resource`] for background work and loading,
23//!   [`stored`] for settings that persist.
24//! - **Views and layout:** [`vstack`], [`hstack`], [`grid`], [`spacer`],
25//!   [`scroll`], [`for_each`] (keyed lists), [`dynamic`], and the
26//!   [`ViewExt`] modifiers (padding, sizes, context menus, accessibility
27//!   labels), and [`ViewExt::on_command`] for menu [`Command`]s that act
28//!   on the focus.
29//! - **Controls:** [`text_field`], [`toggle`], [`checkbox`], [`picker`],
30//!   [`slider`], [`stepper`], [`progress`], [`image`], [`button`].
31//! - **Deep widgets:** [`table`] (millions of rows, sorting, editing, drag
32//!   and drop), [`outline`] and [`sidebar`], [`text_editor`].
33//! - **App shell:** menus ([`App::menu`]), toolbars, [`split`] views and
34//!   [`Window::sidebar`]/[`Window::inspector`], [`sheet`]s, [`alert`]s,
35//!   popovers ([`ViewExt::popover`]), open and save panels, document apps, a Settings window,
36//!   window restoration, undo ([`undoable`]), [`on_frame`] for live data.
37//! - **Forms and more controls:** [`form`], [`date_picker`], [`tabs`],
38//!   [`gauge`], token fields, path controls, ratings.
39//! - **Look:** text styles, cards and shadows ([`ViewExt::font`],
40//!   [`ViewExt::background`], [`ViewExt::corner_radius`],
41//!   [`ViewExt::shadow`]), materials and Liquid Glass ([`ViewExt::material`],
42//!   [`ViewExt::glass`]), motion ([`animated`], [`ViewExt::transition`],
43//!   [`ViewExt::on_hover`]).
44//! - **Charts and drawing:** [`bar_chart`], [`line_chart`], [`area_chart`],
45//!   [`scatter_chart`], [`pie_chart`], and a [`canvas`].
46//! - **Web, PDF, video and services:** [`web_view`], [`pdf_view`],
47//!   [`video_player`], [`share_button`], [`print`](fn@print), [`notify`].
48//! - **Testing:** [`testing`] (self-checks, real input, accessibility
49//!   audits, window captures, soaks).
50//!
51//! **Start with the [guide], 15 chapters whose examples are compiled as doc
52//! tests.** `API.md`, in the crate's source and
53//! [on GitHub](https://github.com/lhassa8/ferrokit/blob/main/crates/ferrokit/API.md),
54//! lists every public item on one page. macOS 15 or later. Main thread only.
55//!
56//! **AI coding agents:** read `AGENTS.md` first, in the crate's source
57//! beside `API.md` and
58//! [on GitHub](https://github.com/lhassa8/ferrokit/blob/main/crates/ferrokit/AGENTS.md):
59//! how a Ferrokit app is written, recipes that compile, and the known
60//! limits. `cargo ferrokit agents` writes it into an app.
61
62#![warn(missing_docs)]
63#![doc(html_logo_url = "https://raw.githubusercontent.com/lhassa8/ferrokit/main/assets/icon.png", html_favicon_url = "https://raw.githubusercontent.com/lhassa8/ferrokit/main/assets/icon-128.png")]
64
65mod appkit_views;
66mod canvas;
67mod charts;
68mod chrome;
69mod collection;
70mod commands;
71mod controls;
72mod dialogs;
73mod documents;
74mod frame;
75mod l10n;
76mod layout;
77mod material;
78mod browser;
79mod crash;
80mod failure;
81mod filter;
82mod form;
83mod media;
84mod quicklook;
85mod services;
86mod status;
87mod motion;
88mod native;
89mod related;
90mod widgets;
91mod interact;
92mod menu;
93mod models;
94mod outline;
95mod platform;
96mod popover;
97mod resource;
98mod signal;
99mod store;
100mod style;
101mod surface;
102mod syntax;
103mod task;
104mod transfer;
105mod undo;
106pub mod updates;
107mod value;
108pub mod testing;
109mod view;
110mod window_ref;
111
112use ferrokit_core::kept::{UiCell, UiLocal};
113use std::any::Any;
114use std::cell::{Cell, RefCell};
115use std::collections::HashMap;
116use std::rc::Rc;
117
118use objc2::runtime::ProtocolObject;
119use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send};
120use objc2_app_kit::{
121    NSApplication, NSApplicationActivationPolicy, NSBackingStoreType, NSResponder, NSView, NSWindowStyleMask,
122};
123use objc2_foundation::NSObject;
124
125use platform::{Native, Platform};
126use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};
127
128pub use ferrokit_core::{is_dark, system_colors};
129pub use frame::{FrameLoop, on_frame};
130pub use store::{Stored, read_stored, remove_stored, stored, write_stored};
131pub use undo::{set_undoable, undoable, undoable_in};
132pub use commands::{Command, can_perform, can_perform_in, focused_value, focused_value_in, focused_window, menu_command, perform, perform_in, toolbar_command};
133pub use resource::{Cancel, Load, Resource};
134pub use task::{Answer, Background, Sleep, Task, background, sleep, spawn_local};
135#[cfg(feature = "tokio")]
136pub use task::{OnRuntime, on_runtime};
137pub use signal::{Effect, Memo, Signal, after_batch, batch, untrack};
138pub use controls::{
139    ColorWell, ComboBox, DatePicker, SearchField, Segmented, TimePicker, color_well, combo_box, combo_box_with, date_picker, search_field, segmented, segmented_with, time_picker,
140    Checkbox, Image, Picker, Progress, Slider, Stepper, SymbolEffect, TextField, checkbox, image, image_data, image_file, picker, progress, secure_field, slider,
141    stepper, text_field, toggle,
142};
143pub use chrome::{MenuItem, Modifier, Split, customize_toolbar_item, dynamic_submenu, format_menu, submenu, ToolbarItem, menu_item, menu_separator, split, toolbar_button, toolbar_fixed_space, toolbar_group, toolbar_picker, toolbar_search, toolbar_space};
144pub use dialogs::{Alert, OpenOptions, Reply, SheetHandle, alert, alert_async, open_panel, open_panel_async, save_panel, save_panel_async, sheet, sheet_async, sheet_with};
145pub use documents::{
146    Document, DocumentType, choose_documents, document_edited, new_document, open_document, recent_documents, regain_access, set_recent_documents, remember_access, revert_document, save_document, save_document_as, show_welcome, welcome_window,
147};
148pub use models::{Table, TextEditor, table, text_editor};
149pub use outline::{Outline, TreeNode, outline, sidebar};
150pub use collection::{Collection, CollectionItem, ItemImage, collection};
151pub use ferrokit_core::table::{CellImage, CellStyle, Column, ColumnState, Sort, TableKey, TableModel};
152pub use ferrokit_core::text::{Color, Completion, TextModel, TextStyle};
153pub use syntax::Syntax;
154pub use style::{Font, Weight};
155pub use surface::Shadow;
156pub use material::{Glass, Material, has_liquid_glass};
157pub use widgets::{Gauge, Link, PathControl, RadioGroup, TabStyle, Tabs, TokenField, gauge, link, path_control, radio_group, rating, tabs, token_field};
158pub use media::{PdfView, VideoControls, VideoPlayer, WebPage, WebView, pdf_view, pdf_view_data, video_player, video_stream, web_view};
159pub use browser::{ColumnBrowser, column_browser};
160pub use crash::CrashReport;
161pub use updates::UpdateEvent;
162pub use failure::Failure;
163pub use filter::{FieldKind, FieldValue, Filter, FilterEditor, FilterField, FilterRule, FilterTest, Match, filter_editor};
164pub use form::{Form, FormRow, FormStyle, Section, disclosure, form, form_content, form_row, group_box, section};
165pub use quicklook::{Thumbnail, close_quick_look, is_quick_look_open, quick_look, thumbnail};
166pub use services::{FULL_DISK_ACCESS_SETTINGS, FileDates, Notification, SentNotification, ShareButton, ShareItem, asks_before_reading, cancel_notification, file_dates, has_full_disk_access, move_to_trash, notifications_supported, notify, open_url, pdf_data, print, reveal_in_finder, save_pdf, share_button};
167pub use status::MenuBarExtra;
168pub use motion::{Animation, Keyframes, Transition, animate, animated, animated_with, keyframes, reduce_motion, stop_animation};
169pub use popover::{Edge, toolbar_popover};
170pub use canvas::{Canvas, CanvasDrag, Painter, canvas};
171pub use native::{NativeView, native};
172pub use related::{RelatedFiles, related_files};
173pub use value::{IntoValue, Value};
174pub use transfer::{Clipboard, DragItem, WriteFile};
175pub use l10n::{format_date, format_number, format_number_for, local_day, local_day_start, today, weekday, language, parse_strings, plural_category, set_language, t, t_plural, t_with};
176pub use charts::{Chart, Format, Rule, Series, area_chart, bar_chart, heatmap, histogram, line_chart, pie_chart, scatter_chart, sparkline, stacked_bar_chart};
177pub use window_ref::WindowRef;
178/// The owning pointer to an AppKit object (what the escape hatches, such as
179/// [`WindowRef::ns`]'s callers and `testing`'s view lookups, hold).
180pub use objc2::rc::Retained;
181use objc2_app_kit::NSWindow;
182pub use view::{
183    Align, AnyView, Axis, Cx, Dynamic, ForEach, Grid, Identifiable, Modified, Node, Size, Spacer, Stack, View, ViewExt, Views,
184    dynamic, for_each, grid, hstack, zstack, Layers, spacer, vstack, watch, Watch,
185};
186#[allow(deprecated)]
187pub use appkit_views::{Button, ButtonStyle, ControlSize, Divider, HelpButton, MenuButton, Scroll, Text, button, divider, help_button, menu_button, scroll, text};
188
189fn mtm() -> MainThreadMarker {
190    MainThreadMarker::new().expect("ferrokit must be used on the main thread")
191}
192
193/// A window to open when the app starts.
194pub struct Window {
195    title: String,
196    size: (f64, f64),
197    content: Option<Box<dyn FnOnce() -> Retained<NSView>>>,
198    view: Option<AnyView>,
199    toolbar: Vec<ToolbarItem>,
200    customizable_toolbar: Option<String>,
201    autosave: Option<String>,
202    fixed: bool,
203    responds: commands::Responds,
204    drops: Option<FileDrop>,
205    chrome: WindowChrome,
206    panel: Option<PanelStyle>,
207    tabbing: Option<(Tabbing, Option<String>)>,
208    full_screen: bool,
209    /// The sidebar and inspector shell's panes, and their hidden signals.
210    sidebar: Option<(AnyView, Option<Signal<bool>>)>,
211    inspector: Option<(AnyView, Option<Signal<bool>>)>,
212}
213
214/// Whether a window opens as a tab of its app's other windows
215/// ([`Window::tabbing`]).
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217#[non_exhaustive]
218pub enum Tabbing {
219    /// As the user set in System Settings ▸ Desktop & Dock ("Prefer tabs").
220    Automatic,
221    /// Always as a tab, as Safari's and the Finder's windows do.
222    Preferred,
223    /// Never as a tab, and no tab bar (a settings window, a viewer).
224    Disallowed,
225}
226
227/// A panel's kind ([`Window::panel`]): a secondary window serving the main
228/// ones, which hides while the app is in the background.
229#[derive(Debug, Clone, Copy, PartialEq, Eq)]
230#[non_exhaustive]
231pub enum PanelStyle {
232    /// Stays above the app's other windows: an inspector, a palette, a
233    /// find panel. It becomes key only when a field in it is clicked, so
234    /// the main window keeps the keyboard.
235    Floating,
236    /// As `Floating`, with a slimmer title bar: tool palettes.
237    Utility,
238    /// A dark, translucent heads-up panel over media or a canvas.
239    Hud,
240}
241
242/// How a window's title bar and toolbar look.
243#[derive(Default)]
244struct WindowChrome {
245    toolbar_style: Option<ToolbarStyle>,
246    hide_title: bool,
247    transparent_title_bar: bool,
248    full_size_content: bool,
249    background: Option<Color>,
250}
251
252/// How a window's toolbar sits with its title (see [`Window::toolbar_style`]).
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254#[non_exhaustive]
255pub enum ToolbarStyle {
256    /// The title and toolbar items in one bar (the default).
257    Unified,
258    /// One bar, shorter: for windows with few toolbar items.
259    UnifiedCompact,
260    /// The title above the toolbar, items labelled (as in Settings windows).
261    /// The other styles show symbols alone.
262    Expanded,
263    /// The title above the toolbar, items centred (Settings' tabs).
264    Preference,
265}
266
267impl ToolbarStyle {
268    fn ns(self) -> objc2_app_kit::NSWindowToolbarStyle {
269        use objc2_app_kit::NSWindowToolbarStyle as S;
270        match self {
271            ToolbarStyle::Unified => S::Unified,
272            ToolbarStyle::UnifiedCompact => S::UnifiedCompact,
273            ToolbarStyle::Expanded => S::Expanded,
274            ToolbarStyle::Preference => S::Preference,
275        }
276    }
277}
278
279/// What a window takes when files are dropped on it.
280struct FileDrop {
281    /// Extensions it takes (lowercase; empty: any file).
282    extensions: Vec<String>,
283    action: Rc<dyn Fn(Vec<std::path::PathBuf>)>,
284}
285
286impl FileDrop {
287    fn accepted(&self, pasteboard: &objc2_app_kit::NSPasteboard) -> Vec<std::path::PathBuf> {
288        transfer::files_on(pasteboard)
289            .into_iter()
290            .filter(|p| {
291                self.extensions.is_empty()
292                    || p.extension().is_some_and(|e| self.extensions.contains(&e.to_string_lossy().to_lowercase()))
293            })
294            .collect()
295    }
296}
297
298thread_local! {
299    /// Window roots that take dropped files, and what they do with them.
300    static DROPS: UiCell<Vec<(usize, Rc<FileDrop>)>> = const { UiCell::new(Vec::new()) };
301}
302
303fn drop_operation(root: &RootView, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation {
304    use objc2_app_kit::NSDraggingInfo;
305    let takes = file_drop(root).is_some_and(|d| !d.accepted(&info.draggingPasteboard()).is_empty());
306    if takes { objc2_app_kit::NSDragOperation::Copy } else { objc2_app_kit::NSDragOperation::None }
307}
308
309fn perform_drop(root: &RootView, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> bool {
310    use objc2_app_kit::NSDraggingInfo;
311    let Some(drop) = file_drop(root) else { return false };
312    let paths = drop.accepted(&info.draggingPasteboard());
313    if paths.is_empty() {
314        return false;
315    }
316    // After AppKit's drag ends: the action may open windows.
317    let action = drop.action.clone();
318    let paths = RefCell::new(Some(paths));
319    later(move || {
320        if let Some(paths) = paths.borrow_mut().take() {
321            batch(|| action(paths));
322        }
323    });
324    true
325}
326
327fn file_drop(root: &RootView) -> Option<Rc<FileDrop>> {
328    DROPS.with_borrow(|d| d.iter().find(|(k, _)| *k == root as *const RootView as usize).map(|(_, f)| f.clone()))
329}
330
331impl Window {
332    /// Files dropped anywhere on the window (that its views don't take
333    /// themselves) go to `action`: those with one of `extensions`, or any
334    /// file if it's empty. The pointer shows a copy badge over the window
335    /// while they're dragged.
336    pub fn on_drop_files(mut self, extensions: &[&str], action: impl Fn(Vec<std::path::PathBuf>) + 'static) -> Self {
337        self.drops = Some(FileDrop { extensions: extensions.iter().map(|e| e.to_lowercase()).collect(), action: Rc::new(action) });
338        self
339    }
340
341    /// A titled, resizable window of 800 × 600 points.
342    pub fn new(title: &str) -> Self {
343        Window {
344            title: title.into(),
345            size: (800.0, 600.0),
346            content: None,
347            view: None,
348            toolbar: Vec::new(),
349            customizable_toolbar: None,
350            autosave: None,
351            fixed: false,
352            responds: commands::Responds::default(),
353            drops: None,
354            chrome: WindowChrome::default(),
355            panel: None,
356            tabbing: None,
357            full_screen: true,
358            sidebar: None,
359            inspector: None,
360        }
361    }
362
363    /// A sidebar beside the window's [`view`](Self::view), as in Mail,
364    /// Notes and the Finder (AppKit's split view controller): full height,
365    /// under the title bar, on the sidebar material; the title and toolbar
366    /// items start beside it, a Toggle Sidebar button leads the toolbar,
367    /// and the user can drag it narrower, wider or shut. Put an
368    /// [`outline`] or a source-list [`sidebar`](fn@crate::sidebar) in it.
369    pub fn sidebar(mut self, view: impl View) -> Self {
370        self.sidebar = Some((AnyView::new(view), self.sidebar.and_then(|s| s.1)));
371        self
372    }
373
374    /// Whether the sidebar is hidden, bound two ways: setting it shows or
375    /// hides the sidebar (animated), and the user's toggling sets it.
376    pub fn sidebar_hidden(mut self, hidden: &Signal<bool>) -> Self {
377        if let Some(s) = &mut self.sidebar {
378            s.1 = Some(*hidden);
379        }
380        self
381    }
382
383    /// An inspector after the window's [`view`](Self::view), as in Keynote
384    /// and Xcode (AppKit's inspector split item, macOS 14): full height, a
385    /// Toggle Inspector button ending the toolbar, the user can drag it
386    /// wider or shut.
387    pub fn inspector(mut self, view: impl View) -> Self {
388        self.inspector = Some((AnyView::new(view), self.inspector.and_then(|s| s.1)));
389        self
390    }
391
392    /// Whether the inspector is hidden, bound two ways.
393    pub fn inspector_hidden(mut self, hidden: &Signal<bool>) -> Self {
394        if let Some(s) = &mut self.inspector {
395            s.1 = Some(*hidden);
396        }
397        self
398    }
399
400    /// How the window joins its app's other windows as tabs. Windows join
401    /// those with the same `group` (all the app's, if `None`); the Window
402    /// menu's Show Tab Bar, Merge All Windows and the tab bar's + work as in
403    /// any Mac app.
404    pub fn tabbing(mut self, tabbing: Tabbing, group: Option<&str>) -> Self {
405        self.tabbing = Some((tabbing, group.map(Into::into)));
406        self
407    }
408
409    /// No full screen: the green button only zooms (a palette, a small
410    /// utility). Resizable windows can go full screen by default.
411    pub fn no_full_screen(mut self) -> Self {
412        self.full_screen = false;
413        self
414    }
415
416    /// Makes it a panel (`NSPanel`): floating above the app's windows,
417    /// hidden while the app is inactive, and not in the Window menu's list
418    /// of documents.
419    pub fn panel(mut self, style: PanelStyle) -> Self {
420        self.panel = Some(style);
421        self
422    }
423
424    /// How the toolbar sits with the title ([`ToolbarStyle::Unified`] by
425    /// default).
426    pub fn toolbar_style(mut self, style: ToolbarStyle) -> Self {
427        self.chrome.toolbar_style = Some(style);
428        self
429    }
430
431    /// Hides the title in the title bar (it still names the window in the
432    /// Window menu and Mission Control): for windows whose content says
433    /// what they are.
434    pub fn hide_title(mut self) -> Self {
435        self.chrome.hide_title = true;
436        self
437    }
438
439    /// A title bar without its own background: the window's background
440    /// shows through it, so the title bar and content read as one surface.
441    pub fn transparent_title_bar(mut self) -> Self {
442        self.chrome.transparent_title_bar = true;
443        self
444    }
445
446    /// Content under the title bar and toolbar, which become transparent.
447    /// The content's backgrounds and materials, and a [`split`]'s panes,
448    /// reach the window's top edge (a sidebar's material runs up behind the
449    /// window buttons, as in Apple's apps), while the content itself starts
450    /// below the title bar.
451    pub fn full_size_content(mut self) -> Self {
452        self.chrome.full_size_content = true;
453        self.chrome.transparent_title_bar = true;
454        self
455    }
456
457    /// The window's background colour (the system's window background by
458    /// default). Named colours follow Dark Mode.
459    pub fn background(mut self, color: Color) -> Self {
460        self.chrome.background = Some(color);
461        self
462    }
463
464    /// The content size in points.
465    pub fn size(mut self, width: f64, height: f64) -> Self {
466        self.size = (width, height);
467        self
468    }
469
470    /// The window's content: `view`, laid out to fill the window.
471    pub fn view(mut self, view: impl View) -> Self {
472        self.view = Some(AnyView::new(view));
473        self
474    }
475
476    /// A unified toolbar with these items.
477    pub fn toolbar(mut self, items: Vec<ToolbarItem>) -> Self {
478        self.toolbar = items;
479        self
480    }
481
482    /// Lets the user customise the toolbar: Customize Toolbar… on its
483    /// right-click menu (and in a View menu, with
484    /// [`customize_toolbar_item`]) opens AppKit's sheet, where items can be
485    /// added, removed and moved, including [optional](ToolbarItem::optional)
486    /// ones and spaces; Command-dragging moves them too. The layout is
487    /// remembered under `name` across launches; until the user changes it,
488    /// the app's own layout shows.
489    pub fn customizable_toolbar(mut self, name: &str) -> Self {
490        self.customizable_toolbar = Some(name.into());
491        self
492    }
493
494    /// Handles `command` while this window is focused and nothing nearer the
495    /// focus handles it (see [`Command`]), wherever the focus is: in the
496    /// content, the sidebar or the inspector.
497    pub fn on_command(mut self, command: Command, action: impl Fn() + 'static) -> Self {
498        self.responds.commands.push((command, commands::Handler::new(action, None)));
499        self
500    }
501
502    /// Handles `command` like [`on_command`](Self::on_command), enabled only
503    /// while `enabled` returns true.
504    pub fn on_command_when(mut self, command: Command, enabled: impl Fn() -> bool + 'static, action: impl Fn() + 'static) -> Self {
505        self.responds.commands.push((command, commands::Handler::new(action, Some(Box::new(enabled)))));
506        self
507    }
508
509    /// Saves the window's position and size under `name` whenever they
510    /// change, and reopens it there next time (AppKit's frame autosave, in
511    /// the app's user defaults).
512    pub fn remember_frame(mut self, name: &str) -> Self {
513        self.autosave = Some(name.into());
514        self
515    }
516
517    /// A plain `NSView` as the window's content (escape hatch; no layout).
518    pub fn content(mut self, build: impl FnOnce() -> Retained<NSView> + 'static) -> Self {
519        self.content = Some(Box::new(build));
520        self
521    }
522
523    pub(crate) fn open(mut self, mtm: MainThreadMarker) -> Retained<NSWindow> {
524        let (sidebar, inspector) = (self.sidebar.take(), self.inspector.take());
525        let shell = (sidebar.is_some(), inspector.is_some());
526        // A sidebar runs up under the title bar.
527        if shell.0 {
528            self.chrome.full_size_content = true;
529        }
530        let rect = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(self.size.0, self.size.1));
531        let mut style = if self.fixed {
532            NSWindowStyleMask::Titled | NSWindowStyleMask::Closable
533        } else {
534            NSWindowStyleMask::Titled | NSWindowStyleMask::Closable | NSWindowStyleMask::Miniaturizable | NSWindowStyleMask::Resizable
535        };
536        if self.chrome.full_size_content {
537            style |= NSWindowStyleMask::FullSizeContentView;
538        }
539        let window: Retained<NSWindow> = match self.panel {
540            None => {
541                // SAFETY: standard window creation on the main thread.
542                unsafe { NSWindow::initWithContentRect_styleMask_backing_defer(NSWindow::alloc(mtm), rect, style, NSBackingStoreType::Buffered, false) }
543            }
544            Some(kind) => {
545                style.remove(NSWindowStyleMask::Miniaturizable);
546                match kind {
547                    PanelStyle::Floating => {}
548                    PanelStyle::Utility => style |= NSWindowStyleMask::UtilityWindow,
549                    PanelStyle::Hud => style |= NSWindowStyleMask::UtilityWindow | NSWindowStyleMask::HUDWindow,
550                }
551                let panel =
552                    objc2_app_kit::NSPanel::initWithContentRect_styleMask_backing_defer(objc2_app_kit::NSPanel::alloc(mtm), rect, style, NSBackingStoreType::Buffered, false);
553                panel.setFloatingPanel(true);
554                panel.setBecomesKeyOnlyIfNeeded(true);
555                panel.setHidesOnDeactivate(true);
556                panel.setExcludedFromWindowsMenu(true);
557                Retained::into_super(panel)
558            }
559        };
560        // SAFETY: the app keeps its windows (see `App::windows`), so AppKit
561        // must not release them on close.
562        unsafe { window.setReleasedWhenClosed(false) };
563        window.setTitle(&NSString::from_str(&self.title));
564        if let Some((tabbing, group)) = &self.tabbing {
565            use objc2_app_kit::NSWindowTabbingMode;
566            window.setTabbingMode(match tabbing {
567                Tabbing::Automatic => NSWindowTabbingMode::Automatic,
568                Tabbing::Preferred => NSWindowTabbingMode::Preferred,
569                Tabbing::Disallowed => NSWindowTabbingMode::Disallowed,
570            });
571            if let Some(g) = group {
572                window.setTabbingIdentifier(&NSString::from_str(g));
573            }
574        }
575        if !self.full_screen {
576            use objc2_app_kit::NSWindowCollectionBehavior;
577            window.setCollectionBehavior((window.collectionBehavior() - NSWindowCollectionBehavior::FullScreenPrimary) | NSWindowCollectionBehavior::FullScreenNone);
578        }
579        let mut toolbar_delegate = None;
580        if !self.toolbar.is_empty() {
581            let delegate = chrome::install_toolbar(&window, self.toolbar, self.customizable_toolbar, shell);
582            toolbar_delegate = Some(delegate.clone());
583            WINDOW_EXTRAS.with_borrow_mut(|e| e.push((window.clone(), delegate)));
584        }
585        if let Some(style) = self.chrome.toolbar_style {
586            window.setToolbarStyle(style.ns());
587            // The title-above styles label their items.
588            if matches!(style, ToolbarStyle::Expanded | ToolbarStyle::Preference)
589                && let Some(t) = window.toolbar()
590            {
591                t.setDisplayMode(objc2_app_kit::NSToolbarDisplayMode::IconAndLabel);
592            }
593        }
594        if self.chrome.hide_title {
595            window.setTitleVisibility(objc2_app_kit::NSWindowTitleVisibility::Hidden);
596        }
597        window.setTitlebarAppearsTransparent(self.chrome.transparent_title_bar);
598        if let Some(color) = self.chrome.background {
599            window.setBackgroundColor(Some(&color.ns()));
600        }
601        let (delegate, undo) = undo::install(mtm, &window);
602        WINDOW_EXTRAS.with_borrow_mut(|e| e.push((window.clone(), delegate)));
603        // Tab follows the views' positions (top-left to bottom-right).
604        window.setAutorecalculatesKeyViewLoop(true);
605        if let Some(build) = self.content {
606            window.setContentView(Some(&build()));
607        }
608        // (Taken only for a shell: other windows build it below.)
609        if let Some(view) = if shell.0 || shell.1 { self.view.take() } else { None } {
610            let make = |v: AnyView| {
611                // SAFETY: NSView's designated initialiser.
612                let root: Retained<RootView> = unsafe { msg_send![RootView::alloc(mtm), initWithFrame: rect] };
613                let node = undo::building(&undo, || batch(|| Node::build_owned(v, &mut Cx::new(Retained::into_super(root.clone())))));
614                (root, node)
615            };
616            let (croot, mut cnode) = make(view);
617            {
618                let mut r = cnode.meta.responds.borrow_mut();
619                r.commands.splice(0..0, std::mem::take(&mut self.responds.commands));
620                r.values.splice(0..0, std::mem::take(&mut self.responds.values));
621            }
622            let controller = objc2_app_kit::NSSplitViewController::new(mtm);
623            let item = |root: &RootView, kind: u8| {
624                let vc = objc2_app_kit::NSViewController::new(mtm);
625                vc.setView(root);
626                match kind {
627                    0 => objc2_app_kit::NSSplitViewItem::sidebarWithViewController(&vc),
628                    2 => objc2_app_kit::NSSplitViewItem::inspectorWithViewController(&vc),
629                    _ => objc2_app_kit::NSSplitViewItem::splitViewItemWithViewController(&vc),
630                }
631            };
632            let mut panes: Vec<(Retained<objc2_app_kit::NSSplitViewItem>, Option<Signal<bool>>)> = Vec::new();
633            let mut roots = Vec::new();
634            // The sidebar and inspector start at their usual widths; the
635            // content takes the rest, and gives way first as the window resizes.
636            if let Some((v, hidden)) = sidebar {
637                let (root, node) = make(v);
638                root.setFrameSize(NSSize::new(220.0, rect.size.height));
639                let it = item(&root, 0);
640                it.setMinimumThickness(180.0);
641                it.setMaximumThickness(400.0);
642                controller.addSplitViewItem(&it);
643                panes.push((it, hidden));
644                roots.push((root, node));
645            }
646            let content_item = item(&croot, 1);
647            content_item.setMinimumThickness(300.0);
648            content_item.setHoldingPriority(objc2_app_kit::NSLayoutPriorityDefaultLow - 10.0);
649            croot.setFrameSize(NSSize::new((rect.size.width - 220.0 * f64::from(u8::from(shell.0)) - 260.0 * f64::from(u8::from(shell.1))).max(300.0), rect.size.height));
650            controller.addSplitViewItem(&content_item);
651            if let Some((v, hidden)) = inspector {
652                let (root, node) = make(v);
653                root.setFrameSize(NSSize::new(260.0, rect.size.height));
654                let it = item(&root, 2);
655                it.setMinimumThickness(220.0);
656                it.setMaximumThickness(420.0);
657                controller.addSplitViewItem(&it);
658                panes.push((it, hidden));
659                roots.push((root, node));
660            }
661            // The hidden signals, both ways: set, the pane slides shut or
662            // open; the user's toggling or dragging sets them.
663            for (it, hidden) in &panes {
664                let Some(hidden) = *hidden else { continue };
665                it.setCollapsed(hidden.get_untracked());
666                let it = it.clone();
667                cnode.own(signal::Effect::new(move || {
668                    let h = hidden.get();
669                    if it.isCollapsed() != h {
670                        // SAFETY: the item's animator proxy takes its setters.
671                        unsafe {
672                            let a: Retained<objc2::runtime::AnyObject> = msg_send![&*it, animator];
673                            let () = msg_send![&*a, setCollapsed: h];
674                        }
675                    }
676                }));
677            }
678            let followed: Vec<(Retained<objc2_app_kit::NSSplitViewItem>, Signal<bool>)> = panes.iter().filter_map(|(i, h)| h.map(|h| (i.clone(), h))).collect();
679            if !followed.is_empty() {
680                // SAFETY: AppKit's notification name.
681                let name = unsafe { objc2_app_kit::NSSplitViewDidResizeSubviewsNotification };
682                let observer = media::Observer::new(name, Some(&controller.splitView()), move || {
683                    for (it, h) in &followed {
684                        h.set_if_changed(it.isCollapsed());
685                    }
686                });
687                cnode.hold(Rc::new(observer));
688            }
689            // Files dropped anywhere in the window: on the content, the
690            // sidebar or the inspector.
691            if let Some(drop) = self.drops.take() {
692                let drop = Rc::new(drop);
693                for root in std::iter::once(&croot).chain(roots.iter().map(|(r, _)| r)) {
694                    // SAFETY: AppKit's pasteboard type constant.
695                    root.registerForDraggedTypes(&objc2_foundation::NSArray::from_slice(&[unsafe { objc2_app_kit::NSPasteboardTypeFileURL }]));
696                    DROPS.with_borrow_mut(|d| d.push((Retained::as_ptr(root) as usize, drop.clone())));
697                }
698            }
699            SHELL_ROOTS.with_borrow_mut(|s| s.push((Retained::as_ptr(&window) as usize, Retained::into_super(croot.clone()))));
700            SHELL_PANES.with_borrow_mut(|p| p.extend(std::iter::once(&croot).chain(roots.iter().map(|(r, _)| r)).map(|r| Retained::as_ptr(r) as usize)));
701            ROOTS.with_borrow_mut(|r| {
702                r.push((croot.clone(), cnode));
703                r.extend(roots);
704            });
705            window.setContentViewController(Some(&controller));
706            window.setContentSize(rect.size);
707            relayout_all();
708        }
709        if let Some(view) = self.view {
710            // SAFETY: NSView's designated initialiser.
711            let root: Retained<RootView> = unsafe { msg_send![RootView::alloc(mtm), initWithFrame: rect] };
712            // The window's tree owns the signals made while building it.
713            let node = undo::building(&undo, || batch(|| Node::build_owned(view, &mut Cx::new(Retained::into_super(root.clone())))));
714            {
715                // The window's handlers answer after its views'.
716                let mut r = node.meta.responds.borrow_mut();
717                r.commands.splice(0..0, self.responds.commands);
718                r.values.splice(0..0, self.responds.values);
719            }
720            // Side-by-side panes at the top: the first is a sidebar, and the
721            // toolbar's title and items start beside it (once it's in the
722            // window).
723            let sidebar = match &node.kind {
724                view::Kind::Split { split, panes, stacked: false, .. } if panes.len() >= 2 => Some(split.clone()),
725                _ => None,
726            };
727            ROOTS.with_borrow_mut(|r| r.push((root.clone(), node)));
728            if let Some(drop) = self.drops {
729                // SAFETY: AppKit's pasteboard type constant.
730                root.registerForDraggedTypes(&objc2_foundation::NSArray::from_slice(&[unsafe { objc2_app_kit::NSPasteboardTypeFileURL }]));
731                DROPS.with_borrow_mut(|d| d.push((Retained::as_ptr(&root) as usize, Rc::new(drop))));
732            }
733            window.setContentView(Some(&root));
734            relayout_all();
735            if let (Some(split), Some(delegate)) = (sidebar, toolbar_delegate.as_ref()) {
736                chrome::track_sidebar(&window, delegate, &split);
737            }
738        }
739        window.center();
740        // In a preview (`cargo ferrokit preview`), every window keeps its
741        // place and size across restarts, by its title.
742        let preview_name = (self.autosave.is_none() && preview_mode()).then(|| format!("ferrokit preview {}", self.title));
743        if let Some(name) = self.autosave.as_ref().or(preview_name.as_ref()) {
744            let name = NSString::from_str(name);
745            // Restore first: setting the name alone doesn't move the window.
746            window.setFrameUsingName(&name);
747            window.setFrameAutosaveName(&name);
748        }
749        window
750    }
751}
752
753/// What the app hears about its environment.
754#[derive(Debug, Clone, PartialEq)]
755#[non_exhaustive]
756pub enum AppEvent {
757    /// Dark Mode or the accent colour changed. Read [`is_dark`] /
758    /// [`system_colors`].
759    AppearanceChanged,
760}
761
762type Handler = Rc<dyn Fn(AppEvent)>;
763
764define_class!(
765    // A window's content view: flipped (top-left origin), lays its node out
766    // whenever its size changes (same transaction as the window resize).
767    #[unsafe(super(NSView, NSResponder, NSObject))]
768    #[thread_kind = MainThreadOnly]
769    #[name = "FerrokitRootView"]
770    struct RootView;
771
772    impl RootView {
773        #[unsafe(method(isFlipped))]
774        fn is_flipped(&self) -> bool {
775            true
776        }
777
778        #[unsafe(method(setFrameSize:))]
779        fn set_frame_size(&self, size: NSSize) {
780            crate::failure::guard("a window's content view (set_frame_size)", (), || {
781                let _: () = unsafe { msg_send![super(self), setFrameSize: size] };
782                relayout(self);
783            })
784        }
785
786        #[unsafe(method(draggingEntered:))]
787        fn dragging_entered(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation {
788            crate::failure::guard("a window's content view (dragging_entered)", objc2_app_kit::NSDragOperation::None, || {
789                drop_operation(self, info)
790            })
791        }
792
793        #[unsafe(method(draggingUpdated:))]
794        fn dragging_updated(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2_app_kit::NSDragOperation {
795            crate::failure::guard("a window's content view (dragging_updated)", objc2_app_kit::NSDragOperation::None, || {
796                drop_operation(self, info)
797            })
798        }
799
800        #[unsafe(method(performDragOperation:))]
801        fn perform_drag(&self, info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) -> objc2::runtime::Bool {
802            crate::failure::guard("a window's content view (perform_drag)", objc2::runtime::Bool::NO, || {
803                objc2::runtime::Bool::new(perform_drop(self, info))
804            })
805        }
806
807        // Escape in a popover's content closes it: the popover's window
808        // answers `cancelOperation:`, but a plain view never turns the key
809        // into it (only text views interpret keys).
810        #[unsafe(method(keyDown:))]
811        fn key_down(&self, event: &objc2_app_kit::NSEvent) {
812            crate::failure::guard("a window's content view (key_down)", (), || {
813                let window = self.window();
814                let escape = event.keyCode() == 53;
815                match window.filter(|w| escape && popover::is_popover_window(w)) {
816                    Some(w) => {
817                        let _: () = unsafe { msg_send![&*w, cancelOperation: Option::<&objc2::runtime::AnyObject>::None] };
818                    }
819                    None => {
820                        let _: () = unsafe { msg_send![super(self), keyDown: event] };
821                    }
822                }
823            })
824        }
825    }
826);
827
828thread_local! {
829    static ROOTS: UiCell<Vec<(Retained<RootView>, Node)>> = const { UiCell::new(Vec::new()) };
830    static IN_LAYOUT: Cell<bool> = const { Cell::new(false) };
831    /// Objects windows need for the app's lifetime (toolbar delegates).
832    static EXTRAS: UiCell<Vec<Retained<NSObject>>> = const { UiCell::new(Vec::new()) };
833    /// Objects a window needs while it's open (its delegate, its toolbar's
834    /// delegate); released when it closes.
835    static WINDOW_EXTRAS: UiCell<Vec<(Retained<NSWindow>, Retained<NSObject>)>> = const { UiCell::new(Vec::new()) };
836    static LAYOUT_US: UiCell<Vec<f64>> = const { UiCell::new(Vec::new()) };
837    static LAYOUT_PASSES: Cell<u64> = const { Cell::new(0) };
838}
839
840fn relayout(root: &RootView) {
841    // At exit the thread's storage is torn down, and dropping the windows'
842    // views resizes them: there's nothing to lay out then.
843    if ROOTS.try_with(|_| ()).is_err() || IN_LAYOUT.try_with(|_| ()).is_err() || LAYOUT_US.try_with(|_| ()).is_err() || LAYOUT_PASSES.try_with(|_| ()).is_err() {
844        return;
845    }
846    if IN_LAYOUT.with(Cell::get) {
847        return;
848    }
849    let t = std::time::Instant::now();
850    // In a batch: a signal set while views are placed (a canvas told its
851    // new size, a split view its panes') runs its effects once the pass is
852    // over, not inside it, where one could rebuild the views being placed.
853    batch(|| {
854        // Cleared also if the pass unwinds (a failure caught further out).
855        struct Done;
856        impl Drop for Done {
857            fn drop(&mut self) {
858                let _ = IN_LAYOUT.try_with(|l| l.set(false));
859            }
860        }
861        IN_LAYOUT.with(|l| l.set(true));
862        let _done = Done;
863        ROOTS.with_borrow(|roots| {
864            for (view, node) in roots {
865                if std::ptr::eq(&**view, root) {
866                    let b = view.bounds().size;
867                    let window = view.window();
868                    let scale = window.as_ref().map_or(2.0, |w| w.backingScaleFactor());
869                    let top = window.as_deref().map_or(0.0, |w| title_bar_inset(w, view));
870                    layout::mirrored(right_to_left(), b.width, || layout::place_under_bar(node, b.width, b.height, top, &layout::Snap(scale)));
871                }
872            }
873        });
874    });
875    LAYOUT_US.with_borrow_mut(|v| {
876        // Keep the recent passes only: an app resized for hours mustn't grow.
877        if v.len() >= 2 * LAYOUT_KEPT {
878            v.drain(..LAYOUT_KEPT);
879        }
880        v.push(t.elapsed().as_secs_f64() * 1e6);
881    });
882    LAYOUT_PASSES.with(|n| n.set(n.get() + 1));
883}
884
885/// How far a window with full-size content has its title bar and toolbar
886/// over `root`, its content view (0 for other windows).
887fn title_bar_inset(window: &NSWindow, root: &RootView) -> f64 {
888    if !window.styleMask().contains(NSWindowStyleMask::FullSizeContentView) {
889        return 0.0;
890    }
891    // The window's content view, or a shell's pane (in the split view that
892    // is the content view): both run the window's full height, up under
893    // the title bar and toolbar.
894    let Some(content) = window.contentView() else { return 0.0 };
895    let key = root as *const RootView as usize;
896    let pane = SHELL_PANES.with_borrow(|p| p.contains(&key));
897    if !std::ptr::eq(&*content, &**root) && !pane {
898        return 0.0;
899    }
900    (content.bounds().size.height - window.contentLayoutRect().size.height).max(0.0)
901}
902
903thread_local! {
904    static FORCE_RTL: Cell<Option<bool>> = const { Cell::new(None) };
905}
906
907/// Whether the app lays out right to left: its language is Arabic, Hebrew,
908/// Persian or Urdu (the app's localisation and the user's languages), or
909/// the `NSForceRightToLeftWritingDirection` default is set. Ferrokit
910/// mirrors its layout then, as AppKit mirrors its own.
911pub fn right_to_left() -> bool {
912    FORCE_RTL.with(Cell::get).unwrap_or_else(|| {
913        MainThreadMarker::new().is_some_and(|mtm| NSApplication::sharedApplication(mtm).userInterfaceLayoutDirection() == objc2_app_kit::NSUserInterfaceLayoutDirection::RightToLeft)
914    })
915}
916
917/// Overrides [`right_to_left`] (`None`: the app's own), for checks.
918pub(crate) fn force_right_to_left(on: Option<bool>) {
919    FORCE_RTL.with(|f| f.set(on));
920}
921
922/// The root view of `window`'s main tree: its content view, or a shell's
923/// content pane.
924fn main_root(window: &NSWindow) -> Option<Retained<NSView>> {
925    let key = window as *const NSWindow as usize;
926    SHELL_ROOTS.with_borrow(|s| s.iter().find(|(w, _)| *w == key).map(|(_, r)| r.clone())).or_else(|| window.contentView())
927}
928
929/// The root node of `window`'s view tree.
930pub(crate) fn root_meta(window: &NSWindow) -> Option<Rc<view::Meta>> {
931    let content = main_root(window)?;
932    ROOTS.with_borrow(|r| r.iter().find(|(v, _)| std::ptr::eq(&***v as *const NSView, &*content as *const NSView)).map(|(_, n)| n.meta.clone()))
933}
934
935/// Tears down the view tree of `window`'s content (its node is dropped:
936/// effects stop, native views go).
937pub(crate) fn drop_root(window: &NSWindow) {
938    let Some(content) = main_root(window) else { return };
939    let key = Retained::as_ptr(&content) as usize;
940    DROPS.with_borrow_mut(|d| d.retain(|(k, _)| *k != key));
941    // The window's roots: its content view's, or each of its shell's panes'.
942    let wkey = window as *const NSWindow as usize;
943    SHELL_ROOTS.with_borrow_mut(|s| s.retain(|(w, _)| *w != wkey));
944    let nodes: Vec<(Retained<RootView>, Node)> = ROOTS.with_borrow_mut(|r| {
945        let mut gone = Vec::new();
946        let mut i = 0;
947        while i < r.len() {
948            let mine = std::ptr::eq(&**r[i].0 as *const NSView, &*content as *const NSView) || r[i].0.window().is_some_and(|w| std::ptr::eq(&*w, window));
949            if mine {
950                gone.push(r.remove(i));
951            } else {
952                i += 1;
953            }
954        }
955        gone
956    });
957    SHELL_PANES.with_borrow_mut(|p| p.retain(|k| !nodes.iter().any(|(r, _)| Retained::as_ptr(r) as usize == *k)));
958    drop(nodes);
959    // The shell's controller goes with its window.
960    window.setContentViewController(None);
961}
962
963/// Builds `view` (under its own owner) in a new root view of `size`
964/// points, laid out like a window's content: for content AppKit hosts in a
965/// window of its own (a popover). Returns the root and the view's ideal
966/// size. Release it with [`drop_hosted`].
967pub(crate) fn host_view(view: view::AnyView) -> (Retained<NSView>, NSSize) {
968    let mtm = mtm();
969    // SAFETY: NSView's designated initialiser.
970    let root: Retained<RootView> = unsafe { msg_send![RootView::alloc(mtm), initWithFrame: NSRect::new(NSPoint::ZERO, NSSize::new(100.0, 100.0))] };
971    let node = batch(|| Node::build_owned(view, &mut Cx::new(Retained::into_super(root.clone()))));
972    let size = layout::ideal(&node);
973    ROOTS.with_borrow_mut(|r| r.push((root.clone(), node)));
974    root.setFrameSize(NSSize::new(size.w.ceil(), size.h.ceil()));
975    (Retained::into_super(root), NSSize::new(size.w.ceil(), size.h.ceil()))
976}
977
978/// The ideal size of a root made by [`host_view`], measured again.
979pub(crate) fn hosted_ideal(root: &NSView) -> Option<NSSize> {
980    ROOTS.with_borrow(|r| {
981        let (_, node) = r.iter().find(|(v, _)| std::ptr::eq(&***v as *const NSView, root as *const NSView))?;
982        let s = layout::ideal(node);
983        Some(NSSize::new(s.w.ceil(), s.h.ceil()))
984    })
985}
986
987/// Drops the tree of a root made by [`host_view`].
988pub(crate) fn drop_hosted(root: &NSView) {
989    // `try_with`: this also runs while the window roots are being dropped
990    // at exit.
991    let node = ROOTS
992        .try_with(|r| {
993            let mut r = r.try_borrow_mut().ok()?;
994            let i = r.iter().position(|(v, _)| std::ptr::eq(&***v as *const NSView, root as *const NSView))?;
995            Some(r.remove(i))
996        })
997        .ok()
998        .flatten();
999    drop(node);
1000}
1001
1002/// Whether a layout pass is running.
1003pub(crate) fn in_layout() -> bool {
1004    IN_LAYOUT.with(Cell::get)
1005}
1006
1007/// Lays every window out now (after AppKit resized part of one).
1008pub(crate) fn relayout_now() {
1009    relayout_all();
1010}
1011
1012fn relayout_all() {
1013    view::LAYOUT_DIRTY.with(|d| d.set(false));
1014    let roots: Vec<Retained<RootView>> = ROOTS.with_borrow(|r| r.iter().map(|(v, _)| v.clone()).collect());
1015    for r in roots {
1016        relayout(&r);
1017    }
1018}
1019
1020/// How many layout passes [`layout_times_us`] keeps at least.
1021const LAYOUT_KEPT: usize = 10_000;
1022
1023/// Microseconds of the recent layout passes, oldest first (diagnostic; at
1024/// least the last 10,000).
1025pub(crate) fn layout_times_us() -> Vec<f64> {
1026    LAYOUT_US.with_borrow(Clone::clone)
1027}
1028
1029/// Layout passes so far. With [`layout_times_us`], the times of the passes
1030/// since an earlier count: `let t = layout_times_us(); &t[t.len() - (layout_passes() - n0) as usize..]`.
1031pub(crate) fn layout_passes() -> u64 {
1032    LAYOUT_PASSES.with(Cell::get)
1033}
1034
1035thread_local! {
1036    /// Windows with a sidebar or inspector shell, and their content pane's
1037    /// root (their main tree's).
1038    static SHELL_ROOTS: UiCell<Vec<(usize, Retained<NSView>)>> = const { UiCell::new(Vec::new()) };
1039    /// The root views of shells' panes (each AppKit wraps in a view of its own).
1040    static SHELL_PANES: UiCell<Vec<usize>> = const { UiCell::new(Vec::new()) };
1041    static HANDLERS: UiCell<Vec<Handler>> = const { UiCell::new(Vec::new()) };
1042    static WINDOWS: UiCell<Vec<Retained<NSWindow>>> = const { UiCell::new(Vec::new()) };
1043}
1044
1045/// The application: a name, its windows and the AppKit run loop.
1046pub struct App {
1047    name: String,
1048    windows: Vec<Window>,
1049    on_launch: Option<Box<dyn FnOnce()>>,
1050    menus: Vec<(String, Vec<MenuItem>)>,
1051    settings: Option<Window>,
1052    documents: Option<Box<dyn FnOnce()>>,
1053    extras: Vec<MenuBarExtra>,
1054    menu_bar_only: bool,
1055    welcome: Option<Rc<dyn Fn() -> Window>>,
1056    dock_menu: Option<Rc<dyn Fn() -> Vec<MenuItem>>>,
1057    open_url: Option<documents::OpenUrl>,
1058    crash_reports: Option<Box<dyn Fn(CrashReport)>>,
1059    about: Option<(String, Option<(String, String)>)>,
1060}
1061
1062impl App {
1063    /// An app called `name` (shown in the menu bar).
1064    pub fn new(name: &str) -> Self {
1065        failure::install();
1066        App { name: name.into(), windows: Vec::new(), on_launch: None, menus: Vec::new(), settings: None, documents: None, extras: Vec::new(), menu_bar_only: false, welcome: None, dock_menu: None, open_url: None, crash_reports: None, about: None }
1067    }
1068
1069    /// Opens `window` at launch. Call more than once for several windows.
1070    pub fn window(mut self, window: Window) -> Self {
1071        self.windows.push(window);
1072        self
1073    }
1074
1075    /// The app's translations: `(language, .strings text)` pairs, e.g.
1076    /// `("de", include_str!("../locales/de.strings"))`. The languages here
1077    /// are the ones the app speaks; see [`t`] and the [`l10n`](crate::t)
1078    /// functions.
1079    pub fn translations(self, tables: &[(&str, &str)]) -> Self {
1080        l10n::add_translations(tables);
1081        self
1082    }
1083
1084    /// Adds a menu to the menu bar, between Edit and Window ("View", "Go"…).
1085    /// A menu titled "Edit" adds its items to the standard Edit menu (after
1086    /// Find), and one titled "Help" fills the standard Help menu.
1087    /// A menu titled "File" fills the standard File menu instead, above its
1088    /// Close item. Items run in a [`batch`]; their enabled and checked
1089    /// states are evaluated when the menu opens or a key equivalent fires.
1090    pub fn menu(mut self, title: &str, items: Vec<MenuItem>) -> Self {
1091        self.menus.push((title.into(), items));
1092        self
1093    }
1094
1095    /// Credits for About {app}: `credits` under the app's name, icon and
1096    /// version (from the bundle), and `link` (title, URL) after it, e.g.
1097    /// `.about("Made with Ferrokit.", Some(("ferrokit.dev", "https://…")))`.
1098    pub fn about(mut self, credits: &str, link: Option<(&str, &str)>) -> Self {
1099        self.about = Some((credits.into(), link.map(|(t, u)| (t.into(), u.into()))));
1100        self
1101    }
1102
1103    /// The app's Settings window: "Settings…" (⌘,) in the app menu opens it
1104    /// (built on first use, then brought to the front). It isn't resizable
1105    /// or listed in the Window menu, and it remembers its position.
1106    pub fn settings(mut self, window: Window) -> Self {
1107        self.settings = Some(window);
1108        self
1109    }
1110
1111    /// Makes this a document app for `kind` (see [`DocumentType`]): the File
1112    /// menu gets New, Open…, Open Recent, Save, Save As… and Revert to
1113    /// Saved; closing an edited document asks to save it, and quitting
1114    /// reviews the unsaved ones. With no windows given, the app starts with
1115    /// an untitled document.
1116    pub fn documents<T: Clone + PartialEq + 'static>(mut self, kind: DocumentType<T>) -> Self {
1117        self.documents = Some(Box::new(move || documents::install(kind)));
1118        self
1119    }
1120
1121    /// A welcome window for a document app, shown at launch instead of an
1122    /// untitled document (as Xcode's is): recent documents, a sample,
1123    /// Open… `make` builds it each time it opens. It closes when a document
1124    /// opens, and Window ▸ Welcome to … (⇧⌘1) or [`show_welcome`] brings it
1125    /// back.
1126    pub fn welcome(mut self, make: impl Fn() -> Window + 'static) -> Self {
1127        self.welcome = Some(Rc::new(make));
1128        self
1129    }
1130
1131    /// Adds an item to the right side of the menu bar, with a menu or a
1132    /// panel (see [`MenuBarExtra`]).
1133    pub fn menu_bar_extra(mut self, extra: MenuBarExtra) -> Self {
1134        self.extras.push(extra);
1135        self
1136    }
1137
1138    /// Makes this a menu-bar app: no Dock icon and no menu bar of its own,
1139    /// only its [`menu_bar_extra`](Self::menu_bar_extra)s (and any windows
1140    /// it opens).
1141    pub fn menu_bar_only(mut self) -> Self {
1142        self.menu_bar_only = true;
1143        self
1144    }
1145
1146    /// Items for the Dock icon's menu (Control-click or a long press on the
1147    /// icon), above the system's own: "New Window", a recent item. `items`
1148    /// runs each time the menu opens, so it can read the app's state.
1149    pub fn dock_menu(mut self, items: impl Fn() -> Vec<MenuItem> + 'static) -> Self {
1150        self.dock_menu = Some(Rc::new(items));
1151        self
1152    }
1153
1154    /// Links in the app's own URL schemes: `f` gets each one opened while
1155    /// the app runs or that launched it (`myapp://open?id=3`, from a web
1156    /// page, another app or `open` in Terminal), after its windows are up.
1157    /// Declare the schemes in `Cargo.toml`: `cargo ferrokit bundle` writes
1158    /// them into the app's `Info.plist`, and macOS learns them the first
1159    /// time the bundled app runs (`cargo ferrokit run` does both):
1160    ///
1161    /// ```toml
1162    /// [package.metadata.ferrokit]
1163    /// url-schemes = ["myapp"]
1164    /// ```
1165    ///
1166    /// macOS only sends links to a bundled app (`cargo ferrokit run`), not
1167    /// to a bare `cargo run`. The link comes as macOS gives it, scheme
1168    /// first and percent-encoded; anyone can send one, so read it as
1169    /// untrusted input.
1170    ///
1171    /// ```no_run
1172    /// use ferrokit::*;
1173    /// let shown = Signal::new(String::new());
1174    /// App::new("Notes")
1175    ///     .on_open_url(move |url| {
1176    ///         if let Some(id) = url.strip_prefix("notes://open/") {
1177    ///             shown.set(id.to_string());
1178    ///         }
1179    ///     })
1180    ///     .window(Window::new("Notes").view(text(move || shown.get())))
1181    ///     .run();
1182    /// ```
1183    pub fn on_open_url(mut self, f: impl Fn(&str) + 'static) -> Self {
1184        self.open_url = Some(Rc::new(f));
1185        self
1186    }
1187
1188    /// Crash reports. From now on, a panic Ferrokit doesn't catch (one
1189    /// outside a control's action, menu item, timer or the like, which
1190    /// [`on_error`](Self::on_error) hears about and survives; or one on a
1191    /// background thread) writes a report before the app ends: the app,
1192    /// its version, macOS, the thread, the message and where, and the
1193    /// backtrace, in `~/Library/Logs/<app>/Crashes`. At the next launch,
1194    /// after the windows are on screen, `f` gets each report not yet
1195    /// [marked sent](CrashReport::mark_sent): ask the user to send it, send
1196    /// it to a service, or keep it.
1197    ///
1198    /// ```no_run
1199    /// use ferrokit::*;
1200    ///
1201    /// let app = App::new("Notes").crash_reports(|report| {
1202    ///     // Show it, send it, then:
1203    ///     let _ = report.mark_sent();
1204    /// });
1205    /// # let _ = app;
1206    /// ```
1207    ///
1208    /// A crash that isn't a panic (a bad memory access in unsafe code or a
1209    /// C library) ends the app at once; macOS writes those to
1210    /// `~/Library/Logs/DiagnosticReports`.
1211    pub fn crash_reports(mut self, f: impl Fn(CrashReport) + 'static) -> Self {
1212        crash::install(&self.name);
1213        self.crash_reports = Some(Box::new(f));
1214        self
1215    }
1216
1217    /// Runs `f` on the first run-loop pass after the windows are on screen.
1218    ///
1219    /// `f` runs outside any owner: signals made in it live as long as the
1220    /// app, and a [`spawn_local`] task started in it runs until it finishes,
1221    /// whatever window closes (no [`Task::detach`] needed). Start work that
1222    /// lasts the app's life here: following a file, a timer, the self-checks.
1223    pub fn on_launch(mut self, f: impl FnOnce() + 'static) -> Self {
1224        self.on_launch = Some(Box::new(f));
1225        self
1226    }
1227
1228    /// Handles `command` when nothing nearer the focus does (or no window is
1229    /// open). See [`Command`].
1230    pub fn on_command(self, command: Command, action: impl Fn() + 'static) -> Self {
1231        commands::app_command(command, commands::Handler::new(action, None));
1232        self
1233    }
1234
1235    /// Calls `f` when something fails where AppKit called into the app (an
1236    /// action, a menu item, a timer, a notification, a sheet's completion):
1237    /// an Objective-C exception or a Rust panic, caught there so the app
1238    /// goes on (it's also printed to stderr). Log it, or tell the user.
1239    ///
1240    /// ```no_run
1241    /// use ferrokit::*;
1242    ///
1243    /// let app = App::new("Notes").on_error(|failure| eprintln!("send to the crash log: {failure}"));
1244    /// # let _ = app;
1245    /// ```
1246    pub fn on_error(self, f: impl Fn(&Failure) + 'static) -> Self {
1247        failure::set_hook(f);
1248        self
1249    }
1250
1251    /// Calls `f` for every [`AppEvent`].
1252    pub fn on_event(self, f: impl Fn(AppEvent) + 'static) -> Self {
1253        HANDLERS.with_borrow_mut(|h| h.push(Rc::new(f)));
1254        self
1255    }
1256
1257    /// Creates the menu bar and windows, then runs the AppKit run loop. Does
1258    /// not return while the app is running.
1259    pub fn run(self) {
1260        let mtm = mtm();
1261        let app = NSApplication::sharedApplication(mtm);
1262        app.setActivationPolicy(if self.menu_bar_only { NSApplicationActivationPolicy::Accessory } else { NSApplicationActivationPolicy::Regular });
1263        let settings = self.settings.map(|w| {
1264            SETTINGS.with_borrow_mut(|s| *s = Some(Err(w)));
1265            Retained::into_super(appkit_views::ActionTarget::new(mtm, || {
1266                open_settings_ns();
1267            }))
1268        });
1269        let about = self.about.map(|(credits, link)| Retained::into_super(appkit_views::ActionTarget::new(mtm, move || show_about(&credits, link.as_ref()))));
1270        let is_documents = self.documents.is_some();
1271        let mut menus = self.menus;
1272        let mut file_after = Vec::new();
1273        if let Some(install) = self.documents {
1274            install();
1275            let (above, after) = documents::file_items();
1276            file_after = after;
1277            match menus.iter_mut().find(|(t, _)| t == "File") {
1278                Some((_, items)) => {
1279                    let own = std::mem::take(items);
1280                    *items = above.into_iter().chain(own).collect();
1281                }
1282                None => menus.insert(0, ("File".into(), above)),
1283            }
1284        }
1285        let welcome = self.welcome.filter(|_| is_documents);
1286        let start_welcome = welcome.is_some() && self.windows.is_empty();
1287        let start_untitled = is_documents && self.windows.is_empty() && !start_welcome;
1288        let mut window_items = Vec::new();
1289        if let Some(make) = welcome {
1290            documents::set_welcome(make);
1291            window_items.push(menu_item(t_with("Welcome to {app}", &[("app", &self.name)]), || {
1292                show_welcome();
1293            }).key_with("1", &[Modifier::Shift]));
1294        }
1295        // Sparkle, when the bundle has it: Check for Updates… in the app menu.
1296        let updater = objc2::rc::autoreleasepool(|_| updates::start());
1297        let targets = menu::install(mtm, &self.name, menus, menu::AppTargets { about, settings, updater }, file_after, window_items);
1298        EXTRAS.with_borrow_mut(|e| e.extend(targets));
1299        for extra in self.extras {
1300            status::install(extra, &self.name);
1301        }
1302        if let Some(items) = self.dock_menu {
1303            documents::DOCK_MENU.with_borrow_mut(|d| *d = Some(items));
1304            documents::install_delegate();
1305        }
1306        if let Some(f) = self.open_url {
1307            documents::OPEN_URL.with_borrow_mut(|o| *o = Some(f));
1308            documents::install_delegate();
1309        }
1310        after_batch(|| {
1311            motion::run_layout(|| {
1312                if view::LAYOUT_DIRTY.with(Cell::get) {
1313                    relayout_all();
1314                }
1315            });
1316        });
1317
1318        services::listen_for_notifications();
1319        ferrokit_core::observe_appearance();
1320        ferrokit_core::set_event_sink(|event| match event {
1321            ferrokit_core::Event::AppearanceChanged => emit(AppEvent::AppearanceChanged),
1322            // A model queued events: deliver them on the next pass (they
1323            // arrive inside AppKit callbacks).
1324            ferrokit_core::Event::Redraw => later(models::drain_all),
1325            _ => {}
1326        });
1327
1328        // Startup runs before the run loop exists, so it needs its own
1329        // autorelease pool (see `later`).
1330        objc2::rc::autoreleasepool(|_| {
1331            for window in self.windows {
1332                let w = window.open(mtm);
1333                w.makeKeyAndOrderFront(None);
1334                WINDOWS.with_borrow_mut(|ws| ws.push(w));
1335            }
1336        });
1337        // What was open at the last quit, if the user keeps windows; else
1338        // an untitled document, or the welcome window.
1339        let restored = if start_untitled || start_welcome { objc2::rc::autoreleasepool(|_| documents::restore_open()) } else { 0 };
1340        if start_untitled && restored == 0 {
1341            objc2::rc::autoreleasepool(|_| documents::new_launch_document());
1342        }
1343        if start_welcome && restored == 0 {
1344            objc2::rc::autoreleasepool(|_| show_welcome());
1345        }
1346        if preview_mode() {
1347            // A preview restarts on every save: show the windows above the
1348            // others without taking the keyboard from the editor.
1349            WINDOWS.with_borrow(|ws| ws.iter().for_each(|w| w.orderFrontRegardless()));
1350        } else {
1351            #[allow(deprecated)]
1352            app.activateIgnoringOtherApps(true);
1353        }
1354        if let Some(f) = self.on_launch {
1355            let f = RefCell::new(Some(f));
1356            later(move || {
1357                if let Some(f) = f.borrow_mut().take() {
1358                    f();
1359                }
1360            });
1361        }
1362        if let Some(f) = self.crash_reports {
1363            // The last run's reports, once the windows are up.
1364            let dir = crash::folder(&self.name);
1365            later(move || {
1366                for report in crash::pending(&dir) {
1367                    failure::entry("a crash report's handler", (), || f(report));
1368                }
1369            });
1370        }
1371        app.run();
1372    }
1373}
1374
1375fn emit(event: AppEvent) {
1376    let handlers: Vec<Handler> = HANDLERS.with_borrow(|h| h.clone());
1377    for h in handlers {
1378        h(event.clone());
1379    }
1380}
1381
1382/// The standard About panel, with `credits` and a link under them.
1383fn show_about(credits: &str, link: Option<&(String, String)>) {
1384    use objc2_app_kit::{NSFont, NSForegroundColorAttributeName, NSFontAttributeName, NSLinkAttributeName, NSParagraphStyleAttributeName};
1385    use objc2_foundation::{NSAttributedString, NSMutableAttributedString, NSRange, NSURL};
1386    let text = match link {
1387        Some((title, _)) => format!("{credits}\n{title}"),
1388        None => credits.to_string(),
1389    };
1390    let s = NSMutableAttributedString::from_nsstring(&NSString::from_str(&text));
1391    let all = NSRange::new(0, text.encode_utf16().count());
1392    let centred = objc2_app_kit::NSMutableParagraphStyle::new();
1393    centred.setAlignment(objc2_app_kit::NSTextAlignment::Center);
1394    // SAFETY: AppKit's attribute names with values of their kinds.
1395    unsafe {
1396        s.addAttribute_value_range(NSFontAttributeName, &NSFont::systemFontOfSize(11.0), all);
1397        s.addAttribute_value_range(NSForegroundColorAttributeName, &objc2_app_kit::NSColor::labelColor(), all);
1398        s.addAttribute_value_range(NSParagraphStyleAttributeName, &centred, all);
1399        if let Some((title, url)) = link
1400            && let Some(u) = NSURL::URLWithString(&NSString::from_str(url))
1401        {
1402            let start = text.encode_utf16().count() - title.encode_utf16().count();
1403            s.addAttribute_value_range(NSLinkAttributeName, &u, NSRange::new(start, title.encode_utf16().count()));
1404        }
1405    }
1406    let credits: Retained<NSAttributedString> = Retained::into_super(s);
1407    let options = objc2_foundation::NSDictionary::from_retained_objects(&[unsafe { objc2_app_kit::NSAboutPanelOptionCredits }], &[Retained::into_super(Retained::into_super(credits))]);
1408    // SAFETY: the options AppKit documents.
1409    unsafe { NSApplication::sharedApplication(mtm()).orderFrontStandardAboutPanelWithOptions(&options) };
1410    ABOUT_SHOWN.with(|a| a.set(a.get() + 1));
1411}
1412
1413thread_local! {
1414    /// How many times About {app} was shown with credits (for checks).
1415    pub(crate) static ABOUT_SHOWN: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
1416}
1417
1418/// Opens `window` as a new tab of `beside` (the tab bar's + and a "New
1419/// Tab" command use this).
1420pub fn open_tab(beside: &WindowRef, window: Window) -> WindowRef {
1421    let beside = beside.ns();
1422    let w = open_ns(window);
1423    beside.addTabbedWindow_ordered(&w, objc2_app_kit::NSWindowOrderingMode::Above);
1424    w.makeKeyAndOrderFront(None);
1425    WindowRef::new(w)
1426}
1427
1428/// Puts `window` into full screen, or takes it out (as the green button
1429/// and View ▸ Enter Full Screen do).
1430pub fn toggle_full_screen(window: &crate::WindowRef) {
1431    let window = window.ns();
1432    window.toggleFullScreen(None);
1433}
1434
1435/// Whether `window` is in full screen.
1436pub fn is_full_screen(window: &crate::WindowRef) -> bool {
1437    let window = window.ns();
1438    window.styleMask().contains(NSWindowStyleMask::FullScreen)
1439}
1440
1441/// The Dock icon's badge: a count or a short word (`Some("3")`), or none.
1442pub fn set_dock_badge(badge: Option<&str>) {
1443    let tile = NSApplication::sharedApplication(mtm()).dockTile();
1444    tile.setBadgeLabel(badge.map(NSString::from_str).as_deref());
1445}
1446
1447/// The Dock icon's badge, if any.
1448pub fn dock_badge() -> Option<String> {
1449    NSApplication::sharedApplication(mtm()).dockTile().badgeLabel().map(|b| b.to_string())
1450}
1451
1452/// Opens the window `make` builds, now, and returns it: the signals `make`
1453/// creates (a form's fields, a selection) belong to the window and are
1454/// freed when it closes. Prefer it to [`open`] in an action: a signal made
1455/// in an action outside any view lives as long as the app.
1456///
1457/// ```no_run
1458/// use ferrokit::*;
1459///
1460/// let add = button("New Note", || {
1461///     open_with(|| {
1462///         let title = Signal::new(String::new());
1463///         Window::new("New Note").size(320.0, 120.0).view(text_field(&title).padding(16.0))
1464///     });
1465/// });
1466/// # let _ = add;
1467/// ```
1468pub fn open_with(make: impl FnOnce() -> Window) -> WindowRef {
1469    let owner = signal::Owner::new();
1470    let window = owner.with(make);
1471    let w = open_ns(window);
1472    keep_until_closed(&w, owner);
1473    WindowRef::new(w)
1474}
1475
1476thread_local! {
1477    /// What windows keep until they close (their builders' signals).
1478    static KEPT: UiCell<Vec<(usize, Box<dyn std::any::Any>)>> = const { UiCell::new(Vec::new()) };
1479}
1480
1481/// Keeps `value` until `window` closes (then drops it with the window's
1482/// views).
1483pub(crate) fn keep_until_closed(window: &NSWindow, value: impl std::any::Any) {
1484    KEPT.with_borrow_mut(|k| k.push((window as *const NSWindow as usize, Box::new(value))));
1485}
1486
1487/// Opens `window` now (while the app runs) and returns it.
1488pub fn open(window: Window) -> WindowRef {
1489    WindowRef::new(open_ns(window))
1490}
1491
1492pub(crate) fn open_ns(window: Window) -> Retained<NSWindow> {
1493    let mtm = mtm();
1494    objc2::rc::autoreleasepool(|_| {
1495        let w = window.open(mtm);
1496        w.makeKeyAndOrderFront(None);
1497        WINDOWS.with_borrow_mut(|ws| ws.push(w.clone()));
1498        w
1499    })
1500}
1501
1502thread_local! {
1503    /// The Settings window: not yet built, or open.
1504    static SETTINGS: UiCell<Option<Result<Retained<NSWindow>, Window>>> = const { UiCell::new(None) };
1505}
1506
1507/// Opens the app's Settings window (see [`App::settings`]), or brings it to
1508/// the front, and returns it. `None` if the app has none.
1509pub fn open_settings() -> Option<WindowRef> {
1510    open_settings_ns().map(WindowRef::new)
1511}
1512
1513pub(crate) fn open_settings_ns() -> Option<Retained<NSWindow>> {
1514    let mtm = mtm();
1515    let pending = SETTINGS.with_borrow_mut(|s| match s.take() {
1516        Some(Err(w)) => Some(w),
1517        other => {
1518            *s = other;
1519            None
1520        }
1521    });
1522    if let Some(mut w) = pending {
1523        w.fixed = true;
1524        if w.autosave.is_none() {
1525            w.autosave = Some("ferrokit settings".into());
1526        }
1527        let window = objc2::rc::autoreleasepool(|_| w.open(mtm));
1528        window.setExcludedFromWindowsMenu(true);
1529        SETTINGS.with_borrow_mut(|s| *s = Some(Ok(window)));
1530    }
1531    let window = SETTINGS.with_borrow(|s| s.as_ref().and_then(|w| w.as_ref().ok().cloned()))?;
1532    window.makeKeyAndOrderFront(None);
1533    Some(window)
1534}
1535
1536/// Closes `window` and tears down its views (its node is dropped: effects
1537/// stop, native views go). The app no longer lists it in [`windows`].
1538///
1539/// The close button and ⌘W do the same (except for the Settings window,
1540/// which is kept and reused).
1541pub fn close_window(window: &crate::WindowRef) {
1542    let window = window.ns();
1543    window.close();
1544    teardown(window);
1545}
1546
1547/// Called by the window delegate as `window` closes (close button, ⌘W,
1548/// `close`): tears it down on the next pass, outside AppKit's close
1549/// sequence and the delegate's own call.
1550pub(crate) fn window_will_close(window: &NSWindow) {
1551    if is_settings(window) {
1552        return;
1553    }
1554    let window = objc2::Message::retain(window);
1555    later(move || {
1556        // Reopened since (`makeKeyAndOrderFront` on a kept handle): keep it.
1557        if !window.isVisible() {
1558            teardown(&window);
1559        }
1560    });
1561}
1562
1563fn is_settings(window: &NSWindow) -> bool {
1564    SETTINGS.with_borrow(|s| matches!(s, Some(Ok(w)) if std::ptr::eq(&**w, window)))
1565}
1566
1567/// Drops a closed window's undo history, view tree, delegates and entry in
1568/// [`windows`]. Running it again does nothing.
1569pub(crate) fn teardown(window: &NSWindow) {
1570    if let Some(undo) = window.undoManager() {
1571        undo.removeAllActions();
1572    }
1573    drop_root(window);
1574    // What the window's builder made goes with it.
1575    let key = window as *const NSWindow as usize;
1576    let kept: Vec<_> = KEPT.with_borrow_mut(|k| {
1577        let (mine, rest): (Vec<_>, Vec<_>) = std::mem::take(k).into_iter().partition(|(w, _)| *w == key);
1578        *k = rest;
1579        mine
1580    });
1581    drop(kept);
1582    documents::forget(window);
1583    WINDOWS.with_borrow_mut(|ws| ws.retain(|w| !std::ptr::eq(&**w, window)));
1584    let extras: Vec<Retained<NSObject>> = WINDOW_EXTRAS.with_borrow_mut(|e| {
1585        let (mine, rest): (Vec<_>, Vec<_>) = std::mem::take(e).into_iter().partition(|(w, _)| std::ptr::eq(&**w, window));
1586        *e = rest;
1587        mine.into_iter().map(|(_, x)| x).collect()
1588    });
1589    if !extras.is_empty() {
1590        // The delegates are about to go: AppKit mustn't call them again.
1591        window.setDelegate(None);
1592        if let Some(toolbar) = window.toolbar() {
1593            toolbar.setDelegate(None);
1594        }
1595    }
1596    drop(extras);
1597}
1598
1599/// The app's windows, in the order they were opened.
1600pub fn windows() -> Vec<WindowRef> {
1601    windows_ns().into_iter().map(WindowRef::new).collect()
1602}
1603
1604pub(crate) fn windows_ns() -> Vec<Retained<NSWindow>> {
1605    WINDOWS.with_borrow(|w| w.clone())
1606}
1607
1608/// Runs `f` on a later pass of the main run loop.
1609pub fn later(f: impl Fn() + 'static) {
1610    Native::later(Box::new(f));
1611}
1612
1613/// The app's appearance.
1614#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1615pub enum Appearance {
1616    /// Follow the system setting.
1617    System,
1618    /// Always light.
1619    Light,
1620    /// Always dark.
1621    Dark,
1622}
1623
1624/// Sets the app's appearance; every native view follows, and an
1625/// [`AppEvent::AppearanceChanged`] is delivered.
1626pub fn set_appearance(appearance: Appearance) {
1627    let name = match appearance {
1628        Appearance::System => None,
1629        // SAFETY: AppKit's appearance name constants.
1630        Appearance::Light => Some(unsafe { objc2_app_kit::NSAppearanceNameAqua }),
1631        Appearance::Dark => Some(unsafe { objc2_app_kit::NSAppearanceNameDarkAqua }),
1632    };
1633    let appearance = name.and_then(objc2_app_kit::NSAppearance::appearanceNamed);
1634    NSApplication::sharedApplication(mtm()).setAppearance(appearance.as_deref());
1635}
1636
1637/// Ends the app (as ⌘Q does), on the next pass of the run loop. Quitting
1638/// can wait for answers (a document app asks about unsaved changes) inside
1639/// a nested run loop; starting it outside the caller's batch keeps the UI
1640/// updating meanwhile.
1641pub fn quit() {
1642    later(|| NSApplication::sharedApplication(mtm()).terminate(None));
1643}
1644
1645type Continuation = Box<dyn FnOnce(Result<Box<dyn Any + Send>, String>)>;
1646
1647thread_local! {
1648    static CONTINUATIONS: UiCell<HashMap<u64, Continuation>> = UiCell::new(HashMap::new());
1649    static NEXT_TASK: Cell<u64> = const { Cell::new(0) };
1650}
1651
1652/// Runs `work` on a background thread, then `then` with its result on the
1653/// main thread, inside a [`batch`]. Call from the main thread.
1654///
1655/// If `work` panics, `then` doesn't run: the panic is reported like any
1656/// other failure (see [`App::on_error`], as "a background task") and the
1657/// app goes on. Return a `Result` from `work` for errors you expect.
1658pub fn spawn<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static, then: impl FnOnce(T) + 'static) {
1659    spawn_outcome(work, move |outcome| {
1660        if let Ok(result) = outcome {
1661            then(result);
1662        }
1663    });
1664}
1665
1666/// [`spawn`], with `then` always run: with the result, or with the message
1667/// of the panic that ended `work` (already reported).
1668pub(crate) fn spawn_outcome<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static, then: impl FnOnce(Result<T, String>) + 'static) {
1669    let _ = mtm();
1670    let id = NEXT_TASK.with(|n| n.replace(n.get() + 1));
1671    CONTINUATIONS.with_borrow_mut(|c| {
1672        c.insert(
1673            id,
1674            Box::new(move |outcome: Result<Box<dyn Any + Send>, String>| {
1675                then(outcome.map(|result| *result.downcast::<T>().expect("spawned task result type")));
1676            }),
1677        )
1678    });
1679    std::thread::spawn(move || {
1680        // A panic here is caught and reported, not a crash.
1681        let outcome: Result<Box<dyn Any + Send>, String> = crash::catching(|| std::panic::catch_unwind(std::panic::AssertUnwindSafe(work)))
1682            .map(|result| Box::new(result) as Box<dyn Any + Send>)
1683            .map_err(|payload| payload.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| payload.downcast_ref::<String>().cloned()).unwrap_or_else(|| "(no message)".into()));
1684        // On the main thread the continuation (a main-thread value) is
1685        // looked up by id: it runs, and goes, however the work ended.
1686        Native::on_main(Box::new(move || {
1687            if let Err(message) = &outcome {
1688                failure::report(Failure { place: "a background task", message: message.clone(), exception: false });
1689            }
1690            if let Some(then) = CONTINUATIONS.with_borrow_mut(|c| c.remove(&id)) {
1691                batch(|| then(outcome));
1692            }
1693        }));
1694    });
1695}
1696
1697thread_local! {
1698    /// The progress signal of each job started by [`spawn_with_progress`].
1699    static PROGRESS: UiCell<HashMap<u64, Signal<Option<f64>>>> = UiCell::new(HashMap::new());
1700}
1701
1702/// What a job started by [`spawn_with_progress`] reports its progress
1703/// through, from its background thread.
1704pub struct Reporter {
1705    id: u64,
1706    /// The latest fraction's bits, and whether an update is on its way to
1707    /// the main thread (so a job reporting often posts only now and then).
1708    latest: std::sync::Arc<(std::sync::atomic::AtomicU64, std::sync::atomic::AtomicBool)>,
1709}
1710
1711impl Reporter {
1712    /// How far the job is, from 0 to 1 (clamped). Cheap to call often: the
1713    /// signal gets the latest value on the main thread's next pass.
1714    pub fn report(&self, fraction: f64) {
1715        use std::sync::atomic::Ordering;
1716        let (latest, pending) = &*self.latest;
1717        latest.store(fraction.clamp(0.0, 1.0).to_bits(), Ordering::Relaxed);
1718        if pending.swap(true, Ordering::AcqRel) {
1719            return;
1720        }
1721        let (id, shared) = (self.id, self.latest.clone());
1722        Native::on_main(Box::new(move || {
1723            let (latest, pending) = &*shared;
1724            pending.store(false, Ordering::Release);
1725            let value = f64::from_bits(latest.load(Ordering::Relaxed));
1726            if let Some(signal) = PROGRESS.with_borrow(|p| p.get(&id).copied()) {
1727                batch(|| signal.set_if_changed(Some(value)));
1728            }
1729        }));
1730    }
1731}
1732
1733/// [`spawn`] for a long job that reports how far it is: `progress` reads
1734/// `Some(0.0)` at once, the fractions `work` reports through its
1735/// [`Reporter`] as it goes, and `None` once it's done (just before `then`
1736/// runs; also if `work` panics, when `then` doesn't run). Show it with
1737/// [`progress`]:
1738///
1739/// ```no_run
1740/// # use ferrokit::*;
1741/// let done = Signal::new(None);
1742/// spawn_with_progress(&done, |r| {
1743///     for i in 0..100 {
1744///         // … a hundredth of the work …
1745///         r.report((i + 1) as f64 / 100.0);
1746///     }
1747///     42
1748/// }, |answer| println!("{answer}"));
1749/// let bar = progress(move || done.get());
1750/// ```
1751pub fn spawn_with_progress<T: Send + 'static>(progress: &Signal<Option<f64>>, work: impl FnOnce(&Reporter) -> T + Send + 'static, then: impl FnOnce(T) + 'static) {
1752    let id = NEXT_TASK.with(|n| n.replace(n.get() + 1));
1753    PROGRESS.with_borrow_mut(|p| p.insert(id, *progress));
1754    progress.set(Some(0.0));
1755    let reporter = Reporter { id, latest: std::sync::Arc::new((std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicBool::new(false))) };
1756    let signal = *progress;
1757    spawn_outcome(
1758        move || work(&reporter),
1759        move |outcome| {
1760            // Also when the work panicked: the job is over.
1761            PROGRESS.with_borrow_mut(|p| p.remove(&id));
1762            signal.set(None);
1763            if let Ok(result) = outcome {
1764                then(result);
1765            }
1766        },
1767    );
1768}
1769
1770/// The guide: how to build an app with Ferrokit, chapter by chapter. Its
1771/// examples are compiled as doc tests, so they match the API. Start with
1772/// [chapter 1](guide::ch01_getting_started); [`API.md`](https://github.com/lhassa8/ferrokit/blob/main/crates/ferrokit/API.md)
1773/// lists every public item on one page.
1774///
1775/// - [Getting started](guide::ch01_getting_started): an app, a window, a button.
1776/// - [State](guide::ch02_state): signals, memos, effects, batching, background work, async tasks.
1777/// - [Views and layout](guide::ch03_views_and_layout): stacks, grids, modifiers, lists and identity.
1778/// - [Controls and forms](guide::ch04_controls_and_forms): fields, toggles, pickers, sliders, and naming them for VoiceOver.
1779/// - [Tables, outlines and editors](guide::ch05_tables_outlines_editors): the deep widgets.
1780/// - [The app shell](guide::ch06_app_shell): menus, commands, toolbars, split views, sheets, panels, Settings, restoration and undo.
1781/// - [Live data](guide::ch07_live_data): per-frame updates and growing tables.
1782/// - [Testing and shipping](guide::ch08_testing_and_shipping): self-checks, accessibility audits, packaging and notarisation.
1783/// - [Styling](guide::ch09_styling): text styles, colours, cards, shadows, symbols and pictures.
1784/// - [Materials and windows](guide::ch10_materials_and_windows): sidebar and panel materials, Liquid Glass, title bar and toolbar styles.
1785/// - [Motion](guide::ch11_motion): animated changes, transitions, hover and click, and Reduce Motion.
1786/// - [More controls and charts](guide::ch12_more_controls_and_charts): tabs, radio groups, gauges, token fields, tooltips, and charts.
1787/// - [Web, PDF, video and services](guide::ch13_web_pdf_video_and_services): web pages, PDFs, video, Share, printing, notifications, menu-bar extras.
1788/// - [Custom native views](guide::ch14_custom_native_views): any `NSView` as a Ferrokit view (a map, a view of your own drawing).
1789/// - [Coming from egui, Iced or Slint](guide::ch15_coming_from_egui_iced_slint): how their ideas map to Ferrokit's, with one app written each way.
1790#[cfg(any(doc, doctest))]
1791pub mod guide {
1792    // The chapters' links name the crate's items.
1793    #[allow(unused_imports)]
1794    use crate::*;
1795    #[cfg(doctest)]
1796    #[doc = include_str!("../README.md")]
1797    mod readme {}
1798    #[doc = include_str!("../guide/01-getting-started.md")]
1799    pub mod ch01_getting_started {}
1800    #[doc = include_str!("../guide/02-state.md")]
1801    pub mod ch02_state {}
1802    #[doc = include_str!("../guide/03-views-and-layout.md")]
1803    pub mod ch03_views_and_layout {}
1804    #[doc = include_str!("../guide/04-controls-and-forms.md")]
1805    pub mod ch04_controls_and_forms {}
1806    #[doc = include_str!("../guide/05-tables-outlines-editors.md")]
1807    pub mod ch05_tables_outlines_editors {}
1808    #[doc = include_str!("../guide/06-app-shell.md")]
1809    pub mod ch06_app_shell {}
1810    #[doc = include_str!("../guide/07-live-data.md")]
1811    pub mod ch07_live_data {}
1812    #[doc = include_str!("../guide/08-testing-and-shipping.md")]
1813    pub mod ch08_testing_and_shipping {}
1814    #[doc = include_str!("../guide/09-styling.md")]
1815    pub mod ch09_styling {}
1816    #[doc = include_str!("../guide/10-materials-and-windows.md")]
1817    pub mod ch10_materials_and_windows {}
1818    #[doc = include_str!("../guide/11-motion.md")]
1819    pub mod ch11_motion {}
1820    #[doc = include_str!("../guide/12-more-controls-and-charts.md")]
1821    pub mod ch12_more_controls_and_charts {}
1822    #[doc = include_str!("../guide/13-web-pdf-video-and-services.md")]
1823    pub mod ch13_web_pdf_video_and_services {}
1824    #[doc = include_str!("../guide/14-custom-native-views.md")]
1825    pub mod ch14_custom_native_views {}
1826    #[doc = include_str!("../guide/15-coming-from-egui-iced-slint.md")]
1827    pub mod ch15_coming_from_egui_iced_slint {}
1828}
1829
1830thread_local! {
1831    /// Preview mode, overridden by checks (`testing::set_preview_mode`).
1832    static PREVIEW: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1833}
1834
1835/// Whether the app runs under `cargo ferrokit preview` (`FERROKIT_PREVIEW=1`):
1836/// windows keep their frames across restarts and launches don't take the
1837/// focus.
1838pub(crate) fn preview_mode() -> bool {
1839    PREVIEW.with(|p| match p.get() {
1840        Some(on) => on,
1841        None => {
1842            let on = std::env::var("FERROKIT_PREVIEW").is_ok_and(|v| v == "1");
1843            p.set(Some(on));
1844            on
1845        }
1846    })
1847}
1848
1849pub(crate) fn set_preview_mode(on: bool) {
1850    PREVIEW.with(|p| p.set(Some(on)));
1851}