Skip to main content

kui_native/
lib.rs

1//! The windowed kui runner: a winit window and a wgpu renderer around
2//! `kui_core`, with the [`App`] trait an application implements.
3//!
4//! kui is a Rust UI library whose view is a plain data tree rebuilt every
5//! frame. `kui_core` holds the model, the layout and the widgets, `kui_wgpu`
6//! draws them, and this crate puts a window around both; it is the crate
7//! most apps depend on. It re-exports all of kui-core, so `kui_native::`
8//! reaches everything, and adds the [`App`] trait, the [`app`] launcher
9//! builder, multiple windows, the clipboard, file dialogs, audio, AccessKit
10//! and a headless [`testing`] driver. `kui-derive` supplies
11//! `#[derive(Message)]`; kui-lua, kui-ffi and kui-node are bindings over the
12//! same core.
13//!
14//! # Quick start
15//!
16//! ```rust,no_run
17//! use kui_native::{App, TextStyle, Ui};
18//!
19//! struct Hello;
20//!
21//! impl App for Hello {
22//!     // Called once per frame. Everything on screen is declared here,
23//!     // from scratch, every time.
24//!     fn view(&mut self, ui: &mut Ui<'_>) {
25//!         let theme = ui.theme();
26//!         ui.text("Hello, kui", TextStyle::new(24.0).color(theme.fg));
27//!     }
28//! }
29//!
30//! fn main() -> Result<(), Box<dyn std::error::Error>> {
31//!     kui_native::app("Hello").size(360.0, 200.0).run(Hello)
32//! }
33//! ```
34//!
35//! # State and events
36//!
37//! A button carries a message. After the frame, each event it produced
38//! reaches [`App::on_event`], and [`UiEvent::message`] reads the message
39//! back as the app's own enum.
40//!
41//! ```rust,no_run
42//! use kui_native::widgets;
43//! use kui_native::{App, Message, NodeSpec, TextStyle, Ui, UiEvent};
44//!
45//! // `derive(Message)` turns each variant into plain data on the way out
46//! // and back into `Msg` on the way in.
47//! #[derive(Message, Clone, Debug, PartialEq)]
48//! enum Msg {
49//!     Inc,
50//!     Dec,
51//! }
52//!
53//! #[derive(Default)]
54//! struct Counter {
55//!     count: i64,
56//! }
57//!
58//! impl App for Counter {
59//!     fn view(&mut self, ui: &mut Ui<'_>) {
60//!         let t = ui.theme();
61//!         ui.with(NodeSpec::column().fill().center().gap(16.0).bg(t.bg), |ui| {
62//!             ui.text(&self.count.to_string(), TextStyle::new(56.0).color(t.fg));
63//!             ui.with(NodeSpec::row().gap(8.0), |ui| {
64//!                 widgets::button(ui, "-1", Msg::Dec);
65//!                 widgets::button(ui, "+1", Msg::Inc);
66//!             });
67//!         });
68//!     }
69//!
70//!     fn on_event(&mut self, ev: UiEvent) {
71//!         match ev.message::<Msg>() {
72//!             Some(Msg::Inc) => self.count += 1,
73//!             Some(Msg::Dec) => self.count -= 1,
74//!             // Not ours: a resize, a focus change, a window event.
75//!             None => {}
76//!         }
77//!     }
78//! }
79//!
80//! fn main() -> Result<(), Box<dyn std::error::Error>> {
81//!     kui_native::app("Counter").size(360.0, 240.0).run(Counter::default())
82//! }
83//! ```
84//!
85//! The book walks from here through controls, lists, the keyboard, floating
86//! windows, motion, effects and tests, one step per chapter.
87//!
88//! # Where to look
89//!
90//! - [`App`]: the trait an app implements; `view`, `on_event`, `setup`,
91//!   `teardown`.
92//! - [`app`] and [`Launcher`]: title, size, chrome, icon, extensions, then
93//!   [`Launcher::run`]; [`Launcher::open`] gives a host that owns the loop a
94//!   [`PumpRunner`] instead.
95//! - [`Ui`]: what `view` is given; [`Ui::with`], [`Ui::text`],
96//!   [`Ui::window`].
97//! - [`NodeSpec`] and [`TextStyle`]: a box's layout, look and handlers; a
98//!   text's size, font and colour.
99//! - [`widgets`]: buttons, checkboxes, text inputs, selects, sliders,
100//!   lists, tables and menus.
101//! - [`UiEvent`]: what `on_event` receives, with the readers on it.
102//! - [`testing`]: a headless driver for an `App`, for `cargo test`.
103//! - From kui-core: [`theme`], [`anim`] (transitions and springs),
104//!   [`window`] (several windows), [`message`] and [`Value`] (the payload
105//!   behind a message), [`Core`] (one window's runtime, for hosts and
106//!   tests).
107//!
108//! # Windows
109//!
110//! One event loop, any number of windows. The launcher opens the main
111//! window; a frame that declares another with [`Ui::window`] opens it on the
112//! same session and GPU device, and a frame that stops declaring it closes
113//! it. `view` runs once per open window per frame, [`Ui::window_name`] says
114//! which (`"main"` for the launcher's), and every event carries its window's
115//! [`WindowId`].
116//!
117//! # Features
118//!
119//! - `audio` (default): plays sounds through kira and cpal. Off, audio
120//!   commands are dropped and no audio library is linked (ALSA on Linux).
121//! - `accesskit` (default): exposes the access tree to screen readers
122//!   through AccessKit. Off, the tree is still built and nothing reaches
123//!   the OS.
124//! - `derive` (default): `#[derive(Message)]`. Off, messages are built and
125//!   matched as [`Value`]s by hand.
126//! - `dialogs` (default): the platform's file dialogs through rfd (the XDG
127//!   portal on Linux). Off, every dialog answers at once as cancelled.
128//! - `smoke`: honours `KUI_SMOKE_FRAMES=n`, which closes the window after
129//!   `n` frames, in a release build. A debug build honours it regardless.
130//!
131//! # Linux
132//!
133//! Building needs `pkg-config` and ALSA's headers (`libasound2-dev` on
134//! Debian and Ubuntu). A window loads the rest at run time: `libxkbcommon`
135//! (and `libxkbcommon-x11` on X11); `libX11`, `libXcursor`, `libXrandr` and
136//! `libXi` on X11 or `libwayland-client` on Wayland; `libvulkan` with a
137//! driver, or `libEGL`. A missing one fails when the window opens, naming
138//! the library. macOS and Windows need only a Rust toolchain.
139//!
140//! The book: <https://kui-book.qxuken.dev>. Repository and design records
141//! (under `docs/adr`): <https://github.com/qxuken/kui>.
142
143use std::sync::Arc;
144
145pub use kui_core::widgets;
146pub use kui_core::*;
147
148mod access_bridge;
149pub mod audio;
150mod axis_lock;
151/// What shows through the window: a blur, a tint, the desktop, or nothing.
152mod backdrop;
153mod clipboard;
154mod dialogs;
155/// The wallpaper a `Tinted` backdrop draws where the OS has no material.
156mod ground;
157mod icon;
158mod keys;
159/// A `Blur` backdrop asked of a Linux compositor.
160#[cfg(not(any(target_os = "macos", target_os = "windows")))]
161mod linux_blur;
162/// The traffic lights' keep-out and the OS titlebar's height, measured.
163#[cfg(target_os = "macos")]
164mod macos_chrome;
165/// Files dragged in from the Finder, with where they are.
166#[cfg(target_os = "macos")]
167mod macos_drop;
168#[cfg(target_os = "macos")]
169mod macos_force;
170/// A non-activating window that refuses to become key (the popup flick).
171#[cfg(target_os = "macos")]
172mod macos_key;
173/// The platform's own context menu, where there is one.
174#[cfg(target_os = "macos")]
175mod macos_menu;
176/// The documents the Finder, the Dock and `open -a` hand the app.
177#[cfg(target_os = "macos")]
178mod macos_open;
179/// The palette's and dictation's inserts, which winit's view drops.
180#[cfg(target_os = "macos")]
181mod macos_text_input;
182mod menus;
183mod pacer;
184mod pane;
185mod popups;
186mod retarget;
187mod retry;
188mod scroll_gesture;
189mod secure_input;
190pub mod testing;
191mod windows;
192
193use pane::{
194    Pane, appearance_of, apply_ime_off, ime_off_change, level_change, level_supported,
195    option_as_alt_change, sync_env, theme_appearance,
196};
197/// The OS settings winit has no call for, asked once and re-asked when the
198/// user has evidently been in a settings app.
199mod system_env;
200/// The installed fonts changing while the app runs: the platform's signal,
201/// turned into a rescan (`Core::reload_system_fonts`).
202mod system_fonts;
203#[cfg(target_os = "windows")]
204mod windows_anim;
205/// The terminal a `windows_subsystem = "windows"` app was launched from,
206/// given back to it (`attach_parent`).
207#[cfg(target_os = "windows")]
208mod windows_console;
209#[cfg(target_os = "windows")]
210mod windows_nc;
211/// The OS's light/dark switch reaching winit while the app runs.
212#[cfg(target_os = "windows")]
213mod windows_theme;
214
215use winit::application::ApplicationHandler;
216use winit::dpi::{LogicalPosition, LogicalSize};
217use winit::event::{ElementState, Ime, MouseButton as WinitButton, WindowEvent};
218use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop, EventLoopProxy};
219use winit::keyboard::{Key as WinitKey, ModifiersState, NamedKey};
220// `WindowId` is `kui_core`'s here (re-exported above); winit's own is the
221// OS handle the event loop routes by, and only this file names it.
222use winit::window::{CursorIcon, ResizeDirection, Window, WindowId as WinitWindowId};
223
224/// What a kui application implements: a `view` that declares each frame
225/// and an `on_event` that answers what the frame produced.
226///
227/// Only [`view`](Self::view) is required. Hand a value of the type to
228/// [`Launcher::run`], or to [`testing::Drive`] in a test.
229pub trait App {
230    /// Builds one window's frame. Called once per open window per frame;
231    /// `ui.window_name()` says which (`"main"` for the launcher's).
232    fn view(&mut self, ui: &mut Ui<'_>);
233    /// Receives one event the frame produced: a click's message, a key
234    /// press, a resize, a window event. Called after the frame, once per
235    /// event; [`UiEvent::message`] reads a `#[derive(Message)]` back out.
236    /// The default ignores every event.
237    fn on_event(&mut self, _ev: UiEvent) {}
238    /// [`Self::on_event`] with the [`Core`] of the window the event came
239    /// from. Override it when answering an event means calling the core:
240    /// writing the clipboard, asking for a paste, moving focus, revealing a
241    /// row, asking for a frame. A clipboard write goes out with this turn's
242    /// actions; a focus move or a reveal is seen by the next frame. The
243    /// default calls `on_event`, so an app that overrides only that one is
244    /// unchanged.
245    fn on_event_with(&mut self, ev: UiEvent, _core: &mut Core) {
246        self.on_event(ev)
247    }
248    /// Called once, before the window opens, with a [`Waker`] the app may
249    /// clone into any thread. The loop parks between events, so a thread
250    /// that changed what `view` will show (a PTY reader, a file watcher, a
251    /// socket) calls [`Waker::wake`] to get a frame drawn. The default
252    /// drops the waker.
253    fn setup(&mut self, _waker: Waker) {}
254    /// Called once, when the main window is going for good (its close
255    /// button, Quit, `WindowCommand::Close` on it, a pumped runner ending),
256    /// before `run` returns. Save a session, a draft or a position here;
257    /// the frame is over, there is no `Ui` and nothing draws. A crash under
258    /// `run` does not reach it; a panic unwinding through a [`PumpRunner`]
259    /// does, and a `teardown` that panics there aborts. The default does
260    /// nothing.
261    fn teardown(&mut self) {}
262}
263
264/// A handle into the event loop that any thread may hold; [`Waker::wake`]
265/// asks for a frame from wherever the app's data arrived. Cheap to clone,
266/// and harmless after the loop has ended (a wake nobody hears is dropped).
267/// An app gets one in [`App::setup`], a host from [`PumpRunner::waker`].
268#[derive(Clone)]
269pub struct Waker(EventLoopProxy<access_bridge::UserEvent>);
270
271impl Waker {
272    /// Asks every window for a frame: the loop wakes, `view` runs and the
273    /// frame is drawn. Safe from any thread and at any rate, since wakes
274    /// coalesce into the loop's next turn rather than queueing frames.
275    pub fn wake(&self) {
276        let _ = self.0.send_event(access_bridge::UserEvent::Wake);
277    }
278}
279
280impl std::fmt::Debug for Waker {
281    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282        f.write_str("Waker")
283    }
284}
285
286/// Who draws the window chrome.
287#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
288pub enum Chrome {
289    /// The OS titlebar and buttons (the default).
290    #[default]
291    Native,
292    /// The app draws its own titlebar (`widgets::titlebar`). On macOS the
293    /// native traffic lights stay, overlaid on the content (their rect is
294    /// reported in `env.window.native_controls`); elsewhere the window is
295    /// undecorated and the runner synthesizes edge resizing, double-click
296    /// maximize, and applies the `WindowCommand`s chrome nodes produce.
297    Custom,
298    /// No decorations and no chrome expectations (splash screens, popups).
299    Borderless,
300}
301
302/// How outline glyphs are antialiased.
303#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
304pub enum TextAa {
305    /// LCD subpixel coverage when the GPU can blend per channel, grayscale
306    /// otherwise (the default). `KUI_TEXT_AA=gray|subpixel` overrides.
307    #[default]
308    Auto,
309    Grayscale,
310    Subpixel,
311}
312
313/// Starts a [`Launcher`] for a window titled `title`.
314///
315/// Chain the window's options, then [`Launcher::run`]:
316///
317/// ```rust,no_run
318/// # use kui_native::{App, Ui};
319/// # struct Mine;
320/// # impl App for Mine { fn view(&mut self, _ui: &mut Ui<'_>) {} }
321/// kui_native::app("Mine")
322///     .size(800.0, 600.0)
323///     .min_size(320.0, 240.0)
324///     .devtools(true)
325///     .run(Mine)
326///     .unwrap();
327/// ```
328///
329/// The default window is 960 by 640 logical pixels with the OS's own
330/// chrome. `KUI_WINDOW=WxH` in the environment overrides the size.
331pub fn app(title: &str) -> Launcher {
332    Launcher {
333        title: title.to_string(),
334        chrome: Chrome::Native,
335        size: (960.0, 640.0),
336        min_size: None,
337        max_size: None,
338        extensions: Extensions::new(),
339        text_aa: TextAa::Auto,
340        diagnostics: None,
341        core: None,
342        setup_core: Vec::new(),
343        deferred_events: false,
344        system: SystemEnv::default(),
345        icon: None,
346        icon_resource: None,
347        frame_latency: kui_wgpu::DEFAULT_FRAME_LATENCY,
348        backdrop: Backdrop::Opaque,
349    }
350}
351
352/// One [`Launcher::setup_core`] step.
353type CoreSetup = Box<dyn FnOnce(&mut Core)>;
354
355/// The windowed runner's builder, made by [`app`].
356///
357/// Every method takes and returns the launcher; [`Launcher::run`] opens the
358/// window and runs the event loop, [`Launcher::open`] opens it and hands the
359/// loop back as a [`PumpRunner`].
360pub struct Launcher {
361    title: String,
362    chrome: Chrome,
363    size: (f64, f64),
364    /// Inner-size bounds (logical px) handed to the OS, which enforces them
365    /// for user resizing; `None` leaves that side unbounded.
366    min_size: Option<(f64, f64)>,
367    max_size: Option<(f64, f64)>,
368    extensions: Extensions,
369    text_aa: TextAa,
370    /// The main window's core, when the host made it ahead
371    /// ([`Launcher::core`]); the launcher makes one otherwise.
372    core: Option<Core>,
373    /// What to do to the main core before its first frame
374    /// ([`Launcher::setup_core`]).
375    setup_core: Vec<CoreSetup>,
376    /// Whether the core's diagnostics run (see `kui_core::diag`); None =
377    /// on in debug builds, off in release.
378    diagnostics: Option<bool>,
379    /// Whether the host answers events after the loop has handed them over
380    /// (see [`Launcher::deferred_events`]).
381    deferred_events: bool,
382    /// The OS settings the app pinned ([`Launcher::system`]); unknown is
383    /// not pinned.
384    system: SystemEnv,
385    /// The windows' icon ([`Launcher::icon`]), checked when it was given.
386    icon: Option<winit::window::Icon>,
387    /// The executable's icon resource on Windows
388    /// ([`Launcher::icon_resource`]).
389    icon_resource: Option<u16>,
390    /// Frames queued ahead of the one on screen
391    /// ([`Launcher::frame_latency`]).
392    frame_latency: u32,
393    /// What shows through the app's windows ([`Launcher::backdrop`]).
394    backdrop: Backdrop,
395}
396
397impl Launcher {
398    /// Who draws the window chrome; see [`Chrome`]. The OS by default.
399    pub fn chrome(mut self, chrome: Chrome) -> Self {
400        self.chrome = chrome;
401        self
402    }
403
404    /// Glyph antialiasing; see [`TextAa`].
405    pub fn text_aa(mut self, aa: TextAa) -> Self {
406        self.text_aa = aa;
407        self
408    }
409
410    /// How many frames may be queued ahead of the one on screen, for every
411    /// window. Two by default ([`kui_wgpu::DEFAULT_FRAME_LATENCY`]), which
412    /// keeps every vsync fed at light load; one on Windows, where one
413    /// already does. On macOS 14+ frames are paced to the display, so the
414    /// second queued frame costs no latency; on Linux and under a pumped
415    /// runner it reaches the screen one vsync later. `KUI_FRAME_LATENCY`
416    /// overrides the value and `KUI_FRAME_PACING=0` turns the pacing off.
417    /// Values below one are one.
418    pub fn frame_latency(mut self, frames: u32) -> Self {
419        self.frame_latency = frames.max(1);
420        self
421    }
422
423    /// Whether the core looks for silent misconfigurations and the runner
424    /// prints them to stderr (see [`diag`]). On in debug builds and off in
425    /// release unless set, so a shipped app stays quiet.
426    pub fn diagnostics(mut self, on: bool) -> Self {
427        self.diagnostics = Some(on);
428        self
429    }
430
431    /// Opens the app with the devtools panel docked beside it: the event
432    /// stream, the runtime's facts and the node tree. `KUI_DEVTOOLS=1` in
433    /// the environment asks the same of an app that never called this.
434    /// Sugar for `setup_core(|c| c.set_devtools(on))`.
435    pub fn devtools(self, on: bool) -> Self {
436        self.setup_core(move |core| core.set_devtools(on))
437    }
438
439    /// Respells the chord that moves the keyboard into the devtools panel
440    /// and back, and brings a hidden panel back, from its default
441    /// `Ctrl+Shift+I`: `Accel::parse("f12")`, `"mod+shift+d"`, any spelling
442    /// a menu item takes. The panel's other chords stay
443    /// `Ctrl+Shift+<letter>`, and `Ctrl+Shift+I` is the app's again. Sugar
444    /// for `setup_core(|c| c.set_devtools_key(key))`.
445    pub fn devtools_key(self, key: Accel) -> Self {
446        self.setup_core(move |core| core.set_devtools_key(key))
447    }
448
449    /// Runs `f` on the main window's [`Core`] before its first frame: the
450    /// place for what a core is told rather than declared in a view, such
451    /// as a pinned theme, `set_native_menus` or the devtools. Every call
452    /// adds one; they run in order.
453    pub fn setup_core(mut self, f: impl FnOnce(&mut Core) + 'static) -> Self {
454        self.setup_core.push(Box::new(f));
455        self
456    }
457
458    /// Opens the main window on `core` rather than on one the launcher
459    /// makes. Everything registered on it beforehand (fonts, images,
460    /// sounds, tokens, a pinned theme, menus) reaches the window, and its
461    /// session becomes the app's, so a second window joins it and handles
462    /// minted by an earlier headless frame keep drawing. The launcher's own
463    /// settings still apply on top, in order: [`Launcher::diagnostics`],
464    /// then `KUI_DEVTOOLS`, then every [`Launcher::setup_core`]. For a host
465    /// that drew headless first, or built the core through a binding.
466    pub fn core(mut self, core: Core) -> Self {
467        self.core = Some(core);
468        self
469    }
470
471    /// Declares that the app answers an event after `on_event` returns,
472    /// which only a host driving the loop itself can do ([`Launcher::open`],
473    /// [`PumpRunner`]): `on_event` keeps the event, the pump returns, the
474    /// host runs its handler and submits the next view.
475    ///
476    /// With it set, an input whose events reached the app does not ask for
477    /// a frame itself; the host asks with [`PumpRunner::request_redraw`]
478    /// once its handler has run, so a button's release and what the release
479    /// did land in one frame instead of two. Nothing else changes: a
480    /// transition, a caret blink, a [`Waker`] wake or the OS's own repaint
481    /// still paint when they ask, and an input that reached nobody still
482    /// asks for its own frame.
483    pub fn deferred_events(mut self) -> Self {
484        self.deferred_events = true;
485        self
486    }
487
488    /// Pins part of `env.system` for this app's windows. Every field of
489    /// `pinned` that is not "cannot tell" is what the views read, over
490    /// whatever the OS says, for as long as the app runs; the fields left
491    /// at their default keep following the OS, and a change to one of
492    /// those still arrives as the `system` event.
493    ///
494    /// ```rust,no_run
495    /// # use kui_native::{SystemEnv, MotionPref};
496    /// kui_native::app("mine").system(SystemEnv { motion: MotionPref::Reduced, ..Default::default() });
497    /// ```
498    ///
499    /// Use it to see the window a user who asked for less motion, or a
500    /// dark appearance, would get. It is on the launcher rather than an
501    /// environment variable so that a shipped app's motion is decided in
502    /// its own code; a headless core takes the same reading through
503    /// `core.env.system`.
504    pub fn system(mut self, pinned: SystemEnv) -> Self {
505        self.system = pinned;
506        self
507    }
508
509    /// The icon every window of the app is created with: `rgba` is
510    /// `width` by `height` pixels, four bytes each, row by row from the top
511    /// left, alpha not premultiplied. Windows shows it in the title bar,
512    /// Alt-Tab and the taskbar, X11 in the window manager's; macOS and
513    /// Wayland take the app's icon from the bundle or the `.desktop` file
514    /// and ignore this. Pass something a taskbar can shrink cleanly, 64 to
515    /// 256 px. Panics when the pixels are not that size;
516    /// [`Launcher::try_icon`] returns the reason instead.
517    ///
518    /// ```rust,no_run
519    /// # let rgba = vec![0u8; 64 * 64 * 4];
520    /// kui_native::app("mine").icon(rgba, 64, 64);
521    /// ```
522    ///
523    /// On Windows, [`Launcher::icon_resource`] names the icon linked into
524    /// the executable and wins over these pixels.
525    pub fn icon(self, rgba: Vec<u8>, width: u32, height: u32) -> Self {
526        match self.try_icon(rgba, width, height) {
527            Ok(this) => this,
528            Err(e) => panic!("kui: {e}"),
529        }
530    }
531
532    /// [`Launcher::icon`] for pixels that came from outside the program,
533    /// refused with the reason rather than a panic. The launcher is
534    /// consumed either way.
535    pub fn try_icon(mut self, rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, String> {
536        self.icon = Some(icon::from_rgba(rgba, width, height)?);
537        Ok(self)
538    }
539
540    /// The executable's icon resource `id` as every window's icon, on
541    /// Windows: the `.ico` a `1 ICON "app.ico"` line in the program's `.rc`
542    /// links in, from which the title bar and the taskbar each load the
543    /// frame drawn for their size. A resource the executable does not have
544    /// is reported once on stderr, and [`Launcher::icon`]'s pixels are used
545    /// if there are any. Nothing on other platforms, so an app passes both
546    /// and each OS takes its own.
547    pub fn icon_resource(mut self, id: u16) -> Self {
548        self.icon_resource = Some(id);
549        self
550    }
551
552    /// What shows through the app's windows where a frame paints nothing,
553    /// or paints with alpha (backlog F126), by effect: `Transparent` (the
554    /// desktop as it is), `Blur` (a live blur of what is behind the
555    /// window), `Tinted` (the desktop's colour, steady). `Backdrop::Opaque`,
556    /// the default, is the window every app had before. Which regions show
557    /// it is the app's: paint them with alpha and the rest opaque.
558    ///
559    /// ```rust,no_run
560    /// # use kui_native::{App, Backdrop, Ui};
561    /// # struct Notes;
562    /// # impl App for Notes { fn view(&mut self, _ui: &mut Ui<'_>) {} }
563    /// kui_native::app("Notes")
564    ///     .custom_titlebar()
565    ///     .backdrop(Backdrop::Blur)
566    ///     .run(Notes)
567    ///     .unwrap();
568    /// ```
569    ///
570    /// How each platform gives it:
571    ///
572    /// | | `Blur` | `Tinted` |
573    /// |---|---|---|
574    /// | macOS | `NSVisualEffectView`, behind-window (the sidebar material) | `NSVisualEffectView`, the window-background material |
575    /// | Windows 11 22H2+ | Acrylic | Mica |
576    /// | KDE Plasma | the compositor's blur (`ext-background-effect-v1`, `org_kde_kwin_blur`, `_KDE_NET_WM_BLUR_BEHIND_REGION`) | the wallpaper, drawn by kui |
577    /// | GNOME, other Linux, Windows 10 | the wallpaper, drawn by kui (reads `Tinted`) | the wallpaper, drawn by kui |
578    ///
579    /// "The wallpaper, drawn by kui" is the desktop's picture — GNOME's
580    /// `picture-uri` (or `-dark`), Plasma's config, Windows'
581    /// `SPI_GETDESKWALLPAPER` — read on a thread, scaled down and blurred
582    /// once, and drawn under the frame aligned to where the window sits on
583    /// its monitor (centred on Wayland, which does not say); with no
584    /// wallpaper to read, the window is opaque. Hyprland, SwayFX and picom
585    /// blur translucent windows themselves when configured to: ask for
586    /// `Transparent` there. `KUI_BACKDROP_EMULATE=1` draws the wallpaper
587    /// for `Blur` and `Tinted` on Windows and Linux, to look at it (macOS
588    /// reads no wallpaper, so the window there is `Opaque`).
589    ///
590    /// Asking changes three things. Where the OS draws the effect the
591    /// frame is cleared to nothing rather than to the theme's `bg`, so what
592    /// a view paints is all that sits over it: a region with a translucent
593    /// `bg` (`theme.bg.with_alpha(0.6)`) shows the effect through it, and a
594    /// region with an opaque `bg` does not. Glyphs are antialiased in
595    /// grayscale under `TextAa::Auto`, since an LCD mask cannot be
596    /// composited over what the window cannot see. And on Windows the
597    /// device presents through DirectComposition, the one D3D12 swapchain
598    /// that takes alpha.
599    ///
600    /// What the platform gave is `ui.env().window.backdrop`, every frame,
601    /// and is what a view decides by — less where the platform has less
602    /// (a `Blur` asked of GNOME reads `Tinted`, or `Opaque` with no
603    /// wallpaper). Paint the translucent regions opaque when it reads
604    /// `Opaque`:
605    ///
606    /// ```rust
607    /// # use kui_native::{Backdrop, Color, Env};
608    /// fn pane_bg(env: &Env, base: Color) -> Color {
609    ///     match env.window.backdrop {
610    ///         Backdrop::Opaque => base,
611    ///         // The desktop unblurred: text over it is a lottery.
612    ///         Backdrop::Transparent => base.with_alpha(0.92),
613    ///         Backdrop::Blur | Backdrop::Tinted => base.with_alpha(0.55),
614    ///     }
615    /// }
616    /// # let _ = pane_bg(&Env::default(), Color::hex(0x202020ff));
617    /// ```
618    ///
619    /// It applies to the main window and to every window the app's frames
620    /// declare (`Ui::window`) — not to a popup, which is a menu surface,
621    /// nor to the devtools' window.
622    pub fn backdrop(mut self, backdrop: Backdrop) -> Self {
623        self.backdrop = backdrop;
624        self
625    }
626
627    /// Shorthand for `.chrome(Chrome::Custom)`.
628    pub fn custom_titlebar(self) -> Self {
629        self.chrome(Chrome::Custom)
630    }
631
632    /// Shorthand for `.chrome(Chrome::Borderless)`.
633    pub fn borderless(self) -> Self {
634        self.chrome(Chrome::Borderless)
635    }
636
637    /// Initial inner size, logical px (`KUI_WINDOW=WxH` still overrides).
638    /// Clamped into the `min_size`/`max_size` bounds, as the OS would.
639    pub fn size(mut self, w: f64, h: f64) -> Self {
640        self.size = (w, h);
641        self
642    }
643
644    /// Smallest inner size the user may resize the window to, logical px.
645    /// The OS enforces it; the initial size is clamped up into it.
646    pub fn min_size(mut self, w: f64, h: f64) -> Self {
647        self.min_size = Some((w, h));
648        self
649    }
650
651    /// Largest inner size the user may resize the window to, logical px.
652    /// A bound below the matching `min_size` loses to it, as on the OS side.
653    pub fn max_size(mut self, w: f64, h: f64) -> Self {
654        self.max_size = Some((w, h));
655        self
656    }
657
658    /// Loads `ext` under its own name as its namespace. The slots it fills
659    /// are declared as `ui.slot("<name>/<slot>")`. Panics when the name is
660    /// already another extension's namespace; two of one name need
661    /// [`Launcher::extension_as`].
662    pub fn extension(self, ext: impl Extension + 'static) -> Self {
663        let ns = ext.name().to_owned();
664        self.extension_as(ns, ext)
665    }
666
667    /// Loads `ext` under `namespace`, so the same extension loaded twice is
668    /// two namespaces with two sets of slots and params. Panics on a
669    /// namespace already taken, an empty one, or an extension whose slot
670    /// names contain `/`.
671    pub fn extension_as(self, namespace: impl Into<String>, ext: impl Extension + 'static) -> Self {
672        match self.try_extension_as(namespace, ext) {
673            Ok(this) => this,
674            Err(e) => panic!("kui: {e}"),
675        }
676    }
677
678    /// [`Launcher::extension_as`] for a caller that reports the refusal
679    /// rather than panicking, such as a plugin named from outside the
680    /// program. The launcher is consumed either way.
681    pub fn try_extension_as(
682        mut self,
683        namespace: impl Into<String>,
684        ext: impl Extension + 'static,
685    ) -> Result<Self, String> {
686        self.extensions.push_as(namespace, Box::new(ext))?;
687        Ok(self)
688    }
689
690    /// Takes an [`Extensions`] list already loaded, replacing any
691    /// `extension` calls before it. For a host that built the list
692    /// elsewhere, as the C binding does.
693    pub fn with_extensions(mut self, extensions: Extensions) -> Self {
694        self.extensions = extensions;
695        self
696    }
697
698    /// [`Launcher::extension`] for each, in order.
699    pub fn extensions(mut self, exts: Vec<Box<dyn Extension>>) -> Self {
700        for ext in exts {
701            if let Err(e) = self.extensions.push(ext) {
702                panic!("kui: {e}");
703            }
704        }
705        self
706    }
707
708    /// The shell for `app`, boxed: the one generic step between an app
709    /// and the runner, kept to moving fields. Everything after it
710    /// takes the box unsized, as a [`DynShell`].
711    fn shell<A: App>(mut self, app: A) -> Box<Shell<A>> {
712        let (diagnostics, session, core) = self.main_core();
713        Box::new(Shell {
714            title: self.title,
715            icon: icon::AppIcon::new(self.icon, self.icon_resource),
716            chrome: self.chrome,
717            size: clamp_size(self.size, self.min_size, self.max_size),
718            min_size: self.min_size,
719            max_size: self.max_size,
720            text_aa: self.text_aa,
721            frame_latency: wanted_frame_latency(self.frame_latency),
722            backdrop: self.backdrop,
723            diagnostics,
724            subpixel: false,
725            extensions: self.extensions,
726            session,
727            main_core: Some(core),
728            panes: Vec::new(),
729            gpu: None,
730            reopened: None,
731            reopen_owed: false,
732            pretended_loss: false,
733            locks: kui_core::KeyLocks::default(),
734            script: kui_core::LayoutScript::default(),
735            epoch: std::time::Instant::now(),
736            system: system_env::query(),
737            pinned_system: self.system,
738            clipboard: arboard::Clipboard::new().ok(),
739            #[cfg(target_os = "macos")]
740            native_menu: macos_menu::MacMenu::new(),
741            #[cfg(target_os = "macos")]
742            menu_shown: false,
743            #[cfg(target_os = "macos")]
744            native_menu_bar: macos_menu::MacMenuBar::new(),
745            #[cfg(target_os = "macos")]
746            applied_menu_bar: None,
747            audio: audio::Audio::new(),
748            audio_touch: std::time::Instant::now(),
749            smoke_frames: Self::smoke_frames(),
750            frames_drawn: 0,
751            exit_requested: false,
752            startup_error: None,
753            torn_down: false,
754            secure_input: secure_input::SecureInput::default(),
755            pumped: false,
756            opened: false,
757            primary_down: None,
758            armed: Vec::new(),
759            swallowed_press: None,
760            proxy: None,
761            next_deadline: None,
762            saw_event: false,
763            woke: false,
764            deferred_events: self.deferred_events,
765            owed: std::cell::Cell::new(false),
766            app,
767        })
768    }
769
770    /// A shell as the runner sees it, for the tests.
771    #[cfg(test)]
772    fn dyn_shell<A: App + 'static>(self, app: A) -> Box<DynShell<'static>> {
773        self.shell(app)
774    }
775
776    /// Whether diagnostics are on, the session, and the main window's core
777    /// with the launcher's setup applied — the part of `shell` that does
778    /// not need the app's type.
779    fn main_core(&mut self) -> (bool, Session, Core) {
780        // Before anything prints: a windows-subsystem app started from a
781        // shell has no stdout until it takes its parent's, and the
782        // diagnostics, the panics and `report_faults` are all worth
783        // reading there (`mod windows_console`).
784        #[cfg(target_os = "windows")]
785        windows_console::attach_parent();
786        // Diagnostics are a development aid: on in debug builds unless the
787        // launcher says otherwise, so a shipped app pays and prints nothing.
788        let diagnostics = self.diagnostics.unwrap_or(cfg!(debug_assertions));
789        // A handed core brings its session; a made one gets a fresh one.
790        let (session, mut core) = match self.core.take() {
791            Some(core) => (core.session().clone(), core),
792            None => {
793                let session = Session::new();
794                let core = Core::new_in(&session);
795                (session, core)
796            }
797        };
798        core.set_diagnostics(diagnostics);
799        // `KUI_DEVTOOLS=1` opens the panel for a program that never asked
800        // (ADR 0024); read here, for a window, and never by a headless
801        // core. What the launcher was told comes after, and wins.
802        core.devtools_from_env();
803        for f in std::mem::take(&mut self.setup_core) {
804            f(&mut core);
805        }
806        (diagnostics, session, core)
807    }
808
809    /// `KUI_SMOKE_FRAMES=n`, in a build that honours it.
810    ///
811    /// A development aid, gated the way `shell` gates the diagnostics: an app you
812    /// ship should not close its own window because something in the
813    /// environment it was launched from happened to set a variable, and
814    /// the app's author never asked for that behaviour. Live in a dev
815    /// build, which is where it is used by hand (`KUI_SMOKE_FRAMES=120
816    /// cargo run --example fragment`), and in a release build that asks
817    /// for it with `--features smoke` — which is what
818    /// the smoke round passes under `--release`
819    /// (examples/devtools/src/bin/smoke.rs), and
820    /// the whole reason this is a feature rather than `debug_assertions`
821    /// alone: the round is worth running against what actually ships.
822    fn smoke_frames() -> Option<u32> {
823        if !(cfg!(debug_assertions) || cfg!(feature = "smoke")) {
824            return None;
825        }
826        std::env::var("KUI_SMOKE_FRAMES")
827            .ok()
828            .and_then(|s| s.parse().ok())
829    }
830
831    /// Opens the main window and runs the event loop until the main window
832    /// closes. Returns `Ok` then, or the error when the window or its
833    /// renderer could not be made. One event loop per process: a process
834    /// that has used [`Launcher::open`] opens again rather than calling
835    /// `run`.
836    pub fn run<A: App>(self, app: A) -> Result<(), Box<dyn std::error::Error>> {
837        let event_loop = run_loop()?;
838        run_shell(event_loop, self.shell(app))
839    }
840
841    /// Opens the window but keeps the event loop in the caller's hands: the
842    /// returned [`PumpRunner`] processes OS events only when
843    /// [`PumpRunner::pump`] is called, so a foreign loop (libuv, a game
844    /// loop, a test harness) can interleave with winit on the main thread.
845    /// winit allows one event loop per process, but any number of runners
846    /// in turn: a runner whose main window has closed parks the loop, and
847    /// the next `open` on the thread takes it back.
848    pub fn open<A: App>(self, app: A) -> Result<PumpRunner<A>, Box<dyn std::error::Error>> {
849        let event_loop = take_event_loop()?;
850        let mut shell = self.shell(app);
851        let state = PumpState::open(event_loop, &mut *shell);
852        let mut runner = PumpRunner {
853            state,
854            shell: std::mem::ManuallyDrop::new(shell),
855        };
856        if !runner.state.alive {
857            runner.retire();
858        }
859        // Retired above, so the loop is parked and the next `open` can
860        // try again (backlog RG47).
861        if let Some(why) = runner.shell.startup_error.take() {
862            return Err(why.into());
863        }
864        Ok(runner)
865    }
866}
867
868/// The event loop `run` owns. Not a parked loop: a pumped runner leaves
869/// winit's loop *running* (it never exits it — see `PARKED_LOOP`), and
870/// `run_app` on a running loop is a `debug_assert` in winit's macOS path.
871/// `run` is the one-shot runner; a process that has pumped opens again.
872fn run_loop() -> Result<EventLoop<access_bridge::UserEvent>, Box<dyn std::error::Error>> {
873    if PARKED_LOOP.with(|p| p.borrow().is_some()) {
874        return Err(
875            "kui: `run` cannot follow a pumped runner in this process — a loop \
876                    a `PumpRunner` parked is still running; open another `PumpRunner`"
877                .into(),
878        );
879    }
880    Ok(EventLoop::<access_bridge::UserEvent>::with_user_event().build()?)
881}
882
883/// `Launcher::run` past the one generic step: compiled here, once.
884fn run_shell(
885    event_loop: EventLoop<access_bridge::UserEvent>,
886    mut shell: Box<DynShell<'_>>,
887) -> Result<(), Box<dyn std::error::Error>> {
888    event_loop.set_control_flow(ControlFlow::Wait);
889    shell.attach(&event_loop);
890    event_loop.run_app(&mut Handler(&mut shell))?;
891    match shell.startup_error.take() {
892        Some(why) => Err(why.into()),
893        None => Ok(()),
894    }
895}
896
897impl DynShell<'_> {
898    /// The main window, or its renderer, could not be made: `why` becomes
899    /// the error `run` or `open` returns, and the runner ends. `run`'s
900    /// loop is asked to exit; a pumped one is not — it is parked for the
901    /// next runner, as when a window closes.
902    fn fail_open(&mut self, event_loop: &ActiveEventLoop, why: String) {
903        self.startup_error = Some(why);
904        self.exit_requested = true;
905        if !self.pumped {
906            event_loop.exit();
907        }
908    }
909
910    /// What a shell takes from the loop it runs on before the first
911    /// event: the proxy, the app's waker, and the wakers of the platform
912    /// paths no winit event carries.
913    fn attach(&mut self, event_loop: &EventLoop<access_bridge::UserEvent>) {
914        self.proxy = Some(event_loop.create_proxy());
915        self.app.setup(Waker(event_loop.create_proxy()));
916        // A menu-bar item chosen by its ⌘-shortcut is the whole of the
917        // event as far as winit is concerned — AppKit consumed the key —
918        // so the bar rings the loop itself.
919        #[cfg(target_os = "macos")]
920        if let Some(bar) = &self.native_menu_bar {
921            bar.set_waker(Waker(event_loop.create_proxy()));
922        }
923        // And so does an insert the platform makes from the palette or
924        // dictation: no winit event carries it.
925        #[cfg(target_os = "macos")]
926        macos_text_input::set_waker(Waker(event_loop.create_proxy()));
927        // And a file drag's position (ADR 0031), which winit's do not.
928        #[cfg(target_os = "macos")]
929        macos_drop::set_waker(Waker(event_loop.create_proxy()));
930        // And the documents the OS asks the app to open (backlog F124),
931        // which winit's application delegate does not answer: installed
932        // here, before `run_app` launches the app, since the launch-time
933        // ones come inside `finishLaunching`.
934        #[cfg(target_os = "macos")]
935        {
936            macos_open::set_waker(Waker(event_loop.create_proxy()));
937            macos_open::install();
938        }
939        // And the installed fonts changing, which winit has no event for.
940        system_fonts::watch(event_loop.create_proxy());
941    }
942}
943
944thread_local! {
945    /// The process's one event loop, parked between runners. winit refuses
946    /// to build a second (`EventLoopError::RecreationAttempt`, a static
947    /// flag it never clears), so a host that opens a window, closes it
948    /// and opens another — a smoke test running two configurations in
949    /// sequence, an app whose second launch is in-process — needs the
950    /// first runner to hand the loop back rather than drop it. The pump
951    /// path never calls winit's `exit()` for the same reason: an exited
952    /// loop answers every later pump with `Exit` and nothing public clears
953    /// that; the runner ends itself on `exit_requested` instead, and the
954    /// loop stays live for the next shell.
955    static PARKED_LOOP: std::cell::RefCell<Option<EventLoop<access_bridge::UserEvent>>> =
956        const { std::cell::RefCell::new(None) };
957}
958
959/// The parked loop if an earlier runner left one, else a new one — which
960/// winit allows once per process. For `open` only: `run` builds its own
961/// (above), since a parked loop is a running one.
962fn take_event_loop() -> Result<EventLoop<access_bridge::UserEvent>, winit::error::EventLoopError> {
963    if let Some(parked) = PARKED_LOOP.with(|p| p.borrow_mut().take()) {
964        return Ok(parked);
965    }
966    EventLoop::<access_bridge::UserEvent>::with_user_event().build()
967}
968
969/// Whether this input is one whose own visible effect is finished, so the
970/// app's answer to it belongs in the same frame.
971///
972/// A press or a release changes what the core itself paints — the button
973/// goes down, the button comes up — and that change reads as the whole of
974/// what happened, so a frame showing the button let go with the count
975/// unchanged is a frame that lies. A keystroke, an IME commit and an
976/// assistive-technology action are discrete the same way.
977///
978/// A pointer moving, a wheel turning and a preedit being revised are not:
979/// they arrive as a stream, every frame during one is superseded by the
980/// next, and an app's content trailing the pointer by a frame is what
981/// every toolkit does. Waiting on those would halve the frame rate of a
982/// drag for nothing — measured at 18 frames against 36 in a 578 ms drag —
983/// so they never wait.
984/// Puts a copy on the system clipboard, with the formatting beside the
985/// words where there is any.
986///
987/// Both flavours or neither: `set_html` writes the HTML *and* the plain
988/// text it is given as an alternative, so an app that understands one
989/// takes it and everything else takes the words. A clipboard holding only
990/// HTML pastes markup into every plain-text field on the machine, which is
991/// the failure mode this shape exists to avoid.
992fn set_clipboard(clipboard: Option<&mut arboard::Clipboard>, text: String, html: Option<String>) {
993    let Some(cb) = clipboard else { return };
994    match html {
995        Some(html) => {
996            let _ = cb.set_html(html, Some(text));
997        }
998        None => {
999            let _ = cb.set_text(text);
1000        }
1001    }
1002}
1003
1004fn input_completes(ev: &InputEvent) -> bool {
1005    match ev {
1006        InputEvent::MouseDown { .. }
1007        | InputEvent::MouseUp { .. }
1008        // A force click is one moment and one answer, like a press.
1009        | InputEvent::ForceClick(_)
1010        | InputEvent::Key(..)
1011        | InputEvent::KeyDown(_)
1012        | InputEvent::KeyUp(_)
1013        | InputEvent::Text(_)
1014        | InputEvent::Commit(_)
1015        | InputEvent::Paste { .. }
1016        | InputEvent::Access(_)
1017        // A drop is a release; a cancel ends the drag the same way.
1018        | InputEvent::DropFiles { .. }
1019        | InputEvent::DragCancel
1020        // A dialog's answer is one moment, as a paste is, and so are the
1021        // documents the OS hands over.
1022        | InputEvent::Files(_)
1023        | InputEvent::Open(_) => true,
1024        InputEvent::CursorMoved(_)
1025        | InputEvent::CursorLeft
1026        | InputEvent::Scroll(_)
1027        | InputEvent::ScrollGesture { .. }
1028        | InputEvent::Preedit(..)
1029        | InputEvent::Modifiers(_)
1030        // Files moving over the window is the pointer moving.
1031        | InputEvent::DragFiles { .. } => false,
1032    }
1033}
1034
1035/// Whether a redraw waits for the host's answer instead of painting now.
1036///
1037/// Two conditions, and the second is the one that makes this safe. `owed`
1038/// says an input reached an app that answers later, so what would be
1039/// painted predates that input ([`Launcher::deferred_events`]).
1040/// `deferred_last` says this window's previous redraw already waited — and
1041/// a frame never waits twice running.
1042///
1043/// That bound is not a nicety. Waiting until the host says otherwise is
1044/// the obvious rule and it starves the window: winit hands a pump its
1045/// input before that pump's redraw, so under a stream of input that
1046/// reaches the app — a drag, an auto-repeating key — each pump re-arms the
1047/// wait before the frame the host just asked for is delivered, and the
1048/// window paints **nothing** until the stream ends (measured: one frame in
1049/// a 578 ms drag). The same unbounded rule freezes a window for a whole
1050/// title-bar drag, since a platform's modal move loop never returns to the
1051/// host that would end the wait. Never twice running costs at worst half
1052/// the frame rate under continuous input, and bounds every one of those to
1053/// a single frame.
1054fn frame_waits_for_host(owed: bool, deferred_last: bool) -> bool {
1055    owed && !deferred_last
1056}
1057
1058fn pump_once(
1059    event_loop: &mut EventLoop<access_bridge::UserEvent>,
1060    shell: &mut DynShell<'_>,
1061) -> bool {
1062    use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
1063    match event_loop.pump_app_events(Some(std::time::Duration::ZERO), &mut Handler(shell)) {
1064        PumpStatus::Continue => !shell.exit_requested,
1065        PumpStatus::Exit(_) => false,
1066    }
1067}
1068
1069/// A windowed runner driven from outside, from [`Launcher::open`]: the
1070/// same runner as [`Launcher::run`] (input mapping, IME, clipboard, chrome,
1071/// caret blink), but the host calls [`pump`](Self::pump) or
1072/// [`pump_until`](Self::pump_until) on its own cadence instead of parking
1073/// in the event loop.
1074///
1075/// Ask [`next_deadline`](Self::next_deadline) after each pump for how long
1076/// to sleep, and [`request_redraw`](Self::request_redraw) after changing
1077/// what `view` will produce. The runner ends when the main window closes;
1078/// dropping it earlier closes the windows and parks the loop for the next
1079/// `open`.
1080pub struct PumpRunner<A: App> {
1081    state: PumpState,
1082    /// Dropped by hand, unsized (`drop_shell`): as a plain field its drop
1083    /// glue — every window, core and store the shell owns — was generated
1084    /// in the app's crate.
1085    shell: std::mem::ManuallyDrop<Box<Shell<A>>>,
1086}
1087
1088/// What a [`PumpRunner`] keeps beside its shell, and does to it, without
1089/// its app's type.
1090struct PumpState {
1091    /// `None` once the runner has retired: the loop is parked for the next
1092    /// runner on this thread (see `PARKED_LOOP`).
1093    event_loop: Option<EventLoop<access_bridge::UserEvent>>,
1094    alive: bool,
1095    /// Every turn this runner has taken — [`pump`](PumpRunner::pump) and
1096    /// [`pump_until`](PumpRunner::pump_until) alike, the first one that
1097    /// opened the window included. What a driver's backoff is measured in
1098    ///: the runner knows how often it pumped where the app
1099    /// could only read a process monitor.
1100    pumps: u64,
1101    /// The turns among `pumps` whose batch carried an OS event or a wake
1102    ///: what `saw_event` marks, counted once per turn.
1103    woken_pumps: u64,
1104}
1105
1106impl PumpState {
1107    fn open(
1108        mut event_loop: EventLoop<access_bridge::UserEvent>,
1109        shell: &mut DynShell<'_>,
1110    ) -> PumpState {
1111        event_loop.set_control_flow(ControlFlow::Wait);
1112        shell.pumped = true;
1113        shell.attach(&event_loop);
1114        // First pump delivers `resumed`, creating the window + renderer —
1115        // or, on a loop taken back from an earlier runner, `about_to_wait`
1116        // does, since winit's init events came and went with the first.
1117        let alive = pump_once(&mut event_loop, shell);
1118        let mut state = PumpState {
1119            event_loop: Some(event_loop),
1120            alive,
1121            pumps: 1,
1122            woken_pumps: 0,
1123        };
1124        state.tally(shell);
1125        state
1126    }
1127
1128    /// Counts the turn that just ran as woken if its batch saw an event.
1129    /// The flag is taken, so the quiet turns after it are not counted too.
1130    fn tally(&mut self, shell: &mut DynShell<'_>) {
1131        if std::mem::take(&mut shell.woke) {
1132            self.woken_pumps += 1;
1133        }
1134    }
1135
1136    fn pump(&mut self, shell: &mut DynShell<'_>) -> bool {
1137        let Some(event_loop) = &mut self.event_loop else {
1138            return false;
1139        };
1140        self.pumps += 1;
1141        self.alive = pump_once(event_loop, shell);
1142        self.tally(shell);
1143        if !self.alive {
1144            self.retire(shell);
1145        }
1146        self.alive
1147    }
1148
1149    /// The end of this runner: every window closed (dropping the panes
1150    /// is what closes them — the pump path never asks winit to exit) and
1151    /// the loop handed back for the next `Launcher::open` on the thread.
1152    fn retire(&mut self, shell: &mut DynShell<'_>) {
1153        self.alive = false;
1154        shell.teardown_once();
1155        // The main core outlives its window, as it predated it: a host
1156        // still reads events, warnings and the tree off a runner that
1157        // has ended (`core_mut`), and the Node driver does so for the
1158        // pump that returned false.
1159        let mut panes = std::mem::take(&mut shell.panes);
1160        // The facts the platform's text input reads are keyed by the
1161        // view's address, which the next window's view may get.
1162        #[cfg(target_os = "macos")]
1163        for pane in &panes {
1164            macos_text_input::detach(&pane.window);
1165            macos_drop::detach(&pane.window);
1166        }
1167        if !panes.is_empty() {
1168            shell.main_core = Some(panes.remove(0).core);
1169        }
1170        if let Some(event_loop) = self.event_loop.take() {
1171            PARKED_LOOP.with(|p| *p.borrow_mut() = Some(event_loop));
1172        }
1173    }
1174
1175    fn pump_until(&mut self, shell: &mut DynShell<'_>, deadline: std::time::Instant) -> bool {
1176        use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
1177        let Some(event_loop) = &mut self.event_loop else {
1178            return false;
1179        };
1180        let timeout = deadline.saturating_duration_since(std::time::Instant::now());
1181        self.pumps += 1;
1182        self.alive = match event_loop.pump_app_events(Some(timeout), &mut Handler(shell)) {
1183            PumpStatus::Continue => !shell.exit_requested,
1184            PumpStatus::Exit(_) => false,
1185        };
1186        self.tally(shell);
1187        if !self.alive {
1188            self.retire(shell);
1189        }
1190        self.alive
1191    }
1192
1193    fn waker(&self, shell: &DynShell<'_>) -> Waker {
1194        match &self.event_loop {
1195            Some(event_loop) => Waker(event_loop.create_proxy()),
1196            // Retired: the proxy the shell kept still names the loop.
1197            None => Waker(shell.proxy.clone().expect("a pump runner keeps its proxy")),
1198        }
1199    }
1200}
1201
1202impl DynShell<'_> {
1203    fn core_mut_of(&mut self, id: WindowId) -> Option<&mut Core> {
1204        if id == WindowId::MAIN {
1205            return Some(self.core_mut());
1206        }
1207        self.panes
1208            .iter_mut()
1209            .find(|p| p.id == id)
1210            .map(|p| &mut p.core)
1211    }
1212
1213    fn window_id(&mut self, name: &str) -> Option<WindowId> {
1214        self.core_mut()
1215            .windows()
1216            .into_iter()
1217            .find(|(_, n)| &**n == name)
1218            .map(|(id, _)| id)
1219    }
1220
1221    fn request_redraw(&self) {
1222        self.owed.set(false);
1223        for p in &self.panes {
1224            p.redraw_for(FrameCause::HOST);
1225        }
1226    }
1227}
1228
1229impl<A: App> Drop for PumpRunner<A> {
1230    /// A runner dropped while alive — a host that let go of it without
1231    /// pumping to the end — parks the loop too, so the next `open` on the
1232    /// thread is not refused for its sake.
1233    fn drop(&mut self) {
1234        // `retire` reaches `App::teardown` too, so a runner a panic unwinds
1235        // through hears the window go (backlog RG1); a second panic out of
1236        // that `teardown` is an abort, as any panic in a drop is.
1237        self.retire();
1238        // SAFETY: taken once, here, and the field is not read again.
1239        let shell: Box<Shell<A>> = unsafe { std::mem::ManuallyDrop::take(&mut self.shell) };
1240        drop_shell(shell);
1241    }
1242}
1243
1244/// Drops a shell unsized, so its drop glue is kui's (see `PumpRunner`).
1245fn drop_shell(shell: Box<DynShell<'_>>) {
1246    drop(shell);
1247}
1248
1249impl<A: App> PumpRunner<A> {
1250    fn shell(&self) -> &DynShell<'_> {
1251        &**self.shell
1252    }
1253
1254    fn shell_mut(&mut self) -> &mut DynShell<'_> {
1255        &mut **self.shell
1256    }
1257
1258    fn retire(&mut self) {
1259        self.state.retire(&mut **self.shell);
1260    }
1261
1262    /// Processes all pending OS events without blocking. Returns false once
1263    /// the main window has closed — and from that pump on the windows are
1264    /// gone and the loop is parked for the next runner; further pumps are
1265    /// no-ops.
1266    pub fn pump(&mut self) -> bool {
1267        self.state.pump(&mut **self.shell)
1268    }
1269
1270    /// How many turns this runner has taken, the one that opened the
1271    /// window included: every `pump` and `pump_until` that ran, not the
1272    /// no-ops after it retired. Monotonic, so two readings a second apart
1273    /// give the pump rate over that second. How many of them something
1274    /// outside the app caused is [`woken_pumps`](Self::woken_pumps).
1275    pub fn pumps(&self) -> u64 {
1276        self.state.pumps
1277    }
1278
1279    /// How many of those [`pumps`](Self::pumps) found an OS event or a
1280    /// wake in their batch: any window event but a redraw (a key, the
1281    /// pointer crossing the window, a focus change, a resize, the window
1282    /// moved or occluded), or anything that came through the loop's proxy
1283    /// (a [`Waker::wake`], assistive technology asking, a file dialog's
1284    /// answer). Monotonic, and never more than `pumps`.
1285    ///
1286    /// Unmoved over a second, the desktop left the window alone and
1287    /// whatever it drew was the app's own doing; moved, the desktop or a
1288    /// person reached in, so an idle-window measurement should restart
1289    /// rather than fail.
1290    pub fn woken_pumps(&self) -> u64 {
1291        self.state.woken_pumps
1292    }
1293
1294    /// [`pump`](Self::pump), but parked until an OS event, a
1295    /// [`Waker::wake`] or `deadline`, whichever comes first, so a host that
1296    /// owns the loop blocks on all three instead of polling on a timer.
1297    /// Returns false once the main window has closed.
1298    pub fn pump_until(&mut self, deadline: std::time::Instant) -> bool {
1299        self.state.pump_until(&mut **self.shell, deadline)
1300    }
1301
1302    /// When the runner next needs pumping, as the last [`pump`](Self::pump)
1303    /// left it: a caret blink, a tick, a transition's next frame, the audio
1304    /// poll or a first-frame retry. `None` when nothing it knows about is
1305    /// due. Ask after each pump and sleep until the answer rather than
1306    /// pumping on a fixed interval.
1307    ///
1308    /// It does not say whether an OS event is waiting, since nothing short
1309    /// of pumping can, so a driver still needs a ceiling of its own; this
1310    /// only ever says to come back sooner.
1311    pub fn next_deadline(&self) -> Option<std::time::Instant> {
1312        self.shell.next_deadline
1313    }
1314
1315    /// A [`Waker`] for this loop, to clone into the threads the host's
1316    /// data arrives on.
1317    pub fn waker(&self) -> Waker {
1318        self.state.waker(&**self.shell)
1319    }
1320
1321    /// The app, for a host that reads or changes its state between pumps.
1322    pub fn app_mut(&mut self) -> &mut A {
1323        &mut self.shell.app
1324    }
1325
1326    /// Delivers `events` the way this runner's own loop does: an
1327    /// extension's event to the extension, and the rest, with whatever the
1328    /// extension replied, to `to_app`. Use it for events the loop never
1329    /// saw, such as those a host produced by driving the core directly
1330    /// (`core_mut().press`, an access action, a drained
1331    /// `take_pending_events`); pushing those straight at the app would
1332    /// hand it an extension's clicks and leave the extension deaf to them.
1333    ///
1334    /// `to_app` is lent the core of the window each event came from, as
1335    /// [`App::on_event_with`] is.
1336    pub fn route_events(
1337        &mut self,
1338        events: impl IntoIterator<Item = UiEvent>,
1339        mut to_app: impl FnMut(&mut A, UiEvent, &mut Core),
1340    ) {
1341        let Shell {
1342            extensions,
1343            app,
1344            panes,
1345            main_core,
1346            ..
1347        } = &mut **self.shell;
1348        extensions.route(events, |ev| {
1349            if let Some(core) = window_core(panes, main_core, ev.window) {
1350                to_app(app, ev, core);
1351            }
1352        });
1353    }
1354
1355    /// The main window's core. Every window of the app shares its session,
1356    /// so resources registered through it draw in all of them, and
1357    /// `Core::windows` on it lists them.
1358    pub fn core_mut(&mut self) -> &mut Core {
1359        self.shell_mut().core_mut()
1360    }
1361
1362    /// The core of the window `id` names, if that window is open; the main
1363    /// window's for `WindowId::MAIN`. Everything that is one window's
1364    /// rather than the session's (its focus, its editors' text, its scroll
1365    /// offsets, its tokens) is answered by this core and no other.
1366    pub fn core_mut_of(&mut self, id: WindowId) -> Option<&mut Core> {
1367        self.shell_mut().core_mut_of(id)
1368    }
1369
1370    /// The id of the open window named `name` (`"main"` for the launcher's),
1371    /// or `None` while no window of that name is open — before its first
1372    /// frame's diff, or after the user closed it.
1373    pub fn window_id(&mut self, name: &str) -> Option<WindowId> {
1374        self.shell_mut().window_id(name)
1375    }
1376
1377    /// The main window's inner size (logical px) and its scale factor.
1378    /// Unlike `core_mut().viewport()` this is known before the first frame,
1379    /// so a host can size its model at setup. `core_mut().host_area(size)`
1380    /// is what the next frame lays out against: the window less the
1381    /// devtools' dock while the panel is docked, the window otherwise.
1382    pub fn window_size(&self) -> (Size, f32) {
1383        self.shell().window_size()
1384    }
1385
1386    /// Schedules a redraw of every window; call it after changing what
1387    /// `view` will produce. Under [`Launcher::deferred_events`] it also
1388    /// ends a frame's wait: the host is saying its view is current, so the
1389    /// waiting frame is painted with the answer in it.
1390    pub fn request_redraw(&self) {
1391        self.shell().request_redraw();
1392    }
1393
1394    /// Asks the app to close; the next `pump` observes it and returns false.
1395    pub fn request_exit(&mut self) {
1396        self.shell.exit_requested = true;
1397    }
1398
1399    /// Hands the core's queued audio commands to the device now rather than
1400    /// at the next pump, for a host that calls `Core::play` between pumps
1401    /// and wants the sound to start at once.
1402    pub fn flush_audio(&mut self) {
1403        self.shell_mut().apply_audio();
1404    }
1405}
1406
1407/// `app(title).extensions(extensions).run(application)` in one call.
1408pub fn run<A: App>(
1409    title: &str,
1410    application: A,
1411    extensions: Vec<Box<dyn Extension>>,
1412) -> Result<(), Box<dyn std::error::Error>> {
1413    app(title).extensions(extensions).run(application)
1414}
1415
1416/// Clamps a requested inner size into `min`/`max` (logical px), the way the
1417/// OS clamps a resize once the window exists — so a host reading
1418/// `PumpRunner::window_size` before the first frame sees the real size.
1419/// `min` wins where the two bounds cross, matching the platforms.
1420fn clamp_size(size: (f64, f64), min: Option<(f64, f64)>, max: Option<(f64, f64)>) -> (f64, f64) {
1421    let (mut w, mut h) = size;
1422    if let Some((mw, mh)) = max {
1423        w = w.min(mw);
1424        h = h.min(mh);
1425    }
1426    if let Some((mw, mh)) = min {
1427        w = w.max(mw);
1428        h = h.max(mh);
1429    }
1430    (w, h)
1431}
1432
1433/// Width of the invisible resize band synthesized on undecorated windows.
1434const RESIZE_BAND: f32 = 6.0;
1435/// A second titlebar press within this window toggles maximize.
1436const DOUBLE_CLICK_MS: u128 = 350;
1437/// Presses within this window (and `MULTI_CLICK_SLOP` px) count up the
1438/// multi-click sent with `InputEvent::MouseDown` (double = word select).
1439const MULTI_CLICK_MS: u128 = 400;
1440const MULTI_CLICK_SLOP: f32 = 4.0;
1441/// Caret blink half-period while an edit widget is focused.
1442const BLINK_INTERVAL: std::time::Duration = std::time::Duration::from_millis(500);
1443/// How often the loop wakes to notice a playing sound finishing.
1444const AUDIO_POLL: std::time::Duration = std::time::Duration::from_millis(50);
1445
1446/// How long the output device is held open after the last input or sound.
1447/// An open device is a real-time thread the OS runs ~94 times a second
1448/// whether or not anything is playing, which is the entire idle CPU cost of
1449/// an app that owns a sound — the counter example sat at 0.3% doing nothing.
1450/// Held rather than closed at once because the point of opening early is
1451/// that a click finds it open (the ~90 ms open used to stall the counter's
1452/// first click), and any input at all re-warms it: the pointer moving
1453/// towards a button is minutes of warning before the button is pressed.
1454const AUDIO_IDLE_CLOSE: std::time::Duration = std::time::Duration::from_secs(5);
1455/// How long after one try at opening a new device (`Shell::reopen_device`)
1456/// the next may be made. A device that will not open — a driver still
1457/// being installed, an adapter gone — is tried once a second, and the
1458/// loop sleeps until then rather than asking for frames that could only
1459/// ask again.
1460const REOPEN_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
1461/// Frames in a row a surface may refuse for being configured wrong, each
1462/// answered by configuring it again, before it is given up with its device.
1463const SURFACE_TRIES: u8 = 3;
1464
1465/// When a new device asked for at `now` may be opened: at once if none
1466/// has been tried, else `REOPEN_INTERVAL` after the last try and never
1467/// sooner. A time not after `now` means now; a later one is the wake the
1468/// loop sleeps until (`about_to_wait`), since nothing else is bound to ask
1469/// — an idle app's windows draw nothing on their own, and an animating
1470/// one's frames, with no surface to present to, are not paced by vsync
1471/// and would spin the loop until the second was up.
1472fn reopen_due(last_try: Option<std::time::Instant>, now: std::time::Instant) -> std::time::Instant {
1473    last_try.map_or(now, |t| (t + REOPEN_INTERVAL).max(now))
1474}
1475
1476/// What a frame does with a surface refused for being configured wrong.
1477#[derive(Debug, PartialEq, Eq)]
1478enum Refused {
1479    /// Configure it to the window's size and draw again at once.
1480    Retry,
1481    /// Give it up with its device (`Shell::reopen_device`); `say` on the
1482    /// first frame past the tries, not on each one refused after it while
1483    /// the reopen waits out its second.
1484    GiveUp { say: bool },
1485}
1486
1487/// Counts one more refusal in `tries` — saturating, since while a reopen
1488/// is owed every frame input asks for is refused again and counted, and
1489/// a `u8` that wrapped would start the retries over (or, in a debug
1490/// build, panic) — and says what the frame does with it: the first
1491/// `SURFACE_TRIES` are retried, the rest give the surface up.
1492fn surface_refused(tries: &mut u8) -> Refused {
1493    *tries = tries.saturating_add(1);
1494    if *tries <= SURFACE_TRIES {
1495        Refused::Retry
1496    } else {
1497        Refused::GiveUp {
1498            say: *tries == SURFACE_TRIES + 1,
1499        }
1500    }
1501}
1502
1503/// Whether text is drawn with LCD subpixel masks: what was asked for
1504/// (`KUI_TEXT_AA` over the launcher's `text_aa`, `wanted_text_aa`), and
1505/// for `Auto` or `Subpixel` only where the device blends per channel —
1506/// a mask the blend cannot split draws coloured fringes. Decided with each
1507/// device, the first and every one opened after a loss, since a reopen can
1508/// land on another adapter.
1509fn subpixel_on(wanted: TextAa, dual_source: bool) -> bool {
1510    match wanted {
1511        TextAa::Grayscale => false,
1512        TextAa::Subpixel | TextAa::Auto => dual_source,
1513    }
1514}
1515
1516/// The antialiasing `Auto` means for an app that asked for a backdrop
1517/// (backlog F126): grayscale, since an LCD mask is a blend against the
1518/// pixels under it and the window cannot see what the OS composites
1519/// behind a translucent one — subpixel text over a sidebar's material
1520/// draws colour fringes the size of a stem. One decision for every
1521/// window of the app, made before any knows what it got. A `Subpixel`
1522/// the app or `KUI_TEXT_AA` named is kept.
1523fn aa_under(wanted: TextAa, backdrop: Backdrop) -> TextAa {
1524    match wanted {
1525        TextAa::Auto if backdrop.is_translucent() => TextAa::Grayscale,
1526        other => other,
1527    }
1528}
1529
1530/// The frame latency asked for: `KUI_FRAME_LATENCY` if it is a positive
1531/// number, for comparing without a rebuild, else the launcher's.
1532fn wanted_frame_latency(launcher: u32) -> u32 {
1533    std::env::var("KUI_FRAME_LATENCY")
1534        .ok()
1535        .and_then(|v| v.trim().parse::<u32>().ok())
1536        .filter(|n| *n >= 1)
1537        .unwrap_or(launcher)
1538}
1539
1540/// The text antialiasing asked for: `KUI_TEXT_AA` if set, for quick A/B
1541/// comparisons, else what the launcher was told.
1542fn wanted_text_aa(launcher: TextAa) -> TextAa {
1543    match std::env::var("KUI_TEXT_AA").ok().as_deref() {
1544        Some("gray") | Some("grayscale") => TextAa::Grayscale,
1545        Some("subpixel") | Some("lcd") => TextAa::Subpixel,
1546        _ => launcher,
1547    }
1548}
1549
1550/// The core's derived pointer shape in winit's vocabulary. One-to-one:
1551/// `CursorShape` is spelled after the platform names on purpose.
1552/// Chromeless, in the spelling each platform actually honours.
1553///
1554/// Everywhere but macOS that is `with_decorations(false)`. On macOS it is
1555/// **not**: `with_decorations(false)` gives a window with the borderless
1556/// style mask, and AppKit never sends `mouseUp:` to one — every press in it
1557/// lands and never releases, so nothing in the window can be clicked, no
1558/// drag ever ends, and a pressed style never clears. A hidden titlebar over
1559/// a fullsize content view looks the same, is a real window, and is what
1560/// `Chrome::Custom` already asks for; chromeless is that plus the traffic
1561/// lights hidden. It keeps the rounded corners, the drop shadow and the
1562/// native edge-resizing that a borderless window has none of.
1563///
1564/// Found by pressing a menu item and watching nothing happen;
1565/// the popup surface and `Chrome::Borderless` share this because they were
1566/// separately wrong in the same way.
1567fn undecorated(attrs: winit::window::WindowAttributes) -> winit::window::WindowAttributes {
1568    #[cfg(target_os = "macos")]
1569    {
1570        use winit::platform::macos::WindowAttributesExtMacOS;
1571        attrs
1572            .with_titlebar_transparent(true)
1573            .with_fullsize_content_view(true)
1574            .with_title_hidden(true)
1575            .with_titlebar_buttons_hidden(true)
1576    }
1577    #[cfg(not(target_os = "macos"))]
1578    {
1579        attrs.with_decorations(false)
1580    }
1581}
1582
1583/// A popup this press is about : one that opened while the primary button was down, or the
1584/// one the button went down inside. For the rest of that press the owner's
1585/// moves are retargeted into it and its release is classified against it.
1586struct Armed {
1587    /// The popup. Its owner and its anchor are the pane's, so nothing here
1588    /// can go stale against the window it names.
1589    id: WindowId,
1590    /// Whether the last retargeted move landed inside this popup, so that
1591    /// dragging off the list costs one `CursorLeft` and staying off it
1592    /// costs nothing.
1593    inside: bool,
1594}
1595
1596/// The runner's state for one app, over every window it opens.
1597///
1598/// Generic only in its last field: everything is written against
1599/// [`DynShell`] and compiled once, here; a `Shell<A>` is only built,
1600/// boxed, and handed over unsized. Written `impl<A: App> Shell<A>`,
1601/// the whole runner was instantiated and optimised again inside every app
1602/// crate, on every edit: the counter's release rebuild went from 1.20 s
1603/// to 1.57 s as the runner grew.
1604struct Shell<A: App + ?Sized> {
1605    title: String,
1606    /// What every window is created with (`Launcher::icon`).
1607    icon: icon::AppIcon,
1608    chrome: Chrome,
1609    /// Initial inner size (logical px), already clamped into the bounds.
1610    size: (f64, f64),
1611    min_size: Option<(f64, f64)>,
1612    max_size: Option<(f64, f64)>,
1613    text_aa: TextAa,
1614    /// What every renderer is configured with: `Launcher::frame_latency`
1615    /// under `KUI_FRAME_LATENCY`.
1616    frame_latency: u32,
1617    /// What the app asked to show through its windows
1618    /// (`Launcher::backdrop`); what each window got is its pane's.
1619    backdrop: Backdrop,
1620    /// What every core is created with; see `Launcher::diagnostics`.
1621    diagnostics: bool,
1622    /// Whether the GPU blends per channel, decided by the first renderer,
1623    /// again by each device opened after a loss (`reopen_device`), and
1624    /// applied to every core.
1625    subpixel: bool,
1626    /// Each under the namespace the host gave it; their `Fill` is what fills
1627    /// the slots a view declares.
1628    extensions: Extensions,
1629    /// What every window shares: fonts, images, sounds, the audio queue and
1630    /// the declared window set.
1631    session: Session,
1632    /// The main window's core until `resumed` moves it into its pane, so
1633    /// `PumpRunner::core_mut` has an answer before the first pump.
1634    main_core: Option<Core>,
1635    /// The open windows, main first.
1636    panes: Vec<Pane>,
1637    /// The device every window renders with, from the first renderer.
1638    gpu: Option<kui_wgpu::Gpu>,
1639    /// When the device was last opened again after being lost
1640    /// (`reopen_device`), so a device that will not open is tried once a
1641    /// second rather than once a frame.
1642    reopened: Option<std::time::Instant>,
1643    /// A new device was asked for inside the second after the last try,
1644    /// or the last try left a window without a renderer: `about_to_wait`
1645    /// opens it when `reopen_due` says, and sleeps until then — the ask
1646    /// is kept here rather than in a frame asked for again, which in an
1647    /// idle app nothing would ask for and in an animating one would be
1648    /// asked for every turn with no vsync to pace it.
1649    reopen_owed: bool,
1650    /// Whether `KUI_LOSE_DEVICE` has had its one loss.
1651    pretended_loss: bool,
1652    /// Caps Lock and Num Lock as the lock keys' presses have turned them,
1653    /// in any window — what a press reports where the OS is not asked
1654    /// (`keys::lock_state`). One keyboard, one record: it
1655    /// was each pane's, so a popup began at off and a toggle in one window
1656    /// never reached another.
1657    locks: kui_core::KeyLocks,
1658    /// The layout's script as the letter keys have shown it — what a
1659    /// press goes by where the OS is not asked (`keys::layout_script`).
1660    /// One keyboard, one record, as `locks`.
1661    script: kui_core::LayoutScript,
1662    /// Origin of the frame clock handed to the cores for transitions.
1663    epoch: std::time::Instant,
1664    /// What the OS was asked for at startup — the accent colour, the
1665    /// reduce-motion setting and the language (`mod system_env`) — pushed
1666    /// into every pane's env each frame and re-asked when the user has
1667    /// evidently been somewhere else. The appearance is not here: it is
1668    /// per-window and comes off the window itself.
1669    system: system_env::Queried,
1670    /// What the app pinned over it (`Launcher::system`); merged in
1671    /// `sync_env`, so it is never lost to the per-frame write.
1672    pinned_system: SystemEnv,
1673    clipboard: Option<arboard::Clipboard>,
1674    /// The platform's context menu, where the platform has one.
1675    /// `None` on every other platform and on a macOS build that
1676    /// could not reach the main thread, and then the core draws its own.
1677    #[cfg(target_os = "macos")]
1678    native_menu: Option<macos_menu::MacMenu>,
1679    /// Whether a menu the core opened has been handed to the platform and
1680    /// is waiting for an answer. One per app: only one menu can be up.
1681    /// Beside `native_menu` because it means nothing without one.
1682    #[cfg(target_os = "macos")]
1683    menu_shown: bool,
1684    /// The platform's application menu bar, where the platform has one
1685    ///. One per process,
1686    /// because that is what macOS has: it carries the declaration of the
1687    /// window that has the keyboard, or of whichever window made one.
1688    #[cfg(target_os = "macos")]
1689    native_menu_bar: Option<macos_menu::MacMenuBar>,
1690    /// What it currently carries: a declaration — the window it came from
1691    /// and that core's `menu_bar_revision` — or the standard bar. The diff
1692    /// that keeps a re-declared bar from being rebuilt sixty times a second.
1693    #[cfg(target_os = "macos")]
1694    applied_menu_bar: Option<AppliedBar>,
1695    /// The audio device the core's audio commands drive; see `audio`.
1696    audio: audio::Audio,
1697    /// When the app was last doing something that could lead to a sound:
1698    /// any input, or any audio command. The device is warmed while this is
1699    /// recent and let go once it is not — see `AUDIO_IDLE_CLOSE`. Starts at
1700    /// launch, so a session holding sounds still opens the device before
1701    /// its first click the way it always did.
1702    audio_touch: std::time::Instant,
1703    /// `KUI_SMOKE_FRAMES=n`: quit after the main window has presented `n`
1704    /// frames, so an example is a self-terminating check — a real window
1705    /// on a real GPU, driven by the real loop, that exits 0 when it drew
1706    /// and non-zero when it did not. It is what the smoke round
1707    /// (examples/devtools/src/bin/smoke.rs) runs; the wgpu validation
1708    /// error that made `fragments` panic on
1709    /// first paint (an alignment the adapter and the device disagreed
1710    /// about) is exactly the class of bug no headless test can see.
1711    /// `None` — unset, or unparseable — is the ordinary endless run.
1712    smoke_frames: Option<u32>,
1713    /// Main-window frames presented so far, counted only while
1714    /// `smoke_frames` is set.
1715    frames_drawn: u32,
1716    /// Set by `WindowCommand::Close` on the main window; honored at the end
1717    /// of the event.
1718    exit_requested: bool,
1719    /// Why the main window or its renderer could not be made, when they
1720    /// could not: `run` and `open` return it as their error. It was an
1721    /// `expect`, and a panic there aborted a Node process outright — the
1722    /// unwind cannot cross the addon's boundary — when a compositor that
1723    /// had just gone away refused the window.
1724    startup_error: Option<String>,
1725    /// Whether `App::teardown` has run: once, whichever of the loop's
1726    /// exit and the runner's retirement comes first.
1727    torn_down: bool,
1728    /// The one count of secure keyboard entry this runner may hold, moved
1729    /// at the end of every batch to whether a window whose frame asked
1730    /// (`Ui::secure_input`) has the keyboard, given back at teardown and
1731    /// on drop (`mod secure_input`).
1732    secure_input: secure_input::SecureInput,
1733    /// Driven by a `PumpRunner` rather than `run_app`: the main window's
1734    /// close ends the runner (`exit_requested`) instead of exiting winit's
1735    /// loop, which the next runner on this thread reuses.
1736    pumped: bool,
1737    /// Whether `resumed` has opened the main window — once per shell, so a
1738    /// reused loop that delivers no `resumed` opens it from `about_to_wait`
1739    /// and a main window the user closed is not reopened from there.
1740    opened: bool,
1741    /// Which pane the primary button is down in, if any. A
1742    /// popup is armed against it: a non-activating popup that opens while this is
1743    /// set joins that press, which is the observable form of "the drag
1744    /// whose press opened the popup" and needs no geometry.
1745    primary_down: Option<WindowId>,
1746    /// The popups armed into the press `primary_down` names, in opening
1747    /// order — where two overlap the last is on top. Emptied by the release
1748    /// that classifies it, and by `close_pane` for a window that goes
1749    /// first.
1750    armed: Vec<Armed>,
1751    /// A primary press that dismissed a non-activating popup and was
1752    /// consumed rather than dispatched, by the pane
1753    /// it landed in. Its release is swallowed with it: the core never saw
1754    /// the `down`, so nothing should see the `up`.
1755    swallowed_press: Option<WindowId>,
1756    /// Hands AccessKit a way back into the loop; set before the window
1757    /// exists.
1758    proxy: Option<EventLoopProxy<access_bridge::UserEvent>>,
1759    /// What the last `about_to_wait` decided the control flow should be, kept
1760    /// so a host that owns the loop can read it (`PumpRunner::next_deadline`).
1761    /// `None` is `ControlFlow::Wait`: nothing the shell knows about is due.
1762    next_deadline: Option<std::time::Instant>,
1763    /// Whether this batch carried an OS event the shell acted on. A driver
1764    /// cannot see most of them — a pointer crossing a window that declares no
1765    /// hover produces no *app* event at all, and neither does a key nothing
1766    /// is listening for — so a driver pacing itself on what the app saw
1767    /// concludes that a window being moved across is idle. It is the reason
1768    /// `next_deadline` reports "now" after an event: the shell asked for a
1769    /// redraw and wants pumping to present it, and that is also the honest
1770    /// signal for "somebody is using this window".
1771    saw_event: bool,
1772    /// `saw_event` as `about_to_wait` took it, left for the pump runner to
1773    /// take in turn and count (`PumpRunner::woken_pumps`). A
1774    /// loop that owns itself never reads it.
1775    woke: bool,
1776    /// The host answers events after the loop hands them over
1777    /// (`Launcher::deferred_events`).
1778    deferred_events: bool,
1779    /// An input reached the app and the host has not answered yet, so the
1780    /// next frame would be painted from a view that predates that input.
1781    /// Set only under `deferred_events`; cleared when the host says its
1782    /// view is current ([`PumpRunner::request_redraw`], which every
1783    /// `setView` and every drained `pollEvents` reaches).
1784    ///
1785    /// A `Cell` because the clearing is the host's `&self` call, and the
1786    /// alternative — taking `&mut self` there — is a signature break for
1787    /// what is bookkeeping.
1788    owed: std::cell::Cell<bool>,
1789    /// Last, so a `Box<Shell<A>>` unsizes to a `Box<DynShell>`.
1790    app: A,
1791}
1792
1793/// A shell over any app: what the runner is written against. Generic only
1794/// in a lifetime, which is erased, so its code is kui's and not the app
1795/// crate's, and an app that borrows is still an app.
1796type DynShell<'a> = Shell<dyn App + 'a>;
1797
1798/// The core of window `id`, from a shell's two homes for one: the panes,
1799/// and the main window's core before its pane exists — the main window's
1800/// for a window that has closed since its event was made. Over the fields
1801/// rather than `&mut Shell`, so the app can be lent beside it.
1802fn window_core<'a>(
1803    panes: &'a mut [Pane],
1804    main_core: &'a mut Option<Core>,
1805    id: WindowId,
1806) -> Option<&'a mut Core> {
1807    let at = panes
1808        .iter()
1809        .position(|p| p.id == id)
1810        .or_else(|| panes.iter().position(|p| p.id == WindowId::MAIN));
1811    match at {
1812        Some(i) => Some(&mut panes[i].core),
1813        None => main_core.as_mut(),
1814    }
1815}
1816
1817/// What winit's loop drives: it wants a sized handler, and a `DynShell`
1818/// is not one.
1819struct Handler<'s, 'a>(&'s mut DynShell<'a>);
1820
1821impl ApplicationHandler<access_bridge::UserEvent> for Handler<'_, '_> {
1822    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
1823        self.0.resumed(event_loop);
1824    }
1825
1826    fn window_event(
1827        &mut self,
1828        event_loop: &ActiveEventLoop,
1829        window: WinitWindowId,
1830        event: WindowEvent,
1831    ) {
1832        self.0.window_event(event_loop, window, event);
1833    }
1834
1835    fn exiting(&mut self, event_loop: &ActiveEventLoop) {
1836        self.0.exiting(event_loop);
1837    }
1838
1839    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: access_bridge::UserEvent) {
1840        self.0.user_event(event_loop, event);
1841    }
1842
1843    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
1844        self.0.about_to_wait(event_loop);
1845    }
1846}
1847
1848impl DynShell<'_> {
1849    /// The main window's core: its pane's once it exists, the one the
1850    /// launcher built before that.
1851    fn core_mut(&mut self) -> &mut Core {
1852        match self.panes.first_mut() {
1853            Some(p) => &mut p.core,
1854            None => self
1855                .main_core
1856                .as_mut()
1857                .expect("the main core exists until its pane takes it"),
1858        }
1859    }
1860
1861    /// What the device is opened for: surfaces that can take alpha when
1862    /// the app asked for a backdrop, which on Windows is another D3D12
1863    /// swapchain (backlog F126) — so only then.
1864    fn gpu_options(&self) -> kui_wgpu::GpuOptions {
1865        kui_wgpu::GpuOptions::transparent(self.backdrop.is_translucent())
1866    }
1867
1868    /// Main inner size in logical px plus the scale factor; the launcher's
1869    /// requested size until the window exists.
1870    fn window_size(&self) -> (Size, f32) {
1871        match self.panes.first() {
1872            Some(p) => p.size(),
1873            None => (Size::new(self.size.0 as f32, self.size.1 as f32), 1.0),
1874        }
1875    }
1876
1877    /// `App::teardown`, once: from `exiting` — the loop's
1878    /// last word, which the OS's Quit reaches too, on macOS through
1879    /// `applicationWillTerminate` where the process ends without `run`
1880    /// ever returning — and from a pumped runner's retirement, whichever
1881    /// comes first.
1882    fn teardown_once(&mut self) {
1883        // The keyboard is given back before the app's teardown runs, and
1884        // on every path here: a process that ends from `exiting` never
1885        // drops the runner (backlog F85).
1886        self.secure_input.set(false);
1887        if !self.torn_down {
1888            self.torn_down = true;
1889            self.app.teardown();
1890        }
1891    }
1892
1893    /// The main window is done: `run_app`'s loop exits; a pumped loop is
1894    /// left running for the next runner, and the runner ends itself on
1895    /// the flag (see `PARKED_LOOP`).
1896    fn exit_main(&mut self, event_loop: &ActiveEventLoop) {
1897        self.exit_requested = true;
1898        if !self.pumped {
1899            event_loop.exit();
1900        }
1901    }
1902
1903    /// Whether the platform's own drag callbacks are answering for every
1904    /// window, so winit's positionless file events are the duplicates.
1905    fn file_drag_is_overridden(&self) -> bool {
1906        #[cfg(target_os = "macos")]
1907        {
1908            macos_drop::installed()
1909        }
1910        #[cfg(not(target_os = "macos"))]
1911        {
1912            false
1913        }
1914    }
1915
1916    /// The file drags the platform reported since the last turn:
1917    /// on macOS the delegate override's messages, each with the
1918    /// position AppKit gave it, dispatched to the pane whose delegate
1919    /// spoke and followed by the stamp that delegate answers the OS from;
1920    /// elsewhere the batch winit's per-file events built, at the pane's
1921    /// last cursor.
1922    fn pump_file_drag(&mut self, event_loop: &ActiveEventLoop) {
1923        #[cfg(target_os = "macos")]
1924        for (delegate, msg) in macos_drop::take_messages() {
1925            let Some(i) = self
1926                .panes
1927                .iter()
1928                .position(|p| macos_drop::delegate_ptr(&p.window) == Some(delegate))
1929            else {
1930                continue;
1931            };
1932            let ev = match msg {
1933                macos_drop::DragMsg::Over(paths, at) => InputEvent::DragFiles { paths, at },
1934                macos_drop::DragMsg::Drop(paths, at) => InputEvent::DropFiles { paths, at },
1935                macos_drop::DragMsg::Cancel => InputEvent::DragCancel,
1936            };
1937            if let Some(i) = self.dispatch(event_loop, i, ev) {
1938                let pane = &self.panes[i];
1939                macos_drop::stamp(&pane.window, pane.core.drop_target().is_some());
1940            }
1941        }
1942        // Collected first, then dispatched by window id: a drop's handler
1943        // may close its window, and a pane's index is not its identity
1944        // (backlog AR39).
1945        let batches: Vec<(WindowId, InputEvent)> = self
1946            .panes
1947            .iter_mut()
1948            .filter_map(|pane| {
1949                let dropped = pane.file_drag_pending.take()?;
1950                let paths = std::mem::take(&mut pane.file_drag);
1951                let at = pane.cursor;
1952                let ev = if dropped {
1953                    InputEvent::DropFiles { paths, at }
1954                } else {
1955                    InputEvent::DragFiles { paths, at }
1956                };
1957                Some((pane.id, ev))
1958            })
1959            .collect();
1960        for (id, ev) in batches {
1961            if let Some(i) = self.pane_of(id) {
1962                self.dispatch(event_loop, i, ev);
1963            }
1964        }
1965    }
1966
1967    /// The documents the OS asked the app to open since the last turn
1968    /// (backlog F124), each list as one `InputEvent::Open` to the main
1969    /// window's core. Before that window has opened — the launch-time
1970    /// open, which AppKit sends inside `finishLaunching` — they stay
1971    /// queued for the first turn after it has. Nothing sends them off
1972    /// macOS: there the documents are in the process's arguments.
1973    fn pump_open_documents(&mut self, event_loop: &ActiveEventLoop) {
1974        #[cfg(target_os = "macos")]
1975        {
1976            if !macos_open::pending() || self.pane_of(WindowId::MAIN).is_none() {
1977                return;
1978            }
1979            for paths in macos_open::take() {
1980                // Looked up per list: a handler may close a window.
1981                let Some(i) = self.pane_of(WindowId::MAIN) else {
1982                    // Gone between two lists: the rest wait, as the
1983                    // launch-time ones do, for a main window to hear them.
1984                    macos_open::requeue(paths);
1985                    continue;
1986                };
1987                self.dispatch(event_loop, i, InputEvent::Open(paths));
1988            }
1989        }
1990        #[cfg(not(target_os = "macos"))]
1991        let _ = event_loop;
1992    }
1993
1994    /// Hands one input to pane `i`'s core and does what followed from it:
1995    /// the events routed, the menu actions, the window commands, the
1996    /// audio. Returns where that pane is afterwards — the commands may
1997    /// have closed a window, and a close in front of it moves it down,
1998    /// so its index is not its identity; `None` when the
1999    /// input closed the pane itself. A caller that goes on addressing the
2000    /// pane goes on with the returned index.
2001    fn dispatch(
2002        &mut self,
2003        event_loop: &ActiveEventLoop,
2004        i: usize,
2005        ev: InputEvent,
2006    ) -> Option<usize> {
2007        let t0 = std::time::Instant::now();
2008        // Someone is using the app, so a sound may be moments away: keep
2009        // the device warm (`AUDIO_IDLE_CLOSE`).
2010        self.audio_touch = t0;
2011        let completes = input_completes(&ev);
2012        let here = self.panes[i].id;
2013        let events = self.panes[i].core.handle_input(ev);
2014        let reached_app = self.route_events(events);
2015        self.owe_for(reached_app && completes);
2016        self.apply_menu_actions(event_loop, i);
2017        self.apply_window_commands(event_loop);
2018        self.apply_audio();
2019        self.pump_native_menu(event_loop);
2020        let i = self.pane_of(here)?;
2021        let pane = &mut self.panes[i];
2022        pane.apply_cursor();
2023        // Hover styling depends on input too, so any input redraws. A
2024        // damage pass can tighten this later.
2025        pane.core.stats.pending_input_ms += t0.elapsed().as_secs_f32() * 1e3;
2026        pane.window.request_redraw();
2027        Some(i)
2028    }
2029
2030    /// Hands the session's queued audio commands to the device. A session
2031    /// that holds a sound is going to play one: the device starts opening
2032    /// here, on its own thread, so the first play finds it open instead of
2033    /// stalling the frame for the ~90 ms the open takes.
2034    fn apply_audio(&mut self) {
2035        let core = self.core_mut();
2036        let cmds = core.take_audio_commands();
2037        let resources = core.resources.clone();
2038        if !cmds.is_empty() {
2039            self.audio_touch = std::time::Instant::now();
2040        }
2041        // Warmed while the app is being used and let go when it is not.
2042        // Not every frame: a frame is drawn for the caret, for a
2043        // transition, for a window moving over the top — none of which is
2044        // anybody about to play anything, and re-warming on one of those
2045        // would reopen the device the moment `about_to_wait` closed it.
2046        if resources.has_sounds() && self.audio_touch.elapsed() < AUDIO_IDLE_CLOSE {
2047            self.audio.warm();
2048        }
2049        // Two things only the device knows come back here. A `Stop` it found
2050        // still playing is a one-shot cut off, which the core turns into
2051        // `truncated-playback` on the node that went away; a refused play
2052        // never starts and so never ends, so the core turns that into a
2053        // `refused` event and a warning, or a tagged node waits on an
2054        // `ended` that cannot come.
2055        let answered = self.audio.apply(cmds, &resources);
2056        if answered.truncated.is_empty() && answered.refused.is_empty() {
2057            return;
2058        }
2059        let core = self.core_mut();
2060        for (playback, at) in answered.truncated {
2061            core.audio_truncated(playback, at);
2062        }
2063        for playback in answered.refused {
2064            core.audio_refused(playback);
2065        }
2066        self.route_playback_events();
2067    }
2068
2069    /// Folds playbacks that finished on their own back into the core, and
2070    /// routes the `sound` events tagged ones become.
2071    fn poll_audio(&mut self) {
2072        let ended = self.audio.poll_ended();
2073        if ended.is_empty() {
2074            return;
2075        }
2076        let core = self.core_mut();
2077        for playback in ended {
2078            core.audio_ended(playback);
2079        }
2080        self.route_playback_events();
2081    }
2082
2083    /// Routes whatever the audio fold-back queued (`ended`, `refused`) and
2084    /// redraws for what handling it changed.
2085    fn route_playback_events(&mut self) {
2086        let pending = self.core_mut().take_pending_events();
2087        if pending.is_empty() {
2088            return;
2089        }
2090        self.route_events(pending);
2091        for p in &self.panes {
2092            p.redraw_for(FrameCause::AUDIO);
2093        }
2094    }
2095
2096    /// An input's events reached the app: under `deferred_events` the next
2097    /// frame owes the host's answer (see `frame_waits_for_host`).
2098    fn owe_for(&self, reached_app: bool) {
2099        if reached_app && self.deferred_events {
2100            self.owed.set(true);
2101        }
2102    }
2103
2104    /// Returns whether anything reached the app (as against an extension
2105    /// answering for itself).
2106    fn route_events(&mut self, events: Vec<UiEvent>) -> bool {
2107        let mut reached_app = false;
2108        // An extension's replies go to whoever declared its slot (ADR 0014
2109        // decision 6): not routed by origin — a reply is addressed by being
2110        // one — and carrying the extension's origin, the window and the key
2111        // of the event it answered, so the receiver knows who spoke and
2112        // from where. For every extension this host placed itself, the
2113        // receiver is this host; for one a guest placed, it is the guest,
2114        // and `route` is the walk up.
2115        let Shell {
2116            extensions,
2117            app,
2118            panes,
2119            main_core,
2120            ..
2121        } = self;
2122        extensions.route(events, |ev| {
2123            reached_app = true;
2124            // Lent the core of the window the event came from (ADR 0036).
2125            match window_core(panes, main_core, ev.window) {
2126                Some(core) => app.on_event_with(ev, core),
2127                None => app.on_event(ev),
2128            }
2129        });
2130        // One app, one model, N windows: a handler that ran in answer to
2131        // input in *this* window can change what *another* window declares
2132        // — choosing an item in a popup is the app closing the popup, and
2133        // the declaration that closes it lives in the window that opened
2134        // it. So anything that reached the app redraws every window; the
2135        // caller has already redrawn the one the input landed in. Guarded
2136        // on there being more than one, so the single-window path — every
2137        // hover, every keystroke — is exactly what it was.
2138        if reached_app && self.panes.len() > 1 {
2139            for p in &self.panes {
2140                p.redraw_for(FrameCause::ELSEWHERE);
2141            }
2142        }
2143        reached_app
2144    }
2145
2146    /// Direct edits (cut) mutate the document outside `handle_input`, so
2147    /// the `changed` the core queued for it is routed here, and the window
2148    /// redrawn. The core posts the event (AR15: this used to build one by
2149    /// hand, and the menu's Cut posted none), so it is stamped and routed
2150    /// like the ones a keystroke makes.
2151    fn after_direct_edit(&mut self, i: usize) {
2152        let events = self.panes[i].core.take_pending_events();
2153        // A cut is input too: the frame that shows the text gone should
2154        // show what the app made of `changed`.
2155        let reached_app = self.route_events(events);
2156        self.owe_for(reached_app);
2157        // The one caller is the runner's own ⌘X, which the core never
2158        // hears as a key.
2159        self.panes[i].redraw_for(FrameCause::KEY);
2160    }
2161
2162    /// Builds and draws one window's frame.
2163    fn redraw(&mut self, i: usize) {
2164        let Shell {
2165            app,
2166            extensions,
2167            panes,
2168            min_size,
2169            max_size,
2170            epoch,
2171            system,
2172            pinned_system,
2173            audio,
2174            pretended_loss,
2175            ..
2176        } = self;
2177        let pane = &mut panes[i];
2178        // What the driver knows and the view only reads, refreshed for
2179        // this frame (it was already filled in when the pane opened).
2180        sync_env(pane, system, *pinned_system, audio.env());
2181        let window = &pane.window;
2182        // The core turns a changed viewport into a `resize` event, routed
2183        // with the rest of the pending events after this frame.
2184        let (viewport, scale) = pane.size();
2185        let size = window.inner_size();
2186        let t_view = std::time::Instant::now();
2187        pane.core.set_time(epoch.elapsed().as_secs_f64());
2188        // Why the runner asked, beside the input the core recorded: the
2189        // view reads both as `frame_cause` (backlog F111).
2190        pane.core.note_frame_cause(pane.cause.take());
2191        // The extensions fill the slots the host's view declares, in place
2192        // (`Ui::slot`), and `"root"` after it unless the host placed that
2193        // too — `finish` below does the latter and reports slots nobody
2194        // declared (ADR 0014). The core numbers their origins.
2195        let mut ui = pane.core.frame_with(viewport, scale, extensions);
2196        app.view(&mut ui);
2197        let view_ms = t_view.elapsed().as_secs_f32() * 1e3;
2198
2199        let t_layout = std::time::Instant::now();
2200        ui.finish();
2201        let layout_ms = t_layout.elapsed().as_secs_f32() * 1e3;
2202
2203        // Silent misconfigurations the core noticed (a grow weight with
2204        // nothing to split against, a transition on a positional key, two
2205        // nodes on one key): each once, to stderr, so they stop looking
2206        // like "the feature is broken".
2207        for w in pane.core.take_warnings() {
2208            eprintln!(
2209                "kui: warning [{}] node {:016x}: {}",
2210                w.code, w.key.0, w.message
2211            );
2212        }
2213
2214        // Mirror this frame's hit regions into the WM_NCHITTEST answerer.
2215        #[cfg(target_os = "windows")]
2216        if let Some(nc) = &pane.nc {
2217            nc.update(
2218                scale,
2219                window.is_maximized(),
2220                pane.core
2221                    .interaction
2222                    .hits()
2223                    .iter()
2224                    .map(|h| (h.window, h.rect.intersect(&h.clip))),
2225            );
2226        }
2227
2228        if let Some(t) = pane.core.window_title()
2229            && t != pane.applied_title
2230        {
2231            pane.applied_title = t.to_string();
2232            window.set_title(&pane.applied_title);
2233        }
2234
2235        // The level, the same way (backlog C30): a per-frame fact, applied
2236        // when it differs from what this pane has, and a popup's is never
2237        // touched. What the OS made of it is `env.window.always_on_top`
2238        // on the next `sync_env`, from the record `level_change` keeps.
2239        if let Some(level) = level_change(
2240            pane.kind,
2241            pane.core.always_on_top(),
2242            &mut pane.applied_on_top,
2243        ) {
2244            window.set_window_level(level);
2245        }
2246
2247        // Which Option keys are Alt, the same way (backlog F113): applied
2248        // when it differs from what this window has, never per frame. A
2249        // popup's own ask is applied too and never read — it cannot
2250        // become key on macOS, so its keys come through its owner.
2251        if let Some(_option_as_alt) =
2252            option_as_alt_change(pane.core.option_as_alt(), &mut pane.applied_option_as_alt)
2253        {
2254            #[cfg(target_os = "macos")]
2255            {
2256                use winit::platform::macos::{OptionAsAlt as Winit, WindowExtMacOS};
2257                window.set_option_as_alt(match _option_as_alt {
2258                    kui_core::OptionAsAlt::None => Winit::None,
2259                    kui_core::OptionAsAlt::Left => Winit::OnlyLeft,
2260                    kui_core::OptionAsAlt::Right => Winit::OnlyRight,
2261                    kui_core::OptionAsAlt::Both => Winit::Both,
2262                });
2263            }
2264        }
2265
2266        // The input method, the same way (backlog F125). Off, winit's
2267        // `keyDown:` stops calling `interpretKeyEvents:`, and everything
2268        // the OS composes there goes with it — an IME, a dead key, and
2269        // macOS's press-and-hold, which is an input method that swallows a
2270        // held letter's repeats; the key still arrives with the layout's
2271        // character as its text. A key still held from a press the IME
2272        // never saw keeps it off until it comes up (`Pane::ime_off_held`).
2273        if let Some(off) = ime_off_change(pane.ime_off_wanted(), &mut pane.applied_ime_off) {
2274            apply_ime_off(window, off);
2275        }
2276
2277        // The floor the app declared is a floor on the *app*: while the
2278        // devtools are docked in the main window, the pane's extent goes
2279        // on top of it, so the OS stops the window where the app is at
2280        // its minimum and not where the app less the dock is. After the
2281        // frame, since the handle's drag and the placement buttons land
2282        // in one; on change only, since it is a window-manager call.
2283        if pane.id == WindowId::MAIN
2284            && let Some((mw, mh)) = *min_size
2285        {
2286            let inset = pane.core.devtools_inset();
2287            let want = clamp_size((mw + inset.w as f64, mh + inset.h as f64), None, *max_size);
2288            if pane.applied_min != Some(want) {
2289                pane.applied_min = Some(want);
2290                window.set_min_inner_size(Some(LogicalSize::new(want.0, want.1)));
2291            }
2292        }
2293
2294        // Anchor the OS IME candidate window at the focused caret.
2295        if let Some(r) = pane.core.ime_rect() {
2296            window.set_ime_cursor_area(
2297                winit::dpi::LogicalPosition::new(r.x, r.y),
2298                winit::dpi::LogicalSize::new(r.w.max(1.0), r.h),
2299            );
2300        }
2301        // And say what the platform's own text input may ask the view:
2302        // whether there is somewhere to type, and where the caret is.
2303        #[cfg(target_os = "macos")]
2304        macos_text_input::stamp(window, &pane.core);
2305
2306        let t_render = std::time::Instant::now();
2307        // KUI_LOSE_DEVICE=SECS marks the device lost that long after
2308        // launch, once, to see the reopening below happen without a
2309        // driver update to cause it.
2310        if let Some(secs) = lose_device_at()
2311            && !*pretended_loss
2312            && epoch.elapsed().as_secs_f64() >= secs
2313            && let Some(r) = pane.renderer.as_ref()
2314        {
2315            *pretended_loss = true;
2316            r.gpu().mark_lost();
2317        }
2318        // The ground under the frame is a theme role like any other
2319        // (ADR 0019). Without this a view that paints no root background
2320        // — every example that lets the window show through — would show
2321        // the renderer's own near-black on a light desktop, which is the
2322        // one surface a `bg` prop cannot reach.
2323        // Written straight through: the renderer asks for a non-sRGB
2324        // surface, so a clear component is the byte it lands as, the same
2325        // way a quad's colour is.
2326        // Over a backdrop the ground is nothing at all (backlog F126): what
2327        // the view paints is what covers the material, and a view that
2328        // paints no root background shows it whole.
2329        let ground = pane.core.theme().bg;
2330        // The wallpaper kui draws where the OS has no material: handed to
2331        // the renderer once it has loaded, and the part behind the window
2332        // set when the window moved. A wallpaper that would not read is
2333        // said once, and the window is opaque from then on.
2334        if let (Some(g), Some(r)) = (pane.ground.as_mut(), pane.renderer.as_mut())
2335            && let Err(why) = g.prepare(window, r)
2336        {
2337            eprintln!("kui: no wallpaper to draw behind the window: {why}");
2338            pane.ground = None;
2339            pane.backdrop = Backdrop::Opaque;
2340            r.clear_ground();
2341        }
2342        let clear = if pane.backdrop.is_translucent() && pane.ground.is_none() {
2343            kui_wgpu::wgpu::Color::TRANSPARENT
2344        } else {
2345            kui_wgpu::wgpu::Color {
2346                r: ground.r as f64,
2347                g: ground.g as f64,
2348                b: ground.b as f64,
2349                a: ground.a as f64,
2350            }
2351        };
2352        let (dl, atlas) = pane.core.output();
2353        let mut wait_ms = 0.0;
2354        let mut reopen = false;
2355        let drawn = pane.renderer.as_mut().map(|r| {
2356            r.clear_color = clear;
2357            r.render(dl, atlas)
2358        });
2359        match drawn {
2360            Some(Ok(report)) => {
2361                wait_ms = report.vsync_wait_ms;
2362                pane.pacer
2363                    .presented(std::time::Instant::now(), (size.width, size.height));
2364                pane.retry.presented();
2365                pane.surface_tries = 0;
2366                pane.awaits_device = false;
2367            }
2368            Some(Err(kui_wgpu::RenderError::Reconfigure)) => {
2369                if let Some(r) = pane.renderer.as_mut() {
2370                    r.resize(size.width, size.height);
2371                }
2372                pane.redraw_for(FrameCause::RETRY);
2373            }
2374            // The surface is configured wrong for the window — a size the
2375            // platform never told us, a swapchain a driver update left
2376            // behind: configure it to the window's size and draw again;
2377            // a surface that stays wrong is given up with its device.
2378            // Past the tries the frame asks for no other: the reopen is
2379            // what asks for the next one, and if it has to wait out its
2380            // second, a frame asked for now would only be refused again —
2381            // at once, with no vsync to pace it. Said once per surface
2382            // given up, not once per refused frame.
2383            Some(Err(kui_wgpu::RenderError::Validation)) => {
2384                match surface_refused(&mut pane.surface_tries) {
2385                    Refused::Retry => {
2386                        if let Some(r) = pane.renderer.as_mut() {
2387                            r.resize(size.width, size.height);
2388                        }
2389                        pane.redraw_for(FrameCause::RETRY);
2390                    }
2391                    Refused::GiveUp { say } => {
2392                        if say {
2393                            eprintln!("kui: the surface stays invalid; reopening the device");
2394                        }
2395                        reopen = true;
2396                    }
2397                }
2398            }
2399            // Occluded or timed out: nothing to present, and the frame is
2400            // owed — *scheduled*, since nothing else may ask for one. A
2401            // window ordered front, or brought back with ⌘-Tab, reports
2402            // itself occluded for a beat or two before the platform
2403            // catches up; its frame dropped, it showed the one from
2404            // before until a stray mouse move woke it (F102). Only for a
2405            // bounded number of tries, and not while the platform says
2406            // the window is covered, so a hidden window does not spin.
2407            Some(Err(kui_wgpu::RenderError::Skip)) => {
2408                let now = std::time::Instant::now();
2409                pane.retry.skipped(now);
2410                // A skipped frame paces the next as a presented one does:
2411                // what asks while the surface skips (a waker, the host) is
2412                // held for the display, or its fallback, instead of drawn
2413                // at once into another skip (backlog RG98).
2414                pane.pacer.presented(now, (size.width, size.height));
2415            }
2416            // The device is gone (a driver update, a GPU reset), or a
2417            // frame ago it was and no new one could be opened: open one.
2418            Some(Err(kui_wgpu::RenderError::DeviceLost)) | None => reopen = true,
2419        }
2420        pane.awaits_device |= reopen;
2421        let render_ms = (t_render.elapsed().as_secs_f32() * 1e3 - wait_ms).max(0.0);
2422
2423        pane.core.stats.push(FrameSample {
2424            input_ms: 0.0,
2425            view_ms,
2426            layout_ms,
2427            render_ms,
2428            wait_ms,
2429        });
2430        if reopen {
2431            self.reopen_device();
2432        }
2433    }
2434
2435    /// The device is gone — a driver update or a GPU reset took it, and
2436    /// every swapchain with it — so one new device is opened, and a
2437    /// renderer on it for every window, each window's old one dropped
2438    /// before its new surface is made (DXGI gives a window one flip-model
2439    /// swapchain). The windows keep their cores: the next frame draws
2440    /// what the last one would have. A window whose renderer cannot be
2441    /// made has none, and the device is tried again a second later; a
2442    /// device that cannot be opened is tried, and said, once a second, not
2443    /// once a frame. Asked for inside that second, the ask is owed
2444    /// (`reopen_owed`) and `about_to_wait` makes it when the second is up.
2445    fn reopen_device(&mut self) {
2446        let now = std::time::Instant::now();
2447        if reopen_due(self.reopened, now) > now {
2448            self.reopen_owed = true;
2449            return;
2450        }
2451        self.reopened = Some(now);
2452        // Dropped, not leaked: the old swapchain has to be released for
2453        // DXGI to allow the window a new one (leaked, the new surface's
2454        // configure fails with "invalid surface").
2455        for pane in &mut self.panes {
2456            pane.renderer = None;
2457            pane.surface_tries = 0;
2458        }
2459        self.gpu = None;
2460        let mut gpu: Option<kui_wgpu::Gpu> = None;
2461        let options = self.gpu_options();
2462        for pane in &mut self.panes {
2463            let px = pane.window.inner_size();
2464            let made = match &gpu {
2465                None => pollster::block_on(kui_wgpu::Renderer::new_with(
2466                    pane.window.clone(),
2467                    px.width,
2468                    px.height,
2469                    options,
2470                )),
2471                Some(gpu) => kui_wgpu::Renderer::new_in_with(
2472                    gpu,
2473                    pane.window.clone(),
2474                    px.width,
2475                    px.height,
2476                    pane.backdrop.is_translucent(),
2477                ),
2478            };
2479            match made {
2480                Ok(mut r) => {
2481                    r.set_frame_latency(self.frame_latency);
2482                    // The window keeps its backdrop where the new surface
2483                    // takes alpha too; one that will not any more leaves
2484                    // the window opaque, and says so.
2485                    if pane.backdrop.is_translucent() && pane.ground.is_none() && !r.transparent() {
2486                        pane.backdrop = Backdrop::Opaque;
2487                    }
2488                    // A wallpaper drawn by kui goes to the new renderer too.
2489                    if let Some(g) = pane.ground.as_mut() {
2490                        g.renderer_replaced();
2491                    }
2492                    let opened = gpu.is_none();
2493                    gpu.get_or_insert_with(|| r.gpu().clone());
2494                    if opened {
2495                        eprintln!("kui: device reopened");
2496                    }
2497                    pane.renderer = Some(r);
2498                    pane.redraw_for(FrameCause::DEVICE);
2499                }
2500                Err(err) => eprintln!("kui: cannot reopen window {}: {err}", pane.id.0),
2501            }
2502            pane.awaits_device = pane.renderer.is_none();
2503        }
2504        // A window left without a renderer — or every window, when no
2505        // device would open — is tried again a second from now, whether
2506        // or not anything asks it for a frame.
2507        self.reopen_owed = self.panes.iter().any(|p| p.awaits_device);
2508        // The new device may be another adapter's, with or without the
2509        // per-channel blend LCD masks need: decided again, for every core,
2510        // or a core keeps rasterising masks the new pipeline cannot split.
2511        // A changed decision empties each core's atlas (`set_subpixel_text`),
2512        // which the fresh renderer was going to upload whole anyway.
2513        if let Some(gpu) = &gpu {
2514            let wanted = aa_under(wanted_text_aa(self.text_aa), self.backdrop);
2515            let on = subpixel_on(wanted, gpu.dual_source());
2516            if on != self.subpixel {
2517                self.subpixel = on;
2518                for pane in &mut self.panes {
2519                    pane.core.set_subpixel_text(on);
2520                }
2521            }
2522        }
2523        self.gpu = gpu;
2524    }
2525}
2526
2527/// Which bar `pump_menu_bar` last handed the platform.
2528#[cfg(target_os = "macos")]
2529#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2530enum AppliedBar {
2531    /// The standard bar: no window declared one, or the front
2532    /// window draws its own declaration and the platform's is the standard.
2533    Standard,
2534    /// A window's declaration, at that revision.
2535    Declared(WindowId, u64),
2536}
2537
2538impl ApplicationHandler<access_bridge::UserEvent> for DynShell<'_> {
2539    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
2540        if !self.panes.is_empty() || self.opened {
2541            return;
2542        }
2543        self.opened = true;
2544        // KUI_WINDOW=WxH overrides the initial size (useful for testing).
2545        let size = std::env::var("KUI_WINDOW")
2546            .ok()
2547            .and_then(|s| {
2548                let (w, h) = s.split_once('x')?;
2549                Some((w.parse().ok()?, h.parse().ok()?))
2550            })
2551            .map(|s| clamp_size(s, self.min_size, self.max_size))
2552            .unwrap_or(self.size);
2553        let mut attrs = self.window_attrs(&self.title.clone(), size, self.chrome, self.backdrop);
2554        if let Some((mw, mh)) = self.min_size {
2555            attrs = attrs.with_min_inner_size(LogicalSize::new(mw, mh));
2556        }
2557        if let Some((mw, mh)) = self.max_size {
2558            attrs = attrs.with_max_inner_size(LogicalSize::new(mw, mh));
2559        }
2560        // KUI_WINDOW_AT=X,Y places it, logical px from the screen's top
2561        // left: the smoke round's `--jobs` cascades its windows by it, so
2562        // none is wholly covered — a covered window is `Occluded` and
2563        // presents nothing, and the round counts presents.
2564        if let Some((x, y)) = std::env::var("KUI_WINDOW_AT").ok().and_then(|s| {
2565            let (x, y) = s.split_once(',')?;
2566            Some((x.parse::<f64>().ok()?, y.parse::<f64>().ok()?))
2567        }) {
2568            attrs = attrs.with_position(LogicalPosition::new(x, y));
2569        }
2570        let window = match event_loop.create_window(attrs) {
2571            Ok(w) => Arc::new(w),
2572            Err(e) => return self.fail_open(event_loop, format!("cannot open the window: {e}")),
2573        };
2574        self.icon.set_on(&window);
2575        let px = window.inner_size();
2576        let renderer = pollster::block_on(kui_wgpu::Renderer::new_with(
2577            window.clone(),
2578            px.width,
2579            px.height,
2580            self.gpu_options(),
2581        ));
2582        let mut renderer = match renderer {
2583            Ok(r) => r,
2584            Err(e) => return self.fail_open(event_loop, format!("cannot draw in the window: {e}")),
2585        };
2586        renderer.set_frame_latency(self.frame_latency);
2587        // What shows through it, now that there is a surface to present
2588        // with alpha (backlog F126); before it is shown.
2589        let backdrop = backdrop::apply(&window, &renderer, self.backdrop);
2590        // Subpixel text only where the renderer blends per channel; the
2591        // env var wins over the builder for quick A/B comparisons.
2592        self.subpixel = subpixel_on(
2593            aa_under(wanted_text_aa(self.text_aa), self.backdrop),
2594            renderer.subpixel_text(),
2595        );
2596        self.gpu = Some(renderer.gpu().clone());
2597        let mut core = self
2598            .main_core
2599            .take()
2600            .expect("the main core is built once, by the launcher");
2601        core.set_subpixel_text(self.subpixel);
2602        core.env.window.id = WindowId::MAIN;
2603        self.push_pane(
2604            event_loop,
2605            WindowId::MAIN,
2606            WindowConfig::default(),
2607            WindowId::MAIN,
2608            self.chrome,
2609            core,
2610            window,
2611            renderer,
2612            backdrop,
2613        );
2614        self.panes[0].applied_title = self.title.clone();
2615        self.panes[0].applied_min = self.min_size;
2616    }
2617
2618    fn window_event(
2619        &mut self,
2620        event_loop: &ActiveEventLoop,
2621        id: WinitWindowId,
2622        event: WindowEvent,
2623    ) {
2624        let Some(i) = self.pane_index(id) else { return };
2625        // Everything but the redraw itself: a redraw is the *answer* to an
2626        // event, so counting it would make a frame its own reason for the
2627        // next one and an animation would report activity for ever.
2628        if !matches!(event, WindowEvent::RedrawRequested) {
2629            self.saw_event = true;
2630        }
2631        {
2632            let pane = &mut self.panes[i];
2633            if let Some(bridge) = &mut pane.access {
2634                bridge.process_event(&pane.window, &event);
2635            }
2636        }
2637        match event {
2638            WindowEvent::CloseRequested => {
2639                if self.panes[i].id == WindowId::MAIN {
2640                    self.exit_main(event_loop);
2641                } else {
2642                    let id = self.panes[i].id;
2643                    self.close_pane(event_loop, id);
2644                }
2645            }
2646            // On Windows minimizing and restoring are each a `WM_SIZE`:
2647            // the first is where the window went dark, the second the
2648            // frame that brings it back (backlog RG97).
2649            WindowEvent::Resized(size) => {
2650                let pane = &mut self.panes[i];
2651                if let Some(r) = pane.renderer.as_mut() {
2652                    r.resize(size.width, size.height);
2653                }
2654                if let Some(g) = pane.ground.as_mut() {
2655                    g.moved();
2656                }
2657                if pane.minimized() {
2658                    pane.cause.went_dark();
2659                    pane.redraw_for(FrameCause::RESIZE);
2660                } else if pane.cause.is_dark() && cfg!(target_os = "windows") {
2661                    pane.came_back(FrameCause::RESIZE);
2662                } else {
2663                    // Elsewhere a window resized while covered is still
2664                    // covered; `Occluded(false)` is its way back.
2665                    pane.redraw_for(FrameCause::RESIZE);
2666                }
2667            }
2668            WindowEvent::ScaleFactorChanged { .. } => {
2669                self.panes[i].redraw_for(FrameCause::SCALE);
2670            }
2671            // The wallpaper kui draws behind a window stays put on the
2672            // screen as the window moves over it (backlog F126); nothing
2673            // else here cares where the window is.
2674            WindowEvent::Moved(_) => {
2675                let pane = &mut self.panes[i];
2676                if let Some(g) = pane.ground.as_mut() {
2677                    g.moved();
2678                    pane.redraw_for(FrameCause::RESIZE);
2679                }
2680            }
2681            WindowEvent::CursorMoved { position, .. } => {
2682                let pane = &mut self.panes[i];
2683                let scale = pane.window.scale_factor() as f32;
2684                let p = Vec2::new(position.x as f32 / scale, position.y as f32 / scale);
2685                if pane.synthesizes_resize() {
2686                    pane.resize_edge = pane.resize_edge_at(p);
2687                }
2688                if pane.cursor != p {
2689                    pane.scroll_gesture.pointer_moved();
2690                }
2691                pane.cursor = p;
2692                let from = pane.id;
2693                self.dispatch(event_loop, i, InputEvent::CursorMoved(p));
2694                // And then, if this pane is holding a press that a popup
2695                // joined, the same move again in that popup's coordinates.
2696                self.retarget_move(event_loop, from, p);
2697            }
2698            WindowEvent::CursorLeft { .. } => {
2699                self.dispatch(event_loop, i, InputEvent::CursorLeft);
2700            }
2701            // Files dragged in from the OS, as winit reports them: one
2702            // event per file and no position (ADR 0031, decision 5). On
2703            // macOS the delegate override supersedes all three with the
2704            // position AppKit has (`mod macos_drop`); elsewhere the files
2705            // are collected per batch and dispatched at its end, at the
2706            // pane's last reported cursor — the point at enter and at
2707            // release, since no platform here reports the drag moving.
2708            WindowEvent::HoveredFile(path) => {
2709                if !self.file_drag_is_overridden() {
2710                    let pane = &mut self.panes[i];
2711                    pane.file_drag.push(path.to_string_lossy().into_owned());
2712                    pane.file_drag_pending = Some(false);
2713                }
2714            }
2715            WindowEvent::DroppedFile(path) => {
2716                if !self.file_drag_is_overridden() {
2717                    let pane = &mut self.panes[i];
2718                    // A hover batch still waiting in the same turn is the
2719                    // same files: the drop's list starts over.
2720                    if pane.file_drag_pending != Some(true) {
2721                        pane.file_drag.clear();
2722                    }
2723                    pane.file_drag.push(path.to_string_lossy().into_owned());
2724                    pane.file_drag_pending = Some(true);
2725                }
2726            }
2727            WindowEvent::HoveredFileCancelled => {
2728                if !self.file_drag_is_overridden() {
2729                    let pane = &mut self.panes[i];
2730                    pane.file_drag.clear();
2731                    pane.file_drag_pending = None;
2732                    self.dispatch(event_loop, i, InputEvent::DragCancel);
2733                }
2734            }
2735            // Recorded, not acted on: what a view reads is derived from
2736            // every window's copy at the end of the batch (`settle_focus`),
2737            // because focus *moving* is two events and neither alone is the
2738            // answer.
2739            WindowEvent::Focused(focused) => {
2740                self.panes[i].os_focused = focused;
2741                // A modifier let go elsewhere never comes up here: what
2742                // was down is forgotten with the keyboard (backlog F108).
2743                if !focused {
2744                    self.panes[i].modifier_keys_down.clear();
2745                    // And so is a key held through a mode change: its
2746                    // release lands elsewhere, so the IME it was keeping
2747                    // off is the frame's to decide again.
2748                    self.panes[i].ime_off_held.clear();
2749                    self.panes[i].sync_ime();
2750                }
2751                // Coming back to the app is the cheap, reliable sign that
2752                // the user may have been in a settings app: the accent and
2753                // the reduce-motion setting have no event to subscribe to
2754                // here, and re-asking costs microseconds against something
2755                // that happens when a human switches windows.
2756                if focused {
2757                    let before = (self.system, self.panes[i].appearance);
2758                    self.system = system_env::query();
2759                    // And the window's own setting, in case the platform
2760                    // changed it without an event while we were away.
2761                    self.panes[i].appearance = appearance_of(&self.panes[i].window);
2762                    // A change found this way has no event of its own
2763                    // behind it, so ask for the frame that reports it:
2764                    // `begin_frame` turns the difference into a `system`
2765                    // event, and a host that only draws on input would
2766                    // otherwise not learn of it until it drew for
2767                    // something else (F40).
2768                    if before != (self.system, self.panes[i].appearance) {
2769                        for p in &self.panes {
2770                            p.redraw_for(FrameCause::APPEARANCE);
2771                        }
2772                    }
2773                }
2774            }
2775            // Covered or uncovered — where the platform says (macOS, X11):
2776            // uncovered, the window shows what it presented before it was
2777            // covered, so a frame is owed now (F102); covered, frames the
2778            // surface skips are not retried.
2779            // Covered is where a window goes dark, minimized on macOS
2780            // included, and uncovered where it comes back (RG97).
2781            WindowEvent::Occluded(covered) => {
2782                self.panes[i]
2783                    .retry
2784                    .occluded(covered, std::time::Instant::now());
2785                if covered {
2786                    self.panes[i].cause.went_dark();
2787                } else {
2788                    self.panes[i].came_back(FrameCause::OCCLUSION);
2789                }
2790            }
2791            // The theme changing is the other one, and the only one that
2792            // arrives while the app is in front. The next frame reads the
2793            // appearance off the window anyway; the redraw is what makes
2794            // there *be* a next frame in an app that only draws on input.
2795            WindowEvent::ThemeChanged(theme) => {
2796                self.panes[i].appearance = theme_appearance(Some(theme));
2797                self.system = system_env::query();
2798                self.panes[i].redraw_for(FrameCause::APPEARANCE);
2799            }
2800            // The four keyboard events go to `key_target`, which is this
2801            // pane unless it is lending its keyboard to a non-activating
2802            // popup. The modifier mirror follows them, or the popup would
2803            // read a stale Shift.
2804            WindowEvent::ModifiersChanged(m) => {
2805                // The keyboard's state is one fact for the pair: the OS
2806                // delivers the edge to the owner, the target reads it for
2807                // the keys it borrows, and the owner keeps reading it once
2808                // the popup is gone — written to the target alone, a Shift
2809                // released while a menu was up left the owner's next key a
2810                // Shift chord (AR23).
2811                let t = self.key_target(i);
2812                self.panes[i].modifiers = m.state();
2813                self.panes[t].modifiers = m.state();
2814                use winit::keyboard::ModifiersKeyState::Pressed;
2815                let alt = (m.lalt_state() == Pressed, m.ralt_state() == Pressed);
2816                self.panes[i].alt_held = alt;
2817                self.panes[t].alt_held = alt;
2818                let kmods = self.panes[t].kmods();
2819                self.dispatch(event_loop, t, InputEvent::Modifiers(kmods));
2820            }
2821            // Not a press winit made up: on Windows and X11 a window
2822            // gaining focus is handed a press of every key already held —
2823            // made in another window or another app — and a key whose
2824            // press closed a window pressed again in the one beneath it
2825            // (backlog RG100). The releases it makes up as a window loses
2826            // focus are kept: they are what lets go of a key a sink held.
2827            WindowEvent::KeyboardInput {
2828                event,
2829                is_synthetic,
2830                ..
2831            } => {
2832                if !(is_synthetic && event.state == ElementState::Pressed) {
2833                    let t = self.key_target(i);
2834                    self.on_key(event_loop, i, t, event)
2835                }
2836            }
2837            WindowEvent::Ime(Ime::Commit(text)) => {
2838                // Its own channel, not `Text`: a sink hears a commit as a
2839                // `text` event and a keystroke as a `key` event, once each
2840                // (backlog C17); a stock editor takes both the same way.
2841                self.panes[i].preedit_open = false;
2842                let t = self.key_target(i);
2843                self.dispatch(event_loop, t, InputEvent::Commit(text));
2844            }
2845            WindowEvent::Ime(Ime::Preedit(text, cursor)) => {
2846                self.panes[i].preedit_open = !text.is_empty();
2847                let t = self.key_target(i);
2848                self.dispatch(event_loop, t, InputEvent::Preedit(text, cursor));
2849            }
2850            // The IME went away — the frame turned it off (`imeOff`), or
2851            // the user switched input source — and winit's contract is
2852            // that a pending preedit is cleared: a composition still open
2853            // ends without a commit, as an empty preedit, the way an IME
2854            // that cancels says it.
2855            WindowEvent::Ime(Ime::Disabled) => {
2856                if std::mem::take(&mut self.panes[i].preedit_open) {
2857                    let t = self.key_target(i);
2858                    self.dispatch(event_loop, t, InputEvent::Preedit(String::new(), None));
2859                }
2860            }
2861            // Force Touch: stage 2 is the deepened press macOS calls a
2862            // force click. winit reports the whole ramp, and only the
2863            // *edge* into stage 2 is the gesture — a stage that stays at 2
2864            // while the finger presses harder is the same click still
2865            // happening (ADR 0017, decision 6). macOS-only: no other
2866            // winit backend reports pressure at all.
2867            WindowEvent::TouchpadPressure { stage, .. } => {
2868                let pane = &mut self.panes[i];
2869                let was = std::mem::replace(&mut pane.pressure_stage, stage);
2870                if stage >= 2 && was < 2 {
2871                    let at = pane.cursor;
2872                    self.dispatch(event_loop, i, InputEvent::ForceClick(at));
2873                }
2874            }
2875            WindowEvent::MouseWheel { delta, phase, .. } => {
2876                let started = phase == winit::event::TouchPhase::Started;
2877                let pane = &mut self.panes[i];
2878                let scale = pane.window.scale_factor() as f32;
2879                let now = std::time::Instant::now();
2880                let (d, kind) = match delta {
2881                    winit::event::MouseScrollDelta::LineDelta(x, y) => {
2882                        pane.axis_lock.end();
2883                        (
2884                            Vec2::new(Core::lines_to_px(x), Core::lines_to_px(y)),
2885                            scroll_gesture::Kind::Line,
2886                        )
2887                    }
2888                    // A trackpad's swipe keeps to its axis (`mod axis_lock`),
2889                    // and a finger put down begins the next, glide or no
2890                    // glide (backlog F117).
2891                    winit::event::MouseScrollDelta::PixelDelta(p) => {
2892                        if pane.scroll_gesture.phase(phase, now) {
2893                            pane.axis_lock.end();
2894                        }
2895                        (
2896                            pane.axis_lock
2897                                .pixel(Vec2::new(p.x as f32 / scale, p.y as f32 / scale), now),
2898                            scroll_gesture::Kind::Pixel,
2899                        )
2900                    }
2901                };
2902                // The gesture it is part of keeps the targets it began
2903                // with (`mod scroll_gesture`, backlog F107).
2904                if d != Vec2::ZERO {
2905                    let begins = pane.scroll_gesture.begins(kind, started, now);
2906                    self.dispatch(
2907                        event_loop,
2908                        i,
2909                        InputEvent::ScrollGesture { delta: d, begins },
2910                    );
2911                } else {
2912                    pane.scroll_gesture.note(kind, started, now);
2913                }
2914            }
2915            WindowEvent::MouseInput { state, button, .. } => {
2916                let button = match button {
2917                    WinitButton::Left => MouseButton::Primary,
2918                    WinitButton::Right => MouseButton::Secondary,
2919                    WinitButton::Middle => MouseButton::Middle,
2920                    // `onButton` hears these as `Other`'s code (backlog
2921                    // F105), so the numbering has to be stable: back,
2922                    // forward, then whatever the platform reports beyond
2923                    // them.
2924                    WinitButton::Back => MouseButton::Other(0),
2925                    WinitButton::Forward => MouseButton::Other(1),
2926                    WinitButton::Other(n) => {
2927                        MouseButton::Other(n.saturating_add(2).min(u8::MAX as u16) as u8)
2928                    }
2929                };
2930                let primary = button == MouseButton::Primary;
2931                let here = self.panes[i].id;
2932                // Which pane holds a primary press, for ADR 0009's arming.
2933                // Set for a consumed press too: the button is down whatever
2934                // the core was told, and the release below clears it.
2935                if primary {
2936                    self.primary_down = (state == ElementState::Pressed).then_some(here);
2937                    if state == ElementState::Pressed {
2938                        // A consumed press whose release never arrived — the
2939                        // window lost the keyboard mid-gesture, say — must
2940                        // not swallow the next one instead.
2941                        self.swallowed_press = None;
2942                    }
2943                }
2944                // A press anywhere but inside a popup is "outside" it —
2945                // the owner's own window included, which is exactly the
2946                // line a separate surface draws. Reported before the press
2947                // is dispatched, so an app that stops declaring the popup
2948                // on the dismissal still sees the click it was dismissed
2949                // by, the way a modal's dismissal works (ADR 0003).
2950                //
2951                // And then a primary press that dismissed a
2952                // **non-activating** popup is **consumed** — not dispatched
2953                // to the window it landed in, and its release swallowed with
2954                // it (ADR 0009 decision 5). The pass-through this replaces
2955                // claimed to mirror ADR 0003 and had it backwards: under an
2956                // in-window modal everything outside emits no hit region, so
2957                // the outside press dismisses and lands on nothing, while a
2958                // popup's owner is live (ADR 0004 decision 10) and the press
2959                // dismisses *and* acts. Invisible with click-to-open;
2960                // decisive with open-on-press, where a press on the open
2961                // field would otherwise dismiss and reopen in one gesture,
2962                // and no ordering of the two events lets the app tell that
2963                // press from the first. An **activating** popup — a tear-off
2964                // panel — keeps the pass-through, since someone working in a
2965                // panel beside the app expects a click in the app to act.
2966                if state == ElementState::Pressed {
2967                    let mut consumed = false;
2968                    let mut reached_app = false;
2969                    for (id, activates) in self.popups_outside(i) {
2970                        reached_app |= self.dismiss(id, DismissReason::Outside);
2971                        consumed |= primary && !activates;
2972                    }
2973                    if consumed {
2974                        self.swallowed_press = Some(here);
2975                        // Choosing in a menu closes it *and* does what it
2976                        // says: one frame, so this one waits for the host.
2977                        self.owe_for(reached_app);
2978                        // The press the core never saw.
2979                        for p in &self.panes {
2980                            p.redraw_for(FrameCause::BUTTON);
2981                        }
2982                        return;
2983                    }
2984                }
2985                // A press inside a non-activating popup arms that popup for
2986                // its own release (ADR 0009 decision 4's last paragraph):
2987                // the OS keeps the drag here whatever it wanders over, so a
2988                // drag off the top edge and a release on the desktop has to
2989                // be classified rather than ignored — the measured case in
2990                // backlog W2. It gets no retargeted moves, having the real
2991                // ones already.
2992                if primary
2993                    && state == ElementState::Pressed
2994                    && self.panes[i].kind == WindowKind::Popup
2995                    && !self.panes[i].activates
2996                    && !self.armed.iter().any(|a| a.id == here)
2997                {
2998                    self.armed.push(Armed {
2999                        id: here,
3000                        inside: true,
3001                    });
3002                }
3003                if state == ElementState::Released && primary {
3004                    // The release of a press the driver ate goes with it:
3005                    // the core never saw the `down`, so nothing should see
3006                    // this `up`.
3007                    if self.swallowed_press == Some(here) {
3008                        self.swallowed_press = None;
3009                        self.primary_down = None;
3010                        return;
3011                    }
3012                    let at = self.panes[i].cursor;
3013                    self.classify_release(event_loop, here, at);
3014                }
3015                // The frame the classification ran may have closed a window
3016                // and moved this one down the list.
3017                let Some(i) = self.pane_of(here) else { return };
3018                let pane = &mut self.panes[i];
3019                // A press on the synthesized resize band starts an OS resize
3020                // instead of reaching the UI.
3021                if primary
3022                    && state == ElementState::Pressed
3023                    && let Some(dir) = pane.resize_edge
3024                {
3025                    let _ = pane.window.drag_resize_window(dir);
3026                    return;
3027                }
3028                let ev = match state {
3029                    ElementState::Pressed => {
3030                        // Multi-click is the primary button's: a right
3031                        // press between two left ones does not break the
3032                        // run, and never counts up one of its own.
3033                        let clicks = if primary {
3034                            let now = std::time::Instant::now();
3035                            let clicks = match pane.last_click {
3036                                Some((t, p, n))
3037                                    if now.duration_since(t).as_millis() < MULTI_CLICK_MS
3038                                        && (p.x - pane.cursor.x).abs() < MULTI_CLICK_SLOP
3039                                        && (p.y - pane.cursor.y).abs() < MULTI_CLICK_SLOP =>
3040                                {
3041                                    // Cycle 1 → 2 → 3 → 1 like most editors.
3042                                    n % 3 + 1
3043                                }
3044                                _ => 1,
3045                            };
3046                            pane.last_click = Some((now, pane.cursor, clicks));
3047                            clicks
3048                        } else {
3049                            1
3050                        };
3051                        InputEvent::MouseDown { button, clicks }
3052                    }
3053                    ElementState::Released => InputEvent::MouseUp { button },
3054                };
3055                self.dispatch(event_loop, i, ev);
3056            }
3057            WindowEvent::RedrawRequested
3058                if frame_waits_for_host(self.owed.get(), self.panes[i].deferred_frame) =>
3059            {
3060                // What would be painted predates an input the app has been
3061                // told about and not yet answered — the release of a
3062                // button, with the count still at its old value. The host
3063                // asks again the moment its handler has run, and that
3064                // frame carries both. Never twice running, so nothing here
3065                // can stop a window painting.
3066                self.panes[i].deferred_frame = true;
3067            }
3068            // A frame asked for while frames run back to back waits for
3069            // the display, which asks again at the vsync (`mod pacer`).
3070            WindowEvent::RedrawRequested if !self.panes[i].admit_frame() => {}
3071            WindowEvent::RedrawRequested => {
3072                self.panes[i].deferred_frame = false;
3073                self.redraw(i);
3074                // KUI_SMOKE_FRAMES: count what the main window actually
3075                // landed and quit at the target. Counted only once a
3076                // present succeeded, so a window that never draws never
3077                // counts and the run fails on the caller's timeout rather
3078                // than passing quietly. Asking for the next
3079                // one keeps an app that paints only on input painting, so
3080                // every example reaches the count at the same speed.
3081                if let Some(n) = self.smoke_frames
3082                    && let Some(p) = self.panes.get(i)
3083                    && p.id == WindowId::MAIN
3084                    && p.retry.presented_once()
3085                {
3086                    self.frames_drawn += 1;
3087                    if self.frames_drawn >= n {
3088                        self.exit_requested = true;
3089                    } else {
3090                        self.panes[i].redraw_for(FrameCause::SMOKE);
3091                    }
3092                }
3093                self.panes[i].publish_access();
3094                // Views can declare windows and window commands too
3095                // (ui.window, ui.window_command); apply them the same frame
3096                // they were declared. Likewise the sounds a frame started
3097                // (audio nodes, ui.play), and the clipboard work a view
3098                // queued (ui.set_clipboard, ui.request_paste — backlog
3099                // C33), which until now only an input's drain reached.
3100                self.apply_menu_actions(event_loop, i);
3101                self.apply_window_commands(event_loop);
3102                self.apply_audio();
3103                // The frame may have closed this very pane.
3104                let Some(i) = self.pane_index(id) else { return };
3105                // A new frame can put something else under a still cursor.
3106                self.panes[i].apply_cursor();
3107                // A frame can resize the viewport, and can change what sits
3108                // under a still cursor; route the resulting resize / hover
3109                // events now rather than with the next input, and redraw for
3110                // what they change.
3111                let pending = self.panes[i].core.take_pending_events();
3112                if !pending.is_empty() {
3113                    self.route_events(pending);
3114                    if let Some(p) = self.panes.get(i) {
3115                        p.redraw_for(FrameCause::AFTER_FRAME);
3116                    }
3117                }
3118                // Windows moves and resizes a window inside its own modal
3119                // loop, where `about_to_wait` — the pacing that asks for
3120                // the next frame of an animation — does not run, so a
3121                // transition froze for as long as the title bar was held
3122                // (backlog W3). The pane's own timer is what answers that,
3123                // and this is where it learns whether there is anything to
3124                // animate; `mod windows_anim` is why it is a timer and not
3125                // a redraw asked for from right here. Not while the window
3126                // waits for a device: `about_to_wait` asks it for no
3127                // animation frames then (RG29), and the timer asked for 64
3128                // a second, each a view built for no renderer (RG40). The
3129                // reopen's own `request_redraw` arms it again. Nor while
3130                // it is minimized (RG45); the restore's `Resized` does.
3131                #[cfg(target_os = "windows")]
3132                if let Some(p) = self.panes.get_mut(i) {
3133                    let animating = p.animates_now();
3134                    if let Some(t) = &mut p.anim_timer {
3135                        t.set(animating);
3136                    }
3137                }
3138            }
3139            _ => {}
3140        }
3141        if self.exit_requested {
3142            self.exit_main(event_loop);
3143        }
3144    }
3145
3146    /// AccessKit's side of the conversation: assistive technology attaching
3147    /// (send it the tree, and let the view know), detaching, or asking for
3148    /// an action (input).
3149    /// The loop's last event: the app's `teardown`, before the process
3150    /// goes (a Quit from the OS) or `run` returns (the main window
3151    /// closed).
3152    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
3153        self.teardown_once();
3154    }
3155
3156    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: access_bridge::UserEvent) {
3157        // A wake is the app saying "what `view` shows has changed": every
3158        // window draws, as after any input. Coalesced by the platform's
3159        // queue, so a thread waking a thousand times a frame costs one.
3160        self.saw_event = true;
3161        if matches!(event, access_bridge::UserEvent::Wake) {
3162            for pane in &self.panes {
3163                pane.redraw_for(FrameCause::WAKE);
3164            }
3165            return;
3166        }
3167        // The installed fonts changed: the session scans again, through
3168        // any one window's core since every window shares it, and the
3169        // windows draw — each shapes its text again on that frame
3170        // (`weights_rev`), fallback being free to land on a new face. A
3171        // signal that found nothing new (a second window's copy of a
3172        // Windows broadcast) changes nothing and draws nothing.
3173        if matches!(event, access_bridge::UserEvent::FontsChanged) {
3174            system_fonts::handled();
3175            let changed = self
3176                .panes
3177                .first_mut()
3178                .map_or(0, |pane| pane.core.reload_system_fonts());
3179            if changed > 0 {
3180                for pane in &self.panes {
3181                    pane.redraw_for(FrameCause::APPEARANCE);
3182                }
3183            }
3184            return;
3185        }
3186        let Some(i) = access_bridge::window_of(&event).and_then(|w| self.pane_index(w)) else {
3187            return;
3188        };
3189        // A file dialog's answer, from the thread that waited on it: the
3190        // window that asked hears it as input.
3191        let event = match event {
3192            access_bridge::UserEvent::Files { paths, .. } => {
3193                self.dispatch(event_loop, i, InputEvent::Files(paths));
3194                return;
3195            }
3196            other => other,
3197        };
3198        let Some(bridge) = &mut self.panes[i].access else {
3199            return;
3200        };
3201        let was_listening = bridge.active();
3202        let req = bridge.on_event(event);
3203        // A client attaching or leaving is a fact the view reads
3204        // (`env.system.assistive`, backlog F48): `sync_env` writes it on
3205        // the next frame and the core reports it as a `system` event, so
3206        // the frame has to happen — an app that only redraws on input
3207        // would otherwise hear it with the next click.
3208        if bridge.active() != was_listening {
3209            self.panes[i].redraw_for(FrameCause::APPEARANCE);
3210        }
3211        if let Some(req) = req {
3212            self.dispatch(event_loop, i, InputEvent::Access(req));
3213        }
3214        if let Some(pane) = self.panes.get_mut(i) {
3215            pane.publish_access();
3216        }
3217    }
3218
3219    /// Runs after every event batch (including timer wake-ups): the caret
3220    /// blink clock, the transition clock, and the audio poll. Any caret
3221    /// activity re-arms the blink timer with the caret solid; each expiry
3222    /// toggles the phase and schedules the next. A transition mid-flight
3223    /// asks for the next frame right away (vsync paces it). While a sound
3224    /// plays, the loop wakes every `AUDIO_POLL` to notice it finishing.
3225    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
3226        // A loop taken back from an earlier runner delivered its init
3227        // events — `resumed` among them — to that runner's shell; this one
3228        // opens its window from the first turn it gets instead.
3229        if self.pumped && !self.opened && !self.exit_requested {
3230            self.resumed(event_loop);
3231        }
3232        // The platform's menu comes and goes between turns of the loop, so
3233        // this is where its answer is collected. The menu bar is handed
3234        // over and read back from the same place, for the same reason.
3235        self.pump_native_menu(event_loop);
3236        self.pump_menu_bar(event_loop);
3237        self.pump_text_input(event_loop);
3238        self.pump_file_drag(event_loop);
3239        self.pump_open_documents(event_loop);
3240        self.settle_focus();
3241        self.apply_secure_input();
3242        self.dismiss_popups_if_deactivated();
3243        self.poll_audio();
3244        self.apply_audio();
3245        let now = std::time::Instant::now();
3246        let mut deadline: Option<std::time::Instant> = None;
3247        // A new device owed (`reopen_owed`): made now if its second is
3248        // up, and otherwise — or when this try left a window without one —
3249        // woken for when it is. This deadline is the only thing that
3250        // brings the loop back to it: a window waiting for a device asks
3251        // for no frames of its own, below.
3252        if self.reopen_owed {
3253            if reopen_due(self.reopened, now) <= now {
3254                self.reopen_device();
3255            }
3256            if self.reopen_owed {
3257                let at = reopen_due(self.reopened, now);
3258                deadline = Some(deadline.map_or(at, |d| d.min(at)));
3259            }
3260        }
3261        for pane in &mut self.panes {
3262            // Not while the window waits for a device: with nothing to
3263            // present to there is no vsync to pace the frame, and each one
3264            // would only find the device still owed. Nor while it is
3265            // minimized or covered (`Pane::animates_now`, RG45, RG98).
3266            // Nor while the pacer holds one for the display: the link
3267            // brings that frame back at the next vsync, `overdue` below
3268            // is the wake if it does not, and asking again in between is
3269            // held again at once — the loop went round as fast as it
3270            // could until the vsync came (backlog F103). Nor straight
3271            // after a frame the surface skipped: that returned at once,
3272            // with no vsync behind it, and the next is asked for a retry
3273            // apart instead of on the loop's next turn (`mod retry`).
3274            if pane.animates_now() && !pane.pacer.holding() {
3275                match pane.retry.animation_waits(now) {
3276                    None => pane.redraw_for(FrameCause::OWED),
3277                    Some(at) => deadline = Some(deadline.map_or(at, |d| d.min(at))),
3278                }
3279            }
3280            // A frame held for a display that stopped firing is drawn
3281            // anyway once it has waited too long (`mod pacer`).
3282            if let Some((at, due)) = pane.pacer.overdue(now) {
3283                if due {
3284                    pane.redraw_for(FrameCause::OVERDUE);
3285                } else {
3286                    deadline = Some(deadline.map_or(at, |d| d.min(at)));
3287                }
3288            }
3289            // A frame the surface skipped asks again — a retry apart, and
3290            // only so many times (`mod retry`).
3291            let (ask, wake) = pane.retry.poll(now);
3292            if ask {
3293                pane.redraw_for(FrameCause::RETRY);
3294            }
3295            if let Some(at) = wake {
3296                deadline = Some(deadline.map_or(at, |d| d.min(at)));
3297            }
3298            // A caret to blink: the stock editor's, or the `caret` a
3299            // custom editor declares on one of its lines (backlog C35).
3300            // None, or a solid one (`caret_solid`, F68): the phase is
3301            // parked on — focused window or not, since the clock owns
3302            // the phase only of a caret it blinks; what a solid caret
3303            // looks like without the keyboard (hollow, as a GUI editor's
3304            // block goes; dimmed; gone) is the view's own reading of
3305            // `env.focused`, which the hiding below is not a substitute
3306            // for (RG14 (j), in F68's entry). Caught mid-blink — Escape
3307            // from insert mode on the off phase — the frame that handled
3308            // the key read the phase off, so one more is asked for; once,
3309            // not a loop.
3310            if !pane.core.has_caret() {
3311                if !pane.blink_visible {
3312                    pane.blink_visible = true;
3313                    pane.core.set_caret_visible(true);
3314                    pane.redraw_for(FrameCause::CARET);
3315                }
3316                pane.blink_deadline = None;
3317                continue;
3318            }
3319            // A caret in a window that does not have the keyboard is not
3320            // blinking on any platform, and the blink is the one thing in
3321            // an idle app that asks for a frame twice a second forever: an
3322            // editor left in the background drew 120 frames a minute for a
3323            // caret nobody could type into. Hidden rather than parked
3324            // solid, because solid is what a *focused* field looks like.
3325            // The caret comes back with the keyboard: `blink_deadline` is
3326            // cleared here, and a cleared deadline is what the arm below
3327            // reads as "start blinking", so the first `about_to_wait`
3328            // after focus returns shows it and re-arms.
3329            if !pane.core.env.focused {
3330                if pane.blink_visible {
3331                    pane.blink_visible = false;
3332                    pane.core.set_caret_visible(false);
3333                    pane.redraw_for(FrameCause::CARET);
3334                }
3335                pane.blink_deadline = None;
3336                continue;
3337            }
3338            let stamp = pane.core.caret_stamp();
3339            if stamp != pane.caret_stamp_seen || pane.blink_deadline.is_none() {
3340                pane.caret_stamp_seen = stamp;
3341                pane.blink_deadline = Some(now + BLINK_INTERVAL);
3342                if !pane.blink_visible {
3343                    pane.blink_visible = true;
3344                    pane.core.set_caret_visible(true);
3345                    pane.redraw_for(FrameCause::CARET);
3346                }
3347            } else if now >= pane.blink_deadline.unwrap() {
3348                pane.blink_visible = !pane.blink_visible;
3349                pane.core.set_caret_visible(pane.blink_visible);
3350                pane.blink_deadline = Some(now + BLINK_INTERVAL);
3351                pane.redraw_for(FrameCause::CARET);
3352            }
3353            if let Some(d) = pane.blink_deadline {
3354                deadline = Some(deadline.map_or(d, |e| e.min(d)));
3355            }
3356        }
3357        if self.audio.active() {
3358            let poll = now + AUDIO_POLL;
3359            deadline = Some(deadline.map_or(poll, |d| d.min(poll)));
3360        }
3361        // An output device nothing has used for `AUDIO_IDLE_CLOSE` is let
3362        // go: it is a real-time thread the OS keeps calling, and it is what
3363        // an idle app that owns a sound spends its whole CPU on. The wake
3364        // this schedules is the point — under `ControlFlow::Wait` a truly
3365        // idle app is never called again, so without a deadline the close
3366        // would be scheduled and never run.
3367        if self.audio.holds_device() {
3368            if !self.audio.active() && self.audio_touch.elapsed() >= AUDIO_IDLE_CLOSE {
3369                self.audio.close();
3370            }
3371            if self.audio.holds_device() {
3372                // Either it is still in use (wake when the hold expires) or
3373                // the close found it mid-open (ask again shortly).
3374                let at = (self.audio_touch + AUDIO_IDLE_CLOSE).max(now + AUDIO_POLL);
3375                deadline = Some(deadline.map_or(at, |d| d.min(at)));
3376            }
3377        }
3378        // A batch that carried an event has left a redraw asked for, so the
3379        // shell wants pumping at once to present it — and a driver reading
3380        // this is also being told that the window is in use, which is the
3381        // one thing it cannot work out from the events *it* was handed.
3382        if std::mem::take(&mut self.saw_event) {
3383            deadline = Some(now);
3384            self.woke = true;
3385        }
3386        self.next_deadline = deadline;
3387        event_loop.set_control_flow(match deadline {
3388            Some(d) => ControlFlow::WaitUntil(d),
3389            None => ControlFlow::Wait,
3390        });
3391    }
3392}
3393
3394// Re-exported so apps can reach the renderer without depending on kui-wgpu.
3395pub use kui_wgpu::{RenderError, Renderer, wgpu};
3396
3397/// `KUI_LOSE_DEVICE=SECS`, read once: when after launch to pretend the
3398/// device was lost (`Shell::redraw`), or never.
3399fn lose_device_at() -> Option<f64> {
3400    static AT: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
3401    *AT.get_or_init(|| std::env::var("KUI_LOSE_DEVICE").ok()?.parse().ok())
3402}
3403
3404#[cfg(test)]
3405mod tests {
3406    use super::*;
3407
3408    struct Empty;
3409    impl App for Empty {
3410        fn view(&mut self, _ui: &mut Ui<'_>) {}
3411    }
3412
3413    /// An app that borrows is still an app: the runner is compiled once
3414    /// against `Shell<dyn App + 'a>`, and neither `run` nor
3415    /// `open` asks for `'static`. Checked by the compiler alone: a loop
3416    /// cannot be built on a test's worker thread.
3417    #[test]
3418    fn an_app_that_borrows_still_runs() {
3419        struct Borrowing<'a>(&'a str);
3420        impl App for Borrowing<'_> {
3421            fn view(&mut self, ui: &mut Ui<'_>) {
3422                ui.text(self.0, TextStyle::new(12.0));
3423            }
3424        }
3425        let title = String::from("t");
3426        let _run = || app("t").run(Borrowing(&title));
3427        let _open = || {
3428            let mut runner = app("t").open(Borrowing(&title))?;
3429            let Borrowing(s) = runner.app_mut();
3430            assert_eq!(*s, "t");
3431            Ok::<_, Box<dyn std::error::Error>>(())
3432        };
3433    }
3434
3435    /// `App::teardown` runs once, whichever of the runner's ends comes
3436    /// first and however many come after:
3437    /// `retire` — what a pump returning false, `request_exit` and the
3438    /// runner's drop all reach — and `teardown_once` itself, which is what
3439    /// the loop's `exiting` calls. The runner is built without a loop
3440    /// here: winit builds its loop on the main thread only, and a test
3441    /// runs on a worker.
3442    #[test]
3443    fn teardown_runs_once_across_retire_and_drop() {
3444        use std::cell::Cell;
3445        use std::rc::Rc;
3446        struct Counting(Rc<Cell<u32>>);
3447        impl App for Counting {
3448            fn view(&mut self, _ui: &mut Ui<'_>) {}
3449            fn teardown(&mut self) {
3450                self.0.set(self.0.get() + 1);
3451            }
3452        }
3453        let count = Rc::new(Cell::new(0));
3454        let runner_of = |app: Counting| PumpRunner {
3455            state: PumpState {
3456                event_loop: None,
3457                alive: true,
3458                pumps: 0,
3459                woken_pumps: 0,
3460            },
3461            shell: std::mem::ManuallyDrop::new(super::app("t").diagnostics(false).shell(app)),
3462        };
3463        let mut runner = runner_of(Counting(count.clone()));
3464        assert_eq!(count.get(), 0, "nothing before the end");
3465        runner.request_exit();
3466        assert_eq!(count.get(), 0, "asking is not the end");
3467        runner.retire();
3468        assert_eq!(count.get(), 1, "retiring is");
3469        assert!(!runner.state.alive);
3470        runner.retire();
3471        runner.shell_mut().teardown_once();
3472        assert_eq!(count.get(), 1, "once, however many ends come after");
3473        drop(runner);
3474        assert_eq!(
3475            count.get(),
3476            1,
3477            "the drop retires again, and it is still once"
3478        );
3479
3480        // The drop alone — a runner let go of while alive — is an end too.
3481        let count = Rc::new(Cell::new(0));
3482        drop(runner_of(Counting(count.clone())));
3483        assert_eq!(count.get(), 1);
3484    }
3485
3486    /// A turn whose batch saw an event is counted once, and the flag is
3487    /// taken with it: left set, every quiet turn after the first event
3488    /// would count, and a test reading `woken_pumps` would
3489    /// see the desktop in every idle second. Driven through `tally`, the
3490    /// step each pump ends with, since `about_to_wait` — which sets the
3491    /// flag — needs a live loop, and winit builds one on the main thread
3492    /// only.
3493    #[test]
3494    fn a_woken_turn_is_counted_once() {
3495        let mut runner = PumpRunner {
3496            state: PumpState {
3497                event_loop: None,
3498                alive: true,
3499                pumps: 0,
3500                woken_pumps: 0,
3501            },
3502            shell: std::mem::ManuallyDrop::new(super::app("t").diagnostics(false).shell(Empty)),
3503        };
3504        let tally = |r: &mut PumpRunner<Empty>| r.state.tally(&mut **r.shell);
3505        tally(&mut runner);
3506        assert_eq!(runner.woken_pumps(), 0, "a quiet turn is not woken");
3507        runner.shell_mut().woke = true;
3508        tally(&mut runner);
3509        assert_eq!(runner.woken_pumps(), 1);
3510        assert!(!runner.shell().woke, "taken by the turn that counted it");
3511        tally(&mut runner);
3512        tally(&mut runner);
3513        assert_eq!(
3514            runner.woken_pumps(),
3515            1,
3516            "and the quiet turns after it are quiet"
3517        );
3518    }
3519
3520    /// A frame waits only for an answer that is actually owed, and never
3521    /// twice running — the bound that keeps a stream of input, or a
3522    /// platform modal loop the host cannot interrupt, from stopping the
3523    /// window altogether.
3524    /// A press and a release finish something the core drew; a pointer
3525    /// moving and a wheel turning do not, and a frame that waited on those
3526    /// would cost a drag half its frames.
3527    #[test]
3528    fn only_a_discrete_input_is_worth_waiting_for() {
3529        assert!(input_completes(&InputEvent::mouse_down(1)));
3530        assert!(input_completes(&InputEvent::mouse_up()));
3531        assert!(input_completes(&InputEvent::Text("x".into())));
3532        assert!(!input_completes(&InputEvent::CursorMoved(Vec2::ZERO)));
3533        assert!(!input_completes(&InputEvent::Scroll(Vec2::ZERO)));
3534        assert!(!input_completes(&InputEvent::CursorLeft));
3535    }
3536
3537    #[test]
3538    fn a_frame_never_waits_twice_running() {
3539        assert!(frame_waits_for_host(true, false));
3540        assert!(!frame_waits_for_host(true, true));
3541        assert!(!frame_waits_for_host(false, false));
3542        assert!(!frame_waits_for_host(false, true));
3543    }
3544
3545    /// The default is an app that answers inside `on_event`; only a host
3546    /// driving the loop itself opts out.
3547    #[test]
3548    fn deferred_events_is_opt_in() {
3549        assert!(!app("t").deferred_events);
3550        assert!(app("t").deferred_events().deferred_events);
3551    }
3552
3553    #[test]
3554    fn clamp_size_honors_each_bound() {
3555        let bounds = (Some((400.0, 300.0)), Some((1200.0, 900.0)));
3556        assert_eq!(
3557            clamp_size((800.0, 600.0), bounds.0, bounds.1),
3558            (800.0, 600.0)
3559        );
3560        assert_eq!(
3561            clamp_size((100.0, 100.0), bounds.0, bounds.1),
3562            (400.0, 300.0)
3563        );
3564        assert_eq!(
3565            clamp_size((4000.0, 4000.0), bounds.0, bounds.1),
3566            (1200.0, 900.0)
3567        );
3568        // Per-axis, and unbounded sides pass through untouched.
3569        assert_eq!(
3570            clamp_size((100.0, 4000.0), bounds.0, bounds.1),
3571            (400.0, 900.0)
3572        );
3573        assert_eq!(clamp_size((10.0, 10.0), None, None), (10.0, 10.0));
3574        // A max below the min loses to it, as the platforms resolve it.
3575        assert_eq!(
3576            clamp_size((800.0, 600.0), Some((500.0, 500.0)), Some((200.0, 200.0))),
3577            (500.0, 500.0)
3578        );
3579    }
3580
3581    #[test]
3582    fn diagnostics_follow_the_build_unless_told_otherwise() {
3583        assert_eq!(
3584            app("t").dyn_shell(Empty).core_mut().diagnostics(),
3585            cfg!(debug_assertions)
3586        );
3587        assert!(
3588            app("t")
3589                .diagnostics(true)
3590                .dyn_shell(Empty)
3591                .core_mut()
3592                .diagnostics()
3593        );
3594        assert!(
3595            !app("t")
3596                .diagnostics(false)
3597                .dyn_shell(Empty)
3598                .core_mut()
3599                .diagnostics()
3600        );
3601    }
3602
3603    /// `Launcher::core`: what the host registered on the
3604    /// core it hands over is the window's, its session is the app's, and
3605    /// what the launcher was told still lands on top, in order.
3606    #[test]
3607    fn a_handed_core_is_the_main_window_s_and_its_session_the_app_s() {
3608        let session = Session::new();
3609        let mut core = Core::new_in(&session);
3610        core.set_devtools(true);
3611        core.set_native_menus(false);
3612        let image = core.resources.add_image(1, 1, vec![0; 4]);
3613        let mut shell = app("t").diagnostics(false).core(core).dyn_shell(Empty);
3614        assert!(shell.session.is(&session), "the session came along");
3615        assert!(shell.core_mut().devtools(), "the devtools door held");
3616        assert!(!shell.core_mut().native_menus(), "so did the menus one");
3617        assert!(
3618            !shell.core_mut().diagnostics(),
3619            "the launcher's own setting lands after"
3620        );
3621        assert_eq!(
3622            shell.core_mut().resources.image_size(image),
3623            Some((1, 1)),
3624            "a resource the host registered draws in the window"
3625        );
3626
3627        // `setup_core` runs on the handed core, last.
3628        let mut core = Core::new();
3629        core.set_devtools(true);
3630        let mut shell = app("t")
3631            .core(core)
3632            .setup_core(|c| c.set_devtools(false))
3633            .dyn_shell(Empty);
3634        assert!(!shell.core_mut().devtools());
3635    }
3636
3637    /// `Launcher::devtools_key` is the `set_devtools_key` door in builder
3638    /// form: the chord lands on the main window's core before its first
3639    /// frame, and the default stands for an app that never asked.
3640    #[test]
3641    fn the_devtools_chord_is_the_launcher_s_to_respell() {
3642        let mut shell = app("t").diagnostics(false).dyn_shell(Empty);
3643        assert_eq!(shell.core_mut().devtools_key().spelling(), "ctrl+shift+i");
3644        let mut shell = app("t")
3645            .diagnostics(false)
3646            .devtools_key(Accel::parse("f12").unwrap())
3647            .dyn_shell(Empty);
3648        assert_eq!(shell.core_mut().devtools_key().spelling(), "f12");
3649    }
3650
3651    #[test]
3652    fn launcher_clamps_the_initial_size_into_the_bounds() {
3653        let shell = app("t")
3654            .size(320.0, 240.0)
3655            .min_size(640.0, 480.0)
3656            .dyn_shell(Empty);
3657        assert_eq!(shell.size, (640.0, 480.0));
3658        assert_eq!(shell.min_size, Some((640.0, 480.0)));
3659
3660        let shell = app("t")
3661            .size(1600.0, 1200.0)
3662            .max_size(800.0, 600.0)
3663            .dyn_shell(Empty);
3664        assert_eq!(shell.size, (800.0, 600.0));
3665        assert_eq!(shell.max_size, Some((800.0, 600.0)));
3666
3667        // Builder order is irrelevant: the clamp happens once, at `shell`.
3668        let shell = app("t")
3669            .min_size(640.0, 480.0)
3670            .size(320.0, 240.0)
3671            .dyn_shell(Empty);
3672        assert_eq!(shell.size, (640.0, 480.0));
3673    }
3674
3675    /// A device that will not open is tried once a second (RG29): the
3676    /// first ask runs at once, an ask inside the second after a try waits
3677    /// for the second to be up — the instant `about_to_wait` sleeps until,
3678    /// not a frame asked for every turn — and one after it runs at once.
3679    #[test]
3680    fn a_reopen_waits_out_the_second_after_the_last_try() {
3681        let now = std::time::Instant::now();
3682        assert_eq!(reopen_due(None, now), now, "the first try is at once");
3683        let recent = now - std::time::Duration::from_millis(300);
3684        assert_eq!(
3685            reopen_due(Some(recent), now),
3686            recent + REOPEN_INTERVAL,
3687            "inside the second: woken when it is up"
3688        );
3689        assert!(reopen_due(Some(recent), now) > now, "and not before");
3690        let old = now - std::time::Duration::from_secs(5);
3691        assert_eq!(reopen_due(Some(old), now), now, "past it: at once");
3692        let edge = now - REOPEN_INTERVAL;
3693        assert_eq!(reopen_due(Some(edge), now), now, "at it: at once");
3694    }
3695
3696    /// A surface refused frame after frame while its reopen waits (RG30):
3697    /// retried `SURFACE_TRIES` times, then given up — said once — and the
3698    /// count saturates rather than wrapping back into retries or, in a
3699    /// debug build, panicking, however many frames input asks for.
3700    #[test]
3701    fn a_refused_surface_is_retried_then_given_up_once_and_the_count_saturates() {
3702        let mut tries = 0u8;
3703        let answers: Vec<Refused> = (0..1000).map(|_| surface_refused(&mut tries)).collect();
3704        let retries = SURFACE_TRIES as usize;
3705        assert!(answers[..retries].iter().all(|a| *a == Refused::Retry));
3706        assert_eq!(answers[retries], Refused::GiveUp { say: true });
3707        assert!(
3708            answers[retries + 1..]
3709                .iter()
3710                .all(|a| *a == Refused::GiveUp { say: false }),
3711            "given up, and said only the once"
3712        );
3713        assert_eq!(tries, u8::MAX);
3714    }
3715
3716    /// Subpixel text follows the device it is drawn on (RG32): asked for
3717    /// or left to `Auto`, it is on only where the device blends per
3718    /// channel — so a reopen onto an adapter without dual-source blending
3719    /// turns it off — and grayscale asked for is grayscale everywhere.
3720    #[test]
3721    fn subpixel_text_is_decided_by_each_device() {
3722        assert!(subpixel_on(TextAa::Auto, true));
3723        assert!(!subpixel_on(TextAa::Auto, false));
3724        assert!(subpixel_on(TextAa::Subpixel, true));
3725        assert!(!subpixel_on(TextAa::Subpixel, false));
3726        assert!(!subpixel_on(TextAa::Grayscale, true));
3727        assert!(!subpixel_on(TextAa::Grayscale, false));
3728    }
3729
3730    /// Over a backdrop `Auto` is grayscale (backlog F126): an LCD mask is
3731    /// a blend against pixels the window cannot see. What the app named
3732    /// stands, and an opaque window keeps `Auto`.
3733    #[test]
3734    fn a_backdrop_takes_auto_to_grayscale() {
3735        assert_eq!(aa_under(TextAa::Auto, Backdrop::Opaque), TextAa::Auto);
3736        for b in [Backdrop::Transparent, Backdrop::Blur, Backdrop::Tinted] {
3737            assert_eq!(aa_under(TextAa::Auto, b), TextAa::Grayscale);
3738            assert_eq!(aa_under(TextAa::Subpixel, b), TextAa::Subpixel);
3739        }
3740        assert!(!subpixel_on(aa_under(TextAa::Auto, Backdrop::Tinted), true));
3741    }
3742
3743    /// An app that never asked opens its device as it always did: no
3744    /// transparent surfaces, so on Windows the swapchain on the window's
3745    /// handle it always had.
3746    #[test]
3747    fn only_a_backdrop_opens_a_transparent_device() {
3748        let shell = app("plain").dyn_shell(Empty);
3749        assert!(!shell.gpu_options().transparent);
3750        let shell = app("glass").backdrop(Backdrop::Blur).dyn_shell(Empty);
3751        assert!(shell.gpu_options().transparent);
3752    }
3753}