Skip to main content

nsh_engine/
lib.rs

1//! The engine thread of one surface.
2//!
3//! The engine owns a [`nsh_core::Core`] on a dedicated thread and runs one
4//! app ([`App`]): a Rust app's root component, or a JS bundle in a QuickJS
5//! VM (`nsh_js::Host`, feature `js-core`; `js` adds the standard modules
6//! `zlib` and `crypto`). Each wake-up (input event, timer,
7//! resize) runs the app's code (component tasks; JS and its microtasks),
8//! applies what JS committed, lays out, and hands one [`MountBatch`] to the
9//! platform through a [`MountSink`]. The platform thread never blocks on
10//! the engine.
11
12#[cfg(all(feature = "browser", target_arch = "wasm32", not(feature = "js-core")))]
13pub mod browser;
14
15mod access;
16mod app_directory;
17mod cache;
18mod error;
19mod host_channel;
20mod local_storage;
21#[cfg(feature = "net")]
22pub mod net;
23pub mod perf;
24mod script;
25#[cfg_attr(not(feature = "shader"), path = "shader_off.rs")]
26pub mod shader;
27mod shader_frame;
28#[cfg(all(feature = "shader", target_vendor = "apple"))]
29mod shader_surfaces;
30#[cfg(not(target_arch = "wasm32"))]
31mod storage;
32#[cfg(feature = "js-core")]
33mod symbolicate;
34#[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
35pub mod updates;
36
37// The typed API check (docs/dev/geometry.md, "Typed API"): the scan is
38// nsh-core's; this crate's lists are `unitless.txt` and `untyped.txt`.
39#[cfg(test)]
40#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
41mod unit_scan;
42
43#[cfg(test)]
44#[test]
45fn public_api_is_typed() {
46    unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
47}
48
49use std::{io, mem::ManuallyDrop, rc::Rc, sync::Arc, time::Duration};
50
51pub use app_directory::app_dir_name;
52use crossbeam_channel::{Receiver, Sender};
53pub use local_storage::local_storage_prefix;
54use nsh_core::{
55    ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
56    PayloadValue, TextEngine, element::JsEvent, platform::content_type, time::Instant,
57};
58pub use nsh_core::{
59    JsonValue,
60    access::{Access, Capabilities},
61    element::{EngineContext, Root, Tokens},
62    geometry::{self, Bounds, Edges, Point, Points, Size},
63    js::{HostLimits, Limits},
64    main_thread::MainThreadTask,
65    platform::{
66        ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HourCycle, HttpBody,
67        HttpHead, HttpRequest, Idiom, Languages, Lifecycle, Locale, LocaleSettings,
68        MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday,
69    },
70    storage::{StorageBackend, StorageChange},
71    time::Clock,
72};
73#[cfg(feature = "js-core")]
74pub use nsh_js::BYTECODE_VERSION;
75/// Signed packages, release-key certificates, revocations and trust stores.
76#[cfg(feature = "js-core")]
77pub use nsh_package as package;
78use rustc_hash::FxHashMap;
79#[cfg(not(target_arch = "wasm32"))]
80pub use storage::{FileStorage, data_dir};
81
82use crate::script::{NetworkQueue, RequestId, Script};
83pub use crate::{
84    cache::{ByteSize, CacheLocation, CacheOptions, CachePolicy},
85    error::{AppError, AppErrorKind, PackageInfo},
86    host_channel::{HostCall, HostChannel, HostReply, OpenUrlRequest},
87};
88
89#[cfg(not(target_arch = "wasm32"))]
90/// Stack size of the engine thread. QuickJS recursion (and deep Solid
91/// component trees) needs more than the 512 KiB default of secondary
92/// threads on Apple platforms.
93const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
94
95/// Minimum time between idle cycle collections. QuickJS frees acyclic
96/// garbage immediately; only cycles (such as detached node subtrees, whose
97/// parent/child links reference each other) wait for the collector.
98const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
99
100/// How long the engine has had nothing to do (no message, no timer due)
101/// before an idle collection: a collection walks every object of the VM,
102/// tens of milliseconds for an app holding a lot of data, so it waits for
103/// a pause rather than land between the turns of a paste held down or of
104/// work done in slices on timers. An engine never quiet that long (a
105/// timer every few frames) still collects every [`IDLE_GC_LONGEST`].
106const IDLE_GC_QUIET: Duration = Duration::from_millis(300);
107
108/// The longest time between idle collections, quiet or not.
109const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);
110
111/// The shortest time between two deliveries of mouse motion: a frame at
112/// 120 Hz. Mice report moves far more often (up to 1000 Hz), and a handler
113/// that redraws a crosshair needs no more than one per frame.
114const MOUSE_MOVE_INTERVAL: Duration = Duration::from_millis(8);
115
116/// The app an engine runs.
117#[derive(Debug, Clone)]
118#[allow(
119    clippy::large_enum_variant,
120    reason = "one app per surface; keep the public constructor API without allocation"
121)]
122pub enum App {
123    /// A Rust app: its root component, mounted as the surface's content.
124    Rust(Root),
125    /// A JS app (feature `js-core`).
126    Js(Bundle),
127}
128
129impl From<Bundle> for App {
130    fn from(bundle: Bundle) -> Self {
131        App::Js(bundle)
132    }
133}
134
135impl App {
136    /// The app's id (`nsh.json` `"id"`), when it carries one.
137    pub fn app_id(&self) -> Option<&str> {
138        match self {
139            App::Rust(root) => root.app_id_ref(),
140            App::Js(bundle) => bundle.app_id.as_deref(),
141        }
142    }
143
144    /// The main window's launch options (`nsh.json` `"window"`): a JS app's
145    /// bundle's ([`Bundle::main_window`]), a Rust app's root's
146    /// ([`nsh_core::element::Root::main_window`]). Runners open the main
147    /// window by them.
148    pub fn main_window(&self) -> Option<&nsh_core::desktop::MainWindowOptions> {
149        match self {
150            App::Rust(root) => root.main_window_ref(),
151            App::Js(bundle) => bundle.main_window.as_ref(),
152        }
153    }
154
155    /// The URL schemes the app claims (`nsh.json` `schemes`):
156    /// the links the core lets through (`nsh_core::url_scheme`).
157    pub fn url_schemes(&self) -> &[String] {
158        match self {
159            App::Rust(root) => root.url_schemes_ref(),
160            App::Js(bundle) => &bundle.url_schemes,
161        }
162    }
163}
164
165impl From<Root> for App {
166    fn from(root: Root) -> Self {
167        App::Rust(root)
168    }
169}
170
171/// An app bundle: its code plus, in development, a source map.
172#[derive(Debug, Clone)]
173#[non_exhaustive]
174pub struct Bundle {
175    /// The code.
176    pub code: BundleCode,
177    /// Source map (JSON) used to show app source locations in stack traces.
178    pub source_map: Option<Arc<str>>,
179    /// What the code may do.
180    pub policy: Policy,
181    /// What relative request URLs resolve against (the page's URL on the
182    /// web); `None`: they are invalid.
183    pub base_url: Option<Arc<str>>,
184    /// The chunks of a split bundle that come with it (`import()` loads
185    /// them without asking the platform); those missing are asked of
186    /// [`MountSink::load_chunk`]. Shared by the bundle's clones.
187    pub chunks: Arc<Vec<Chunk>>,
188    /// The app's id (`nsh.json` `"id"`; a signed package's verified one):
189    /// it names where the app keeps its data (`nsh/storage`).
190    pub app_id: Option<String>,
191    /// The URL schemes the app claims (`nsh.json` `schemes`, a
192    /// packaged app's `app.json`): the links its engine lets through.
193    /// Read from the app's own resources, never from its code; none for a
194    /// signed package, whose embedding app owns the schemes.
195    pub url_schemes: Vec<String>,
196    /// Trusted filesystem anchors selected by the native host, never decoded
197    /// from application code, its manifest or a development server message.
198    /// Missing anchors deny relative and corresponding placeholder grants.
199    pub system_paths: nsh_core::access::TrustedPaths,
200    /// The signed package the bundle came from ([`Bundle::from_package`]),
201    /// named in the app's errors ([`AppError::package`]).
202    pub package: Option<Arc<PackageInfo>>,
203    /// The update configuration `nsh/updater` reads (`nsh-updater.json`,
204    /// as `nsh package` wrote it), from the installed app's own resources;
205    /// `None`: the file among the app's assets, if any. A packaged app
206    /// running a newer package of its code sets the shipped one
207    /// (`updates::launch`).
208    pub updater_config: Option<Arc<[u8]>>,
209    /// Told how the app fares, while it has not proved it runs: a package
210    /// of a packaged app's code running for the first time
211    /// (`updates::launch`).
212    pub trial: Option<Arc<dyn Trial>>,
213    /// The main window's launch-time options (`nsh.json` `"window"`, an
214    /// app's `app.json`, the dev server's app info): runners read them
215    /// before they make the window; the engine sends their attributes to
216    /// the main window with the first frame.
217    pub main_window: Option<nsh_core::desktop::MainWindowOptions>,
218}
219
220/// How long an app on [`Bundle::trial`] runs past its first frame without
221/// a fatal error to be healthy.
222pub const TRIAL_PERIOD: Duration = Duration::from_secs(10);
223
224/// A run on trial ([`Bundle::trial`]): the engine tells it once whether
225/// the app is healthy or failed (later calls are its to ignore). A crash
226/// of the process tells it nothing.
227pub trait Trial: Send + Sync + std::fmt::Debug + 'static {
228    /// The app ran [`TRIAL_PERIOD`] past its first frame, or its engine
229    /// stopped after the first frame, without a fatal error.
230    fn healthy(&self);
231    /// The app did not start, or its VM was stopped ([`AppError::is_fatal`]).
232    fn failed(&self, error: &AppError);
233}
234
235/// A chunk of a split bundle (`nsh_bundler::Chunk`): app code that
236/// `import()` loads on demand.
237#[derive(Debug, Clone)]
238pub struct Chunk {
239    /// Its id (`Screen.js`), as the bundle imports it.
240    pub id: String,
241    /// The code.
242    pub code: BundleCode,
243    /// Source map (JSON), for stack traces.
244    pub source_map: Option<Arc<str>>,
245}
246
247impl Chunk {
248    /// A chunk as JS source.
249    pub fn source(id: impl Into<String>, code: String) -> Self {
250        Self {
251            id: id.into(),
252            code: BundleCode::Source(code),
253            source_map: None,
254        }
255    }
256
257    /// A chunk as bytecode (`nsh_js::compile_chunk_bytecode`).
258    ///
259    /// # Safety
260    ///
261    /// As [`Bundle::bytecode`].
262    pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
263        Self {
264            id: id.into(),
265            code: BundleCode::Bytecode(bytes),
266            source_map: None,
267        }
268    }
269
270    /// Attaches a source map.
271    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
272        self.source_map = Some(map.into());
273        self
274    }
275}
276
277/// What a bundle's code may do.
278#[derive(Debug, Clone)]
279pub struct Policy {
280    /// Run without `eval`, the function constructors and writable shared
281    /// prototypes (see `nsh_js::HostOptions::harden`). On by default; off for
282    /// development bundles.
283    pub harden: bool,
284    /// What the app declared (`nsh.json` `capabilities`); `None`: no
285    /// declaration, everything.
286    pub declared: Option<Capabilities>,
287    /// What the embedding app grants at most; `None`: whatever the app
288    /// declared.
289    pub granted: Option<Capabilities>,
290}
291
292impl Default for Policy {
293    fn default() -> Self {
294        Self {
295            harden: true,
296            declared: None,
297            granted: None,
298        }
299    }
300}
301
302impl Policy {
303    /// Development bundles: `eval` and friends stay (debugging); the
304    /// capabilities are still enforced, so a missing one shows during
305    /// development.
306    pub fn development() -> Self {
307        Self {
308            harden: false,
309            ..Self::default()
310        }
311    }
312
313    /// What the app may reach under this policy.
314    pub fn access(&self) -> Access {
315        Access {
316            declared: self.declared.clone().unwrap_or_else(Capabilities::all),
317            granted: self.granted.clone(),
318        }
319    }
320}
321
322/// The code of a bundle.
323#[derive(Debug, Clone)]
324pub enum BundleCode {
325    /// QuickJS bytecode from `nsh_js::compile_bytecode`.
326    Bytecode(Vec<u8>),
327    /// JS source; slower to start than bytecode.
328    Source(String),
329}
330
331impl Default for Bundle {
332    fn default() -> Self {
333        Self::source(String::new())
334    }
335}
336
337impl Bundle {
338    /// A bytecode bundle.
339    ///
340    /// # Safety
341    ///
342    /// `bytes` must be bytecode from `nsh_js::compile_bytecode` for this
343    /// runtime's `BYTECODE_VERSION`, from a trusted source: QuickJS does not
344    /// validate bytecode, and loading crafted bytecode corrupts memory. Trusted
345    /// are the app's own signed resources, a development server the developer
346    /// pointed the host at, and verified packages ([`Bundle::from_package`]).
347    pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
348        Self {
349            code: BundleCode::Bytecode(bytes),
350            source_map: None,
351            policy: Policy::default(),
352            base_url: None,
353            chunks: Arc::default(),
354            app_id: None,
355            url_schemes: Vec::new(),
356            system_paths: nsh_core::access::TrustedPaths::default(),
357            package: None,
358            updater_config: None,
359            trial: None,
360            main_window: None,
361        }
362    }
363
364    /// A JS source bundle.
365    pub fn source(code: String) -> Self {
366        Self {
367            code: BundleCode::Source(code),
368            source_map: None,
369            policy: Policy::default(),
370            base_url: None,
371            chunks: Arc::default(),
372            app_id: None,
373            url_schemes: Vec::new(),
374            system_paths: nsh_core::access::TrustedPaths::default(),
375            package: None,
376            updater_config: None,
377            trial: None,
378            main_window: None,
379        }
380    }
381
382    /// Selects trusted source/package and home directory anchors. Supplying a
383    /// path grants nothing by itself: the manifest and host grant must still
384    /// allow the filesystem operation. Only existing absolute directories
385    /// are accepted; unavailable anchors are left unset.
386    pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
387        paths.plugin_dir = trusted_directory(paths.plugin_dir);
388        paths.home_dir = trusted_directory(paths.home_dir);
389        self.system_paths = paths;
390        self
391    }
392
393    /// The app's id ([`Bundle::app_id`]), as `nsh.json` or the dev server
394    /// gives it.
395    pub fn with_app_id(mut self, id: Option<&str>) -> Self {
396        self.app_id = id.map(str::to_owned);
397        self
398    }
399
400    /// The main window's launch-time options from their JSON (`nsh.json`
401    /// `"window"`, as the dev server's app info carries it); a wrong one is
402    /// logged and left out.
403    pub fn with_main_window(mut self, json: Option<&str>) -> Self {
404        self.main_window = json.and_then(|json| {
405            let parsed = serde_json::from_str(json)
406                .map_err(|e| e.to_string())
407                .and_then(|v| nsh_core::desktop::MainWindowOptions::from_json(&v));
408            parsed.map_err(|e| log::warn!("nsh.json window: {e}")).ok()
409        });
410        self
411    }
412
413    /// The URL schemes the app claims ([`Bundle::url_schemes`]), as
414    /// `nsh.json` gives them.
415    pub fn with_url_schemes(
416        mut self,
417        schemes: impl IntoIterator<Item = impl Into<String>>,
418    ) -> Self {
419        self.url_schemes = schemes.into_iter().map(Into::into).collect();
420        self
421    }
422
423    /// Attaches a source map.
424    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
425        self.source_map = Some(map.into());
426        self
427    }
428
429    /// Sets the URL relative request URLs resolve against: the page's, for
430    /// an app on a web page. A base marks a page: with one, a media source
431    /// `/x` is the page's path, not a local file under `capabilities.fs`
432    /// ([`nsh_core::access::Access::media_url`]), so a native host sets none.
433    pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
434        self.base_url = Some(url.into());
435        self
436    }
437
438    /// Replaces the policy.
439    pub fn with_policy(mut self, policy: Policy) -> Self {
440        self.policy = policy;
441        self
442    }
443
444    /// Adds chunks of a split bundle (see [`Bundle::chunks`]).
445    pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
446        Arc::make_mut(&mut self.chunks).extend(chunks);
447        self
448    }
449
450    /// Reads a JS source bundle written by `nsh build` (`bundle.js`), plus
451    /// `bundle.js.map`, the app's `capabilities.json`, its id and the
452    /// schemes it claims (`app.json` `"id"` and `"schemes"`) next to it
453    /// if present. Bytecode (`bundle.nshc`) is refused: files can be replaced, and
454    /// only [`Bundle::read_trusted`] (the app's own resources) or a verified
455    /// package may load bytecode.
456    pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
457        if path.extension().is_some_and(|e| e == "nshc") {
458            return Err(io::Error::other(
459                "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
460            ));
461        }
462        // SAFETY: not bytecode.
463        unsafe { Self::read_trusted(path) }
464    }
465
466    /// Like [`Bundle::read`], also reading `bundle.nshc` as bytecode.
467    ///
468    /// # Safety
469    ///
470    /// A `.nshc` file must be trusted as [`Bundle::bytecode`] requires (e.g.
471    /// inside the app's own signed bundle).
472    pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
473        let bytes = std::fs::read(path)?;
474        let bundle = if path.extension().is_some_and(|e| e == "nshc") {
475            // SAFETY: guaranteed by the caller.
476            unsafe { Bundle::bytecode(bytes) }
477        } else {
478            Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
479        };
480        let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
481            Ok(map) if !map.is_empty() => bundle.with_source_map(map),
482            _ => bundle,
483        };
484        if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
485            bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
486        }
487        let info = read_app_json(&path.with_file_name("app.json"));
488        bundle.app_id = info
489            .as_ref()
490            .and_then(|info| info.get("id")?.as_str().map(str::to_owned));
491        if let Some(window) = info.as_ref().and_then(|info| info.get("window")) {
492            bundle.main_window = Some(
493                nsh_core::desktop::MainWindowOptions::from_json(window)
494                    .map_err(|e| io::Error::other(format!("app.json: {e}")))?,
495            );
496        }
497        if let Some(url_schemes) = info.as_ref().and_then(|info| info.get("schemes")) {
498            // A newer NSH's: what this runtime cannot claim is left out.
499            let (schemes, ignored) = nsh_core::url_scheme::schemes_from_json_lenient(url_schemes);
500            for what in ignored {
501                log::warn!("app.json: {what}, ignored");
502            }
503            bundle.url_schemes = schemes;
504        }
505        // The files it opens come as `file:` URLs (`nsh_core::file_type`).
506        if info
507            .as_ref()
508            .is_some_and(nsh_core::file_type::declares_file_types)
509        {
510            bundle
511                .url_schemes
512                .push(nsh_core::file_type::FILE_SCHEME.to_owned());
513        }
514        bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
515            .parent()
516            .map(std::path::Path::to_path_buf);
517        Ok(bundle)
518    }
519}
520
521#[cfg(feature = "js-core")]
522impl Bundle {
523    /// The bundle of a verified package: its bytecode when it was compiled
524    /// for this runtime (else its source), its source map and its declared
525    /// capabilities. What a newer signer wrote that this runtime does not
526    /// know (header fields, files, capabilities) is logged and left out: an
527    /// unknown capability is not granted.
528    pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
529        for ignored in &package.ignored {
530            log::warn!("package {}: ignored {ignored}", package.app.id);
531        }
532        let bundle = match package.bytecode() {
533            // SAFETY: verified: signed by a certified release key, hashed,
534            // and compiled for this runtime.
535            Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
536            None => Bundle::source(package.source.clone()),
537        };
538        let mut bundle = match &package.source_map {
539            Some(map) => bundle.with_source_map(map.clone()),
540            None => bundle,
541        };
542        if let Some(json) = &package.capabilities {
543            let (declared, dropped) = Capabilities::from_json_lenient(json)?;
544            for dropped in dropped {
545                log::warn!("package {}: not granted: {dropped}", package.app.id);
546            }
547            bundle.policy.declared = Some(declared);
548        }
549        bundle.app_id = Some(package.app.id.clone());
550        bundle.package = Some(Arc::new(PackageInfo {
551            id: package.app.id.clone(),
552            name: package.app.name.clone(),
553            version: package.app.version.clone(),
554            build: package.app.build,
555            sha256: package.sha256.clone(),
556        }));
557        Ok(bundle)
558    }
559}
560
561/// An `app.json` (`nsh build`'s, a packaged app's): the app's id, the
562/// schemes it claims.
563fn read_app_json(path: &std::path::Path) -> Option<serde_json::Value> {
564    serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
565}
566
567/// A verified package, unpacked ([`load_package`], [`verify_package`]).
568#[cfg(feature = "js-core")]
569#[derive(Debug)]
570pub struct LoadedPackage {
571    /// Its bundle.
572    pub bundle: Bundle,
573    /// Where its assets are (`asset:/…`).
574    pub assets: std::path::PathBuf,
575    /// Its app.
576    pub app: nsh_package::App,
577    /// What accepting it records ([`accept_package`]).
578    pub receipt: nsh_package::PackageReceipt,
579}
580
581/// Verifies the package `bytes` with `trust`, writes its assets under
582/// `assets_root` (`<root>/<app id>/<package hash>/`, once per package) and
583/// records its build (older builds of the app are refused from now on):
584/// [`verify_package`], then [`accept_package`].
585#[cfg(feature = "js-core")]
586pub fn load_package(
587    trust: &mut nsh_package::TrustStore,
588    bytes: &[u8],
589    assets_root: &std::path::Path,
590) -> Result<LoadedPackage, String> {
591    let package = verify_package(trust, bytes, assets_root)?;
592    accept_package(trust, &package)?;
593    Ok(package)
594}
595
596/// [`load_package`] without recording the build: the package is verified as
597/// strictly (signature, certificate, revocations, hashes, and its build not
598/// older than the highest accepted) and its assets written, but the builds
599/// accepted before keep verifying. An embedding app runs it, and once it
600/// decided the package is healthy (its first frame drawn, no fatal error for
601/// a while) calls [`accept_package`]; if it fails before, the app can go
602/// back to the package it ran before, which still verifies.
603#[cfg(feature = "js-core")]
604pub fn verify_package(
605    trust: &nsh_package::TrustStore,
606    bytes: &[u8],
607    assets_root: &std::path::Path,
608) -> Result<LoadedPackage, String> {
609    let package = trust
610        .verify(bytes, BYTECODE_VERSION)
611        .map_err(|e| e.to_string())?;
612    let bundle = Bundle::from_package(&package)?;
613    let dir = assets_root.join(&package.app.id).join(&package.sha256);
614    let done = dir.join(".complete");
615    if !done.exists() {
616        let assets = dir.join("assets");
617        for (path, data) in &package.assets {
618            // Paths were checked (relative, no `..`) when the package was read.
619            let dest = assets.join(path);
620            if let Some(parent) = dest.parent() {
621                std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
622            }
623            std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
624        }
625        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
626        std::fs::write(&done, b"").map_err(|e| e.to_string())?;
627    }
628    Ok(LoadedPackage {
629        bundle,
630        assets: dir.join("assets"),
631        receipt: package.receipt(),
632        app: package.app,
633    })
634}
635
636/// Rewrites every `bundle.js:LINE:COL` in `text` (a reported error and its
637/// stack) to the app source position `source_map` (the bundle's) gives,
638/// as the engine does with a bundle's own map: for stacks reported by
639/// packages published without their map (`nsh symbolicate`).
640#[cfg(feature = "js-core")]
641pub fn symbolicate(source_map: &str, text: &str) -> String {
642    symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
643}
644
645/// Records the build of `package` ([`verify_package`]) in `trust`: older
646/// builds of its app are refused from now on. Refused if the package or its
647/// release key was revoked since it was verified.
648#[cfg(feature = "js-core")]
649pub fn accept_package(
650    trust: &mut nsh_package::TrustStore,
651    package: &LoadedPackage,
652) -> Result<(), String> {
653    trust
654        .accept_receipt(&package.receipt)
655        .map_err(|e| e.to_string())
656}
657
658/// Parses capabilities in their JSON form (`capabilities.json`, the dev
659/// protocol, an embedder's grant). A newer NSH may have written them: what
660/// this runtime does not know is not granted (a warning says what), so a
661/// bundle built by a newer toolchain still runs here and never gets more
662/// than it declared.
663pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
664    let value: serde_json::Value =
665        serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
666    let (capabilities, dropped) = Capabilities::from_json_lenient(&value)?;
667    for dropped in dropped {
668        log::warn!("not granted: {dropped} (unknown to this NSH)");
669    }
670    Ok(capabilities)
671}
672
673impl Bundle {
674    /// The declared capabilities from their JSON form, if any.
675    pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
676        self.policy.declared = json.map(parse_capabilities).transpose()?;
677        Ok(self)
678    }
679}
680
681/// Receives mount batches on the engine thread. Implementations forward
682/// them to the UI thread.
683pub trait MountSink: Send + 'static {
684    /// Called once per commit, in order.
685    fn submit(&self, batch: MountBatch);
686
687    /// Include logical tree order when the mounted structure changes. Native
688    /// `Insert` items alone describe stacking order, which can differ by `zIndex`.
689    fn needs_tree_order(&self) -> bool {
690        false
691    }
692
693    /// Include the states views show as parts of a control
694    /// ([`nsh_core::MountItem::ProjectStates`]): for a platform that marks
695    /// a list's highlighted option itself, as a terminal does.
696    fn needs_projected_states(&self) -> bool {
697        false
698    }
699
700    /// An error of the app, as text (the message and the stack): the
701    /// bundle failed to load, an exception escaped a JS callback, the VM
702    /// was stopped. Errors are always logged; development hosts also show
703    /// them on screen. What [`MountSink::report`] calls unless it is
704    /// implemented.
705    fn report_error(&self, _message: &str) {}
706
707    /// An error of the app, with its parts: what went wrong (whether the
708    /// app can go on), the message, the stack and the package it came
709    /// from. By default, [`MountSink::report_error`] with its text.
710    fn report(&self, error: &AppError) {
711        self.report_error(&error.to_string());
712    }
713
714    /// JS or a component's task asked for a display frame
715    /// (`requestAnimationFrame`, `nsh_core::element::next_frame`), or lists have
716    /// overscan cells left to bind: call [`EngineControl::frame`] at the
717    /// next vsync. Requests are not repeated until that call.
718    fn request_frame(&self) {}
719
720    /// A development update ([`EngineControl::hot_update`]) could not be
721    /// applied in place: reload the latest full bundle.
722    fn hot_update_failed(&self) {}
723
724    /// Runs `task` on the UI thread, after the batches submitted before it
725    /// (`nsh_core::element::run_on_main_thread`). By default it runs here,
726    /// on the engine thread: what a host without a main thread of its own
727    /// does (headless tests, the web, where the engine runs on the page's
728    /// thread).
729    fn run_on_main_thread(&self, task: MainThreadTask) {
730        task.run();
731    }
732
733    /// The engine laid the app out at `size` ([`EngineControl::resize`]):
734    /// called after the commit of the turn that applied the resize (if it
735    /// changed anything, its batch came before), once per turn, with the
736    /// latest size. A platform that waits for the layout at a new size, to
737    /// show it in the frame the window takes the size, stops waiting here.
738    fn resized(&self, _size: Size<Points>) {}
739
740    /// The engine has handled the first `events` events sent with
741    /// [`EngineControl::dispatch_event`]. Called after the commit of the
742    /// turn that handled them (what they changed came before), once per
743    /// turn. A platform holding typed text for the field an event may focus
744    /// gives it to the focused field from here.
745    fn handled(&self, _events: u64) {}
746
747    /// The app imports chunk `id` of a split bundle (`import()`), which its
748    /// [`Bundle`] does not hold: load it and hand it over with
749    /// [`EngineControl::chunk_loaded`] (or [`EngineControl::chunk_failed`]),
750    /// from any thread, and return true. False (the default): this host
751    /// has no chunks to load, and the import fails.
752    fn load_chunk(&self, _id: &str) -> bool {
753        false
754    }
755}
756
757/// Receives what happens to a request started by [`Network::fetch`], in
758/// order, on any thread. After [`FetchTask::cancel`] it may still be called
759/// (the engine then ignores it).
760pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
761
762/// A request in flight, driven from the engine thread.
763pub trait FetchTask: Send {
764    /// The next chunk of a streamed body ([`HttpBody::Stream`]), after
765    /// [`FetchEvent::BodyWanted`].
766    fn send(&mut self, chunk: Vec<u8>);
767    /// A streamed body is complete.
768    fn finish(&mut self);
769    /// Stops (`true`) or resumes (`false`) reading the response body: JS
770    /// does not read what arrived (back pressure). Bytes already on their
771    /// way may still arrive.
772    fn pause(&mut self, paused: bool);
773    /// Aborts the request.
774    fn cancel(self: Box<Self>);
775}
776
777/// `nsh/updater` on the engine's network and assets: the platform's HTTP stack
778/// (so its TLS and proxies), and the file `nsh package` left among the assets.
779struct UpdaterOverNetwork {
780    network: Arc<dyn Network>,
781    assets: Option<Arc<dyn Assets>>,
782    /// [`Bundle::updater_config`].
783    config: Option<Arc<[u8]>>,
784    /// [`Bundle::package`].
785    running: Option<Arc<PackageInfo>>,
786}
787
788impl UpdaterOverNetwork {
789    /// `None` without a network, or without both assets and the bundle's
790    /// configuration (nothing to update from).
791    #[cfg_attr(
792        not(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32"))),
793        allow(dead_code)
794    )]
795    fn host(
796        network: Option<Arc<dyn Network>>,
797        assets: Option<Arc<dyn Assets>>,
798        bundle: &Bundle,
799    ) -> Option<Arc<dyn nsh_core::runtime::UpdaterHost>> {
800        if assets.is_none() && bundle.updater_config.is_none() {
801            return None;
802        }
803        Some(Arc::new(UpdaterOverNetwork {
804            network: network?,
805            assets,
806            config: bundle.updater_config.clone(),
807            running: bundle.package.clone(),
808        }))
809    }
810}
811
812impl nsh_core::runtime::UpdaterHost for UpdaterOverNetwork {
813    fn config(&self) -> Option<Vec<u8>> {
814        if let Some(config) = &self.config {
815            return Some(config.to_vec());
816        }
817        // Only a package has it; a dev server answers nothing for it.
818        self.assets.as_ref()?.read("asset:/nsh-updater.json").ok()
819    }
820
821    fn running_package(&self) -> Option<nsh_core::runtime::PackageVersion> {
822        let running = self.running.as_ref()?;
823        let mut version = nsh_core::runtime::PackageVersion::default();
824        version.version = running.version.clone();
825        version.build = running.build;
826        Some(version)
827    }
828
829    fn runs_packages(&self) -> bool {
830        cfg!(all(feature = "js-core", not(target_arch = "wasm32")))
831    }
832
833    #[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
834    fn verify_package(
835        &self,
836        file: &std::path::Path,
837        updates: &std::path::Path,
838        app_id: &str,
839        roots: &[String],
840        newer_than: u64,
841    ) -> Result<nsh_core::runtime::PackageVersion, String> {
842        let app = updates::verify_download(file, updates, app_id, roots, newer_than)?;
843        let mut version = nsh_core::runtime::PackageVersion::default();
844        version.version = app.version;
845        version.build = app.build;
846        Ok(version)
847    }
848
849    fn get(&self, url: &str, sink: nsh_core::runtime::UpdaterSink<'_>) -> Result<(), String> {
850        let (tx, rx) = std::sync::mpsc::channel();
851        let events: FetchEvents = Box::new(move |event| {
852            let _ = tx.send(event);
853        });
854        let task = self.network.fetch(HttpRequest::new("GET", url), events);
855        let mut total = None;
856        let result = loop {
857            match rx.recv() {
858                Ok(FetchEvent::Head(head)) => {
859                    if !(200..300).contains(&head.status) {
860                        break Err(format!("HTTP {}", head.status));
861                    }
862                    total = head
863                        .headers
864                        .iter()
865                        .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
866                        .and_then(|(_, value)| value.parse().ok());
867                }
868                Ok(FetchEvent::Data(chunk)) => {
869                    if let Err(e) = sink(&chunk, total) {
870                        break Err(e);
871                    }
872                }
873                Ok(FetchEvent::End) => return Ok(()),
874                Ok(FetchEvent::Failed(e)) => break Err(e),
875                Ok(FetchEvent::BodyWanted) => {}
876                Err(_) => break Err("the network stack went away".to_owned()),
877            }
878        };
879        task.cancel();
880        result
881    }
882}
883
884/// The platform's HTTP stack, used by JS `fetch`.
885pub trait Network: Send + Sync + 'static {
886    /// Starts `request`: its response head, then its body in chunks as they
887    /// arrive, are reported to `events`.
888    fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
889}
890
891/// Reads the app's bundled files (`asset:/…` URIs): from the app's
892/// resources, or from the dev server during development. The engine reads
893/// the fonts it registers with it, and answers the app's requests of
894/// `asset:/` URLs (`fetch`) from it.
895pub trait Assets: Send + Sync + 'static {
896    /// The bytes of `uri`. Blocking: the engine calls it on its thread for
897    /// the fonts it registers, and on a thread of the runtime's blocking
898    /// pool for the app's requests (in WebAssembly on its thread).
899    fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
900
901    /// Where `uri` is served, for files [`Assets::read`] does not have at
902    /// hand: the engine downloads them from there with its network stack
903    /// (the web page, which holds only the files it preloaded). `None`, the
904    /// default, when `read` is the only way.
905    fn url(&self, uri: &str) -> Option<String> {
906        let _ = uri;
907        None
908    }
909
910    /// Where `asset:/` URIs resolve, when it is a directory or a URL the
911    /// image loader can read itself: the core's image loads ([`svg`]s)
912    /// then share the platform's cache entries. `None`: through
913    /// [`Assets::read`].
914    ///
915    /// [`svg`]: nsh_core::element::svg
916    #[cfg(not(target_arch = "wasm32"))]
917    fn base(&self) -> Option<nsh_core::image::loader::AssetBase> {
918        None
919    }
920}
921
922/// Engine settings.
923#[derive(Clone)]
924pub struct EngineConfig {
925    /// The app.
926    pub app: App,
927    /// Initial size of the root view.
928    pub viewport: Size<Points>,
929    /// Log per-commit timings (target `nsh::perf`, level info).
930    pub trace: bool,
931    /// Scroll views make the native views of their content only near
932    /// their viewport (the platforms' apps); off, they make all of it
933    /// (tests, which read whole pages). [`EngineConfig::new`]: off.
934    pub content_culling: bool,
935    /// The HTTP stack behind `fetch`; without one, requests fail.
936    pub network: Option<Arc<dyn Network>>,
937    /// The host transport for WebSockets, including the browser WebSocket API.
938    pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
939    /// Refuses the app's connections (`net` sockets and both WebSocket
940    /// APIs) with the error it gives for what they connect to, before they
941    /// reach the network: a test's, which reaches it only when the test
942    /// asks (`nsh test`'s `network: "live"`). `None`: they connect.
943    pub refuse_connections: Option<nsh_core::element::RefuseConnections>,
944    /// App-private host filesystem service (for browser storage).
945    pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
946    /// Source of bundled files such as fonts; without one, they fail to load.
947    pub assets: Option<Arc<dyn Assets>>,
948    /// The surface's initial environment (its `window` is `viewport`).
949    pub environment: Environment,
950    /// Height of the platform's screen header bar, normal and with a large
951    /// title (status bar excluded).
952    pub header_heights: (Points, Points),
953    /// The JS VM's resource limits (a JS app's; Rust code has none).
954    pub limits: Limits,
955    /// The UI sets JS imports (`nsh_base::registry()` by default, the app's
956    /// own): their Rust components and modules. A Rust app's
957    /// components need no registration.
958    pub ui_sets: Vec<nsh_core::element::Registry>,
959    /// The tokio runtime the components' async tasks use (timers, IO,
960    /// background work); `None`: one shared by the engines of the process.
961    pub runtime: Option<tokio::runtime::Handle>,
962    /// Where apps keep their data: each app in `<data_dir>/<app id>`
963    /// ([`App::app_id`]; `default` without one), its storage
964    /// (`nsh/storage`) in `storage.json` there. The platform's: the
965    /// system's data directory ([`data_dir`]) for apps of their own,
966    /// `…/nsh` in an embedding app's. `None`: nothing is kept.
967    pub data_dir: Option<std::path::PathBuf>,
968    /// Where the app's caches are kept and how much each keeps: the engine
969    /// opens them in `<root>/<app id>/<kind>` ([`Engine::image_cache`]).
970    /// [`EngineConfig::new`]: none.
971    pub cache: CacheOptions,
972    /// The app's storage, overriding the one [`EngineConfig::data_dir`]
973    /// names (the browser's `localStorage`, an embedder's own); `None`
974    /// with no data directory either: in memory, for the engine's life.
975    pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
976    /// The time the app runs on: the system's, or a manual clock a test
977    /// moves (`nsh_core::time::Clock::manual`), which its timers, frames
978    /// and `Date` follow.
979    pub clock: Clock,
980    /// What the host gives this engine's Rust code, which its UI sets'
981    /// functions and components read while it runs them
982    /// (`nsh_core::element::engine_context`): a host serving several engines
983    /// tells them apart by it.
984    pub context: EngineContext,
985    /// Values of the environment kept whatever the platform reports (a
986    /// test's locale, reduced motion and safe area: `nsh test --target`).
987    pub pinned: EnvironmentPins,
988    /// Serves the app's clipboard calls in place of the platform's
989    /// clipboard (a test's own: `nsh test --target`); `None`: the
990    /// platform's.
991    pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
992    /// The embedding app's channel with the app (`nsh/host`): its launch
993    /// parameters, its events and its handlers of the app's calls and
994    /// posts. A view keeps one for every app it runs; the default is a
995    /// channel of the engine's own, with none of them.
996    pub host: HostChannel,
997    /// Answers the app's picks (`Picker.pickImages`, `Picker.pickFiles`) in place of the
998    /// platform's picker: the embedding app's own picker, or a test's
999    /// files; `None`: the platform's.
1000    pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
1001    /// Recognizes the app's speech (`Speech.start`) instead of the
1002    /// platform's recognizer: the embedding app's own, or a test's fake
1003    /// (`nsh_testing`'s). `None` (the default): the platform's, where it
1004    /// has one (`Environment::speech`).
1005    pub speech: Option<Arc<dyn nsh_core::speech::SpeechBackend>>,
1006    /// Plays the app's sound (`Sound`, `AudioPlayer`) instead of the
1007    /// platform: the embedding app's own audio stack, or a test's fake
1008    /// (`nsh_testing`'s). `None` (the default): the platform's, where it
1009    /// has one (`Environment::audio`).
1010    pub audio: Option<Arc<dyn nsh_core::audio::AudioBackend>>,
1011    /// Opens and applies the app's windows of its own (`<Window>`,
1012    /// `Window.open`) instead of the platform: the embedding app's own
1013    /// windows, or a test's fake. `None` (the default): the platform's
1014    /// built-in backend, which every desktop backend has, embedded or
1015    /// standalone. The main window's commands always go to the platform.
1016    pub windows: Option<Arc<dyn nsh_core::desktop::WindowBackend>>,
1017}
1018
1019/// Values of the environment an engine keeps whatever its platform reports
1020/// ([`EngineConfig::pinned`]); `None` leaves the platform's.
1021#[derive(Debug, Clone, Copy, Default, PartialEq)]
1022#[non_exhaustive]
1023pub struct EnvironmentPins {
1024    /// The locale (`Environment::locale`).
1025    pub locale: Option<nsh_core::platform::Locale>,
1026    /// The preferred languages (`LocaleSettings::languages`).
1027    pub languages: Option<nsh_core::platform::Languages>,
1028    /// The hour cycle (`LocaleSettings::hour_cycle`).
1029    pub hour_cycle: Option<nsh_core::platform::HourCycle>,
1030    /// The first day of the week (`LocaleSettings::first_day_of_week`).
1031    pub first_day_of_week: Option<nsh_core::platform::Weekday>,
1032    /// The measurement system (`LocaleSettings::measurement_system`).
1033    pub measurement_system: Option<nsh_core::platform::MeasurementSystem>,
1034    /// The temperature unit (`LocaleSettings::temperature_unit`).
1035    pub temperature_unit: Option<nsh_core::platform::TemperatureUnit>,
1036    /// The time zone (`LocaleSettings::time_zone`).
1037    pub time_zone: Option<nsh_core::platform::TimeZone>,
1038    /// Whether the user asked for less motion
1039    /// (`Environment::reduce_motion`).
1040    pub reduce_motion: Option<bool>,
1041    /// The safe area insets (`Environment::safe_area`).
1042    pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
1043}
1044
1045impl EnvironmentPins {
1046    /// `environment` with these values in place of the platform's.
1047    pub fn apply(&self, environment: &mut Environment) {
1048        if let Some(locale) = self.locale {
1049            environment.locale = locale;
1050        }
1051        let settings = &mut environment.locale_settings;
1052        if let Some(languages) = self.languages {
1053            settings.languages = languages;
1054        }
1055        if let Some(time_zone) = self.time_zone {
1056            settings.time_zone = time_zone;
1057        }
1058        if let Some(hour_cycle) = self.hour_cycle {
1059            settings.hour_cycle = hour_cycle;
1060        }
1061        if let Some(day) = self.first_day_of_week {
1062            settings.first_day_of_week = day;
1063        }
1064        if let Some(system) = self.measurement_system {
1065            settings.measurement_system = system;
1066        }
1067        if let Some(unit) = self.temperature_unit {
1068            settings.temperature_unit = unit;
1069        }
1070        if let Some(reduce_motion) = self.reduce_motion {
1071            environment.reduce_motion = reduce_motion;
1072        }
1073        if let Some(safe_area) = self.safe_area {
1074            environment.safe_area = safe_area;
1075        }
1076    }
1077}
1078
1079fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
1080    let path = path.filter(|path| path.is_absolute())?;
1081    nsh_core::access::canonicalize(&path)
1082        .ok()
1083        .filter(|path| path.is_dir())
1084}
1085
1086/// Native hosts choose these anchors before any application JavaScript runs
1087/// (the VM's `fs/promises` and the core's media files read under them).
1088fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
1089    let mut paths = bundle.system_paths.clone();
1090    paths.plugin_dir = trusted_directory(paths.plugin_dir);
1091    paths.home_dir = trusted_directory(paths.home_dir);
1092    if paths.home_dir.is_none() {
1093        paths.home_dir = ["HOME", "USERPROFILE"]
1094            .into_iter()
1095            .filter_map(std::env::var_os)
1096            .map(std::path::PathBuf::from)
1097            .find_map(|path| trusted_directory(Some(path)));
1098    }
1099    // Local `nsh run` passes its canonical entry directory directly to the
1100    // native child process. Remote dev messages never contain this field.
1101    // A packaged/hardened bundle cannot inherit a development source anchor.
1102    if paths.plugin_dir.is_none() && !bundle.policy.harden {
1103        paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
1104            .map(std::path::PathBuf::from)
1105            .and_then(|path| trusted_directory(Some(path)));
1106    }
1107    paths
1108}
1109
1110impl EngineConfig {
1111    /// `app` on a phone-sized surface (390 × 844 points, iOS's header
1112    /// heights) with nothing else: no network, assets, data directory or
1113    /// UI sets, the default environment and limits, the shared runtime.
1114    /// Set the fields that matter over it (`EngineConfig { ui_sets,
1115    /// ..EngineConfig::new(app) }`). There is no `Default`: an engine has
1116    /// no app to run by default.
1117    pub fn new(app: impl Into<App>) -> Self {
1118        Self {
1119            app: app.into(),
1120            viewport: Size::new(Points(390.0), Points(844.0)),
1121            trace: false,
1122            content_culling: false,
1123            network: None,
1124            websocket: None,
1125            refuse_connections: None,
1126            filesystem: None,
1127            assets: None,
1128            environment: Environment::default(),
1129            header_heights: (Points(44.0), Points(96.0)),
1130            limits: Limits::default(),
1131            ui_sets: Vec::new(),
1132            runtime: None,
1133            data_dir: None,
1134            cache: CacheOptions::off(),
1135            storage: None,
1136            clock: Clock::system(),
1137            context: EngineContext::default(),
1138            pinned: EnvironmentPins::default(),
1139            clipboard: None,
1140            host: HostChannel::default(),
1141            picker: None,
1142            speech: None,
1143            audio: None,
1144            windows: None,
1145        }
1146    }
1147
1148    /// Where a runner opens the main window of an app with nsh.json
1149    /// `window.restoreBounds`: the placement its last run kept in its
1150    /// storage ([`EngineConfig::storage`], or the file in its directory of
1151    /// [`EngineConfig::data_dir`]), fitted on `displays`, the ones there
1152    /// are now. Read before making the window; `None` without
1153    /// `restoreBounds` or a kept placement. The engine keeps it as the
1154    /// window changes (the environment's window state).
1155    pub fn main_window_placement(
1156        &self,
1157        displays: &[nsh_core::desktop::Display],
1158    ) -> Option<nsh_core::desktop::WindowPlacement> {
1159        let options = self.app.main_window()?;
1160        let storage = app_storage(self)?;
1161        options.kept_placement(&*storage, displays)
1162    }
1163}
1164
1165/// The storage of the app `config` runs: [`EngineConfig::storage`], or a
1166/// file in its directory of [`EngineConfig::data_dir`].
1167fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
1168    if let Some(storage) = &config.storage {
1169        return Some(storage.clone());
1170    }
1171    #[cfg(not(target_arch = "wasm32"))]
1172    if let Some(root) = &config.data_dir {
1173        let dir = root.join(app_dir_name(config.app.app_id()));
1174        return Some(FileStorage::open(dir));
1175    }
1176    None
1177}
1178
1179#[cfg(not(target_arch = "wasm32"))]
1180/// The runtime of components' tasks when the embedder gives none: a few
1181/// threads, made on first use, shared by every engine (like a thread pool,
1182/// it holds no engine's state).
1183fn shared_runtime() -> tokio::runtime::Handle {
1184    static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
1185    RUNTIME
1186        .get_or_init(|| {
1187            tokio::runtime::Builder::new_multi_thread()
1188                .worker_threads(2)
1189                .thread_name("nsh-tasks")
1190                .enable_all()
1191                .build()
1192                .expect("the tasks' runtime starts")
1193        })
1194        .handle()
1195        .clone()
1196}
1197
1198impl std::fmt::Debug for EngineConfig {
1199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1200        f.debug_struct("EngineConfig")
1201            .field("app", &self.app)
1202            .field("viewport", &self.viewport)
1203            .field("trace", &self.trace)
1204            .field("content_culling", &self.content_culling)
1205            .field("network", &self.network.is_some())
1206            .field("assets", &self.assets.is_some())
1207            .field("environment", &self.environment)
1208            .field("header_heights", &self.header_heights)
1209            .field("limits", &self.limits)
1210            .field("ui_sets", &self.ui_sets)
1211            .field("clock", &self.clock)
1212            .field("context", &self.context)
1213            .field("pinned", &self.pinned)
1214            .field("clipboard", &self.clipboard.is_some())
1215            .field("host", &self.host)
1216            .field("picker", &self.picker.is_some())
1217            .field("speech", &self.speech.is_some())
1218            .field("audio", &self.audio.is_some())
1219            .field("windows", &self.windows.is_some())
1220            .finish()
1221    }
1222}
1223
1224/// How many times [`EngineControl::advance_clock`] stops for what comes
1225/// due at most (sinon's fake timers stop at 1000 for one `runAll`; this
1226/// leaves room for a long run of 60 Hz intervals).
1227const MAX_ADVANCE_ROUNDS: usize = 100_000;
1228
1229/// How many times [`EngineControl::flush`] runs what is queued again when
1230/// running it queued more (a task woken by another, a request answered at
1231/// once): a task that keeps waking itself leaves the engine busy.
1232const MAX_FLUSH_ROUNDS: usize = 64;
1233
1234enum Message {
1235    Event(NodeId, EventKind, EventPayload),
1236    Scroll(NodeId, Point<Points>, u32),
1237    Kept(Vec<NodeId>),
1238    ContentCulling(bool),
1239    InputScroll(NodeId, Point<Points>, Size<Points>, Size<Points>),
1240    Zoom(NodeId, f32),
1241    ComponentSize(NodeId, Size<Points>),
1242    AnimationsFinished(Vec<nsh_core::animation::Finished>),
1243    Resize(Size<Points>),
1244    /// A component's task was woken: it runs in the loop.
1245    Wake,
1246    /// Boxed: with the locale settings held inline, an
1247    /// environment is several times the size of every other message, and
1248    /// it changes rarely.
1249    Environment(Box<Environment>),
1250    /// The platform found no GPU to draw shader views with
1251    /// ([`EngineControl::shaders_unavailable`]).
1252    ShadersUnavailable,
1253    /// The displays (desktops).
1254    Displays(Arc<[nsh_core::desktop::Display]>),
1255    RootSize(NodeId, Size<Points>, EdgeInsets),
1256    ScreenHeader(NodeId, Option<Points>),
1257    Frame,
1258    States(NodeId, u16),
1259    Modality(nsh_core::platform::InputModality),
1260    FontsChanged,
1261    Remount,
1262    /// An event of a request (by the hop it is for: events of a hop the
1263    /// engine left are dropped).
1264    Fetch(Requester, u64, FetchEvent),
1265    /// Hop `.1` of the request `.2` for a bundled file read it on a
1266    /// blocking thread ([`Net::asset`]): its bytes, or why there are none.
1267    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1268    AssetRead(Requester, u64, HttpRequest, Result<Vec<u8>, String>),
1269    Hot(HotUpdate),
1270    /// A chunk [`MountSink::load_chunk`] was asked for, or why it could
1271    /// not be loaded (its id and the message).
1272    Chunk(Result<Chunk, (String, String)>),
1273    Perf(Option<Arc<perf::PerfMonitor>>),
1274    /// The embedding app's design tokens.
1275    Tokens(Option<Box<Tokens>>),
1276    /// A font file the embedding app registers (TrueType, OpenType, WOFF or
1277    /// WOFF2), before the first frame and whenever it registers another.
1278    HostFont(Vec<u8>),
1279    /// The embedding app's event (`nsh/host`'s `host.on`): its name and
1280    /// data.
1281    HostEvent(String, nsh_core::JsonValue),
1282    /// The embedding app's answer to call `.0` (`host.call`).
1283    HostReply(u64, Result<nsh_core::JsonValue, String>),
1284    /// The embedding app's URL handler answered URL request `id`: it took
1285    /// the URL, or the platform opens it.
1286    UrlHandled {
1287        id: u32,
1288        url: String,
1289        handled: bool,
1290    },
1291    /// Moves a manual clock forward by this much, then calls back.
1292    Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
1293    /// Runs what is queued and due now, then calls back with whether the
1294    /// engine is idle ([`EngineControl::flush`]).
1295    Flush(Box<dyn FnOnce(bool) + Send>),
1296    /// Sent by a dropped [`Engine`] (there is none in WebAssembly).
1297    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1298    Shutdown,
1299}
1300
1301/// A development update that replaces the app's changed modules in place,
1302/// keeping the JS context, the views and the state of everything else
1303/// (made by `nsh_bundler::HotBundle::patch`).
1304#[derive(Debug, Clone)]
1305pub struct HotUpdate {
1306    /// Script name in stack traces, unique per update (e.g. `hot-3.js`).
1307    pub name: String,
1308    /// The script.
1309    pub code: String,
1310    /// Its source map (JSON).
1311    pub source_map: Option<Arc<str>>,
1312}
1313
1314/// Rounds of "list asks for items -> JS renders them -> layout" folded into
1315/// one frame. Bounded so a list that never settles cannot stall the engine;
1316/// leftovers continue next frame.
1317const MAX_LIST_ROUNDS: usize = 8;
1318
1319/// The overscan a turn binds: cells until their ops reach this many (about
1320/// as many mount items, which the main thread applies in one go) or their
1321/// JS takes [`PACED_BIND_TIME`], at least one. A fast scroll asks for a
1322/// screen of cells at once and each bind rebuilds a cell's subtree; what
1323/// shows (the viewport, the leading edge, cells whose item moved) binds
1324/// regardless, the rest on the next display frames.
1325const PACED_BIND_OPS: usize = 150;
1326/// See [`PACED_BIND_OPS`].
1327const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);
1328
1329/// A cheap, cloneable handle for sending input to the engine from any thread.
1330#[derive(Clone)]
1331pub struct EngineControl {
1332    tx: Sender<Message>,
1333    /// The input modality last sent ([`Self::set_input_modality`]), shared
1334    /// by every clone: 0 none, else 1 + the modality.
1335    modality: Arc<std::sync::atomic::AtomicU8>,
1336}
1337
1338impl EngineControl {
1339    /// Delivers an input event (and its data) to a node.
1340    pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
1341        let _ = self.tx.send(Message::Event(id, event, payload));
1342    }
1343
1344    /// Reports the content offset of a scroll view or list, and how many
1345    /// scrolls the core asked for (`MountItem::ScrollBy` items and
1346    /// `Command::ScrollTo` commands for the view) were applied before it.
1347    /// Cheap to call on every scroll frame: offsets are coalesced per
1348    /// engine frame.
1349    pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
1350        let _ = self.tx.send(Message::Scroll(id, offset, applied));
1351    }
1352
1353    /// Keeps the virtual list rows holding `nodes` rendered wherever they
1354    /// scroll (`Core::set_kept`): the ends of a text selection. Replaces
1355    /// the last call's; none releases them.
1356    pub fn keep_rendered(&self, nodes: Vec<NodeId>) {
1357        let _ = self.tx.send(Message::Kept(nodes));
1358    }
1359
1360    /// Whether scroll views make the native views of their content as it
1361    /// comes near their viewport (the default), or all of it
1362    /// (`Core::set_content_culling`): a test driver's, whose steps reach
1363    /// every view of a page.
1364    pub fn set_content_culling(&self, enabled: bool) {
1365        let _ = self.tx.send(Message::ContentCulling(enabled));
1366    }
1367
1368    /// Reports how far a multiline input's text scrolled: its offset, the
1369    /// size of the text it scrolls and of its viewport. Sent while a
1370    /// built-in bar takes the place of its indicator
1371    /// (`InputConfig::replaced`), on every change.
1372    pub fn input_scroll(
1373        &self,
1374        id: NodeId,
1375        offset: Point<Points>,
1376        content: Size<Points>,
1377        viewport: Size<Points>,
1378    ) {
1379        let _ = self
1380            .tx
1381            .send(Message::InputScroll(id, offset, content, viewport));
1382    }
1383
1384    /// Reports the zoom scale of a zoomable scroll view (before the offset
1385    /// the zoom changed); `onScroll` carries it.
1386    pub fn zoom(&self, id: NodeId, scale: f32) {
1387        let _ = self.tx.send(Message::Zoom(id, scale));
1388    }
1389
1390    /// A registered native component's own size (points): it is laid out at
1391    /// it where its style leaves a dimension open.
1392    pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
1393        let _ = self.tx.send(Message::ComponentSize(id, size));
1394    }
1395
1396    /// Reports native animations that finished or were interrupted.
1397    pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
1398        let _ = self.tx.send(Message::AnimationsFinished(finished));
1399    }
1400
1401    /// Resizes the root view.
1402    pub fn resize(&self, size: Size<Points>) {
1403        let _ = self.tx.send(Message::Resize(size));
1404    }
1405
1406    /// Reports a change of the surface's environment (safe area, keyboard,
1407    /// appearance...).
1408    pub fn set_environment(&self, environment: Environment) {
1409        let _ = self.tx.send(Message::Environment(Box::new(environment)));
1410    }
1411
1412    /// The platform has no GPU to draw shader views with
1413    /// ([`shader::Renderer::new`] is `None`): the app's
1414    /// `Environment::shaders` turns `false` now and stays so, whatever the
1415    /// platform reports later. Telling it again does nothing.
1416    pub fn shaders_unavailable(&self) {
1417        let _ = self.tx.send(Message::ShadersUnavailable);
1418    }
1419
1420    /// Reports the displays (desktops: on start, in
1421    /// [`Engine::start_with`]'s setup, so the app reads them as it first
1422    /// renders, then whenever they change).
1423    pub fn set_displays(&self, displays: Vec<nsh_core::desktop::Display>) {
1424        let _ = self.tx.send(Message::Displays(displays.into()));
1425    }
1426
1427    /// The platform presents root `id` (a modal) at `size`, with `insets`
1428    /// of it covered by system UI.
1429    pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
1430        let _ = self.tx.send(Message::RootSize(id, size, insets));
1431    }
1432
1433    /// The platform measured where the content of screen `id` starts below
1434    /// its header (`None`: let the core estimate it).
1435    pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
1436        let _ = self.tx.send(Message::ScreenHeader(id, height));
1437    }
1438
1439    /// Applies a development update in place. When it cannot be applied,
1440    /// [`MountSink::hot_update_failed`] asks the platform to reload.
1441    pub fn hot_update(&self, update: HotUpdate) {
1442        let _ = self.tx.send(Message::Hot(update));
1443    }
1444
1445    /// Hands over the chunk [`MountSink::load_chunk`] asked for: the
1446    /// dynamic imports waiting for it continue.
1447    pub fn chunk_loaded(&self, chunk: Chunk) {
1448        let _ = self.tx.send(Message::Chunk(Ok(chunk)));
1449    }
1450
1451    /// Chunk `id` could not be loaded: the dynamic imports waiting for it
1452    /// fail with `message` (a later import asks for it again).
1453    pub fn chunk_failed(&self, id: String, message: String) {
1454        let _ = self.tx.send(Message::Chunk(Err((id, message))));
1455    }
1456
1457    /// A display frame began, after [`MountSink::request_frame`]: runs the
1458    /// `requestAnimationFrame` callbacks and the tasks waiting for it.
1459    pub fn frame(&self) {
1460        let _ = self.tx.send(Message::Frame);
1461    }
1462
1463    /// Moves the engine's manual clock ([`EngineConfig::clock`]) forward
1464    /// by `by`: the timers and tasks due meanwhile run in the order they
1465    /// come due, each at its time, with what they make due in turn, and the
1466    /// clock's alarms (a response it holds back) go off on the way. Then
1467    /// `done` runs, after the batches of what ran were submitted. With the
1468    /// system's clock it only runs `done`.
1469    pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
1470        let _ = self.tx.send(Message::Advance(by, Box::new(done)));
1471    }
1472
1473    /// Runs everything sent to the engine before it and everything due on
1474    /// its clock now (timers, woken tasks, answers that came at once), with
1475    /// what they queue in turn, without moving the clock. Then `done` runs,
1476    /// after the batches of what ran were submitted, with whether the
1477    /// engine is idle: nothing is left to run and no request waits for
1478    /// the network. False when work keeps coming (a task that keeps waking
1479    /// itself) or a request is in flight, whose answer comes later from
1480    /// elsewhere. A headless driver on a manual clock settles a step with
1481    /// it, instead of waiting for the batches to stop for a while.
1482    pub fn flush(&self, done: impl FnOnce(bool) + Send + 'static) {
1483        let _ = self.tx.send(Message::Flush(Box::new(done)));
1484    }
1485
1486    /// The user gave the surface input with `modality`: a pointer, finger
1487    /// or pen going down, or a key pressed (not a modifier alone). Called
1488    /// for every such event, before the platform acts on it, so it reaches
1489    /// the core ahead of the focus move it causes; only a change crosses
1490    /// to the engine. The core shows the keyboard focus by it
1491    /// (`focus-visible:`; [`nsh_core::Core::set_input_modality`]).
1492    pub fn set_input_modality(&self, modality: nsh_core::platform::InputModality) {
1493        use std::sync::atomic::Ordering;
1494        let code = match modality {
1495            nsh_core::platform::InputModality::Keyboard => 1,
1496            nsh_core::platform::InputModality::Pointer => 2,
1497        };
1498        if self.modality.swap(code, Ordering::Relaxed) != code {
1499            let _ = self.tx.send(Message::Modality(modality));
1500        }
1501    }
1502
1503    /// Reports the interaction states of view `id` that the core asked to
1504    /// track ([`nsh_core::MountItem::TrackStates`]; bits of
1505    /// [`nsh_core::tailwind::state`]). Class styles that depend on them
1506    /// (`active:`, `hover:`, `focus:`) update without JS.
1507    pub fn set_states(&self, id: NodeId, states: u16) {
1508        let _ = self.tx.send(Message::States(id, states));
1509    }
1510
1511    /// Fonts the platform loads asynchronously became usable (on the web,
1512    /// a `FontFace` finished loading): text measured with a fallback font
1513    /// is measured again.
1514    pub fn fonts_changed(&self) {
1515        let _ = self.tx.send(Message::FontsChanged);
1516    }
1517
1518    /// The platform's views get everything again and text is measured
1519    /// again: the unit the platform converts values with changed (Android's
1520    /// density). Send the new environment and size too.
1521    pub fn remount(&self) {
1522        let _ = self.tx.send(Message::Remount);
1523    }
1524
1525    /// Records the engine's commits into `monitor` from now on (`None`:
1526    /// stops). Measuring costs nothing while no monitor is installed.
1527    pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
1528        let _ = self.tx.send(Message::Perf(monitor));
1529    }
1530
1531    /// Sets the embedding app's design tokens (`nsh-base`'s theme's),
1532    /// which the app renders with instead of its own (`None`: its own
1533    /// again; [`Core::set_host_tokens`]). Sent from
1534    /// [`Engine::start_with`]'s `setup`, they are in the first frame.
1535    pub fn set_tokens(&self, tokens: Option<Tokens>) {
1536        let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1537    }
1538
1539    /// Registers a font file the embedding app ships (TrueType, OpenType,
1540    /// WOFF or WOFF2) so every app this engine runs can name its family.
1541    /// Sent from [`Engine::start_with`]'s `setup`, it is registered before
1542    /// the first frame; sent later, text measured already is measured again.
1543    pub fn register_font(&self, data: Vec<u8>) {
1544        let _ = self.tx.send(Message::HostFont(data));
1545    }
1546}
1547
1548#[cfg(not(target_arch = "wasm32"))]
1549/// A running engine. Dropping it stops the thread.
1550pub struct Engine {
1551    control: EngineControl,
1552    thread: Option<std::thread::JoinHandle<()>>,
1553    /// Serializes shutdown with the embedding app's sends.
1554    host: HostChannel,
1555    /// Interrupts running JS when the engine stops.
1556    stop: Arc<std::sync::atomic::AtomicBool>,
1557    /// The app has quit listeners (`on_app_quit`, `Application.on("quit")`):
1558    /// a drop gives them [`QUIT_TIMEOUT`] before interrupting JS.
1559    quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1560    /// The app's disk cache of downloaded images.
1561    image_cache: Option<nsh_core::image::DiskCache>,
1562    /// [`Engine::media_files`].
1563    media_files: Arc<nsh_core::access::MediaFiles>,
1564}
1565
1566#[cfg(not(target_arch = "wasm32"))]
1567impl Engine {
1568    /// Starts the engine thread. `make_text_engine` runs on that thread.
1569    pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
1570    where
1571        M: TextEngine + 'static,
1572        F: FnOnce() -> M + Send + 'static,
1573        S: MountSink,
1574    {
1575        Self::start_with(config, make_text_engine, sink, |_| {})
1576    }
1577
1578    /// [`Engine::start`], with `setup` sending input before the engine
1579    /// starts: what it sends (a theme, the environment) is applied before
1580    /// the first frame.
1581    pub fn start_with<M, F, S>(
1582        config: EngineConfig,
1583        make_text_engine: F,
1584        sink: S,
1585        setup: impl FnOnce(&EngineControl),
1586    ) -> io::Result<Engine>
1587    where
1588        M: TextEngine + 'static,
1589        F: FnOnce() -> M + Send + 'static,
1590        S: MountSink,
1591    {
1592        let image_cache = config.cache.open_images(config.app.app_id());
1593        let media_files = Arc::new(media_files(&config, &app_access(&config.app)));
1594        let (tx, rx) = crossbeam_channel::unbounded();
1595        let modality = Arc::default();
1596        setup(&EngineControl {
1597            tx: tx.clone(),
1598            modality: Arc::clone(&modality),
1599        });
1600        let engine_tx = tx.clone();
1601        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1602        let engine_stop = stop.clone();
1603        let quit_listeners = Arc::new(std::sync::atomic::AtomicBool::new(false));
1604        let engine_quit_listeners = quit_listeners.clone();
1605        let host = config.host.clone();
1606        let thread = std::thread::Builder::new()
1607            .name("nsh-engine".into())
1608            .stack_size(ENGINE_STACK_SIZE)
1609            .spawn(move || {
1610                run(
1611                    config,
1612                    make_text_engine(),
1613                    sink,
1614                    engine_tx,
1615                    rx,
1616                    engine_stop,
1617                    engine_quit_listeners,
1618                )
1619            })?;
1620        Ok(Engine {
1621            control: EngineControl { tx, modality },
1622            thread: Some(thread),
1623            host,
1624            stop,
1625            quit_listeners,
1626            image_cache,
1627            media_files,
1628        })
1629    }
1630
1631    /// The roots the app's local media files are read under
1632    /// ([`nsh_core::access::MediaFiles::open`]). The platform's image
1633    /// loader reads `<Image>` files through them, as the core's does, so a
1634    /// link swapped in after the check is not followed out of them.
1635    pub fn media_files(&self) -> Arc<nsh_core::access::MediaFiles> {
1636        self.media_files.clone()
1637    }
1638
1639    /// The disk cache of the images the app downloads
1640    /// ([`EngineConfig::cache`]; `None`: none). The platform's image loader
1641    /// routes the app's `http(s)` images through it.
1642    pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
1643        self.image_cache.clone()
1644    }
1645
1646    /// A handle for sending input from other threads.
1647    pub fn control(&self) -> EngineControl {
1648        self.control.clone()
1649    }
1650}
1651
1652#[cfg(not(target_arch = "wasm32"))]
1653impl Drop for Engine {
1654    fn drop(&mut self) {
1655        // Dropped on the platform's main thread: a script still running is
1656        // aborted rather than waited for, after the app's quit listeners
1657        // had their time (GPUI's shutdown waits for its quit observers so).
1658        if self
1659            .quit_listeners
1660            .load(std::sync::atomic::Ordering::Relaxed)
1661        {
1662            self.host.request_shutdown(&self.control.tx);
1663            let deadline = Instant::now() + QUIT_TIMEOUT + QUIT_GRACE;
1664            while self.thread.as_ref().is_some_and(|t| !t.is_finished())
1665                && Instant::now() < deadline
1666            {
1667                std::thread::sleep(Duration::from_millis(1));
1668            }
1669        }
1670        self.host.shutdown(&self.control.tx, &self.stop);
1671        if let Some(thread) = self.thread.take() {
1672            let _ = thread.join();
1673        }
1674    }
1675}
1676
1677#[cfg(not(target_arch = "wasm32"))]
1678/// The engine thread turns input into frames: it is as latency-critical as
1679/// the UI thread. Without this, Apple platforms may run it on efficiency
1680/// cores at low clock speeds.
1681fn raise_thread_priority() {
1682    #[cfg(target_vendor = "apple")]
1683    // SAFETY: changes the QoS class of the calling thread only.
1684    unsafe {
1685        libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
1686    }
1687}
1688
1689/// How long the engine runs the app's quit listeners at most.
1690#[cfg(not(target_arch = "wasm32"))]
1691use nsh_core::element::desktop::QUIT_TIMEOUT;
1692
1693/// What the dropping [`Engine`] waits past [`QUIT_TIMEOUT`] for the engine
1694/// to finish its last turn before interrupting JS.
1695#[cfg(not(target_arch = "wasm32"))]
1696const QUIT_GRACE: Duration = Duration::from_millis(20);
1697
1698/// A resize this soon after the last is one of a burst, a window being
1699/// dragged; this long after the last the burst is over ([`Core::set_resizing`]).
1700const RESIZE_BURST_GAP: Duration = Duration::from_millis(120);
1701
1702#[cfg(not(target_arch = "wasm32"))]
1703fn run<M: TextEngine + 'static, S: MountSink>(
1704    config: EngineConfig,
1705    text_engine: M,
1706    sink: S,
1707    tx: Sender<Message>,
1708    rx: Receiver<Message>,
1709    stop: Arc<std::sync::atomic::AtomicBool>,
1710    quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1711) {
1712    raise_thread_priority();
1713    // The thread's time is the engine's from its first line of JS on.
1714    let _clock = config.clock.enter();
1715    let _context = config.context.enter();
1716    let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
1717        return;
1718    };
1719    driver.quit_listeners = quit_listeners;
1720    driver.sync_quit_listeners();
1721    drive(&mut driver, &rx);
1722    driver.quit(&rx);
1723    // Stopped on purpose (a crash never gets here): a trial is over.
1724    if let Some(trial) = &driver.trial {
1725        trial.healthy();
1726    }
1727}
1728
1729/// Tells `trial` the app is healthy [`TRIAL_PERIOD`] after its first frame
1730/// (it ignores this after a fatal error).
1731fn start_trial(trial: Arc<dyn Trial>) {
1732    #[cfg(not(target_arch = "wasm32"))]
1733    {
1734        let spawned = std::thread::Builder::new()
1735            .name("nsh-trial".into())
1736            .spawn(move || {
1737                std::thread::sleep(TRIAL_PERIOD);
1738                trial.healthy();
1739            });
1740        if let Err(err) = spawned {
1741            log::error!("cannot time the app's trial: {err}");
1742        }
1743    }
1744    // WebAssembly runs no packaged apps' updates.
1745    #[cfg(target_arch = "wasm32")]
1746    drop(trial);
1747}
1748
1749/// Runs the engine's loop until it stops.
1750#[cfg(not(target_arch = "wasm32"))]
1751fn drive<M: TextEngine + 'static>(driver: &mut Driver<M>, rx: &Receiver<Message>) {
1752    loop {
1753        let message = match driver.deadline() {
1754            Some(deadline) => match rx.recv_deadline(deadline) {
1755                Ok(message) => Some(message),
1756                Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
1757                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
1758            },
1759            None => match rx.recv() {
1760                Ok(message) => Some(message),
1761                Err(_) => return,
1762            },
1763        };
1764        let started = driver.state.perf.is_some().then(Instant::now);
1765        if let Some(message) = message {
1766            if !driver.handle(message, rx) {
1767                return;
1768            }
1769            // Coalesce everything already queued into this frame.
1770            while let Ok(message) = rx.try_recv() {
1771                if !driver.handle(message, rx) {
1772                    return;
1773                }
1774            }
1775        }
1776        driver.turn();
1777        driver.state.record_perf(started);
1778        if rx.is_empty() {
1779            driver.collect_if_idle();
1780        }
1781    }
1782}
1783
1784/// An engine driven by its host's event loop instead of a thread of its
1785/// own: the browser's main thread in WebAssembly, where there are no
1786/// threads to block. Input sent through its [`EngineControl`] is handled
1787/// at the next [`LocalEngine::pump`].
1788pub struct LocalEngine<M: TextEngine + 'static> {
1789    /// Dropped while this engine's context is the thread's. The guard
1790    /// would otherwise end when `drop` returns, before the fields drop.
1791    driver: ManuallyDrop<Driver<M>>,
1792    rx: Receiver<Message>,
1793    control: EngineControl,
1794    /// The host's wake ([`LocalEngine::set_wake`]).
1795    wake: Option<Arc<dyn Fn() + Send + Sync>>,
1796    /// Set while [`LocalEngine::pump`] runs: what it wakes it runs itself,
1797    /// so the host's wake is not called for it.
1798    pumping: Arc<std::sync::atomic::AtomicBool>,
1799}
1800
1801impl<M: TextEngine + 'static> LocalEngine<M> {
1802    /// Starts the app (its first frame goes to `sink` before this returns);
1803    /// `None` if it could not start (reported to `sink`).
1804    pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
1805        Self::start_with(config, text_engine, sink, |_| {})
1806    }
1807
1808    /// [`LocalEngine::start`], with `setup` sending input before the engine
1809    /// starts, as [`Engine::start_with`]'s does: the link that launched the
1810    /// app is there before its code runs.
1811    pub fn start_with<S: MountSink>(
1812        config: EngineConfig,
1813        text_engine: M,
1814        sink: S,
1815        setup: impl FnOnce(&EngineControl),
1816    ) -> Option<Self> {
1817        let (tx, rx) = crossbeam_channel::unbounded();
1818        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1819        let control = EngineControl {
1820            tx: tx.clone(),
1821            modality: Arc::default(),
1822        };
1823        setup(&control);
1824        let _clock = config.clock.enter();
1825        let _context = config.context.enter();
1826        let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
1827        Some(LocalEngine {
1828            driver: ManuallyDrop::new(driver),
1829            rx,
1830            control,
1831            wake: None,
1832            pumping: Arc::default(),
1833        })
1834    }
1835
1836    /// A handle for sending input.
1837    pub fn control(&self) -> EngineControl {
1838        self.control.clone()
1839    }
1840
1841    /// Calls `wake` when there is work outside a [`pump`](Self::pump): a
1842    /// component task is woken or Rust posts a JS call while no pump runs
1843    /// (a callback of the host's completing what a task waits for, such as
1844    /// a WebSocket message through wasm-bindgen), once per wake-up, or a
1845    /// pump ends with work its bound left. The host then calls `pump` soon,
1846    /// instead of only at the deadline it returned or at the next input.
1847    /// What a pump wakes itself (a task waking another, a reply it hands
1848    /// over) it runs without calling `wake`.
1849    pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
1850        let tx = self.control.tx.clone();
1851        let pumping = self.pumping.clone();
1852        let host = wake.clone();
1853        let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
1854            let _ = tx.send(Message::Wake);
1855            // After the send: a pump that is ending sees the message
1856            // (`pump` clears the flag, then looks at the queue).
1857            if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
1858                host();
1859            }
1860        });
1861        self.driver.state.core.set_task_notify(notify.clone());
1862        self.driver.posts.set_notify(notify);
1863        self.wake = Some(wake);
1864    }
1865
1866    /// Serves `ui_sets` (a superset of the config's, after a UI set or
1867    /// part was registered while the app runs: the web runtime's late
1868    /// gates) to what is mounted from now on.
1869    pub fn extend_ui_sets(&mut self, ui_sets: &[nsh_core::element::Registry]) {
1870        let sets: Vec<_> = nsh_core::runtime::registries()
1871            .iter()
1872            .chain(ui_sets)
1873            .cloned()
1874            .collect();
1875        self.driver
1876            .state
1877            .core
1878            .extend_components(nsh_core::element::Registry::merged(&sets));
1879    }
1880
1881    /// Handles the input sent since the last call, runs what is due
1882    /// (timers, tasks) and commits. Returns when to call again at the
1883    /// latest (sooner if input arrives); `None`: only for input.
1884    pub fn pump(&mut self) -> Option<Instant> {
1885        let _clock = self.driver.clock.enter();
1886        let _context = self.driver.context.enter();
1887        self.pumping
1888            .store(true, std::sync::atomic::Ordering::SeqCst);
1889        // Bounded: messages sent while handling (a task waking another)
1890        // are handled in the same call, a loop that never settles is not.
1891        for _ in 0..4 {
1892            let started = self.driver.state.perf.is_some().then(Instant::now);
1893            while let Ok(message) = self.rx.try_recv() {
1894                self.driver.handle(message, &self.rx);
1895            }
1896            self.driver.turn();
1897            self.driver.state.record_perf(started);
1898            if self.rx.is_empty() {
1899                break;
1900            }
1901        }
1902        self.driver.collect_if_idle();
1903        self.pumping
1904            .store(false, std::sync::atomic::Ordering::SeqCst);
1905        // What the bound left waits for the next pump: soon, not at the
1906        // deadline.
1907        if !self.rx.is_empty()
1908            && let Some(wake) = &self.wake
1909        {
1910            wake();
1911        }
1912        self.driver.deadline()
1913    }
1914}
1915
1916impl<M: TextEngine + 'static> Drop for LocalEngine<M> {
1917    fn drop(&mut self) {
1918        // Cancelling tasks and dropping what they captured reads this
1919        // engine's context. `run` keeps its guard across the driver's
1920        // drop; this path enters for the drop itself.
1921        let _context = self.driver.context.enter();
1922        // SAFETY: `driver` is dropped once, here. `ManuallyDrop` keeps
1923        // the field drop from dropping it again.
1924        unsafe { ManuallyDrop::drop(&mut self.driver) };
1925    }
1926}
1927
1928/// One engine's state and the work of one wake-up, whoever drives it.
1929struct Driver<M: TextEngine + 'static> {
1930    state: State<Rc<M>>,
1931    script: Option<Script>,
1932    sink: Rc<dyn MountSink>,
1933    assets: Option<Arc<dyn Assets>>,
1934    /// A VM stopped for good (out of memory, over a quota) is reported
1935    /// once; its views stay as they were and no JS runs any more.
1936    stopped: bool,
1937    last_gc: Instant,
1938    /// When a message or a due timer last gave the engine work
1939    /// ([`IDLE_GC_QUIET`]).
1940    last_active: Instant,
1941    /// The queue of the JS calls Rust posts: its notify wakes the engine,
1942    /// as the core's task notify does ([`LocalEngine::set_wake`]).
1943    posts: nsh_core::element::Posts,
1944    /// The engine's clock, its thread's ([`Clock::enter`]).
1945    clock: Clock,
1946    /// The host's context, its thread's ([`EngineContext::enter`]).
1947    context: EngineContext,
1948    /// When the last display frame ran, on a clock that moves with the
1949    /// display's frames: the next one comes a frame after it.
1950    last_frame: Option<Instant>,
1951    /// The engine's attachment to the embedding app's channel: its events
1952    /// come here while the engine runs.
1953    _host: host_channel::HostAttachment,
1954    /// [`Bundle::trial`], told the app is healthy when the engine stops
1955    /// after its first frame. Only the native engine thread ([`run`]) stops
1956    /// that way; WebAssembly has no such stop.
1957    #[cfg(not(target_arch = "wasm32"))]
1958    trial: Option<Arc<dyn Trial>>,
1959    /// Tells the dropping [`Engine`] whether the app has quit listeners.
1960    quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1961    /// The quit listeners run ([`Driver::quit`]): frames are not submitted
1962    /// any more.
1963    quitting: bool,
1964}
1965
1966impl<M: TextEngine + 'static> Driver<M> {
1967    /// Sets up the core, starts the app and submits its first frame.
1968    fn start(
1969        mut config: EngineConfig,
1970        text_engine: M,
1971        sink: Rc<dyn MountSink>,
1972        tx: Sender<Message>,
1973        rx: &Receiver<Message>,
1974        stop: Arc<std::sync::atomic::AtomicBool>,
1975    ) -> Option<Self> {
1976        config.pinned.apply(&mut config.environment);
1977        drawn_shaders(&mut config.environment, false);
1978        let trial = match &config.app {
1979            App::Js(bundle) => bundle.trial.clone(),
1980            App::Rust(_) => None,
1981        };
1982        #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
1983        let system_tx = tx.clone();
1984        #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
1985        let host_bridge = config.host.bridge(tx.clone());
1986        let host_tx = tx.clone();
1987        let text_engine = Rc::new(text_engine);
1988        let access = Arc::new(app_access(&config.app));
1989        let mut core = Core::new(text_engine.clone(), config.viewport);
1990        core.set_content_culling(config.content_culling);
1991        core.set_tree_order_tracking(sink.needs_tree_order());
1992        core.set_projected_state_mounting(sink.needs_projected_states());
1993        // The runtime's components (`nsh/mobile`'s `TabBar`) and the UI
1994        // sets the host serves.
1995        let sets: Vec<_> = nsh_core::runtime::registries()
1996            .iter()
1997            .chain(&config.ui_sets)
1998            .cloned()
1999            .collect();
2000        core.set_components(nsh_core::element::Registry::merged(&sets));
2001        // The JS calls Rust posts queue in one place, which the core
2002        // releases in order with the ops (a post during a synchronous call)
2003        // and the script runs.
2004        let posts = nsh_core::element::Posts::new();
2005        core.set_posts(posts.clone());
2006        if let App::Js(_) = &config.app {
2007            // Only JS is limited (Rust code is as trusted as the platform).
2008            core.set_max_nodes(config.limits.max_nodes);
2009        }
2010        core.set_access(access.clone());
2011        if let App::Js(bundle) = &config.app {
2012            // What `//` media sources resolve against, as `fetch`'s URLs do.
2013            core.set_base_url(bundle.base_url.clone());
2014        }
2015        // The roots local media files are read under, as `fs/promises`
2016        // reads files (where it has a file system: the desktops).
2017        let media_files = Arc::new(media_files(&config, &access));
2018        core.set_media_files(media_files.clone());
2019        #[cfg(not(target_arch = "wasm32"))]
2020        core.set_image_context(nsh_core::image::loader::Context {
2021            asset_base: config.assets.as_ref().and_then(|a| a.base()),
2022            read_asset: config.assets.clone().map(|assets| {
2023                Arc::new(move |uri: &str| assets.read(uri)) as nsh_core::image::loader::ReadAsset
2024            }),
2025            access: access.clone(),
2026            media_files,
2027            // The same cache as the platform's ([`Engine::image_cache`]).
2028            disk: config.cache.open_images(config.app.app_id()),
2029            // The platform's, if it set one ([`nsh_core::image::loader::set_transport`]).
2030            transport: None,
2031        });
2032        core.set_storage(app_storage(&config));
2033        core.set_data_dir(
2034            config
2035                .data_dir
2036                .as_ref()
2037                .map(|root| root.join(app_dir_name(config.app.app_id()))),
2038        );
2039        core.set_clipboard(config.clipboard.clone());
2040        core.set_picker(config.picker.clone());
2041        core.set_speech(config.speech.clone());
2042        core.set_url_schemes(config.app.url_schemes().iter().cloned());
2043        // Every VM reads the core's address where it is (`UrlScheme.url()`).
2044        #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2045        let app_url = core.app_url_cell();
2046        core.set_audio(config.audio.clone());
2047        core.set_window_backend(config.windows.clone());
2048        if let Some(window) = config.app.main_window() {
2049            core.set_main_window(window);
2050        }
2051        core.set_font_scale(config.environment.font_scale);
2052        core.set_class_environment(class_environment(&config.environment));
2053        core.set_header_heights(config.header_heights.0, config.header_heights.1);
2054        core.set_safe_area(insets(&config.environment));
2055        core.set_environment(ui_environment(&config.environment, config.viewport));
2056        // WebAssembly has no threads for a runtime: tasks' timers are
2057        // `nsh_core::time`'s there, fired by the driver.
2058        #[cfg(not(target_arch = "wasm32"))]
2059        let runtime = config.runtime.clone().unwrap_or_else(shared_runtime);
2060        #[cfg(not(target_arch = "wasm32"))]
2061        core.set_task_runtime(runtime.clone());
2062        // A Rust app's theme and fonts come with its root (a JS app's from
2063        // its bundle).
2064        if let App::Rust(root) = &config.app {
2065            if let Some(tokens) = root.tokens_ref() {
2066                core.set_tokens(tokens.clone());
2067            }
2068            if let Some(appearance) = root.appearance_ref() {
2069                core.set_appearance(appearance);
2070            }
2071            if let Some(translations) = root.translations_ref() {
2072                core.set_translations(translations.clone());
2073            }
2074            for font in root.fonts() {
2075                if let Err(err) = core.register_font(font) {
2076                    log::error!("font failed: {err}");
2077                    sink.report(&AppError::new(
2078                        AppErrorKind::Asset,
2079                        &format!("font failed: {err}"),
2080                    ));
2081                }
2082            }
2083        }
2084        // The fonts the UI sets' crates ship, before anything is measured.
2085        let fonts = config
2086            .ui_sets
2087            .iter()
2088            .flat_map(nsh_core::element::Registry::asset_files)
2089            .filter(|file| file.kind == nsh_core::element::AssetKind::Font);
2090        for font in fonts {
2091            let result = match config.assets.as_deref() {
2092                Some(assets) => assets.read(font.uri),
2093                None => Err("this host cannot load assets".to_owned()),
2094            }
2095            .and_then(|data| core.register_font(&data));
2096            if let Err(err) = result {
2097                log::error!("font failed: {}: {err}", font.uri);
2098                let message = format!("font failed: {}: {err}", font.uri);
2099                let package = match &config.app {
2100                    App::Js(bundle) => bundle.package.clone(),
2101                    App::Rust(_) => None,
2102                };
2103                sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
2104            }
2105        }
2106        // A task woken on any thread wakes the loop, and so does a JS call
2107        // Rust queues.
2108        let wake = tx.clone();
2109        core.set_task_notify(Arc::new(move || {
2110            let _ = wake.send(Message::Wake);
2111        }));
2112        let wake = tx.clone();
2113        posts.set_notify(Arc::new(move || {
2114            let _ = wake.send(Message::Wake);
2115        }));
2116        // The embedding app's tokens sent before the start
2117        // (`Engine::start_with`) are there as the bundle evaluates, so its
2118        // first render reads them; the rest comes after it, in order.
2119        // So are the displays, which the app reads as it first renders,
2120        // and the link that launched the app, which its first `url()` reads
2121        // (the core keeps it for the first `open` listener too).
2122        let mut early = Vec::new();
2123        let mut displays: Arc<[nsh_core::desktop::Display]> = Arc::from(Vec::new());
2124        while let Ok(message) = rx.try_recv() {
2125            match message {
2126                Message::Tokens(tokens) => core.set_host_tokens(tokens.map(|t| *t)),
2127                Message::HostFont(data) => {
2128                    if let Err(err) = core.register_font(&data) {
2129                        log::error!("font failed: {err}");
2130                    }
2131                }
2132                Message::Displays(list) => {
2133                    core.set_displays(list.clone());
2134                    displays = list;
2135                }
2136                Message::Event(nsh_core::ROOT_ID, EventKind::UrlScheme, payload) => {
2137                    core.component_event(nsh_core::ROOT_ID, EventKind::UrlScheme, &payload);
2138                }
2139                message => early.push(message),
2140            }
2141        }
2142        let js_tokens = core.tokens().clone();
2143        let state = State {
2144            core,
2145            js_tokens,
2146            frame_requested: false,
2147            ops: Vec::new(),
2148            binds: Vec::new(),
2149            events: Vec::new(),
2150            trace: config.trace,
2151            perf: None,
2152            perf_commit: perf::CommitTiming::default(),
2153            committed_since_gc: false,
2154            hot: Vec::new(),
2155            scroll_events: FxHashMap::default(),
2156            touch_move: None,
2157            mouse_moves: Vec::new(),
2158            mouse_moved: None,
2159            sets_seen: FxHashMap::default(),
2160            resized: None,
2161            resize_burst_ends: None,
2162            window_state: WindowStateReport {
2163                shown: config.environment.window_state,
2164                ..WindowStateReport::default()
2165            },
2166            events_handled: 0,
2167            events_reported: 0,
2168            pinned: config.pinned,
2169            environment: config.environment,
2170            shaders_unavailable: false,
2171            app_locale: None,
2172            host: config.host.clone(),
2173            url_opens: Vec::new(),
2174            net: Net {
2175                network: config.network.clone(),
2176                tx,
2177                queue: NetworkQueue::default(),
2178                inflight: FxHashMap::default(),
2179                tasks: Vec::new(),
2180                abandoned: Vec::new(),
2181                access: access.clone(),
2182                hops: 0,
2183                assets: config.assets.clone(),
2184                #[cfg(not(target_arch = "wasm32"))]
2185                runtime,
2186            },
2187        };
2188
2189        let mut environment = config.environment;
2190        environment.window = config.viewport;
2191        let start = Instant::now();
2192        let mut driver = Driver {
2193            state,
2194            script: None,
2195            sink: sink.clone(),
2196            assets: config.assets.clone(),
2197            stopped: false,
2198            last_gc: Instant::now(),
2199            last_active: Instant::now(),
2200            posts: posts.clone(),
2201            clock: config.clock.clone(),
2202            context: config.context.clone(),
2203            last_frame: None,
2204            _host: config.host.attach(host_tx, rx.clone()),
2205            #[cfg(not(target_arch = "wasm32"))]
2206            trial: trial.clone(),
2207            quit_listeners: Arc::default(),
2208            quitting: false,
2209        };
2210        let eval_us = match &config.app {
2211            App::Js(bundle) => {
2212                #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2213                let system = {
2214                    script::SystemConfig {
2215                        access: (*access).clone(),
2216                        websocket: config.websocket.clone(),
2217                        refuse_connections: config.refuse_connections.clone(),
2218                        filesystem: config.filesystem.clone(),
2219                        updater: UpdaterOverNetwork::host(
2220                            config.network.clone(),
2221                            config.assets.clone(),
2222                            bundle,
2223                        ),
2224                        app_url: app_url.clone(),
2225                        data_dir: config
2226                            .data_dir
2227                            .as_ref()
2228                            .map(|root| root.join(app_dir_name(config.app.app_id()))),
2229                        paths: bundle_system_paths(bundle),
2230                        wake: Arc::new(move || {
2231                            let _ = system_tx.send(Message::Wake);
2232                        }),
2233                        host: Rc::new(host_bridge),
2234                        lazy_rows: config.content_culling,
2235                    }
2236                };
2237                #[cfg(not(any(
2238                    feature = "js-core",
2239                    all(feature = "browser", target_arch = "wasm32")
2240                )))]
2241                let system = script::SystemConfig;
2242                let (script, eval_us) = Script::start(
2243                    bundle,
2244                    config.limits,
2245                    &config.ui_sets,
2246                    posts,
2247                    &environment,
2248                    &displays,
2249                    driver.state.js_tokens.clone(),
2250                    driver.state.core.theme_tokens(),
2251                    text_engine,
2252                    stop,
2253                    sink,
2254                    system,
2255                )?;
2256                driver.script = Some(script);
2257                eval_us
2258            }
2259            App::Rust(root) => {
2260                driver.state.core.mount_root(root);
2261                0
2262            }
2263        };
2264        let Driver {
2265            state,
2266            script,
2267            sink,
2268            assets,
2269            ..
2270        } = &mut driver;
2271        let script = script.as_ref();
2272        // What was sent before the start (`Engine::start_with`) is in the
2273        // first frame; a move of the clock comes after it.
2274        let mut moves = Vec::new();
2275        let pending = early
2276            .into_iter()
2277            .chain(std::iter::from_fn(|| rx.try_recv().ok()));
2278        for message in pending {
2279            if let Message::Advance(..) | Message::Flush(..) = message {
2280                moves.push(message);
2281            } else if !handle(script, state, message) {
2282                return None;
2283            }
2284        }
2285        // Workers may finish while the first bundle evaluates. Deliver their
2286        // completions even when the startup drain already consumed their wakeup.
2287        if let Some(script) = script {
2288            script.run_system();
2289        }
2290        state.load_fonts(script, assets.as_deref(), &**sink);
2291        if let Some(batch) = state.commit(script) {
2292            if state.trace {
2293                log::info!(
2294                    target: "nsh::perf",
2295                    "first frame: eval {eval_us}µs, total {}µs",
2296                    start.elapsed().as_micros()
2297                );
2298            }
2299            sink.submit(batch);
2300        }
2301        state.run_on_main_thread(&**sink);
2302        if let Some(trial) = trial {
2303            start_trial(trial);
2304        }
2305        // A resize that came while the app started is in the first frame:
2306        // reported as a turn reports it, or a platform waiting for the
2307        // layout at that size waits until something else wakes the engine.
2308        if let Some(size) = state.resized.take() {
2309            sink.resized(size);
2310        }
2311        state.report_handled(&**sink);
2312        state.net.pump(script, &mut state.core);
2313        state.load_chunks(script, &**sink);
2314        state.request_frame(script, &**sink);
2315        driver.check_stopped();
2316        for message in moves {
2317            if !driver.handle(message, rx) {
2318                return None;
2319            }
2320        }
2321        Some(driver)
2322    }
2323
2324    /// When the loop wakes next: for the next timer or throttled event
2325    /// (on the system's clock; a manual one moves only when told), or the
2326    /// idle collection (the system's time, whatever the clock).
2327    fn deadline(&self) -> Option<Instant> {
2328        let gc_deadline =
2329            (self.script.is_some() && self.state.committed_since_gc).then(|| self.next_gc());
2330        let due = if self.clock.is_manual() {
2331            None
2332        } else {
2333            self.due()
2334        };
2335        [due, gc_deadline].into_iter().flatten().min()
2336    }
2337
2338    /// When the next timer, task timer or throttled scroll or mouse move
2339    /// is due, on the engine's clock.
2340    fn due(&self) -> Option<Instant> {
2341        [
2342            self.script.as_ref().and_then(Script::next_timer),
2343            self.state.next_scroll_event(),
2344            self.state.next_mouse_move(),
2345            self.state.core.next_task_timer(),
2346            self.state.resize_burst_ends,
2347            self.state.window_state.settles,
2348        ]
2349        .into_iter()
2350        .flatten()
2351        .min()
2352    }
2353
2354    /// Handles one message; false on shutdown.
2355    fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
2356        self.last_active = Instant::now();
2357        match message {
2358            Message::Advance(by, done) => {
2359                let running = self.advance(by, rx, self.clock.moves_with_frames());
2360                done();
2361                running
2362            }
2363            Message::Flush(done) => {
2364                let running = self.flush(rx);
2365                done(running && self.idle(rx));
2366                running
2367            }
2368            // A test's clock on a real platform: the display's frame moves it
2369            // to the frame's time first (a frame after the last, else now),
2370            // as a headless run's frames do.
2371            Message::Frame if self.clock.moves_with_frames() => {
2372                // The frame runs there, once, as the frames a move runs on
2373                // the way do (whatever the messages handled meanwhile do).
2374                self.state.frame_requested = true;
2375                let by = self.next_frame() - self.clock.now();
2376                self.advance(by, rx, true)
2377            }
2378            message => handle(self.script.as_ref(), &mut self.state, message),
2379        }
2380    }
2381
2382    /// Moves a manual clock forward by `by` ([`EngineControl::advance_clock`]):
2383    /// to each time something comes due on the way, running it (and the
2384    /// messages its alarms sent) before going on; with `frames`, also to
2385    /// each display frame's time ([`nsh_core::time::FRAME`]) while the app
2386    /// waits for frames, running the frame there, as a headless run's
2387    /// display does (a clock that moves with a real display's frames:
2388    /// [`Clock::with_frames`]). False on shutdown.
2389    fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
2390        if !self.clock.is_manual() {
2391            // What the messages before it did is submitted before `done`.
2392            self.turn();
2393            return true;
2394        }
2395        let to = self.clock.now() + by;
2396        for round in 0.. {
2397            // A timer that keeps scheduling itself at once (`setTimeout(f,
2398            // 0)` in `f`) would hold the clock at one time for good.
2399            let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
2400            let next = [self.due(), self.clock.next_alarm(), frame]
2401                .into_iter()
2402                .flatten()
2403                .min()
2404                .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
2405            if round == MAX_ADVANCE_ROUNDS {
2406                log::warn!(
2407                    "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
2408                     a timer keeps scheduling another at once"
2409                );
2410            }
2411            let at = next.unwrap_or(to);
2412            self.clock.advance_to(at);
2413            while let Ok(message) = rx.try_recv() {
2414                if !self.handle(message, rx) {
2415                    return false;
2416                }
2417            }
2418            // Once: what was handled meanwhile may have run it already.
2419            if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
2420                && self.state.frame_requested
2421            {
2422                self.frame();
2423            }
2424            self.turn();
2425            if next.is_none() {
2426                break;
2427            }
2428        }
2429        true
2430    }
2431
2432    /// Runs what is queued and what is due now ([`EngineControl::flush`]),
2433    /// again while that queues more, [`MAX_FLUSH_ROUNDS`] times at most.
2434    /// False on shutdown.
2435    fn flush(&mut self, rx: &Receiver<Message>) -> bool {
2436        let frames = self.clock.moves_with_frames();
2437        for _ in 0..MAX_FLUSH_ROUNDS {
2438            while let Ok(message) = rx.try_recv() {
2439                if !self.handle(message, rx) {
2440                    return false;
2441                }
2442            }
2443            // A manual clock stays where it is: what is due now runs.
2444            if !self.advance(std::time::Duration::ZERO, rx, frames) {
2445                return false;
2446            }
2447            // What a turn queued (a task's wake, a response answered at
2448            // once) runs too, as long as it stops coming.
2449            if rx.is_empty() {
2450                break;
2451            }
2452        }
2453        true
2454    }
2455
2456    /// Whether nothing is left to run: no message queued, nothing due at
2457    /// the clock's time (a timer that keeps scheduling another at once
2458    /// outlasts a flush's rounds) and no request in flight.
2459    fn idle(&self, rx: &Receiver<Message>) -> bool {
2460        let now = self.clock.now();
2461        rx.is_empty()
2462            && self.state.net.idle()
2463            && [self.due(), self.clock.next_alarm()]
2464                .into_iter()
2465                .flatten()
2466                .all(|at| at > now)
2467    }
2468
2469    /// When the next display frame of a clock that moves with the
2470    /// display's frames is: a frame after the last, at the display's pace
2471    /// whatever else comes due meanwhile, else (the first, or after a
2472    /// pause) a frame from now or now.
2473    fn next_frame(&self) -> Instant {
2474        let now = self.clock.now();
2475        self.last_frame
2476            .map_or(now + nsh_core::time::FRAME, |last| {
2477                last + nsh_core::time::FRAME
2478            })
2479            .max(now)
2480    }
2481
2482    /// Runs a display frame of a clock that moves with the display's
2483    /// frames, now.
2484    fn frame(&mut self) {
2485        self.last_frame = Some(self.clock.now());
2486        handle(self.script.as_ref(), &mut self.state, Message::Frame);
2487    }
2488
2489    /// Runs what the handled messages and the time made due, and submits
2490    /// the frame.
2491    fn turn(&mut self) {
2492        let Driver {
2493            state,
2494            script,
2495            sink,
2496            assets,
2497            ..
2498        } = self;
2499        let script = script.as_ref();
2500        if script
2501            .and_then(Script::next_timer)
2502            .is_some_and(|due| due <= nsh_core::time::now())
2503        {
2504            self.last_active = Instant::now();
2505        }
2506        if state
2507            .resize_burst_ends
2508            .is_some_and(|ends| ends <= nsh_core::time::now())
2509        {
2510            state.resize_burst_ends = None;
2511            state.core.set_resizing(false);
2512        }
2513        if state
2514            .window_state
2515            .settles
2516            .is_some_and(|due| due <= nsh_core::time::now())
2517            && let Some(env) = state.window_state.reported
2518        {
2519            state.window_state.settles = None;
2520            state.window_state.shown = env.window_state;
2521            apply_environment(script, state, env);
2522        }
2523        let turn_start = state.trace.then(Instant::now);
2524        state.dispatch_touch_move(script);
2525        if state
2526            .next_mouse_move()
2527            .is_some_and(|due| due <= nsh_core::time::now())
2528        {
2529            state.dispatch_mouse_moves(script);
2530        }
2531        state.dispatch_scroll_events(script);
2532        let hot = std::mem::take(&mut state.hot);
2533        if let Some(script) = script {
2534            for update in hot {
2535                script.hot_update(update, &**sink);
2536            }
2537            script.run_timers(nsh_core::time::now());
2538            script.run_system();
2539        }
2540        state.core.run_component_tasks();
2541        // What JS timers and Rust component tasks took; a Rust component
2542        // renders in the commit.
2543        let tasks = turn_start.map(|s| s.elapsed());
2544        state.load_fonts(script, assets.as_deref(), &**sink);
2545        let batch = state.commit(script);
2546        if let Some(batch) = batch.filter(|_| !self.quitting) {
2547            sink.submit(batch);
2548            if let (Some(start), Some(tasks)) = (turn_start, tasks) {
2549                log::info!(
2550                    target: "nsh::perf",
2551                    "turn: {}µs (timers and tasks {}µs)",
2552                    start.elapsed().as_micros(),
2553                    tasks.as_micros(),
2554                );
2555            }
2556        }
2557        state.run_on_main_thread(&**sink);
2558        if let Some(size) = state.resized.take() {
2559            sink.resized(size);
2560        }
2561        state.report_handled(&**sink);
2562        state.net.pump(script, &mut state.core);
2563        state.load_chunks(script, &**sink);
2564        state.request_frame(script, &**sink);
2565        self.check_stopped();
2566        self.sync_quit_listeners();
2567    }
2568
2569    /// Tells the [`Engine`] whether the app has quit listeners now.
2570    fn sync_quit_listeners(&self) {
2571        self.quit_listeners.store(
2572            self.state.core.has_quit_listeners(),
2573            std::sync::atomic::Ordering::Relaxed,
2574        );
2575    }
2576
2577    /// The engine stops: runs the app's quit listeners and what they wait
2578    /// for, [`QUIT_TIMEOUT`] at most (the dropping [`Engine`] interrupts JS
2579    /// then). Their frames are not submitted; the embedding app's events
2580    /// stay queued behind the shutdown, for the next app.
2581    #[cfg(not(target_arch = "wasm32"))]
2582    fn quit(&mut self, rx: &Receiver<Message>) {
2583        if !self.state.core.has_quit_listeners() {
2584            return;
2585        }
2586        let deadline = Instant::now() + QUIT_TIMEOUT;
2587        self.quitting = true;
2588        self.state.core.start_quit();
2589        let mut kept = Vec::new();
2590        loop {
2591            self.turn();
2592            if !self.state.core.quit_pending() || self.stopped {
2593                break;
2594            }
2595            let wake = self.deadline().map_or(deadline, |at| at.min(deadline));
2596            match rx.recv_deadline(wake) {
2597                Ok(Message::Shutdown) => {}
2598                Ok(message @ Message::HostEvent(..)) => kept.push(message),
2599                Ok(message) => {
2600                    self.handle(message, rx);
2601                }
2602                Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
2603                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => break,
2604            }
2605            if Instant::now() >= deadline {
2606                log::warn!(
2607                    "the app's quit listeners did not finish in {} ms",
2608                    QUIT_TIMEOUT.as_millis()
2609                );
2610                break;
2611            }
2612        }
2613        for message in kept {
2614            let _ = self.state.net.tx.send(message);
2615        }
2616    }
2617
2618    /// When the next idle collection may run: a second after the last, once
2619    /// the engine has been quiet for [`IDLE_GC_QUIET`] (or at the latest
2620    /// [`IDLE_GC_LONGEST`] after the last).
2621    fn next_gc(&self) -> Instant {
2622        let quiet = (self.last_active + IDLE_GC_QUIET).min(self.last_gc + IDLE_GC_LONGEST);
2623        (self.last_gc + IDLE_GC_INTERVAL).max(quiet)
2624    }
2625
2626    /// Collects cycles when the engine has been idle long enough, so
2627    /// released nodes free their views.
2628    fn collect_if_idle(&mut self) {
2629        if let Some(script) = &self.script
2630            && self.state.committed_since_gc
2631            && Instant::now() >= self.next_gc()
2632        {
2633            let start = self.state.trace.then(Instant::now);
2634            script.collect_garbage();
2635            if let Some(start) = start {
2636                log::info!(target: "nsh::perf", "gc: {}µs", start.elapsed().as_micros());
2637            }
2638            // What the app holds, for the performance monitor: read here,
2639            // when the heap was just walked and nothing waits.
2640            if let Some(monitor) = &self.state.perf {
2641                let (js_heap, js_objects) = script.heap_usage();
2642                monitor.set_memory(perf::MemorySample {
2643                    js_heap,
2644                    js_objects,
2645                    nodes: self.state.core.node_count() as u64,
2646                    node_ids: self.state.core.node_id_room() as u64,
2647                });
2648            }
2649            self.last_gc = Instant::now();
2650            self.state.committed_since_gc = false;
2651            if let Some(batch) = self.state.commit(Some(script)) {
2652                self.sink.submit(batch);
2653            }
2654            self.state.run_on_main_thread(&*self.sink);
2655        }
2656    }
2657
2658    fn check_stopped(&mut self) {
2659        if let Some(script) = &self.script
2660            && !self.stopped
2661            && let Some(reason) = script.fatal()
2662        {
2663            self.stopped = true;
2664            script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
2665        }
2666    }
2667}
2668
2669struct ScrollEvent {
2670    x: f32,
2671    y: f32,
2672    content: Size<Points>,
2673    viewport: Size<Points>,
2674    /// The zoom scale.
2675    zoom: f32,
2676    throttle: Duration,
2677    last: Option<Instant>,
2678    /// An offset not reported yet.
2679    pending: bool,
2680}
2681
2682struct State<M: TextEngine> {
2683    core: Core<M>,
2684    /// The design tokens JS has (`token()`): the core's when they were
2685    /// last sent.
2686    js_tokens: Arc<nsh_core::element::Tokens>,
2687    /// What the environment keeps whatever the platform reports
2688    /// ([`EngineConfig::pinned`]).
2689    pinned: EnvironmentPins,
2690    /// The environment given last, before the app's language is applied.
2691    environment: Environment,
2692    /// The platform found no GPU for shader views
2693    /// ([`EngineControl::shaders_unavailable`]).
2694    shaders_unavailable: bool,
2695    /// The language the app shows in whatever the user's (`setLocale`).
2696    app_locale: Option<nsh_core::platform::Locale>,
2697    /// A display frame was requested and has not begun yet.
2698    frame_requested: bool,
2699    ops: Vec<Op>,
2700    /// List render requests not yet sent to JS.
2701    binds: Vec<ListBind>,
2702    /// Events raised by the core (e.g. `onLoadMore`, `onLayout`).
2703    events: Vec<JsEvent>,
2704    trace: bool,
2705    /// Where commit timings go ([`EngineControl::set_perf_monitor`]).
2706    perf: Option<Arc<perf::PerfMonitor>>,
2707    /// The core's share of the wake-up being measured (`layout`, `ops`,
2708    /// `items`; `js` is the rest of the wake-up).
2709    perf_commit: perf::CommitTiming,
2710    committed_since_gc: bool,
2711    /// The embedding app's channel: its URL handler sees the app's URLs
2712    /// first.
2713    host: HostChannel,
2714    /// URLs the app asked to open, taken from the core (a reused buffer).
2715    url_opens: Vec<(u32, String)>,
2716    net: Net,
2717    /// Development updates to apply.
2718    hot: Vec<HotUpdate>,
2719    /// `onScroll` events: the latest offset per scroll view, sent once per
2720    /// frame at most (and not more often than the view's throttle).
2721    scroll_events: FxHashMap<NodeId, ScrollEvent>,
2722    /// Touch moves not delivered yet: those queued in one frame become one.
2723    touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
2724    /// Mouse moves not delivered yet: the latest per view, in the order they
2725    /// came; sent once per [`MOUSE_MOVE_INTERVAL`] at most, and before
2726    /// any other event.
2727    mouse_moves: Vec<(NodeId, EventPayload)>,
2728    /// When `mouse_moves` were last delivered.
2729    mouse_moved: Option<Instant>,
2730    /// [`keep_last_sets`]'s buffer, reused.
2731    sets_seen: FxHashMap<(u8, NodeId), usize>,
2732    /// The viewport size a resize set this turn ([`MountSink::resized`]).
2733    resized: Option<Size<Points>>,
2734    /// A resize before this time continues a burst of them
2735    /// ([`RESIZE_BURST_GAP`]).
2736    resize_burst_ends: Option<Instant>,
2737    /// The window's bounds as the app reads them, held back while the
2738    /// window moves.
2739    window_state: WindowStateReport,
2740    /// Events received ([`EngineControl::dispatch_event`]), and the count
2741    /// last reported ([`MountSink::handled`]).
2742    events_handled: u64,
2743    events_reported: u64,
2744}
2745
2746/// Who made a request: JS (`fetch`), or a Rust component's task
2747/// (`nsh_core::element::fetch`, [`Core::take_fetches`]).
2748#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2749enum Requester {
2750    Js(RequestId),
2751    Task(u32),
2752}
2753
2754/// Requests between the app (JS and Rust components' tasks) and the
2755/// platform's network stack.
2756struct Net {
2757    network: Option<Arc<dyn Network>>,
2758    tx: Sender<Message>,
2759    queue: NetworkQueue,
2760    inflight: FxHashMap<Requester, Inflight>,
2761    /// The tasks' requests taken from the core, and those they gave up
2762    /// (reused buffers).
2763    tasks: Vec<(u32, HttpRequest)>,
2764    abandoned: Vec<u32>,
2765    /// What the app may reach.
2766    access: Arc<nsh_core::access::Access>,
2767    /// Hops started so far (the id of the next).
2768    hops: u64,
2769    /// Where requests of `asset:/` URLs are answered from
2770    /// ([`EngineConfig::assets`]).
2771    assets: Option<Arc<dyn Assets>>,
2772    /// The runtime whose blocking pool reads them (the components'
2773    /// tasks').
2774    #[cfg(not(target_arch = "wasm32"))]
2775    runtime: tokio::runtime::Handle,
2776}
2777
2778/// The task of a request for a bundled file while it is read: the read
2779/// finishes on its own, and a cancelled request drops what it gives.
2780struct AssetTask;
2781
2782impl FetchTask for AssetTask {
2783    fn send(&mut self, _: Vec<u8>) {}
2784    fn finish(&mut self) {}
2785    fn pause(&mut self, _: bool) {}
2786    fn cancel(self: Box<Self>) {}
2787}
2788
2789/// Whether `url` names a bundled file (`asset:/…`, the scheme in any case,
2790/// as URL schemes are).
2791fn is_asset(url: &str) -> bool {
2792    url.get(..6)
2793        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("asset:"))
2794}
2795
2796/// `url` (an `asset:/` URL) as its response answers at it, and as the
2797/// rest of the engine reads it: the scheme in lower case, as URL parsers
2798/// write it (schemes are case-insensitive, and JS's `fetch` parses the URL
2799/// before the engine sees it), without the fragment, which no request
2800/// sends and no response carries.
2801fn asset_response_url(url: &str) -> String {
2802    let rest = url.get(6..).unwrap_or_default();
2803    format!("asset:{}", rest.split('#').next().unwrap_or_default())
2804}
2805
2806/// The bundled file a request reads, by the URL [`asset_response_url`]
2807/// wrote: its path alone, as hosts read it. A query is no part of a file's
2808/// name, so `asset:/a.json?v=2` reads `asset:/a.json` on every host, as a
2809/// web server serves it.
2810fn asset_file(url: &str) -> &str {
2811    url.split('?').next().unwrap_or_default()
2812}
2813
2814/// A request in flight.
2815struct Inflight {
2816    task: Box<dyn FetchTask>,
2817    /// The hop the task is.
2818    hop: u64,
2819    /// Requests whose redirects the engine follows (to check each hop).
2820    followed: Option<access::Followed>,
2821    /// The `asset:/` URL a download of a bundled file answers at
2822    /// ([`asset_response_url`]): a status other than a success fails it, as
2823    /// a file the host does not have does.
2824    asset: Option<String>,
2825}
2826
2827impl Net {
2828    /// Whether no request waits for the network.
2829    fn idle(&self) -> bool {
2830        self.inflight.is_empty()
2831    }
2832
2833    /// Hands what JS and the components' tasks asked of their requests to
2834    /// the network.
2835    fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
2836        let mut abandoned = std::mem::take(&mut self.abandoned);
2837        core.take_fetches(&mut self.tasks, &mut abandoned);
2838        for id in abandoned.drain(..) {
2839            self.cancel(Requester::Task(id));
2840        }
2841        self.abandoned = abandoned;
2842        let mut tasks = std::mem::take(&mut self.tasks);
2843        for (id, request) in tasks.drain(..) {
2844            if let Err(refused) = self.request(Requester::Task(id), request) {
2845                core.fetch_refused(id, refused.message, refused.url);
2846            }
2847        }
2848        self.tasks = tasks;
2849        let Some(script) = script else { return };
2850        script.take_network(&mut self.queue);
2851        for (id, op) in std::mem::take(&mut self.queue.ops) {
2852            let who = Requester::Js(id);
2853            match op {
2854                FetchOp::Start(request) => {
2855                    if let Err(refused) = self.request(who, request) {
2856                        script.fetch_refused(id, &refused.message, &refused.url);
2857                    }
2858                }
2859                FetchOp::Send(chunk) => {
2860                    if let Some(i) = self.inflight.get_mut(&who) {
2861                        i.task.send(chunk);
2862                    }
2863                }
2864                FetchOp::Finish => {
2865                    if let Some(i) = self.inflight.get_mut(&who) {
2866                        i.task.finish();
2867                    }
2868                }
2869                FetchOp::Pause(paused) => {
2870                    if let Some(i) = self.inflight.get_mut(&who) {
2871                        i.task.pause(paused);
2872                    }
2873                }
2874                FetchOp::Cancel => self.cancel(who),
2875            }
2876        }
2877    }
2878
2879    /// Aborts `who`'s request.
2880    fn cancel(&mut self, who: Requester) {
2881        if let Some(i) = self.inflight.remove(&who) {
2882            i.task.cancel();
2883        }
2884    }
2885
2886    /// Makes `who`'s request, if the app may (else why not). Bundled files
2887    /// are the app's own: their requests need no capability.
2888    fn request(&mut self, who: Requester, mut request: HttpRequest) -> Result<(), access::Refused> {
2889        if is_asset(&request.url) {
2890            self.asset(who, request);
2891            return Ok(());
2892        }
2893        if self.access.is_unrestricted() {
2894            self.start(who, request, None);
2895            return Ok(());
2896        }
2897        // The request goes out with the URL the check granted: Rust's and
2898        // `registerFont`'s URLs come as written, `fetch`'s already parsed.
2899        match self.access.http_url(&request.method, &request.url) {
2900            Some(url) => request.url = url.into_owned(),
2901            None => return Err(access::refused(&request.method, &request.url)),
2902        }
2903        if request.follow_redirects {
2904            let hop = access::hop(&request);
2905            let followed = access::Followed { request, hops: 0 };
2906            self.start(who, hop, Some(followed));
2907        } else {
2908            self.start(who, request, None);
2909        }
2910        Ok(())
2911    }
2912
2913    /// Hands one request (or redirect hop) to the network.
2914    fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
2915        self.hops += 1;
2916        let hop = self.hops;
2917        let Some(network) = &self.network else {
2918            let failed = FetchEvent::Failed("this host has no network stack".to_owned());
2919            let _ = self.tx.send(Message::Fetch(id, hop, failed));
2920            return;
2921        };
2922        let tx = self.tx.clone();
2923        let events: FetchEvents = Box::new(move |event| {
2924            let _ = tx.send(Message::Fetch(id, hop, event));
2925        });
2926        let task = network.fetch(request, events);
2927        self.inflight.insert(
2928            id,
2929            Inflight {
2930                task,
2931                hop,
2932                followed,
2933                asset: None,
2934            },
2935        );
2936    }
2937
2938    /// Answers `who`'s request of a bundled file (an `asset:/` URL) from
2939    /// the host's assets: read on the runtime's blocking pool, which reports
2940    /// with [`Message::AssetRead`] (in WebAssembly, which has no threads,
2941    /// here).
2942    fn asset(&mut self, who: Requester, mut request: HttpRequest) {
2943        request.url = asset_response_url(&request.url);
2944        let file = asset_file(&request.url).to_owned();
2945        self.hops += 1;
2946        let hop = self.hops;
2947        self.inflight.insert(
2948            who,
2949            Inflight {
2950                task: Box::new(AssetTask),
2951                hop,
2952                followed: None,
2953                asset: None,
2954            },
2955        );
2956        // Failed here, before any host reads the file or serves it
2957        // ([`Assets::url`]): a request no host may answer reaches none.
2958        let refused = if !nsh_core::access::is_inside_assets(&file) {
2959            Some(format!(
2960                "{}: bundled files are named by a path inside the app's files",
2961                request.url
2962            ))
2963        } else if !matches!(request.method.as_str(), "GET" | "HEAD") {
2964            Some(format!(
2965                "{} {}: bundled files are read with GET",
2966                request.method, request.url
2967            ))
2968        } else {
2969            None
2970        };
2971        if let Some(refused) = refused {
2972            let _ = self
2973                .tx
2974                .send(Message::Fetch(who, hop, FetchEvent::Failed(refused)));
2975            return;
2976        }
2977        let Some(assets) = &self.assets else {
2978            let failed = Err("this host cannot load assets".to_owned());
2979            self.asset_read(who, hop, request, failed);
2980            return;
2981        };
2982        #[cfg(not(target_arch = "wasm32"))]
2983        {
2984            let assets = assets.clone();
2985            let tx = self.tx.clone();
2986            // The read reports itself; nothing awaits its handle.
2987            drop(self.runtime.spawn_blocking(move || {
2988                let bytes = assets.read(&file);
2989                let _ = tx.send(Message::AssetRead(who, hop, request, bytes));
2990            }));
2991        }
2992        #[cfg(target_arch = "wasm32")]
2993        {
2994            let bytes = assets.read(&file);
2995            self.asset_read(who, hop, request, bytes);
2996        }
2997    }
2998
2999    /// Hop `hop` of `who`'s request of a bundled file read it: its response,
3000    /// or, when the host has no copy but serves the file at a URL
3001    /// ([`Assets::url`]), the download of it. Only requests [`Net::asset`]
3002    /// let through come here. Dropped when the request was cancelled
3003    /// meanwhile.
3004    fn asset_read(
3005        &mut self,
3006        who: Requester,
3007        hop: u64,
3008        request: HttpRequest,
3009        read: Result<Vec<u8>, String>,
3010    ) {
3011        if self.inflight.get(&who).is_none_or(|i| i.hop != hop) {
3012            return;
3013        }
3014        let events = match read {
3015            Ok(bytes) => {
3016                let head = HttpHead {
3017                    status: 200,
3018                    status_text: "OK".to_owned(),
3019                    headers: vec![
3020                        ("content-length".to_owned(), bytes.len().to_string()),
3021                        (
3022                            "content-type".to_owned(),
3023                            content_type(asset_file(&request.url)).to_owned(),
3024                        ),
3025                    ],
3026                    url: request.url.clone(),
3027                    ..HttpHead::default()
3028                };
3029                let mut events = vec![FetchEvent::Head(head)];
3030                if request.method == "GET" && !bytes.is_empty() {
3031                    events.push(FetchEvent::Data(bytes));
3032                }
3033                events.push(FetchEvent::End);
3034                events
3035            }
3036            Err(error) => {
3037                match (self.assets.as_ref()).and_then(|a| a.url(asset_file(&request.url))) {
3038                    Some(url) => {
3039                        self.inflight.remove(&who);
3040                        let uri = request.url.clone();
3041                        self.start(who, HttpRequest { url, ..request }, None);
3042                        if let Some(download) = self.inflight.get_mut(&who) {
3043                            download.asset = Some(uri);
3044                        }
3045                        return;
3046                    }
3047                    None => vec![FetchEvent::Failed(error)],
3048                }
3049            }
3050        };
3051        for event in events {
3052            let _ = self.tx.send(Message::Fetch(who, hop, event));
3053        }
3054    }
3055
3056    /// An event of hop `hop` of request `id`: what JS is told, if anything
3057    /// (`None` for events of hops left behind, and redirects the engine
3058    /// follows; `Err` for a redirect the app may not follow).
3059    fn event(
3060        &mut self,
3061        id: Requester,
3062        hop: u64,
3063        event: FetchEvent,
3064    ) -> Option<Result<FetchEvent, access::Refused>> {
3065        if self.network.is_none() {
3066            return Some(Ok(event));
3067        }
3068        let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
3069        match event {
3070            FetchEvent::Head(mut head) => {
3071                let missing = (inflight.asset.as_ref())
3072                    .filter(|_| !(200..300).contains(&head.status))
3073                    .map(|uri| format!("{uri}: HTTP {}", head.status));
3074                if let Some(missing) = missing {
3075                    if let Some(i) = self.inflight.remove(&id) {
3076                        i.task.cancel();
3077                    }
3078                    return Some(Ok(FetchEvent::Failed(missing)));
3079                }
3080                // A downloaded bundled file answers as one read from the
3081                // app's files: its `asset:/` URL, and a type even where the
3082                // server gave none.
3083                if let Some(uri) = &inflight.asset {
3084                    head.url = uri.clone();
3085                    head.redirected = false;
3086                    if !head
3087                        .headers
3088                        .iter()
3089                        .any(|(name, _)| name.eq_ignore_ascii_case("content-type"))
3090                    {
3091                        let file_type = content_type(asset_file(uri)).to_owned();
3092                        head.headers.push(("content-type".to_owned(), file_type));
3093                    }
3094                }
3095                let Some(followed) = &mut inflight.followed else {
3096                    return Some(Ok(FetchEvent::Head(head)));
3097                };
3098                match access::next(&self.access, followed, head) {
3099                    access::Next::Done(head) => Some(Ok(FetchEvent::Head(head))),
3100                    access::Next::Fail(message) => {
3101                        if let Some(i) = self.inflight.remove(&id) {
3102                            i.task.cancel();
3103                        }
3104                        Some(Ok(FetchEvent::Failed(message)))
3105                    }
3106                    access::Next::Refused(refused) => {
3107                        if let Some(i) = self.inflight.remove(&id) {
3108                            i.task.cancel();
3109                        }
3110                        Some(Err(refused))
3111                    }
3112                    access::Next::Hop(request) => {
3113                        let i = self.inflight.remove(&id)?;
3114                        let followed = i.followed;
3115                        i.task.cancel();
3116                        self.start(id, request, followed);
3117                        None
3118                    }
3119                }
3120            }
3121            FetchEvent::End | FetchEvent::Failed(_) => {
3122                self.inflight.remove(&id);
3123                Some(Ok(event))
3124            }
3125            event => Some(Ok(event)),
3126        }
3127    }
3128}
3129
3130impl<M: TextEngine> State<M> {
3131    /// Ends the measured wake-up that began at `started`
3132    /// ([`EngineControl::set_perf_monitor`]).
3133    fn record_perf(&mut self, started: Option<Instant>) {
3134        let (Some(started), Some(monitor)) = (started, &self.perf) else {
3135            return;
3136        };
3137        let busy = started.elapsed();
3138        monitor.record_busy(busy);
3139        let mut commit = std::mem::take(&mut self.perf_commit);
3140        if commit.ops > 0 || commit.items > 0 {
3141            commit.js = busy.saturating_sub(commit.layout);
3142            monitor.record_commit(commit);
3143        }
3144    }
3145
3146    /// Sends the pending touch move.
3147    fn dispatch_touch_move(&mut self, script: Option<&Script>) {
3148        if let Some((id, touch)) = self.touch_move.take()
3149            && let Some(script) = script
3150        {
3151            script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
3152        }
3153    }
3154
3155    /// When the pending `onMouseMove`s are due.
3156    fn next_mouse_move(&self) -> Option<Instant> {
3157        if self.mouse_moves.is_empty() {
3158            return None;
3159        }
3160        Some(
3161            self.mouse_moved
3162                .map_or_else(nsh_core::time::now, |t| t + MOUSE_MOVE_INTERVAL),
3163        )
3164    }
3165
3166    /// Delivers the pending `onMouseMove`s: to the Rust components whose
3167    /// parts they are on, the others to JS.
3168    fn dispatch_mouse_moves(&mut self, script: Option<&Script>) {
3169        if self.mouse_moves.is_empty() {
3170            return;
3171        }
3172        self.mouse_moved = Some(nsh_core::time::now());
3173        for (id, payload) in std::mem::take(&mut self.mouse_moves) {
3174            if self
3175                .core
3176                .component_event(id, EventKind::MouseMove, &payload)
3177            {
3178                continue;
3179            }
3180            if let Some(script) = script {
3181                script.dispatch_event(id, EventKind::MouseMove, &payload);
3182            }
3183        }
3184    }
3185
3186    /// When a throttled `onScroll` is due.
3187    fn next_scroll_event(&self) -> Option<Instant> {
3188        self.scroll_events
3189            .values()
3190            .filter(|e| e.pending)
3191            .filter_map(|e| e.last.map(|t| t + e.throttle))
3192            .min()
3193    }
3194
3195    /// Sends the `onScroll` events that are due.
3196    fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
3197        if self.scroll_events.is_empty() {
3198            return;
3199        }
3200        let now = nsh_core::time::now();
3201        // Views that stopped listening (or are gone).
3202        let core = &self.core;
3203        self.scroll_events
3204            .retain(|&id, _| core.scroll_listener(id).is_some());
3205        for (&id, e) in &mut self.scroll_events {
3206            if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
3207                continue;
3208            }
3209            e.pending = false;
3210            e.last = Some(now);
3211            let n = |v: f32| PayloadValue::Number(v as f64);
3212            let payload = EventPayload::Map(vec![
3213                (
3214                    "offset",
3215                    PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
3216                ),
3217                ("contentSize", PayloadValue::Size(e.content)),
3218                ("size", PayloadValue::Size(e.viewport)),
3219                ("zoomScale", n(e.zoom)),
3220            ]);
3221            // A Rust component's scroll view is the component's.
3222            if !self.core.component_event(id, EventKind::Scroll, &payload)
3223                && let Some(script) = script
3224            {
3225                script.dispatch_event(id, EventKind::Scroll, &payload);
3226            }
3227        }
3228    }
3229
3230    /// Asks the platform for the chunks JS imports and does not have.
3231    fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
3232        let Some(script) = script else { return };
3233        let mut ids = Vec::new();
3234        script.take_chunk_requests(&mut ids);
3235        for id in ids {
3236            if !sink.load_chunk(&id) {
3237                let message = "this host does not load chunks (the app was built split)".to_owned();
3238                let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
3239            }
3240        }
3241    }
3242
3243    /// Tells the platform how many events were handled, once the commit
3244    /// of what they changed is submitted.
3245    fn report_handled(&mut self, sink: &dyn MountSink) {
3246        if self.events_handled != self.events_reported {
3247            self.events_reported = self.events_handled;
3248            sink.handled(self.events_handled);
3249        }
3250    }
3251
3252    /// Asks the platform for a frame when JS or a component's task waits
3253    /// for one.
3254    fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
3255        if !self.frame_requested
3256            && (script.is_some_and(Script::wants_frame)
3257                || self.core.wants_frame()
3258                || self.core.has_paced_mounts()
3259                || (script.is_some() && self.core.has_paced_list_binds()))
3260        {
3261            self.frame_requested = true;
3262            sink.request_frame();
3263        }
3264    }
3265
3266    /// Hands the sink the functions the app asked to run on the main thread
3267    /// this turn, after the turn's batch.
3268    fn run_on_main_thread(&mut self, sink: &dyn MountSink) {
3269        for task in self.core.take_main_thread_tasks() {
3270            sink.run_on_main_thread(task);
3271        }
3272    }
3273
3274    /// Registers fonts imported by JS. Blocking: text using them must not be
3275    /// measured with a fallback font first.
3276    fn load_fonts(
3277        &mut self,
3278        script: Option<&Script>,
3279        assets: Option<&dyn Assets>,
3280        sink: &dyn MountSink,
3281    ) {
3282        let Some(script) = script else { return };
3283        let mut fonts = Vec::new();
3284        script.take_fonts(&mut fonts);
3285        for uri in fonts {
3286            let result = match assets {
3287                Some(assets) => assets.read(&uri),
3288                None => Err("this host cannot load assets".to_owned()),
3289            }
3290            .and_then(|data| self.core.register_font(&data));
3291            if let Err(err) = result {
3292                script.report(
3293                    sink,
3294                    AppErrorKind::Asset,
3295                    "font failed",
3296                    &format!("{uri}: {err}"),
3297                );
3298            }
3299        }
3300    }
3301
3302    /// Produces one frame: applies JS ops, lays out, and lets lists pull
3303    /// the items they need, merging everything into a single batch.
3304    /// Hands the URLs the app asked to open to the embedding app's URL
3305    /// handler, or, without one, to the platform ([`nsh_core::open_url`]);
3306    /// true when the platform has one to open (the core's commit sends it).
3307    fn open_urls(&mut self) -> bool {
3308        self.core.take_url_opens(&mut self.url_opens);
3309        let mut platform = false;
3310        for (id, url) in self.url_opens.drain(..) {
3311            if self.host.open_url(id, url.clone(), &self.net.tx).is_none() {
3312                self.core.open_url_on_platform(id, url);
3313                platform = true;
3314            }
3315        }
3316        platform
3317    }
3318
3319    fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
3320        let start = Instant::now();
3321        let mut merged: Option<MountBatch> = None;
3322        let mut commits = 0;
3323        let mut op_count = 0;
3324        let mut js = std::time::Duration::ZERO;
3325        // The overscan bound this turn ([`PACED_BIND_OPS`]).
3326        let mut paced = PacedBinds::default();
3327        // The views made this turn share one budget (`nsh_core`'s `pace.rs`).
3328        self.core.begin_mount_turn();
3329        for _ in 0..MAX_LIST_ROUNDS {
3330            // Requests from the previous round (or frame) first.
3331            let js_start = Instant::now();
3332            // Without JS, lists bind nowhere (Rust components' lists bind in
3333            // the core).
3334            let binds = self.binds.drain(..);
3335            if let Some(script) = script {
3336                // What JS queued before this round (a timer, a handler) may
3337                // change a list's items, and the core works out the overscan
3338                // left to bind from the items it has: it applies those ops
3339                // first, and the overscan waits for the next round, or a
3340                // cell would be bound to an item that is gone.
3341                script.take_ops(&mut self.ops);
3342                let unapplied = !self.ops.is_empty();
3343                for bind in binds {
3344                    script.bind_list(bind.list, &bind.binds);
3345                }
3346                script.take_ops(&mut self.ops);
3347                let mut binds = Vec::new();
3348                while !unapplied && paced.left() && self.core.has_paced_list_binds() {
3349                    let start = Instant::now();
3350                    let ops = self.ops.len();
3351                    self.core.take_paced_list_binds(1, &mut binds);
3352                    for bind in binds.drain(..) {
3353                        paced.cells += bind.binds.len();
3354                        script.bind_list(bind.list, &bind.binds);
3355                    }
3356                    script.take_ops(&mut self.ops);
3357                    paced.ops += self.ops.len() - ops;
3358                    paced.time += start.elapsed();
3359                }
3360            } else {
3361                drop(binds);
3362            }
3363            // The JS calls Rust queued (callbacks' posts), in order, before
3364            // the events: a task's posts come before its result.
3365            if let Some(script) = script {
3366                script.run_posted();
3367            }
3368            // The core's events (layouts, ends reached, ...) on a Rust
3369            // component's nodes are the component's; the rest are JS's, in
3370            // order with Rust components' events and calls' results.
3371            for event in self.events.drain(..) {
3372                match event {
3373                    JsEvent::Event(id, event, payload) => {
3374                        if !self.core.component_event(id, event, &payload)
3375                            && let Some(script) = script
3376                        {
3377                            script.dispatch_event(id, event, &payload);
3378                        }
3379                    }
3380                    JsEvent::LayoutListener {
3381                        host,
3382                        id,
3383                        listener,
3384                        frame,
3385                    } => {
3386                        self.core.component_layout(host, id, &listener, frame);
3387                    }
3388                    // Without JS nothing waits for them.
3389                    other => {
3390                        if let Some(script) = script {
3391                            script.deliver(other);
3392                        }
3393                    }
3394                }
3395            }
3396            if let Some(script) = script {
3397                script.take_ops(&mut self.ops);
3398            }
3399            js += js_start.elapsed();
3400            op_count += self.ops.len();
3401            // A stop drops the rest of the ops, releasing what they hold
3402            // for Rust classes.
3403            let mut ops = self.ops.drain(..);
3404            while let Some(op) = ops.next() {
3405                match self.core.apply(op) {
3406                    Ok(()) => {}
3407                    Err(err) if err.is_fatal() => {
3408                        self.core.discard_ops(ops.by_ref());
3409                        let Some(script) = script else { break };
3410                        script.stop(match err {
3411                            ApplyError::TooManyNodes(max) => {
3412                                format!("the app created more than {max} nodes and was stopped")
3413                            }
3414                            other => {
3415                                format!("the app sent an invalid op ({other:?}) and was stopped")
3416                            }
3417                        });
3418                        break;
3419                    }
3420                    Err(err) => log::error!("invalid op: {err:?}"),
3421                }
3422            }
3423            drop(ops);
3424            release_spare_ops(&mut self.ops);
3425            if let Some(batch) = self.core.commit() {
3426                commits += 1;
3427                match &mut merged {
3428                    Some(m) => extend_frame(&mut m.items, batch.items),
3429                    None => merged = Some(batch),
3430                }
3431            }
3432            self.core.take_list_binds(&mut self.binds);
3433            self.core.take_events(&mut self.events);
3434            // URLs the platform opens go out in another round.
3435            let urls = self.open_urls();
3436            // Posts the ops queued (in program order) run in another round.
3437            let posted = script.is_some_and(Script::has_posted);
3438            // New tokens (the app's theme, the embedding app's) reach what
3439            // read them in JS, whose ops come in another round.
3440            let retheme = match script {
3441                Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
3442                    self.js_tokens = self.core.tokens().clone();
3443                    script.set_tokens(self.js_tokens.clone());
3444                    true
3445                }
3446                _ => false,
3447            };
3448            // A language the app asked for reaches the core and JS, whose
3449            // views follow it in another round.
3450            let relocale = match self.core.take_locale_request() {
3451                Some(locale) => {
3452                    self.app_locale = locale;
3453                    apply_environment(script, self, self.environment);
3454                    true
3455                }
3456                None => false,
3457            };
3458            let more_paced = script.is_some() && paced.left() && self.core.has_paced_list_binds();
3459            // What waited for the app's answer to the events just taken runs
3460            // in the next round, once JS has handled them, and shows in this
3461            // batch.
3462            let answers = self.core.has_due_answers();
3463            if self.binds.is_empty()
3464                && self.events.is_empty()
3465                && !posted
3466                && !retheme
3467                && !relocale
3468                && !more_paced
3469                && !urls
3470                && !answers
3471            {
3472                break;
3473            }
3474        }
3475        if commits > 1
3476            && let Some(batch) = &mut merged
3477        {
3478            keep_last_sets(&mut batch.items, &mut self.sets_seen);
3479        }
3480        self.committed_since_gc |= op_count > 0;
3481        if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
3482            let c = &mut self.perf_commit;
3483            c.layout += start.elapsed().saturating_sub(js);
3484            c.ops += op_count as u32;
3485            c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
3486        }
3487        if self.trace && (op_count > 0 || merged.is_some()) {
3488            log::info!(
3489                target: "nsh::perf",
3490                "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
3491                start.elapsed().as_micros(),
3492                js.as_micros(),
3493                merged.as_ref().map_or(0, |b| b.items.len()),
3494                self.core.node_count(),
3495            );
3496        }
3497        merged
3498    }
3499}
3500
3501fn insets(env: &Environment) -> EdgeInsets {
3502    env.safe_area
3503}
3504
3505/// What Rust components read from the environment.
3506fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::element::Environment {
3507    nsh_core::element::Environment {
3508        window,
3509        safe_area: insets(env),
3510        title_bar: env.title_bar,
3511        window_state: env.window_state,
3512        keyboard_height: env.keyboard_height,
3513        keyboard_duration: env.keyboard_duration,
3514        dark: env.color_scheme == ColorScheme::Dark,
3515        font_scale: env.font_scale,
3516        reduce_motion: env.reduce_motion,
3517        screen_reader: env.screen_reader,
3518        rtl: env.rtl,
3519        pixel_ratio: env.pixel_ratio,
3520        os: env.os,
3521        platform: env.platform,
3522        os_version: env.os_version,
3523        idiom: env.idiom,
3524        locale: env.locale,
3525        locale_settings: env.locale_settings,
3526        apple_keyboard: env.apple_keyboard,
3527        ctrl_for_command: env.ctrl_for_command,
3528        host: env.host,
3529        lifecycle: env.lifecycle,
3530        screen_color: env.screen_color,
3531        file_requests: env.file_requests,
3532        speech: env.speech,
3533        notifications: env.notifications,
3534        audio: env.audio,
3535        cell: env.cell,
3536        web_input: env.web_input,
3537        web_evaluate: env.web_evaluate,
3538        web_views: env.web_views,
3539        shaders: env.shaders,
3540    }
3541}
3542
3543/// `Environment::shaders` as the app sees it: the platform's, `false` on a
3544/// grid surface (a terminal's Cells) and once the platform or this process
3545/// found no GPU (`unavailable`: [`EngineControl::shaders_unavailable`]).
3546fn drawn_shaders(env: &mut Environment, unavailable: bool) {
3547    env.shaders &= env.cell.is_none() && !unavailable && !shader::no_gpu();
3548}
3549
3550/// What class variants read from the environment.
3551fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
3552    nsh_core::tailwind::ClassEnvironment {
3553        dark: env.color_scheme == ColorScheme::Dark,
3554        platform: if env.os == Os::Web {
3555            nsh_core::tailwind::Platform::Web
3556        } else if cfg!(target_os = "android") {
3557            nsh_core::tailwind::Platform::Android
3558        } else {
3559            nsh_core::tailwind::Platform::Ios
3560        },
3561        reduce_motion: env.reduce_motion,
3562        pointer: if env.desktop() {
3563            nsh_core::tailwind::Pointer::Fine
3564        } else {
3565            nsh_core::tailwind::Pointer::Coarse
3566        },
3567        terminal: env.idiom == Idiom::Terminal,
3568    }
3569}
3570
3571/// How long the window stays where it is before a move or a resize
3572/// reaches the app ([`WindowStateReport`]).
3573const WINDOW_SETTLE: Duration = Duration::from_millis(150);
3574
3575/// The window's bounds the app reads: a move or a resize reaches it once
3576/// the window has stayed for [`WINDOW_SETTLE`] (one report at the end of a
3577/// drag, not one per point), a change of mode, display or being minimized
3578/// or hidden at once (with the bounds of then).
3579#[derive(Default)]
3580struct WindowStateReport {
3581    /// What the app reads.
3582    shown: Option<nsh_core::desktop::WindowState>,
3583    /// The platform's latest environment while a move settles.
3584    reported: Option<Environment>,
3585    /// When it has settled.
3586    settles: Option<Instant>,
3587}
3588
3589impl WindowStateReport {
3590    /// The environment the app gets of `env`, the platform's at `now`: its
3591    /// window state held back while it moves.
3592    fn report(&mut self, mut env: Environment, now: Instant) -> Environment {
3593        let next = env.window_state;
3594        let moving = match (&self.shown, &next) {
3595            (Some(shown), Some(next)) => shown != next && moved_only(shown, next),
3596            _ => false,
3597        };
3598        if moving {
3599            // The window moved again (not some other part of the
3600            // environment): it settles from now.
3601            let moved = self.reported.map(|r| r.window_state) != Some(next);
3602            if moved || self.settles.is_none() {
3603                self.settles = Some(now + WINDOW_SETTLE);
3604            }
3605            self.reported = Some(env);
3606            env.window_state = self.shown;
3607        } else {
3608            self.reported = None;
3609            self.settles = None;
3610            self.shown = next;
3611        }
3612        env
3613    }
3614}
3615
3616/// Whether `next` differs from `shown` by where the window is or its size
3617/// alone (a move or a resize, which settles before it is reported), not by
3618/// its mode, display, focus, scale or being minimized or visible.
3619fn moved_only(
3620    shown: &nsh_core::desktop::WindowState,
3621    next: &nsh_core::desktop::WindowState,
3622) -> bool {
3623    shown.mode == next.mode
3624        && shown.placement.mode == next.placement.mode
3625        && shown.minimized == next.minimized
3626        && shown.visible == next.visible
3627        && shown.focused == next.focused
3628        && shown.display == next.display
3629        && shown.scale_factor == next.scale_factor
3630}
3631
3632/// Gives the core and JS the environment `env`.
3633fn apply_environment<M: TextEngine>(
3634    script: Option<&Script>,
3635    state: &mut State<M>,
3636    env: Environment,
3637) {
3638    state.environment = env;
3639    let mut env = env;
3640    // The app's language (`set_locale`) over the platform's, as an
3641    // embedding app's own is.
3642    if let Some(locale) = state.app_locale {
3643        env.locale = locale;
3644        env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
3645    }
3646    state.core.set_font_scale(env.font_scale);
3647    state.core.set_class_environment(class_environment(&env));
3648    state.core.set_safe_area(insets(&env));
3649    let window = env.window;
3650    state.core.set_environment(ui_environment(&env, window));
3651    if let Some(script) = script {
3652        script.set_environment(&env);
3653    }
3654}
3655
3656/// Returns false on shutdown.
3657fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
3658    match message {
3659        Message::Event(id, event, mut payload) => {
3660            state.events_handled += 1;
3661            if state.trace {
3662                log::info!(target: "nsh::perf", "event {event:?} on view {id}");
3663            }
3664            // Mouse moves wait for the frame, the latest per view; any other
3665            // event comes after the moves before it (a view hears where the
3666            // mouse went before it hears it leave). A drag on the desktops
3667            // also sends a touch move with each mouse move: that is the same
3668            // motion, not an event after it.
3669            if event == EventKind::MouseMove {
3670                match state.mouse_moves.iter_mut().find(|(v, _)| *v == id) {
3671                    Some((_, pending)) => *pending = payload,
3672                    None => state.mouse_moves.push((id, payload)),
3673                }
3674                return true;
3675            }
3676            if !matches!(&payload, EventPayload::Touch(t) if t.phase == nsh_core::TouchPhase::Move)
3677            {
3678                state.dispatch_mouse_moves(script);
3679            }
3680            // The core tracks input text for layout and to recognize stale
3681            // values (from JS and from Rust components alike).
3682            if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
3683                state.core.input_changed(id, text, *count);
3684            }
3685            // The platform knows the caret in the input, the core where
3686            // the input is.
3687            if event == EventKind::CaretMove {
3688                state.core.locate_caret(id, &mut payload);
3689            }
3690            if event == EventKind::SelectionChange {
3691                state.core.locate_selection(id, &mut payload);
3692            }
3693            if event == EventKind::Paste {
3694                payload = payload.into_paste();
3695            }
3696            // A secondary click goes down as a press does: the overlays it
3697            // is outside of hear `onPressOutside` first, then the view its
3698            // `onContextMenu`, so a context menu open on the view closes
3699            // before the view asks for one again where the pointer is.
3700            if let EventPayload::ContextMenu(menu) = &payload {
3701                for (overlay, pressed) in state.core.context_menu_presses_outside(id, menu) {
3702                    if !state
3703                        .core
3704                        .component_event(overlay, EventKind::PressOutside, &pressed)
3705                        && let Some(script) = script
3706                    {
3707                        script.dispatch_event(overlay, EventKind::PressOutside, &pressed);
3708                    }
3709                }
3710            }
3711            // Events on a Rust component's parts are the component's.
3712            if state.core.component_event(id, event, &payload) {
3713                return true;
3714            }
3715            if let EventPayload::Touch(touch) = payload {
3716                if touch.phase == nsh_core::TouchPhase::Move {
3717                    match &mut state.touch_move {
3718                        Some((_, pending)) => pending.merge_move(*touch),
3719                        None => state.touch_move = Some((id, touch)),
3720                    }
3721                    return true;
3722                }
3723                // Moves before a start, end or cancel go first.
3724                state.dispatch_touch_move(script);
3725                if let Some(script) = script {
3726                    script.dispatch_event(id, event, &EventPayload::Touch(touch));
3727                }
3728                return true;
3729            }
3730            let Some(script) = script else { return true };
3731            let start = state.trace.then(Instant::now);
3732            script.dispatch_event(id, event, &payload);
3733            if let Some(start) = start {
3734                // The handler, its microtasks and the decode of what it
3735                // committed.
3736                log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
3737            }
3738        }
3739        Message::Scroll(id, offset, applied) => {
3740            state.core.set_scroll_offset(id, offset, applied);
3741            let (x, y) = (offset.x.0, offset.y.0);
3742            if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
3743                let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
3744                    x,
3745                    y,
3746                    content,
3747                    viewport,
3748                    zoom,
3749                    throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
3750                    last: None,
3751                    pending: true,
3752                });
3753                (event.x, event.y, event.content, event.viewport, event.zoom) =
3754                    (x, y, content, viewport, zoom);
3755                event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
3756                event.pending = true;
3757            }
3758        }
3759        Message::Kept(nodes) => state.core.set_kept(&nodes),
3760        Message::ContentCulling(enabled) => {
3761            state.core.set_content_culling(enabled);
3762            if let Some(script) = script {
3763                script.set_lazy_rows(enabled);
3764            }
3765        }
3766        Message::InputScroll(id, offset, content, viewport) => {
3767            state.core.set_input_scroll(id, offset, content, viewport);
3768        }
3769        Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
3770        Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
3771        Message::AnimationsFinished(mut finished) => {
3772            // The components' animations end in the core, JS's in JS.
3773            state.core.animations_finished(&mut finished);
3774            if let Some(script) = script {
3775                script.animations_finished(&finished);
3776            }
3777        }
3778        Message::Resize(size) => {
3779            // The next within a burst's gap: a window being dragged. A manual
3780            // clock wakes nothing to end one, and a test wants its layout whole.
3781            if !nsh_core::time::manual() {
3782                let now = nsh_core::time::now();
3783                if state.resize_burst_ends.is_some_and(|ends| now < ends) {
3784                    state.core.set_resizing(true);
3785                }
3786                state.resize_burst_ends = Some(now + RESIZE_BURST_GAP);
3787            }
3788            state.core.set_viewport(size);
3789            state.resized = Some(size);
3790        }
3791        Message::Wake => {}
3792        Message::Environment(mut env) => {
3793            state.pinned.apply(&mut env);
3794            drawn_shaders(&mut env, state.shaders_unavailable);
3795            let env = state.window_state.report(*env, nsh_core::time::now());
3796            apply_environment(script, state, env);
3797        }
3798        Message::ShadersUnavailable => {
3799            state.shaders_unavailable = true;
3800            if state.environment.shaders {
3801                let env = Environment {
3802                    shaders: false,
3803                    ..state.environment
3804                };
3805                apply_environment(script, state, env);
3806            }
3807        }
3808        Message::Displays(displays) => {
3809            state.core.set_displays(displays.clone());
3810            if let Some(script) = script {
3811                script.set_displays(&displays);
3812            }
3813        }
3814        Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
3815        Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
3816        Message::Frame => {
3817            state.frame_requested = false;
3818            state.core.run_frame(nsh_core::time::now());
3819            if let Some(script) = script {
3820                script.run_frame();
3821            }
3822        }
3823        Message::States(id, states) => state.core.set_states(id, states),
3824        Message::Modality(modality) => state.core.set_input_modality(modality),
3825        Message::FontsChanged => state.core.fonts_changed(),
3826        Message::Remount => state.core.remount(),
3827        Message::Fetch(who, hop, event) => match (who, state.net.event(who, hop, event)) {
3828            (_, None) => {}
3829            (Requester::Js(id), Some(event)) => {
3830                if let Some(script) = script {
3831                    match event {
3832                        Ok(event) => script.fetch_event(id, event),
3833                        Err(refused) => script.fetch_refused(id, &refused.message, &refused.url),
3834                    }
3835                }
3836            }
3837            (Requester::Task(id), Some(Ok(event))) => {
3838                if !state.core.fetch_event(id, event) {
3839                    state.net.cancel(who);
3840                }
3841            }
3842            // A redirect the app may not follow: its hop is cancelled
3843            // already (`Net::event`).
3844            (Requester::Task(id), Some(Err(refused))) => {
3845                state.core.fetch_refused(id, refused.message, refused.url)
3846            }
3847        },
3848        Message::AssetRead(who, hop, request, read) => {
3849            state.net.asset_read(who, hop, request, read)
3850        }
3851        Message::Hot(update) => state.hot.push(update),
3852        Message::Chunk(chunk) => {
3853            if let Some(script) = script {
3854                script.chunk(chunk);
3855            }
3856        }
3857        Message::Perf(monitor) => {
3858            state.core.set_perf_monitor(monitor.is_some());
3859            if let Some(script) = script {
3860                script.set_fps_enabled(monitor.is_some());
3861            }
3862            state.perf = monitor;
3863            state.perf_commit = perf::CommitTiming::default();
3864        }
3865        Message::Tokens(tokens) => {
3866            state.core.set_host_tokens(tokens.map(|t| *t));
3867            if let Some(script) = script {
3868                script.set_theme_tokens(state.core.theme_tokens());
3869            }
3870        }
3871        Message::HostFont(data) => {
3872            if let Err(err) = state.core.register_font(&data) {
3873                log::error!("font failed: {err}");
3874            }
3875        }
3876        // A Rust app has no `nsh/host`: what the host sends it goes.
3877        Message::HostEvent(name, data) => {
3878            if let Some(script) = script {
3879                script.host_event(&name, data);
3880            }
3881        }
3882        Message::HostReply(id, result) => {
3883            if let Some(script) = script {
3884                script.host_reply(id, result);
3885            }
3886        }
3887        Message::UrlHandled { id, url, handled } => {
3888            if handled {
3889                state.core.answer_open_url(id, true);
3890            } else {
3891                state.core.open_url_on_platform(id, url);
3892            }
3893        }
3894        // The driver handles it ([`Driver::handle`]), and keeps the ones
3895        // sent before it started for after the first frame.
3896        Message::Advance(..) | Message::Flush(..) => unreachable!("the driver moves the clock"),
3897        Message::Shutdown => return false,
3898    }
3899    true
3900}
3901
3902/// What a turn spent binding overscan cells.
3903#[derive(Default)]
3904struct PacedBinds {
3905    cells: usize,
3906    ops: usize,
3907    time: std::time::Duration,
3908}
3909
3910impl PacedBinds {
3911    /// Whether the turn may bind another: at least one, then within the
3912    /// budget.
3913    fn left(&self) -> bool {
3914        self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
3915    }
3916}
3917
3918/// Appends a commit's items to the frame's. A scroll view's content size
3919/// that the frame already sets is updated to the later size (unless the
3920/// view scrolls in between): a row relaid over two commits must not send
3921/// the platform a transient size, which clamps the offset before the
3922/// content grows back (a list jumping when a row expands).
3923fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
3924    use nsh_core::MountItem;
3925    let start = frame.len();
3926    frame.extend(items);
3927    for k in start..frame.len() {
3928        let MountItem::ScrollContent { id, size } = frame[k] else {
3929            continue;
3930        };
3931        let earlier = frame[..k].iter().rposition(|m| {
3932            matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
3933        });
3934        if let Some(j) = earlier
3935            && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
3936        {
3937            *s = size;
3938        }
3939    }
3940}
3941
3942/// Of the items of a frame merged from several commits that set one part
3943/// of a view whole (its frame, style, text, ...), keeps the last: the
3944/// platform would apply each in one pass, and a list's rounds (binds, then
3945/// the paced ones) relay and restyle the same cells. Once per turn, with
3946/// `last` the reused buffer.
3947fn keep_last_sets(frame: &mut Vec<nsh_core::MountItem>, last: &mut FxHashMap<(u8, NodeId), usize>) {
3948    last.clear();
3949    let mut repeated = false;
3950    for (k, item) in frame.iter().enumerate() {
3951        if let Some(key) = sets_whole(item) {
3952            repeated |= last.insert(key, k).is_some();
3953        }
3954    }
3955    if !repeated {
3956        return;
3957    }
3958    let mut k = 0;
3959    frame.retain(|item| {
3960        k += 1;
3961        sets_whole(item).is_none_or(|key| last[&key] == k - 1)
3962    });
3963}
3964
3965/// The part of a view an item sets whole, and the view: of two such items
3966/// the later is all the view ends up with.
3967fn sets_whole(item: &nsh_core::MountItem) -> Option<(u8, nsh_core::NodeId)> {
3968    use nsh_core::MountItem;
3969    Some(match *item {
3970        MountItem::Frame { id, .. } => (0, id),
3971        MountItem::Overflow { id, .. } => (1, id),
3972        MountItem::ViewStyle { id, .. } => (2, id),
3973        MountItem::Text { id, .. } => (3, id),
3974        MountItem::Events { id, .. } => (4, id),
3975        MountItem::Image { id, .. } => (5, id),
3976        _ => return None,
3977    })
3978}
3979
3980/// The most ops an emptied op buffer keeps room for.
3981const RETAINED_OPS: usize = 16 * 1024;
3982
3983/// Gives back what a large commit (a screen made at once, a long list
3984/// bound) grew the emptied op buffer to: it and the runtime's take turns
3985/// ([`Script::take_ops`] swaps them), and each would otherwise hold the
3986/// largest commit's capacity for the life of the app.
3987fn release_spare_ops(ops: &mut Vec<Op>) {
3988    debug_assert!(ops.is_empty());
3989    if ops.capacity() > RETAINED_OPS {
3990        ops.shrink_to(RETAINED_OPS);
3991    }
3992}
3993
3994/// What `app` may reach: a JS app its policy's grant; native code is
3995/// trusted, it reaches what the platform allows.
3996fn app_access(app: &App) -> Access {
3997    match app {
3998        App::Js(bundle) => bundle.policy.access(),
3999        App::Rust(_) => Policy::default().access(),
4000    }
4001}
4002
4003/// The roots local media files are read under, as `fs/promises` reads
4004/// files (where it has a file system: the desktops).
4005fn media_files(config: &EngineConfig, access: &Access) -> nsh_core::access::MediaFiles {
4006    match &config.app {
4007        App::Js(bundle) => nsh_core::access::MediaFiles::new(
4008            access,
4009            config
4010                .data_dir
4011                .as_ref()
4012                .map(|root| root.join(app_dir_name(config.app.app_id())))
4013                .as_deref(),
4014            &bundle_system_paths(bundle),
4015            nsh_core::access::native_files(config.environment.os),
4016        ),
4017        _ => nsh_core::access::MediaFiles::default(),
4018    }
4019}
4020
4021#[cfg(test)]
4022mod tests {
4023    #[test]
4024    fn an_emptied_op_buffer_gives_back_what_a_large_commit_grew() {
4025        let mut ops: Vec<super::Op> = Vec::with_capacity(super::RETAINED_OPS * 8);
4026        super::release_spare_ops(&mut ops);
4027        assert!(ops.capacity() <= super::RETAINED_OPS);
4028        // A buffer of ordinary commits keeps its room.
4029        let mut ops: Vec<super::Op> = Vec::with_capacity(1024);
4030        super::release_spare_ops(&mut ops);
4031        assert_eq!(ops.capacity(), 1024);
4032    }
4033
4034    #[test]
4035    fn moves_settle_and_changes_of_mode_do_not() {
4036        use nsh_core::{
4037            desktop::{DisplayId, WindowMode, WindowPlacement, WindowState},
4038            geometry::{Bounds, point, px, size},
4039        };
4040        let rect = |x: f32| Bounds::new(point(px(x), px(0.0)), size(px(800.0), px(600.0)));
4041        let a = WindowState::new(
4042            rect(0.0),
4043            WindowPlacement::new(WindowMode::Normal, rect(0.0)),
4044        );
4045        let mut moved = a;
4046        moved.bounds = rect(10.0);
4047        moved.placement = WindowPlacement::new(WindowMode::Normal, rect(10.0));
4048        assert!(super::moved_only(&a, &moved));
4049        let mut maximized = a;
4050        maximized.mode = WindowMode::Maximized;
4051        maximized.placement = WindowPlacement::new(WindowMode::Maximized, rect(0.0));
4052        assert!(!super::moved_only(&a, &maximized));
4053        let mut minimized = a;
4054        minimized.minimized = true;
4055        assert!(!super::moved_only(&a, &minimized));
4056        let mut hidden = a;
4057        hidden.visible = false;
4058        assert!(!super::moved_only(&a, &hidden));
4059        let mut elsewhere = a;
4060        elsewhere.display = Some(DisplayId(2));
4061        assert!(!super::moved_only(&a, &elsewhere));
4062    }
4063
4064    #[test]
4065    fn pinned_values_hold_whatever_the_platform_reports() {
4066        let pins = super::EnvironmentPins {
4067            locale: nsh_core::platform::Locale::parse("de-DE"),
4068            reduce_motion: Some(true),
4069            ..Default::default()
4070        };
4071        let mut reported = super::Environment {
4072            locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
4073            font_scale: 1.5,
4074            ..Default::default()
4075        };
4076        pins.apply(&mut reported);
4077        assert_eq!(reported.locale.as_str(), "de-DE");
4078        assert!(reported.reduce_motion);
4079        // What is not pinned stays the platform's.
4080        assert_eq!(reported.font_scale, 1.5);
4081        assert_eq!(reported.safe_area, Default::default());
4082    }
4083
4084    #[test]
4085    fn bundle_default_has_no_application_selected_path_anchors() {
4086        let bundle = super::Bundle::default();
4087        assert!(bundle.system_paths.plugin_dir.is_none());
4088        assert!(bundle.system_paths.home_dir.is_none());
4089        assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
4090    }
4091
4092    #[test]
4093    fn bundle_trusted_paths_reject_relative_and_missing_directories() {
4094        let mut paths = nsh_core::access::TrustedPaths::default();
4095        paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
4096        paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
4097        let bundle = super::Bundle::default().with_system_paths(paths);
4098        assert!(bundle.system_paths.plugin_dir.is_none());
4099        assert!(bundle.system_paths.home_dir.is_none());
4100        assert!(
4101            super::trusted_directory(Some(std::path::PathBuf::from(
4102                "/nsh-nonexistent-anchor-never-created"
4103            )))
4104            .is_none()
4105        );
4106    }
4107
4108    #[test]
4109    fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
4110        let root = std::env::var_os("TMPDIR")
4111            .map(std::path::PathBuf::from)
4112            .unwrap_or_else(|| {
4113                std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
4114                    .join(".cache/nsh-benchs-test-tmp")
4115            });
4116        assert!(root.is_absolute() && !root.starts_with("/tmp"));
4117        let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
4118        std::fs::create_dir_all(&directory).unwrap();
4119        let path = directory.join("bundle.js");
4120        std::fs::write(&path, "export default null;").unwrap();
4121        let bundle = super::Bundle::read(&path).unwrap();
4122        assert_eq!(
4123            bundle.system_paths.plugin_dir,
4124            Some(nsh_core::access::canonicalize(&directory).unwrap())
4125        );
4126        assert!(bundle.system_paths.home_dir.is_none());
4127        std::fs::remove_dir_all(directory).unwrap();
4128    }
4129
4130    #[test]
4131    fn rust_environment_preserves_native_title_bar_insets() {
4132        use super::{Edges, Points};
4133        let title_bar = Edges {
4134            top: Points(42.0),
4135            left: Points(78.0),
4136            right: Points(138.0),
4137            bottom: Points(0.0),
4138        };
4139        let environment = super::Environment {
4140            title_bar,
4141            ..Default::default()
4142        };
4143        assert_eq!(
4144            super::ui_environment(
4145                &environment,
4146                nsh_core::Size::new(Points(840.0), Points(630.0))
4147            )
4148            .title_bar,
4149            title_bar
4150        );
4151    }
4152
4153    use nsh_core::{MountItem, Points, Size};
4154
4155    #[test]
4156    fn a_frame_sends_a_scroll_views_last_content_size() {
4157        let content = |height| MountItem::ScrollContent {
4158            id: 2,
4159            size: Size::new(Points(390.0), height),
4160        };
4161        let heights = |frame: &[MountItem]| -> Vec<f32> {
4162            frame
4163                .iter()
4164                .filter_map(|m| match m {
4165                    MountItem::ScrollContent { size, .. } => Some(size.height.0),
4166                    _ => None,
4167                })
4168                .collect()
4169        };
4170        let mut frame = vec![content(Points(313.0))];
4171        super::extend_frame(&mut frame, vec![content(Points(544.0))]);
4172        assert_eq!(heights(&frame), [544.0, 544.0]);
4173        // A scroll in between keeps the size it scrolled against.
4174        let mut frame = vec![
4175            content(Points(313.0)),
4176            MountItem::ScrollBy {
4177                id: 2,
4178                dx: Points(0.0),
4179                dy: Points(10.0),
4180            },
4181        ];
4182        super::extend_frame(&mut frame, vec![content(Points(544.0))]);
4183        assert_eq!(heights(&frame), [313.0, 544.0]);
4184    }
4185
4186    #[test]
4187    fn a_frame_sends_a_views_last_frame_once() {
4188        use nsh_core::{Bounds, Point};
4189        let at = |id, y| MountItem::Frame {
4190            id,
4191            frame: Bounds::new(
4192                Point::new(Points(0.0), Points(y)),
4193                Size::new(Points(10.0), Points(10.0)),
4194            ),
4195        };
4196        let mut frame = vec![
4197            MountItem::Create {
4198                id: 4,
4199                kind: nsh_core::ViewKind::View,
4200            },
4201            at(4, 0.0),
4202            at(6, 0.0),
4203        ];
4204        super::extend_frame(&mut frame, vec![at(4, 50.0)]);
4205        super::keep_last_sets(&mut frame, &mut Default::default());
4206        assert!(matches!(frame[0], MountItem::Create { id: 4, .. }));
4207        let frames: Vec<_> = frame
4208            .iter()
4209            .filter_map(|m| match m {
4210                MountItem::Frame { id, frame } => Some((*id, frame.origin.y.0)),
4211                _ => None,
4212            })
4213            .collect();
4214        assert_eq!(frames, [(6, 0.0), (4, 50.0)]);
4215    }
4216}