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        // The wallpaper kui draws where the OS has no material, found and
2179        // read on a thread: an answer that there is none to draw, or none
2180        // that decodes, is said once, and the window is opaque from then
2181        // on — before the view runs, so this frame's already reads it.
2182        if let Some(g) = pane.ground.as_mut()
2183            && let Err(why) = g.settle()
2184        {
2185            eprintln!("kui: no wallpaper to draw behind the window: {why}");
2186            pane.ground = None;
2187            pane.backdrop = Backdrop::Opaque;
2188        }
2189        // What the driver knows and the view only reads, refreshed for
2190        // this frame (it was already filled in when the pane opened).
2191        sync_env(pane, system, *pinned_system, audio.env());
2192        let window = &pane.window;
2193        // The core turns a changed viewport into a `resize` event, routed
2194        // with the rest of the pending events after this frame.
2195        let (viewport, scale) = pane.size();
2196        let size = window.inner_size();
2197        let t_view = std::time::Instant::now();
2198        pane.core.set_time(epoch.elapsed().as_secs_f64());
2199        // Why the runner asked, beside the input the core recorded: the
2200        // view reads both as `frame_cause` (backlog F111).
2201        pane.core.note_frame_cause(pane.cause.take());
2202        // The extensions fill the slots the host's view declares, in place
2203        // (`Ui::slot`), and `"root"` after it unless the host placed that
2204        // too — `finish` below does the latter and reports slots nobody
2205        // declared (ADR 0014). The core numbers their origins.
2206        let mut ui = pane.core.frame_with(viewport, scale, extensions);
2207        app.view(&mut ui);
2208        let view_ms = t_view.elapsed().as_secs_f32() * 1e3;
2209
2210        let t_layout = std::time::Instant::now();
2211        ui.finish();
2212        let layout_ms = t_layout.elapsed().as_secs_f32() * 1e3;
2213
2214        // Silent misconfigurations the core noticed (a grow weight with
2215        // nothing to split against, a transition on a positional key, two
2216        // nodes on one key): each once, to stderr, so they stop looking
2217        // like "the feature is broken".
2218        for w in pane.core.take_warnings() {
2219            eprintln!(
2220                "kui: warning [{}] node {:016x}: {}",
2221                w.code, w.key.0, w.message
2222            );
2223        }
2224
2225        // Mirror this frame's hit regions into the WM_NCHITTEST answerer.
2226        #[cfg(target_os = "windows")]
2227        if let Some(nc) = &pane.nc {
2228            nc.update(
2229                scale,
2230                window.is_maximized(),
2231                pane.core
2232                    .interaction
2233                    .hits()
2234                    .iter()
2235                    .map(|h| (h.window, h.rect.intersect(&h.clip))),
2236            );
2237        }
2238
2239        if let Some(t) = pane.core.window_title()
2240            && t != pane.applied_title
2241        {
2242            pane.applied_title = t.to_string();
2243            window.set_title(&pane.applied_title);
2244        }
2245
2246        // The level, the same way (backlog C30): a per-frame fact, applied
2247        // when it differs from what this pane has, and a popup's is never
2248        // touched. What the OS made of it is `env.window.always_on_top`
2249        // on the next `sync_env`, from the record `level_change` keeps.
2250        if let Some(level) = level_change(
2251            pane.kind,
2252            pane.core.always_on_top(),
2253            &mut pane.applied_on_top,
2254        ) {
2255            window.set_window_level(level);
2256        }
2257
2258        // Which Option keys are Alt, the same way (backlog F113): applied
2259        // when it differs from what this window has, never per frame. A
2260        // popup's own ask is applied too and never read — it cannot
2261        // become key on macOS, so its keys come through its owner.
2262        if let Some(_option_as_alt) =
2263            option_as_alt_change(pane.core.option_as_alt(), &mut pane.applied_option_as_alt)
2264        {
2265            #[cfg(target_os = "macos")]
2266            {
2267                use winit::platform::macos::{OptionAsAlt as Winit, WindowExtMacOS};
2268                window.set_option_as_alt(match _option_as_alt {
2269                    kui_core::OptionAsAlt::None => Winit::None,
2270                    kui_core::OptionAsAlt::Left => Winit::OnlyLeft,
2271                    kui_core::OptionAsAlt::Right => Winit::OnlyRight,
2272                    kui_core::OptionAsAlt::Both => Winit::Both,
2273                });
2274            }
2275        }
2276
2277        // The input method, the same way (backlog F125). Off, winit's
2278        // `keyDown:` stops calling `interpretKeyEvents:`, and everything
2279        // the OS composes there goes with it — an IME, a dead key, and
2280        // macOS's press-and-hold, which is an input method that swallows a
2281        // held letter's repeats; the key still arrives with the layout's
2282        // character as its text. A key still held from a press the IME
2283        // never saw keeps it off until it comes up (`Pane::ime_off_held`).
2284        if let Some(off) = ime_off_change(pane.ime_off_wanted(), &mut pane.applied_ime_off) {
2285            apply_ime_off(window, off);
2286        }
2287
2288        // The floor the app declared is a floor on the *app*: while the
2289        // devtools are docked in the main window, the pane's extent goes
2290        // on top of it, so the OS stops the window where the app is at
2291        // its minimum and not where the app less the dock is. After the
2292        // frame, since the handle's drag and the placement buttons land
2293        // in one; on change only, since it is a window-manager call.
2294        if pane.id == WindowId::MAIN
2295            && let Some((mw, mh)) = *min_size
2296        {
2297            let inset = pane.core.devtools_inset();
2298            let want = clamp_size((mw + inset.w as f64, mh + inset.h as f64), None, *max_size);
2299            if pane.applied_min != Some(want) {
2300                pane.applied_min = Some(want);
2301                window.set_min_inner_size(Some(LogicalSize::new(want.0, want.1)));
2302            }
2303        }
2304
2305        // Anchor the OS IME candidate window at the focused caret.
2306        if let Some(r) = pane.core.ime_rect() {
2307            window.set_ime_cursor_area(
2308                winit::dpi::LogicalPosition::new(r.x, r.y),
2309                winit::dpi::LogicalSize::new(r.w.max(1.0), r.h),
2310            );
2311        }
2312        // And say what the platform's own text input may ask the view:
2313        // whether there is somewhere to type, and where the caret is.
2314        #[cfg(target_os = "macos")]
2315        macos_text_input::stamp(window, &pane.core);
2316
2317        let t_render = std::time::Instant::now();
2318        // KUI_LOSE_DEVICE=SECS marks the device lost that long after
2319        // launch, once, to see the reopening below happen without a
2320        // driver update to cause it.
2321        if let Some(secs) = lose_device_at()
2322            && !*pretended_loss
2323            && epoch.elapsed().as_secs_f64() >= secs
2324            && let Some(r) = pane.renderer.as_ref()
2325        {
2326            *pretended_loss = true;
2327            r.gpu().mark_lost();
2328        }
2329        // The ground under the frame is a theme role like any other
2330        // (ADR 0019). Without this a view that paints no root background
2331        // — every example that lets the window show through — would show
2332        // the renderer's own near-black on a light desktop, which is the
2333        // one surface a `bg` prop cannot reach.
2334        // Written straight through: the renderer asks for a non-sRGB
2335        // surface, so a clear component is the byte it lands as, the same
2336        // way a quad's colour is.
2337        // Over a backdrop the ground is nothing at all (backlog F126): what
2338        // the view paints is what covers the material, and a view that
2339        // paints no root background shows it whole.
2340        let ground = pane.core.theme().bg;
2341        // The wallpaper kui draws where the OS has no material: handed to
2342        // the renderer once it has loaded, and the part behind the window
2343        // set when the window moved.
2344        if let (Some(g), Some(r)) = (pane.ground.as_mut(), pane.renderer.as_mut()) {
2345            g.prepare(window, r);
2346        }
2347        let clear = if pane.backdrop.is_translucent() && pane.ground.is_none() {
2348            kui_wgpu::wgpu::Color::TRANSPARENT
2349        } else {
2350            kui_wgpu::wgpu::Color {
2351                r: ground.r as f64,
2352                g: ground.g as f64,
2353                b: ground.b as f64,
2354                a: ground.a as f64,
2355            }
2356        };
2357        let (dl, atlas) = pane.core.output();
2358        let mut wait_ms = 0.0;
2359        let mut reopen = false;
2360        let drawn = pane.renderer.as_mut().map(|r| {
2361            r.clear_color = clear;
2362            r.render(dl, atlas)
2363        });
2364        match drawn {
2365            Some(Ok(report)) => {
2366                wait_ms = report.vsync_wait_ms;
2367                pane.pacer
2368                    .presented(std::time::Instant::now(), (size.width, size.height));
2369                pane.retry.presented();
2370                pane.surface_tries = 0;
2371                pane.awaits_device = false;
2372            }
2373            Some(Err(kui_wgpu::RenderError::Reconfigure)) => {
2374                if let Some(r) = pane.renderer.as_mut() {
2375                    r.resize(size.width, size.height);
2376                }
2377                pane.redraw_for(FrameCause::RETRY);
2378            }
2379            // The surface is configured wrong for the window — a size the
2380            // platform never told us, a swapchain a driver update left
2381            // behind: configure it to the window's size and draw again;
2382            // a surface that stays wrong is given up with its device.
2383            // Past the tries the frame asks for no other: the reopen is
2384            // what asks for the next one, and if it has to wait out its
2385            // second, a frame asked for now would only be refused again —
2386            // at once, with no vsync to pace it. Said once per surface
2387            // given up, not once per refused frame.
2388            Some(Err(kui_wgpu::RenderError::Validation)) => {
2389                match surface_refused(&mut pane.surface_tries) {
2390                    Refused::Retry => {
2391                        if let Some(r) = pane.renderer.as_mut() {
2392                            r.resize(size.width, size.height);
2393                        }
2394                        pane.redraw_for(FrameCause::RETRY);
2395                    }
2396                    Refused::GiveUp { say } => {
2397                        if say {
2398                            eprintln!("kui: the surface stays invalid; reopening the device");
2399                        }
2400                        reopen = true;
2401                    }
2402                }
2403            }
2404            // Occluded or timed out: nothing to present, and the frame is
2405            // owed — *scheduled*, since nothing else may ask for one. A
2406            // window ordered front, or brought back with ⌘-Tab, reports
2407            // itself occluded for a beat or two before the platform
2408            // catches up; its frame dropped, it showed the one from
2409            // before until a stray mouse move woke it (F102). Only for a
2410            // bounded number of tries, and not while the platform says
2411            // the window is covered, so a hidden window does not spin.
2412            Some(Err(kui_wgpu::RenderError::Skip)) => {
2413                let now = std::time::Instant::now();
2414                pane.retry.skipped(now);
2415                // A skipped frame paces the next as a presented one does:
2416                // what asks while the surface skips (a waker, the host) is
2417                // held for the display, or its fallback, instead of drawn
2418                // at once into another skip (backlog RG98).
2419                pane.pacer.presented(now, (size.width, size.height));
2420            }
2421            // The device is gone (a driver update, a GPU reset), or a
2422            // frame ago it was and no new one could be opened: open one.
2423            Some(Err(kui_wgpu::RenderError::DeviceLost)) | None => reopen = true,
2424        }
2425        pane.awaits_device |= reopen;
2426        let render_ms = (t_render.elapsed().as_secs_f32() * 1e3 - wait_ms).max(0.0);
2427
2428        pane.core.stats.push(FrameSample {
2429            input_ms: 0.0,
2430            view_ms,
2431            layout_ms,
2432            render_ms,
2433            wait_ms,
2434        });
2435        if reopen {
2436            self.reopen_device();
2437        }
2438    }
2439
2440    /// The device is gone — a driver update or a GPU reset took it, and
2441    /// every swapchain with it — so one new device is opened, and a
2442    /// renderer on it for every window, each window's old one dropped
2443    /// before its new surface is made (DXGI gives a window one flip-model
2444    /// swapchain). The windows keep their cores: the next frame draws
2445    /// what the last one would have. A window whose renderer cannot be
2446    /// made has none, and the device is tried again a second later; a
2447    /// device that cannot be opened is tried, and said, once a second, not
2448    /// once a frame. Asked for inside that second, the ask is owed
2449    /// (`reopen_owed`) and `about_to_wait` makes it when the second is up.
2450    fn reopen_device(&mut self) {
2451        let now = std::time::Instant::now();
2452        if reopen_due(self.reopened, now) > now {
2453            self.reopen_owed = true;
2454            return;
2455        }
2456        self.reopened = Some(now);
2457        // Dropped, not leaked: the old swapchain has to be released for
2458        // DXGI to allow the window a new one (leaked, the new surface's
2459        // configure fails with "invalid surface").
2460        for pane in &mut self.panes {
2461            pane.renderer = None;
2462            pane.surface_tries = 0;
2463        }
2464        self.gpu = None;
2465        let mut gpu: Option<kui_wgpu::Gpu> = None;
2466        let options = self.gpu_options();
2467        for pane in &mut self.panes {
2468            let px = pane.window.inner_size();
2469            let made = match &gpu {
2470                None => pollster::block_on(kui_wgpu::Renderer::new_with(
2471                    pane.window.clone(),
2472                    px.width,
2473                    px.height,
2474                    options,
2475                )),
2476                Some(gpu) => kui_wgpu::Renderer::new_in_with(
2477                    gpu,
2478                    pane.window.clone(),
2479                    px.width,
2480                    px.height,
2481                    pane.backdrop.is_translucent(),
2482                ),
2483            };
2484            match made {
2485                Ok(mut r) => {
2486                    r.set_frame_latency(self.frame_latency);
2487                    // The window keeps its backdrop where the new surface
2488                    // takes alpha too; one that will not any more leaves
2489                    // the window opaque, and says so.
2490                    if pane.backdrop.is_translucent() && pane.ground.is_none() && !r.transparent() {
2491                        pane.backdrop = Backdrop::Opaque;
2492                    }
2493                    // A wallpaper drawn by kui goes to the new renderer too.
2494                    if let Some(g) = pane.ground.as_mut() {
2495                        g.renderer_replaced();
2496                    }
2497                    let opened = gpu.is_none();
2498                    gpu.get_or_insert_with(|| r.gpu().clone());
2499                    if opened {
2500                        eprintln!("kui: device reopened");
2501                    }
2502                    pane.renderer = Some(r);
2503                    pane.redraw_for(FrameCause::DEVICE);
2504                }
2505                Err(err) => eprintln!("kui: cannot reopen window {}: {err}", pane.id.0),
2506            }
2507            pane.awaits_device = pane.renderer.is_none();
2508        }
2509        // A window left without a renderer — or every window, when no
2510        // device would open — is tried again a second from now, whether
2511        // or not anything asks it for a frame.
2512        self.reopen_owed = self.panes.iter().any(|p| p.awaits_device);
2513        // The new device may be another adapter's, with or without the
2514        // per-channel blend LCD masks need: decided again, for every core,
2515        // or a core keeps rasterising masks the new pipeline cannot split.
2516        // A changed decision empties each core's atlas (`set_subpixel_text`),
2517        // which the fresh renderer was going to upload whole anyway.
2518        if let Some(gpu) = &gpu {
2519            let wanted = aa_under(wanted_text_aa(self.text_aa), self.backdrop);
2520            let on = subpixel_on(wanted, gpu.dual_source());
2521            if on != self.subpixel {
2522                self.subpixel = on;
2523                for pane in &mut self.panes {
2524                    pane.core.set_subpixel_text(on);
2525                }
2526            }
2527        }
2528        self.gpu = gpu;
2529    }
2530}
2531
2532/// Which bar `pump_menu_bar` last handed the platform.
2533#[cfg(target_os = "macos")]
2534#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2535enum AppliedBar {
2536    /// The standard bar: no window declared one, or the front
2537    /// window draws its own declaration and the platform's is the standard.
2538    Standard,
2539    /// A window's declaration, at that revision.
2540    Declared(WindowId, u64),
2541}
2542
2543impl ApplicationHandler<access_bridge::UserEvent> for DynShell<'_> {
2544    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
2545        if !self.panes.is_empty() || self.opened {
2546            return;
2547        }
2548        self.opened = true;
2549        // KUI_WINDOW=WxH overrides the initial size (useful for testing).
2550        let size = std::env::var("KUI_WINDOW")
2551            .ok()
2552            .and_then(|s| {
2553                let (w, h) = s.split_once('x')?;
2554                Some((w.parse().ok()?, h.parse().ok()?))
2555            })
2556            .map(|s| clamp_size(s, self.min_size, self.max_size))
2557            .unwrap_or(self.size);
2558        let mut attrs = self.window_attrs(&self.title.clone(), size, self.chrome, self.backdrop);
2559        if let Some((mw, mh)) = self.min_size {
2560            attrs = attrs.with_min_inner_size(LogicalSize::new(mw, mh));
2561        }
2562        if let Some((mw, mh)) = self.max_size {
2563            attrs = attrs.with_max_inner_size(LogicalSize::new(mw, mh));
2564        }
2565        // KUI_WINDOW_AT=X,Y places it, logical px from the screen's top
2566        // left: the smoke round's `--jobs` cascades its windows by it, so
2567        // none is wholly covered — a covered window is `Occluded` and
2568        // presents nothing, and the round counts presents.
2569        if let Some((x, y)) = std::env::var("KUI_WINDOW_AT").ok().and_then(|s| {
2570            let (x, y) = s.split_once(',')?;
2571            Some((x.parse::<f64>().ok()?, y.parse::<f64>().ok()?))
2572        }) {
2573            attrs = attrs.with_position(LogicalPosition::new(x, y));
2574        }
2575        let window = match event_loop.create_window(attrs) {
2576            Ok(w) => Arc::new(w),
2577            Err(e) => return self.fail_open(event_loop, format!("cannot open the window: {e}")),
2578        };
2579        self.icon.set_on(&window);
2580        let px = window.inner_size();
2581        let renderer = pollster::block_on(kui_wgpu::Renderer::new_with(
2582            window.clone(),
2583            px.width,
2584            px.height,
2585            self.gpu_options(),
2586        ));
2587        let mut renderer = match renderer {
2588            Ok(r) => r,
2589            Err(e) => return self.fail_open(event_loop, format!("cannot draw in the window: {e}")),
2590        };
2591        renderer.set_frame_latency(self.frame_latency);
2592        // What shows through it, now that there is a surface to present
2593        // with alpha (backlog F126); before it is shown.
2594        let backdrop = backdrop::apply(&window, &renderer, self.backdrop);
2595        // Subpixel text only where the renderer blends per channel; the
2596        // env var wins over the builder for quick A/B comparisons.
2597        self.subpixel = subpixel_on(
2598            aa_under(wanted_text_aa(self.text_aa), self.backdrop),
2599            renderer.subpixel_text(),
2600        );
2601        self.gpu = Some(renderer.gpu().clone());
2602        let mut core = self
2603            .main_core
2604            .take()
2605            .expect("the main core is built once, by the launcher");
2606        core.set_subpixel_text(self.subpixel);
2607        core.env.window.id = WindowId::MAIN;
2608        self.push_pane(
2609            event_loop,
2610            WindowId::MAIN,
2611            WindowConfig::default(),
2612            WindowId::MAIN,
2613            self.chrome,
2614            core,
2615            window,
2616            renderer,
2617            backdrop,
2618        );
2619        self.panes[0].applied_title = self.title.clone();
2620        self.panes[0].applied_min = self.min_size;
2621    }
2622
2623    fn window_event(
2624        &mut self,
2625        event_loop: &ActiveEventLoop,
2626        id: WinitWindowId,
2627        event: WindowEvent,
2628    ) {
2629        let Some(i) = self.pane_index(id) else { return };
2630        // Everything but the redraw itself: a redraw is the *answer* to an
2631        // event, so counting it would make a frame its own reason for the
2632        // next one and an animation would report activity for ever.
2633        if !matches!(event, WindowEvent::RedrawRequested) {
2634            self.saw_event = true;
2635        }
2636        {
2637            let pane = &mut self.panes[i];
2638            if let Some(bridge) = &mut pane.access {
2639                bridge.process_event(&pane.window, &event);
2640            }
2641        }
2642        match event {
2643            WindowEvent::CloseRequested => {
2644                if self.panes[i].id == WindowId::MAIN {
2645                    self.exit_main(event_loop);
2646                } else {
2647                    let id = self.panes[i].id;
2648                    self.close_pane(event_loop, id);
2649                }
2650            }
2651            // On Windows minimizing and restoring are each a `WM_SIZE`:
2652            // the first is where the window went dark, the second the
2653            // frame that brings it back (backlog RG97).
2654            WindowEvent::Resized(size) => {
2655                let pane = &mut self.panes[i];
2656                if let Some(r) = pane.renderer.as_mut() {
2657                    r.resize(size.width, size.height);
2658                }
2659                if let Some(g) = pane.ground.as_mut() {
2660                    g.moved();
2661                }
2662                if pane.minimized() {
2663                    pane.cause.went_dark();
2664                    pane.redraw_for(FrameCause::RESIZE);
2665                } else if pane.cause.is_dark() && cfg!(target_os = "windows") {
2666                    pane.came_back(FrameCause::RESIZE);
2667                } else {
2668                    // Elsewhere a window resized while covered is still
2669                    // covered; `Occluded(false)` is its way back.
2670                    pane.redraw_for(FrameCause::RESIZE);
2671                }
2672            }
2673            WindowEvent::ScaleFactorChanged { .. } => {
2674                self.panes[i].redraw_for(FrameCause::SCALE);
2675            }
2676            // The wallpaper kui draws behind a window stays put on the
2677            // screen as the window moves over it (backlog F126); nothing
2678            // else here cares where the window is.
2679            WindowEvent::Moved(_) => {
2680                let pane = &mut self.panes[i];
2681                if let Some(g) = pane.ground.as_mut() {
2682                    g.moved();
2683                    pane.redraw_for(FrameCause::RESIZE);
2684                }
2685            }
2686            WindowEvent::CursorMoved { position, .. } => {
2687                let pane = &mut self.panes[i];
2688                let scale = pane.window.scale_factor() as f32;
2689                let p = Vec2::new(position.x as f32 / scale, position.y as f32 / scale);
2690                if pane.synthesizes_resize() {
2691                    pane.resize_edge = pane.resize_edge_at(p);
2692                }
2693                if pane.cursor != p {
2694                    pane.scroll_gesture.pointer_moved();
2695                }
2696                pane.cursor = p;
2697                let from = pane.id;
2698                self.dispatch(event_loop, i, InputEvent::CursorMoved(p));
2699                // And then, if this pane is holding a press that a popup
2700                // joined, the same move again in that popup's coordinates.
2701                self.retarget_move(event_loop, from, p);
2702            }
2703            WindowEvent::CursorLeft { .. } => {
2704                self.dispatch(event_loop, i, InputEvent::CursorLeft);
2705            }
2706            // Files dragged in from the OS, as winit reports them: one
2707            // event per file and no position (ADR 0031, decision 5). On
2708            // macOS the delegate override supersedes all three with the
2709            // position AppKit has (`mod macos_drop`); elsewhere the files
2710            // are collected per batch and dispatched at its end, at the
2711            // pane's last reported cursor — the point at enter and at
2712            // release, since no platform here reports the drag moving.
2713            WindowEvent::HoveredFile(path) => {
2714                if !self.file_drag_is_overridden() {
2715                    let pane = &mut self.panes[i];
2716                    pane.file_drag.push(path.to_string_lossy().into_owned());
2717                    pane.file_drag_pending = Some(false);
2718                }
2719            }
2720            WindowEvent::DroppedFile(path) => {
2721                if !self.file_drag_is_overridden() {
2722                    let pane = &mut self.panes[i];
2723                    // A hover batch still waiting in the same turn is the
2724                    // same files: the drop's list starts over.
2725                    if pane.file_drag_pending != Some(true) {
2726                        pane.file_drag.clear();
2727                    }
2728                    pane.file_drag.push(path.to_string_lossy().into_owned());
2729                    pane.file_drag_pending = Some(true);
2730                }
2731            }
2732            WindowEvent::HoveredFileCancelled => {
2733                if !self.file_drag_is_overridden() {
2734                    let pane = &mut self.panes[i];
2735                    pane.file_drag.clear();
2736                    pane.file_drag_pending = None;
2737                    self.dispatch(event_loop, i, InputEvent::DragCancel);
2738                }
2739            }
2740            // Recorded, not acted on: what a view reads is derived from
2741            // every window's copy at the end of the batch (`settle_focus`),
2742            // because focus *moving* is two events and neither alone is the
2743            // answer.
2744            WindowEvent::Focused(focused) => {
2745                self.panes[i].os_focused = focused;
2746                // A modifier let go elsewhere never comes up here: what
2747                // was down is forgotten with the keyboard (backlog F108).
2748                if !focused {
2749                    self.panes[i].modifier_keys_down.clear();
2750                    // And so is a key held through a mode change: its
2751                    // release lands elsewhere, so the IME it was keeping
2752                    // off is the frame's to decide again.
2753                    self.panes[i].ime_off_held.clear();
2754                    self.panes[i].sync_ime();
2755                }
2756                // Coming back to the app is the cheap, reliable sign that
2757                // the user may have been in a settings app: the accent and
2758                // the reduce-motion setting have no event to subscribe to
2759                // here, and re-asking costs microseconds against something
2760                // that happens when a human switches windows.
2761                if focused {
2762                    let before = (self.system, self.panes[i].appearance);
2763                    self.system = system_env::query();
2764                    // And the window's own setting, in case the platform
2765                    // changed it without an event while we were away.
2766                    self.panes[i].appearance = appearance_of(&self.panes[i].window);
2767                    // A change found this way has no event of its own
2768                    // behind it, so ask for the frame that reports it:
2769                    // `begin_frame` turns the difference into a `system`
2770                    // event, and a host that only draws on input would
2771                    // otherwise not learn of it until it drew for
2772                    // something else (F40).
2773                    if before != (self.system, self.panes[i].appearance) {
2774                        for p in &self.panes {
2775                            p.redraw_for(FrameCause::APPEARANCE);
2776                        }
2777                    }
2778                }
2779            }
2780            // Covered or uncovered — where the platform says (macOS, X11):
2781            // uncovered, the window shows what it presented before it was
2782            // covered, so a frame is owed now (F102); covered, frames the
2783            // surface skips are not retried.
2784            // Covered is where a window goes dark, minimized on macOS
2785            // included, and uncovered where it comes back (RG97).
2786            WindowEvent::Occluded(covered) => {
2787                self.panes[i]
2788                    .retry
2789                    .occluded(covered, std::time::Instant::now());
2790                if covered {
2791                    self.panes[i].cause.went_dark();
2792                } else {
2793                    self.panes[i].came_back(FrameCause::OCCLUSION);
2794                }
2795            }
2796            // The theme changing is the other one, and the only one that
2797            // arrives while the app is in front. The next frame reads the
2798            // appearance off the window anyway; the redraw is what makes
2799            // there *be* a next frame in an app that only draws on input.
2800            WindowEvent::ThemeChanged(theme) => {
2801                self.panes[i].appearance = theme_appearance(Some(theme));
2802                self.system = system_env::query();
2803                self.panes[i].redraw_for(FrameCause::APPEARANCE);
2804            }
2805            // The four keyboard events go to `key_target`, which is this
2806            // pane unless it is lending its keyboard to a non-activating
2807            // popup. The modifier mirror follows them, or the popup would
2808            // read a stale Shift.
2809            WindowEvent::ModifiersChanged(m) => {
2810                // The keyboard's state is one fact for the pair: the OS
2811                // delivers the edge to the owner, the target reads it for
2812                // the keys it borrows, and the owner keeps reading it once
2813                // the popup is gone — written to the target alone, a Shift
2814                // released while a menu was up left the owner's next key a
2815                // Shift chord (AR23).
2816                let t = self.key_target(i);
2817                self.panes[i].modifiers = m.state();
2818                self.panes[t].modifiers = m.state();
2819                use winit::keyboard::ModifiersKeyState::Pressed;
2820                let alt = (m.lalt_state() == Pressed, m.ralt_state() == Pressed);
2821                self.panes[i].alt_held = alt;
2822                self.panes[t].alt_held = alt;
2823                let kmods = self.panes[t].kmods();
2824                self.dispatch(event_loop, t, InputEvent::Modifiers(kmods));
2825            }
2826            // Not a press winit made up: on Windows and X11 a window
2827            // gaining focus is handed a press of every key already held —
2828            // made in another window or another app — and a key whose
2829            // press closed a window pressed again in the one beneath it
2830            // (backlog RG100). The releases it makes up as a window loses
2831            // focus are kept: they are what lets go of a key a sink held.
2832            WindowEvent::KeyboardInput {
2833                event,
2834                is_synthetic,
2835                ..
2836            } => {
2837                if !(is_synthetic && event.state == ElementState::Pressed) {
2838                    let t = self.key_target(i);
2839                    self.on_key(event_loop, i, t, event)
2840                }
2841            }
2842            WindowEvent::Ime(Ime::Commit(text)) => {
2843                // Its own channel, not `Text`: a sink hears a commit as a
2844                // `text` event and a keystroke as a `key` event, once each
2845                // (backlog C17); a stock editor takes both the same way.
2846                self.panes[i].preedit_open = false;
2847                let t = self.key_target(i);
2848                self.dispatch(event_loop, t, InputEvent::Commit(text));
2849            }
2850            WindowEvent::Ime(Ime::Preedit(text, cursor)) => {
2851                self.panes[i].preedit_open = !text.is_empty();
2852                let t = self.key_target(i);
2853                self.dispatch(event_loop, t, InputEvent::Preedit(text, cursor));
2854            }
2855            // The IME went away — the frame turned it off (`imeOff`), or
2856            // the user switched input source — and winit's contract is
2857            // that a pending preedit is cleared: a composition still open
2858            // ends without a commit, as an empty preedit, the way an IME
2859            // that cancels says it.
2860            WindowEvent::Ime(Ime::Disabled) => {
2861                if std::mem::take(&mut self.panes[i].preedit_open) {
2862                    let t = self.key_target(i);
2863                    self.dispatch(event_loop, t, InputEvent::Preedit(String::new(), None));
2864                }
2865            }
2866            // Force Touch: stage 2 is the deepened press macOS calls a
2867            // force click. winit reports the whole ramp, and only the
2868            // *edge* into stage 2 is the gesture — a stage that stays at 2
2869            // while the finger presses harder is the same click still
2870            // happening (ADR 0017, decision 6). macOS-only: no other
2871            // winit backend reports pressure at all.
2872            WindowEvent::TouchpadPressure { stage, .. } => {
2873                let pane = &mut self.panes[i];
2874                let was = std::mem::replace(&mut pane.pressure_stage, stage);
2875                if stage >= 2 && was < 2 {
2876                    let at = pane.cursor;
2877                    self.dispatch(event_loop, i, InputEvent::ForceClick(at));
2878                }
2879            }
2880            WindowEvent::MouseWheel { delta, phase, .. } => {
2881                let started = phase == winit::event::TouchPhase::Started;
2882                let pane = &mut self.panes[i];
2883                let scale = pane.window.scale_factor() as f32;
2884                let now = std::time::Instant::now();
2885                let (d, kind) = match delta {
2886                    winit::event::MouseScrollDelta::LineDelta(x, y) => {
2887                        pane.axis_lock.end();
2888                        (
2889                            Vec2::new(Core::lines_to_px(x), Core::lines_to_px(y)),
2890                            scroll_gesture::Kind::Line,
2891                        )
2892                    }
2893                    // A trackpad's swipe keeps to its axis (`mod axis_lock`),
2894                    // and a finger put down begins the next, glide or no
2895                    // glide (backlog F117).
2896                    winit::event::MouseScrollDelta::PixelDelta(p) => {
2897                        if pane.scroll_gesture.phase(phase, now) {
2898                            pane.axis_lock.end();
2899                        }
2900                        (
2901                            pane.axis_lock
2902                                .pixel(Vec2::new(p.x as f32 / scale, p.y as f32 / scale), now),
2903                            scroll_gesture::Kind::Pixel,
2904                        )
2905                    }
2906                };
2907                // The gesture it is part of keeps the targets it began
2908                // with (`mod scroll_gesture`, backlog F107).
2909                if d != Vec2::ZERO {
2910                    let begins = pane.scroll_gesture.begins(kind, started, now);
2911                    self.dispatch(
2912                        event_loop,
2913                        i,
2914                        InputEvent::ScrollGesture { delta: d, begins },
2915                    );
2916                } else {
2917                    pane.scroll_gesture.note(kind, started, now);
2918                }
2919            }
2920            WindowEvent::MouseInput { state, button, .. } => {
2921                let button = match button {
2922                    WinitButton::Left => MouseButton::Primary,
2923                    WinitButton::Right => MouseButton::Secondary,
2924                    WinitButton::Middle => MouseButton::Middle,
2925                    // `onButton` hears these as `Other`'s code (backlog
2926                    // F105), so the numbering has to be stable: back,
2927                    // forward, then whatever the platform reports beyond
2928                    // them.
2929                    WinitButton::Back => MouseButton::Other(0),
2930                    WinitButton::Forward => MouseButton::Other(1),
2931                    WinitButton::Other(n) => {
2932                        MouseButton::Other(n.saturating_add(2).min(u8::MAX as u16) as u8)
2933                    }
2934                };
2935                let primary = button == MouseButton::Primary;
2936                let here = self.panes[i].id;
2937                // Which pane holds a primary press, for ADR 0009's arming.
2938                // Set for a consumed press too: the button is down whatever
2939                // the core was told, and the release below clears it.
2940                if primary {
2941                    self.primary_down = (state == ElementState::Pressed).then_some(here);
2942                    if state == ElementState::Pressed {
2943                        // A consumed press whose release never arrived — the
2944                        // window lost the keyboard mid-gesture, say — must
2945                        // not swallow the next one instead.
2946                        self.swallowed_press = None;
2947                    }
2948                }
2949                // A press anywhere but inside a popup is "outside" it —
2950                // the owner's own window included, which is exactly the
2951                // line a separate surface draws. Reported before the press
2952                // is dispatched, so an app that stops declaring the popup
2953                // on the dismissal still sees the click it was dismissed
2954                // by, the way a modal's dismissal works (ADR 0003).
2955                //
2956                // And then a primary press that dismissed a
2957                // **non-activating** popup is **consumed** — not dispatched
2958                // to the window it landed in, and its release swallowed with
2959                // it (ADR 0009 decision 5). The pass-through this replaces
2960                // claimed to mirror ADR 0003 and had it backwards: under an
2961                // in-window modal everything outside emits no hit region, so
2962                // the outside press dismisses and lands on nothing, while a
2963                // popup's owner is live (ADR 0004 decision 10) and the press
2964                // dismisses *and* acts. Invisible with click-to-open;
2965                // decisive with open-on-press, where a press on the open
2966                // field would otherwise dismiss and reopen in one gesture,
2967                // and no ordering of the two events lets the app tell that
2968                // press from the first. An **activating** popup — a tear-off
2969                // panel — keeps the pass-through, since someone working in a
2970                // panel beside the app expects a click in the app to act.
2971                if state == ElementState::Pressed {
2972                    let mut consumed = false;
2973                    let mut reached_app = false;
2974                    for (id, activates) in self.popups_outside(i) {
2975                        reached_app |= self.dismiss(id, DismissReason::Outside);
2976                        consumed |= primary && !activates;
2977                    }
2978                    if consumed {
2979                        self.swallowed_press = Some(here);
2980                        // Choosing in a menu closes it *and* does what it
2981                        // says: one frame, so this one waits for the host.
2982                        self.owe_for(reached_app);
2983                        // The press the core never saw.
2984                        for p in &self.panes {
2985                            p.redraw_for(FrameCause::BUTTON);
2986                        }
2987                        return;
2988                    }
2989                }
2990                // A press inside a non-activating popup arms that popup for
2991                // its own release (ADR 0009 decision 4's last paragraph):
2992                // the OS keeps the drag here whatever it wanders over, so a
2993                // drag off the top edge and a release on the desktop has to
2994                // be classified rather than ignored — the measured case in
2995                // backlog W2. It gets no retargeted moves, having the real
2996                // ones already.
2997                if primary
2998                    && state == ElementState::Pressed
2999                    && self.panes[i].kind == WindowKind::Popup
3000                    && !self.panes[i].activates
3001                    && !self.armed.iter().any(|a| a.id == here)
3002                {
3003                    self.armed.push(Armed {
3004                        id: here,
3005                        inside: true,
3006                    });
3007                }
3008                if state == ElementState::Released && primary {
3009                    // The release of a press the driver ate goes with it:
3010                    // the core never saw the `down`, so nothing should see
3011                    // this `up`.
3012                    if self.swallowed_press == Some(here) {
3013                        self.swallowed_press = None;
3014                        self.primary_down = None;
3015                        return;
3016                    }
3017                    let at = self.panes[i].cursor;
3018                    self.classify_release(event_loop, here, at);
3019                }
3020                // The frame the classification ran may have closed a window
3021                // and moved this one down the list.
3022                let Some(i) = self.pane_of(here) else { return };
3023                let pane = &mut self.panes[i];
3024                // A press on the synthesized resize band starts an OS resize
3025                // instead of reaching the UI.
3026                if primary
3027                    && state == ElementState::Pressed
3028                    && let Some(dir) = pane.resize_edge
3029                {
3030                    let _ = pane.window.drag_resize_window(dir);
3031                    return;
3032                }
3033                let ev = match state {
3034                    ElementState::Pressed => {
3035                        // Multi-click is the primary button's: a right
3036                        // press between two left ones does not break the
3037                        // run, and never counts up one of its own.
3038                        let clicks = if primary {
3039                            let now = std::time::Instant::now();
3040                            let clicks = match pane.last_click {
3041                                Some((t, p, n))
3042                                    if now.duration_since(t).as_millis() < MULTI_CLICK_MS
3043                                        && (p.x - pane.cursor.x).abs() < MULTI_CLICK_SLOP
3044                                        && (p.y - pane.cursor.y).abs() < MULTI_CLICK_SLOP =>
3045                                {
3046                                    // Cycle 1 → 2 → 3 → 1 like most editors.
3047                                    n % 3 + 1
3048                                }
3049                                _ => 1,
3050                            };
3051                            pane.last_click = Some((now, pane.cursor, clicks));
3052                            clicks
3053                        } else {
3054                            1
3055                        };
3056                        InputEvent::MouseDown { button, clicks }
3057                    }
3058                    ElementState::Released => InputEvent::MouseUp { button },
3059                };
3060                self.dispatch(event_loop, i, ev);
3061            }
3062            WindowEvent::RedrawRequested
3063                if frame_waits_for_host(self.owed.get(), self.panes[i].deferred_frame) =>
3064            {
3065                // What would be painted predates an input the app has been
3066                // told about and not yet answered — the release of a
3067                // button, with the count still at its old value. The host
3068                // asks again the moment its handler has run, and that
3069                // frame carries both. Never twice running, so nothing here
3070                // can stop a window painting.
3071                self.panes[i].deferred_frame = true;
3072            }
3073            // A frame asked for while frames run back to back waits for
3074            // the display, which asks again at the vsync (`mod pacer`).
3075            WindowEvent::RedrawRequested if !self.panes[i].admit_frame() => {}
3076            WindowEvent::RedrawRequested => {
3077                self.panes[i].deferred_frame = false;
3078                self.redraw(i);
3079                // KUI_SMOKE_FRAMES: count what the main window actually
3080                // landed and quit at the target. Counted only once a
3081                // present succeeded, so a window that never draws never
3082                // counts and the run fails on the caller's timeout rather
3083                // than passing quietly. Asking for the next
3084                // one keeps an app that paints only on input painting, so
3085                // every example reaches the count at the same speed.
3086                if let Some(n) = self.smoke_frames
3087                    && let Some(p) = self.panes.get(i)
3088                    && p.id == WindowId::MAIN
3089                    && p.retry.presented_once()
3090                {
3091                    self.frames_drawn += 1;
3092                    if self.frames_drawn >= n {
3093                        self.exit_requested = true;
3094                    } else {
3095                        self.panes[i].redraw_for(FrameCause::SMOKE);
3096                    }
3097                }
3098                self.panes[i].publish_access();
3099                // Views can declare windows and window commands too
3100                // (ui.window, ui.window_command); apply them the same frame
3101                // they were declared. Likewise the sounds a frame started
3102                // (audio nodes, ui.play), and the clipboard work a view
3103                // queued (ui.set_clipboard, ui.request_paste — backlog
3104                // C33), which until now only an input's drain reached.
3105                self.apply_menu_actions(event_loop, i);
3106                self.apply_window_commands(event_loop);
3107                self.apply_audio();
3108                // The frame may have closed this very pane.
3109                let Some(i) = self.pane_index(id) else { return };
3110                // A new frame can put something else under a still cursor.
3111                self.panes[i].apply_cursor();
3112                // A frame can resize the viewport, and can change what sits
3113                // under a still cursor; route the resulting resize / hover
3114                // events now rather than with the next input, and redraw for
3115                // what they change.
3116                let pending = self.panes[i].core.take_pending_events();
3117                if !pending.is_empty() {
3118                    self.route_events(pending);
3119                    if let Some(p) = self.panes.get(i) {
3120                        p.redraw_for(FrameCause::AFTER_FRAME);
3121                    }
3122                }
3123                // Windows moves and resizes a window inside its own modal
3124                // loop, where `about_to_wait` — the pacing that asks for
3125                // the next frame of an animation — does not run, so a
3126                // transition froze for as long as the title bar was held
3127                // (backlog W3). The pane's own timer is what answers that,
3128                // and this is where it learns whether there is anything to
3129                // animate; `mod windows_anim` is why it is a timer and not
3130                // a redraw asked for from right here. Not while the window
3131                // waits for a device: `about_to_wait` asks it for no
3132                // animation frames then (RG29), and the timer asked for 64
3133                // a second, each a view built for no renderer (RG40). The
3134                // reopen's own `request_redraw` arms it again. Nor while
3135                // it is minimized (RG45); the restore's `Resized` does.
3136                #[cfg(target_os = "windows")]
3137                if let Some(p) = self.panes.get_mut(i) {
3138                    let animating = p.animates_now();
3139                    if let Some(t) = &mut p.anim_timer {
3140                        t.set(animating);
3141                    }
3142                }
3143            }
3144            _ => {}
3145        }
3146        if self.exit_requested {
3147            self.exit_main(event_loop);
3148        }
3149    }
3150
3151    /// AccessKit's side of the conversation: assistive technology attaching
3152    /// (send it the tree, and let the view know), detaching, or asking for
3153    /// an action (input).
3154    /// The loop's last event: the app's `teardown`, before the process
3155    /// goes (a Quit from the OS) or `run` returns (the main window
3156    /// closed).
3157    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
3158        self.teardown_once();
3159    }
3160
3161    fn user_event(&mut self, event_loop: &ActiveEventLoop, event: access_bridge::UserEvent) {
3162        // A wake is the app saying "what `view` shows has changed": every
3163        // window draws, as after any input. Coalesced by the platform's
3164        // queue, so a thread waking a thousand times a frame costs one.
3165        self.saw_event = true;
3166        if matches!(event, access_bridge::UserEvent::Wake) {
3167            for pane in &self.panes {
3168                pane.redraw_for(FrameCause::WAKE);
3169            }
3170            return;
3171        }
3172        // The installed fonts changed: the session scans again, through
3173        // any one window's core since every window shares it, and the
3174        // windows draw — each shapes its text again on that frame
3175        // (`weights_rev`), fallback being free to land on a new face. A
3176        // signal that found nothing new (a second window's copy of a
3177        // Windows broadcast) changes nothing and draws nothing.
3178        if matches!(event, access_bridge::UserEvent::FontsChanged) {
3179            system_fonts::handled();
3180            let changed = self
3181                .panes
3182                .first_mut()
3183                .map_or(0, |pane| pane.core.reload_system_fonts());
3184            if changed > 0 {
3185                for pane in &self.panes {
3186                    pane.redraw_for(FrameCause::APPEARANCE);
3187                }
3188            }
3189            return;
3190        }
3191        let Some(i) = access_bridge::window_of(&event).and_then(|w| self.pane_index(w)) else {
3192            return;
3193        };
3194        // A file dialog's answer, from the thread that waited on it: the
3195        // window that asked hears it as input.
3196        let event = match event {
3197            access_bridge::UserEvent::Files { paths, .. } => {
3198                self.dispatch(event_loop, i, InputEvent::Files(paths));
3199                return;
3200            }
3201            other => other,
3202        };
3203        let Some(bridge) = &mut self.panes[i].access else {
3204            return;
3205        };
3206        let was_listening = bridge.active();
3207        let req = bridge.on_event(event);
3208        // A client attaching or leaving is a fact the view reads
3209        // (`env.system.assistive`, backlog F48): `sync_env` writes it on
3210        // the next frame and the core reports it as a `system` event, so
3211        // the frame has to happen — an app that only redraws on input
3212        // would otherwise hear it with the next click.
3213        if bridge.active() != was_listening {
3214            self.panes[i].redraw_for(FrameCause::APPEARANCE);
3215        }
3216        if let Some(req) = req {
3217            self.dispatch(event_loop, i, InputEvent::Access(req));
3218        }
3219        if let Some(pane) = self.panes.get_mut(i) {
3220            pane.publish_access();
3221        }
3222    }
3223
3224    /// Runs after every event batch (including timer wake-ups): the caret
3225    /// blink clock, the transition clock, and the audio poll. Any caret
3226    /// activity re-arms the blink timer with the caret solid; each expiry
3227    /// toggles the phase and schedules the next. A transition mid-flight
3228    /// asks for the next frame right away (vsync paces it). While a sound
3229    /// plays, the loop wakes every `AUDIO_POLL` to notice it finishing.
3230    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
3231        // A loop taken back from an earlier runner delivered its init
3232        // events — `resumed` among them — to that runner's shell; this one
3233        // opens its window from the first turn it gets instead.
3234        if self.pumped && !self.opened && !self.exit_requested {
3235            self.resumed(event_loop);
3236        }
3237        // The platform's menu comes and goes between turns of the loop, so
3238        // this is where its answer is collected. The menu bar is handed
3239        // over and read back from the same place, for the same reason.
3240        self.pump_native_menu(event_loop);
3241        self.pump_menu_bar(event_loop);
3242        self.pump_text_input(event_loop);
3243        self.pump_file_drag(event_loop);
3244        self.pump_open_documents(event_loop);
3245        self.settle_focus();
3246        self.apply_secure_input();
3247        self.dismiss_popups_if_deactivated();
3248        self.poll_audio();
3249        self.apply_audio();
3250        let now = std::time::Instant::now();
3251        let mut deadline: Option<std::time::Instant> = None;
3252        // A new device owed (`reopen_owed`): made now if its second is
3253        // up, and otherwise — or when this try left a window without one —
3254        // woken for when it is. This deadline is the only thing that
3255        // brings the loop back to it: a window waiting for a device asks
3256        // for no frames of its own, below.
3257        if self.reopen_owed {
3258            if reopen_due(self.reopened, now) <= now {
3259                self.reopen_device();
3260            }
3261            if self.reopen_owed {
3262                let at = reopen_due(self.reopened, now);
3263                deadline = Some(deadline.map_or(at, |d| d.min(at)));
3264            }
3265        }
3266        for pane in &mut self.panes {
3267            // Not while the window waits for a device: with nothing to
3268            // present to there is no vsync to pace the frame, and each one
3269            // would only find the device still owed. Nor while it is
3270            // minimized or covered (`Pane::animates_now`, RG45, RG98).
3271            // Nor while the pacer holds one for the display: the link
3272            // brings that frame back at the next vsync, `overdue` below
3273            // is the wake if it does not, and asking again in between is
3274            // held again at once — the loop went round as fast as it
3275            // could until the vsync came (backlog F103). Nor straight
3276            // after a frame the surface skipped: that returned at once,
3277            // with no vsync behind it, and the next is asked for a retry
3278            // apart instead of on the loop's next turn (`mod retry`).
3279            if pane.animates_now() && !pane.pacer.holding() {
3280                match pane.retry.animation_waits(now) {
3281                    None => pane.redraw_for(FrameCause::OWED),
3282                    Some(at) => deadline = Some(deadline.map_or(at, |d| d.min(at))),
3283                }
3284            }
3285            // A frame held for a display that stopped firing is drawn
3286            // anyway once it has waited too long (`mod pacer`).
3287            if let Some((at, due)) = pane.pacer.overdue(now) {
3288                if due {
3289                    pane.redraw_for(FrameCause::OVERDUE);
3290                } else {
3291                    deadline = Some(deadline.map_or(at, |d| d.min(at)));
3292                }
3293            }
3294            // A frame the surface skipped asks again — a retry apart, and
3295            // only so many times (`mod retry`).
3296            let (ask, wake) = pane.retry.poll(now);
3297            if ask {
3298                pane.redraw_for(FrameCause::RETRY);
3299            }
3300            if let Some(at) = wake {
3301                deadline = Some(deadline.map_or(at, |d| d.min(at)));
3302            }
3303            // A caret to blink: the stock editor's, or the `caret` a
3304            // custom editor declares on one of its lines (backlog C35).
3305            // None, or a solid one (`caret_solid`, F68): the phase is
3306            // parked on — focused window or not, since the clock owns
3307            // the phase only of a caret it blinks; what a solid caret
3308            // looks like without the keyboard (hollow, as a GUI editor's
3309            // block goes; dimmed; gone) is the view's own reading of
3310            // `env.focused`, which the hiding below is not a substitute
3311            // for (RG14 (j), in F68's entry). Caught mid-blink — Escape
3312            // from insert mode on the off phase — the frame that handled
3313            // the key read the phase off, so one more is asked for; once,
3314            // not a loop.
3315            if !pane.core.has_caret() {
3316                if !pane.blink_visible {
3317                    pane.blink_visible = true;
3318                    pane.core.set_caret_visible(true);
3319                    pane.redraw_for(FrameCause::CARET);
3320                }
3321                pane.blink_deadline = None;
3322                continue;
3323            }
3324            // A caret in a window that does not have the keyboard is not
3325            // blinking on any platform, and the blink is the one thing in
3326            // an idle app that asks for a frame twice a second forever: an
3327            // editor left in the background drew 120 frames a minute for a
3328            // caret nobody could type into. Hidden rather than parked
3329            // solid, because solid is what a *focused* field looks like.
3330            // The caret comes back with the keyboard: `blink_deadline` is
3331            // cleared here, and a cleared deadline is what the arm below
3332            // reads as "start blinking", so the first `about_to_wait`
3333            // after focus returns shows it and re-arms.
3334            if !pane.core.env.focused {
3335                if pane.blink_visible {
3336                    pane.blink_visible = false;
3337                    pane.core.set_caret_visible(false);
3338                    pane.redraw_for(FrameCause::CARET);
3339                }
3340                pane.blink_deadline = None;
3341                continue;
3342            }
3343            let stamp = pane.core.caret_stamp();
3344            if stamp != pane.caret_stamp_seen || pane.blink_deadline.is_none() {
3345                pane.caret_stamp_seen = stamp;
3346                pane.blink_deadline = Some(now + BLINK_INTERVAL);
3347                if !pane.blink_visible {
3348                    pane.blink_visible = true;
3349                    pane.core.set_caret_visible(true);
3350                    pane.redraw_for(FrameCause::CARET);
3351                }
3352            } else if now >= pane.blink_deadline.unwrap() {
3353                pane.blink_visible = !pane.blink_visible;
3354                pane.core.set_caret_visible(pane.blink_visible);
3355                pane.blink_deadline = Some(now + BLINK_INTERVAL);
3356                pane.redraw_for(FrameCause::CARET);
3357            }
3358            if let Some(d) = pane.blink_deadline {
3359                deadline = Some(deadline.map_or(d, |e| e.min(d)));
3360            }
3361        }
3362        if self.audio.active() {
3363            let poll = now + AUDIO_POLL;
3364            deadline = Some(deadline.map_or(poll, |d| d.min(poll)));
3365        }
3366        // An output device nothing has used for `AUDIO_IDLE_CLOSE` is let
3367        // go: it is a real-time thread the OS keeps calling, and it is what
3368        // an idle app that owns a sound spends its whole CPU on. The wake
3369        // this schedules is the point — under `ControlFlow::Wait` a truly
3370        // idle app is never called again, so without a deadline the close
3371        // would be scheduled and never run.
3372        if self.audio.holds_device() {
3373            if !self.audio.active() && self.audio_touch.elapsed() >= AUDIO_IDLE_CLOSE {
3374                self.audio.close();
3375            }
3376            if self.audio.holds_device() {
3377                // Either it is still in use (wake when the hold expires) or
3378                // the close found it mid-open (ask again shortly).
3379                let at = (self.audio_touch + AUDIO_IDLE_CLOSE).max(now + AUDIO_POLL);
3380                deadline = Some(deadline.map_or(at, |d| d.min(at)));
3381            }
3382        }
3383        // A batch that carried an event has left a redraw asked for, so the
3384        // shell wants pumping at once to present it — and a driver reading
3385        // this is also being told that the window is in use, which is the
3386        // one thing it cannot work out from the events *it* was handed.
3387        if std::mem::take(&mut self.saw_event) {
3388            deadline = Some(now);
3389            self.woke = true;
3390        }
3391        self.next_deadline = deadline;
3392        event_loop.set_control_flow(match deadline {
3393            Some(d) => ControlFlow::WaitUntil(d),
3394            None => ControlFlow::Wait,
3395        });
3396    }
3397}
3398
3399// Re-exported so apps can reach the renderer without depending on kui-wgpu.
3400pub use kui_wgpu::{RenderError, Renderer, wgpu};
3401
3402/// `KUI_LOSE_DEVICE=SECS`, read once: when after launch to pretend the
3403/// device was lost (`Shell::redraw`), or never.
3404fn lose_device_at() -> Option<f64> {
3405    static AT: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
3406    *AT.get_or_init(|| std::env::var("KUI_LOSE_DEVICE").ok()?.parse().ok())
3407}
3408
3409#[cfg(test)]
3410mod tests {
3411    use super::*;
3412
3413    struct Empty;
3414    impl App for Empty {
3415        fn view(&mut self, _ui: &mut Ui<'_>) {}
3416    }
3417
3418    /// An app that borrows is still an app: the runner is compiled once
3419    /// against `Shell<dyn App + 'a>`, and neither `run` nor
3420    /// `open` asks for `'static`. Checked by the compiler alone: a loop
3421    /// cannot be built on a test's worker thread.
3422    #[test]
3423    fn an_app_that_borrows_still_runs() {
3424        struct Borrowing<'a>(&'a str);
3425        impl App for Borrowing<'_> {
3426            fn view(&mut self, ui: &mut Ui<'_>) {
3427                ui.text(self.0, TextStyle::new(12.0));
3428            }
3429        }
3430        let title = String::from("t");
3431        let _run = || app("t").run(Borrowing(&title));
3432        let _open = || {
3433            let mut runner = app("t").open(Borrowing(&title))?;
3434            let Borrowing(s) = runner.app_mut();
3435            assert_eq!(*s, "t");
3436            Ok::<_, Box<dyn std::error::Error>>(())
3437        };
3438    }
3439
3440    /// `App::teardown` runs once, whichever of the runner's ends comes
3441    /// first and however many come after:
3442    /// `retire` — what a pump returning false, `request_exit` and the
3443    /// runner's drop all reach — and `teardown_once` itself, which is what
3444    /// the loop's `exiting` calls. The runner is built without a loop
3445    /// here: winit builds its loop on the main thread only, and a test
3446    /// runs on a worker.
3447    #[test]
3448    fn teardown_runs_once_across_retire_and_drop() {
3449        use std::cell::Cell;
3450        use std::rc::Rc;
3451        struct Counting(Rc<Cell<u32>>);
3452        impl App for Counting {
3453            fn view(&mut self, _ui: &mut Ui<'_>) {}
3454            fn teardown(&mut self) {
3455                self.0.set(self.0.get() + 1);
3456            }
3457        }
3458        let count = Rc::new(Cell::new(0));
3459        let runner_of = |app: Counting| PumpRunner {
3460            state: PumpState {
3461                event_loop: None,
3462                alive: true,
3463                pumps: 0,
3464                woken_pumps: 0,
3465            },
3466            shell: std::mem::ManuallyDrop::new(super::app("t").diagnostics(false).shell(app)),
3467        };
3468        let mut runner = runner_of(Counting(count.clone()));
3469        assert_eq!(count.get(), 0, "nothing before the end");
3470        runner.request_exit();
3471        assert_eq!(count.get(), 0, "asking is not the end");
3472        runner.retire();
3473        assert_eq!(count.get(), 1, "retiring is");
3474        assert!(!runner.state.alive);
3475        runner.retire();
3476        runner.shell_mut().teardown_once();
3477        assert_eq!(count.get(), 1, "once, however many ends come after");
3478        drop(runner);
3479        assert_eq!(
3480            count.get(),
3481            1,
3482            "the drop retires again, and it is still once"
3483        );
3484
3485        // The drop alone — a runner let go of while alive — is an end too.
3486        let count = Rc::new(Cell::new(0));
3487        drop(runner_of(Counting(count.clone())));
3488        assert_eq!(count.get(), 1);
3489    }
3490
3491    /// A turn whose batch saw an event is counted once, and the flag is
3492    /// taken with it: left set, every quiet turn after the first event
3493    /// would count, and a test reading `woken_pumps` would
3494    /// see the desktop in every idle second. Driven through `tally`, the
3495    /// step each pump ends with, since `about_to_wait` — which sets the
3496    /// flag — needs a live loop, and winit builds one on the main thread
3497    /// only.
3498    #[test]
3499    fn a_woken_turn_is_counted_once() {
3500        let mut runner = PumpRunner {
3501            state: PumpState {
3502                event_loop: None,
3503                alive: true,
3504                pumps: 0,
3505                woken_pumps: 0,
3506            },
3507            shell: std::mem::ManuallyDrop::new(super::app("t").diagnostics(false).shell(Empty)),
3508        };
3509        let tally = |r: &mut PumpRunner<Empty>| r.state.tally(&mut **r.shell);
3510        tally(&mut runner);
3511        assert_eq!(runner.woken_pumps(), 0, "a quiet turn is not woken");
3512        runner.shell_mut().woke = true;
3513        tally(&mut runner);
3514        assert_eq!(runner.woken_pumps(), 1);
3515        assert!(!runner.shell().woke, "taken by the turn that counted it");
3516        tally(&mut runner);
3517        tally(&mut runner);
3518        assert_eq!(
3519            runner.woken_pumps(),
3520            1,
3521            "and the quiet turns after it are quiet"
3522        );
3523    }
3524
3525    /// A frame waits only for an answer that is actually owed, and never
3526    /// twice running — the bound that keeps a stream of input, or a
3527    /// platform modal loop the host cannot interrupt, from stopping the
3528    /// window altogether.
3529    /// A press and a release finish something the core drew; a pointer
3530    /// moving and a wheel turning do not, and a frame that waited on those
3531    /// would cost a drag half its frames.
3532    #[test]
3533    fn only_a_discrete_input_is_worth_waiting_for() {
3534        assert!(input_completes(&InputEvent::mouse_down(1)));
3535        assert!(input_completes(&InputEvent::mouse_up()));
3536        assert!(input_completes(&InputEvent::Text("x".into())));
3537        assert!(!input_completes(&InputEvent::CursorMoved(Vec2::ZERO)));
3538        assert!(!input_completes(&InputEvent::Scroll(Vec2::ZERO)));
3539        assert!(!input_completes(&InputEvent::CursorLeft));
3540    }
3541
3542    #[test]
3543    fn a_frame_never_waits_twice_running() {
3544        assert!(frame_waits_for_host(true, false));
3545        assert!(!frame_waits_for_host(true, true));
3546        assert!(!frame_waits_for_host(false, false));
3547        assert!(!frame_waits_for_host(false, true));
3548    }
3549
3550    /// The default is an app that answers inside `on_event`; only a host
3551    /// driving the loop itself opts out.
3552    #[test]
3553    fn deferred_events_is_opt_in() {
3554        assert!(!app("t").deferred_events);
3555        assert!(app("t").deferred_events().deferred_events);
3556    }
3557
3558    #[test]
3559    fn clamp_size_honors_each_bound() {
3560        let bounds = (Some((400.0, 300.0)), Some((1200.0, 900.0)));
3561        assert_eq!(
3562            clamp_size((800.0, 600.0), bounds.0, bounds.1),
3563            (800.0, 600.0)
3564        );
3565        assert_eq!(
3566            clamp_size((100.0, 100.0), bounds.0, bounds.1),
3567            (400.0, 300.0)
3568        );
3569        assert_eq!(
3570            clamp_size((4000.0, 4000.0), bounds.0, bounds.1),
3571            (1200.0, 900.0)
3572        );
3573        // Per-axis, and unbounded sides pass through untouched.
3574        assert_eq!(
3575            clamp_size((100.0, 4000.0), bounds.0, bounds.1),
3576            (400.0, 900.0)
3577        );
3578        assert_eq!(clamp_size((10.0, 10.0), None, None), (10.0, 10.0));
3579        // A max below the min loses to it, as the platforms resolve it.
3580        assert_eq!(
3581            clamp_size((800.0, 600.0), Some((500.0, 500.0)), Some((200.0, 200.0))),
3582            (500.0, 500.0)
3583        );
3584    }
3585
3586    #[test]
3587    fn diagnostics_follow_the_build_unless_told_otherwise() {
3588        assert_eq!(
3589            app("t").dyn_shell(Empty).core_mut().diagnostics(),
3590            cfg!(debug_assertions)
3591        );
3592        assert!(
3593            app("t")
3594                .diagnostics(true)
3595                .dyn_shell(Empty)
3596                .core_mut()
3597                .diagnostics()
3598        );
3599        assert!(
3600            !app("t")
3601                .diagnostics(false)
3602                .dyn_shell(Empty)
3603                .core_mut()
3604                .diagnostics()
3605        );
3606    }
3607
3608    /// `Launcher::core`: what the host registered on the
3609    /// core it hands over is the window's, its session is the app's, and
3610    /// what the launcher was told still lands on top, in order.
3611    #[test]
3612    fn a_handed_core_is_the_main_window_s_and_its_session_the_app_s() {
3613        let session = Session::new();
3614        let mut core = Core::new_in(&session);
3615        core.set_devtools(true);
3616        core.set_native_menus(false);
3617        let image = core.resources.add_image(1, 1, vec![0; 4]);
3618        let mut shell = app("t").diagnostics(false).core(core).dyn_shell(Empty);
3619        assert!(shell.session.is(&session), "the session came along");
3620        assert!(shell.core_mut().devtools(), "the devtools door held");
3621        assert!(!shell.core_mut().native_menus(), "so did the menus one");
3622        assert!(
3623            !shell.core_mut().diagnostics(),
3624            "the launcher's own setting lands after"
3625        );
3626        assert_eq!(
3627            shell.core_mut().resources.image_size(image),
3628            Some((1, 1)),
3629            "a resource the host registered draws in the window"
3630        );
3631
3632        // `setup_core` runs on the handed core, last.
3633        let mut core = Core::new();
3634        core.set_devtools(true);
3635        let mut shell = app("t")
3636            .core(core)
3637            .setup_core(|c| c.set_devtools(false))
3638            .dyn_shell(Empty);
3639        assert!(!shell.core_mut().devtools());
3640    }
3641
3642    /// `Launcher::devtools_key` is the `set_devtools_key` door in builder
3643    /// form: the chord lands on the main window's core before its first
3644    /// frame, and the default stands for an app that never asked.
3645    #[test]
3646    fn the_devtools_chord_is_the_launcher_s_to_respell() {
3647        let mut shell = app("t").diagnostics(false).dyn_shell(Empty);
3648        assert_eq!(shell.core_mut().devtools_key().spelling(), "ctrl+shift+i");
3649        let mut shell = app("t")
3650            .diagnostics(false)
3651            .devtools_key(Accel::parse("f12").unwrap())
3652            .dyn_shell(Empty);
3653        assert_eq!(shell.core_mut().devtools_key().spelling(), "f12");
3654    }
3655
3656    #[test]
3657    fn launcher_clamps_the_initial_size_into_the_bounds() {
3658        let shell = app("t")
3659            .size(320.0, 240.0)
3660            .min_size(640.0, 480.0)
3661            .dyn_shell(Empty);
3662        assert_eq!(shell.size, (640.0, 480.0));
3663        assert_eq!(shell.min_size, Some((640.0, 480.0)));
3664
3665        let shell = app("t")
3666            .size(1600.0, 1200.0)
3667            .max_size(800.0, 600.0)
3668            .dyn_shell(Empty);
3669        assert_eq!(shell.size, (800.0, 600.0));
3670        assert_eq!(shell.max_size, Some((800.0, 600.0)));
3671
3672        // Builder order is irrelevant: the clamp happens once, at `shell`.
3673        let shell = app("t")
3674            .min_size(640.0, 480.0)
3675            .size(320.0, 240.0)
3676            .dyn_shell(Empty);
3677        assert_eq!(shell.size, (640.0, 480.0));
3678    }
3679
3680    /// A device that will not open is tried once a second (RG29): the
3681    /// first ask runs at once, an ask inside the second after a try waits
3682    /// for the second to be up — the instant `about_to_wait` sleeps until,
3683    /// not a frame asked for every turn — and one after it runs at once.
3684    #[test]
3685    fn a_reopen_waits_out_the_second_after_the_last_try() {
3686        let now = std::time::Instant::now();
3687        assert_eq!(reopen_due(None, now), now, "the first try is at once");
3688        let recent = now - std::time::Duration::from_millis(300);
3689        assert_eq!(
3690            reopen_due(Some(recent), now),
3691            recent + REOPEN_INTERVAL,
3692            "inside the second: woken when it is up"
3693        );
3694        assert!(reopen_due(Some(recent), now) > now, "and not before");
3695        let old = now - std::time::Duration::from_secs(5);
3696        assert_eq!(reopen_due(Some(old), now), now, "past it: at once");
3697        let edge = now - REOPEN_INTERVAL;
3698        assert_eq!(reopen_due(Some(edge), now), now, "at it: at once");
3699    }
3700
3701    /// A surface refused frame after frame while its reopen waits (RG30):
3702    /// retried `SURFACE_TRIES` times, then given up — said once — and the
3703    /// count saturates rather than wrapping back into retries or, in a
3704    /// debug build, panicking, however many frames input asks for.
3705    #[test]
3706    fn a_refused_surface_is_retried_then_given_up_once_and_the_count_saturates() {
3707        let mut tries = 0u8;
3708        let answers: Vec<Refused> = (0..1000).map(|_| surface_refused(&mut tries)).collect();
3709        let retries = SURFACE_TRIES as usize;
3710        assert!(answers[..retries].iter().all(|a| *a == Refused::Retry));
3711        assert_eq!(answers[retries], Refused::GiveUp { say: true });
3712        assert!(
3713            answers[retries + 1..]
3714                .iter()
3715                .all(|a| *a == Refused::GiveUp { say: false }),
3716            "given up, and said only the once"
3717        );
3718        assert_eq!(tries, u8::MAX);
3719    }
3720
3721    /// Subpixel text follows the device it is drawn on (RG32): asked for
3722    /// or left to `Auto`, it is on only where the device blends per
3723    /// channel — so a reopen onto an adapter without dual-source blending
3724    /// turns it off — and grayscale asked for is grayscale everywhere.
3725    #[test]
3726    fn subpixel_text_is_decided_by_each_device() {
3727        assert!(subpixel_on(TextAa::Auto, true));
3728        assert!(!subpixel_on(TextAa::Auto, false));
3729        assert!(subpixel_on(TextAa::Subpixel, true));
3730        assert!(!subpixel_on(TextAa::Subpixel, false));
3731        assert!(!subpixel_on(TextAa::Grayscale, true));
3732        assert!(!subpixel_on(TextAa::Grayscale, false));
3733    }
3734
3735    /// Over a backdrop `Auto` is grayscale (backlog F126): an LCD mask is
3736    /// a blend against pixels the window cannot see. What the app named
3737    /// stands, and an opaque window keeps `Auto`.
3738    #[test]
3739    fn a_backdrop_takes_auto_to_grayscale() {
3740        assert_eq!(aa_under(TextAa::Auto, Backdrop::Opaque), TextAa::Auto);
3741        for b in [Backdrop::Transparent, Backdrop::Blur, Backdrop::Tinted] {
3742            assert_eq!(aa_under(TextAa::Auto, b), TextAa::Grayscale);
3743            assert_eq!(aa_under(TextAa::Subpixel, b), TextAa::Subpixel);
3744        }
3745        assert!(!subpixel_on(aa_under(TextAa::Auto, Backdrop::Tinted), true));
3746    }
3747
3748    /// An app that never asked opens its device as it always did: no
3749    /// transparent surfaces, so on Windows the swapchain on the window's
3750    /// handle it always had.
3751    #[test]
3752    fn only_a_backdrop_opens_a_transparent_device() {
3753        let shell = app("plain").dyn_shell(Empty);
3754        assert!(!shell.gpu_options().transparent);
3755        let shell = app("glass").backdrop(Backdrop::Blur).dyn_shell(Empty);
3756        assert!(shell.gpu_options().transparent);
3757    }
3758}