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