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