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