Skip to main content

nsh_engine/
lib.rs

1//! The engine thread of one surface.
2//!
3//! The engine owns a [`nsh_core::Core`] on a dedicated thread and runs one
4//! app ([`App`]): a Rust app's root component, or a JS bundle in a QuickJS
5//! VM (`nsh_js::Host`, feature `js-core`; `js` adds the standard modules
6//! `zlib` and `crypto`). Each wake-up (input event, timer,
7//! resize) runs the app's code (component tasks; JS and its microtasks),
8//! applies what JS committed, lays out, and hands one [`MountBatch`] to the
9//! platform through a [`MountSink`]. The platform thread never blocks on
10//! the engine.
11
12#[cfg(all(feature = "browser", target_arch = "wasm32", not(feature = "js-core")))]
13pub mod browser;
14
15mod access;
16mod app_directory;
17mod cache;
18mod error;
19mod host_channel;
20mod local_storage;
21#[cfg(feature = "net")]
22pub mod net;
23pub mod perf;
24mod script;
25#[cfg(feature = "shader")]
26pub mod shader;
27#[cfg(not(target_arch = "wasm32"))]
28mod storage;
29#[cfg(feature = "js-core")]
30mod symbolicate;
31
32// The typed API check (docs/dev/geometry.md, "Typed API"): the scan is
33// nsh-core's; this crate's lists are `unitless.txt` and `untyped.txt`.
34#[cfg(test)]
35#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
36mod unit_scan;
37
38#[cfg(test)]
39#[test]
40fn public_api_is_typed() {
41    unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
42}
43
44use std::{io, mem::ManuallyDrop, rc::Rc, sync::Arc, time::Duration};
45
46pub use app_directory::app_dir_name;
47use crossbeam_channel::{Receiver, Sender};
48pub use local_storage::local_storage_prefix;
49use nsh_core::{
50    ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
51    PayloadValue, TextEngine, element::JsEvent, time::Instant,
52};
53pub use nsh_core::{
54    JsonValue,
55    access::{Access, Capabilities},
56    element::{EngineContext, Root, Tokens},
57    geometry::{self, Bounds, Edges, Point, Points, Size},
58    js::{HostLimits, Limits},
59    platform::{
60        ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HttpBody, HttpHead,
61        HttpRequest, Idiom, Lifecycle, Locale, Os,
62    },
63    storage::{StorageBackend, StorageChange},
64    time::Clock,
65};
66#[cfg(feature = "js-core")]
67pub use nsh_js::BYTECODE_VERSION;
68/// Signed packages, release-key certificates, revocations and trust stores.
69#[cfg(feature = "js-core")]
70pub use nsh_package as package;
71use rustc_hash::FxHashMap;
72#[cfg(not(target_arch = "wasm32"))]
73pub use storage::{FileStorage, data_dir};
74
75use crate::script::{NetworkQueue, RequestId, Script};
76pub use crate::{
77    cache::{ByteSize, CacheLocation, CacheOptions, CachePolicy},
78    error::{AppError, AppErrorKind, PackageInfo},
79    host_channel::{HostCall, HostChannel, HostReply, OpenUrlRequest},
80};
81
82#[cfg(not(target_arch = "wasm32"))]
83/// Stack size of the engine thread. QuickJS recursion (and deep Solid
84/// component trees) needs more than the 512 KiB default of secondary
85/// threads on Apple platforms.
86const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
87
88/// Minimum time between idle cycle collections. QuickJS frees acyclic
89/// garbage immediately; only cycles (such as detached node subtrees, whose
90/// parent/child links reference each other) wait for the collector.
91const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
92
93/// How long the engine has had nothing to do (no message, no timer due)
94/// before an idle collection: a collection walks every object of the VM,
95/// tens of milliseconds for an app holding a lot of data, so it waits for
96/// a pause rather than land between the turns of a paste held down or of
97/// work done in slices on timers. An engine never quiet that long (a
98/// timer every few frames) still collects every [`IDLE_GC_LONGEST`].
99const IDLE_GC_QUIET: Duration = Duration::from_millis(300);
100
101/// The longest time between idle collections, quiet or not.
102const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);
103
104/// The shortest time between two deliveries of mouse motion: a frame at
105/// 120 Hz. Mice report moves far more often (up to 1000 Hz), and a handler
106/// that redraws a crosshair needs no more than one per frame.
107const MOUSE_MOVE_INTERVAL: Duration = Duration::from_millis(8);
108
109/// The app an engine runs.
110#[derive(Debug, Clone)]
111#[allow(
112    clippy::large_enum_variant,
113    reason = "one app per surface; keep the public constructor API without allocation"
114)]
115pub enum App {
116    /// A Rust app: its root component, mounted as the surface's content.
117    Rust(Root),
118    /// A JS app (feature `js-core`).
119    Js(Bundle),
120}
121
122impl From<Bundle> for App {
123    fn from(bundle: Bundle) -> Self {
124        App::Js(bundle)
125    }
126}
127
128impl App {
129    /// The app's id (`nsh.json` `"id"`), when it carries one.
130    pub fn app_id(&self) -> Option<&str> {
131        match self {
132            App::Rust(root) => root.app_id_ref(),
133            App::Js(bundle) => bundle.app_id.as_deref(),
134        }
135    }
136}
137
138impl From<Root> for App {
139    fn from(root: Root) -> Self {
140        App::Rust(root)
141    }
142}
143
144/// An app bundle: its code plus, in development, a source map.
145#[derive(Debug, Clone)]
146#[non_exhaustive]
147pub struct Bundle {
148    /// The code.
149    pub code: BundleCode,
150    /// Source map (JSON) used to show app source locations in stack traces.
151    pub source_map: Option<Arc<str>>,
152    /// What the code may do.
153    pub policy: Policy,
154    /// What relative request URLs resolve against (the page's URL on the
155    /// web); `None`: they are invalid.
156    pub base_url: Option<Arc<str>>,
157    /// The chunks of a split bundle that come with it (`import()` loads
158    /// them without asking the platform); those missing are asked of
159    /// [`MountSink::load_chunk`]. Shared by the bundle's clones.
160    pub chunks: Arc<Vec<Chunk>>,
161    /// The app's id (`nsh.json` `"id"`; a signed package's verified one):
162    /// it names where the app keeps its data (`nsh/storage`).
163    pub app_id: Option<String>,
164    /// Trusted filesystem anchors selected by the native host, never decoded
165    /// from application code, its manifest or a development server message.
166    /// Missing anchors deny relative and corresponding placeholder grants.
167    pub system_paths: nsh_core::access::TrustedPaths,
168    /// The signed package the bundle came from ([`Bundle::from_package`]),
169    /// named in the app's errors ([`AppError::package`]).
170    pub package: Option<Arc<PackageInfo>>,
171}
172
173/// A chunk of a split bundle (`nsh_bundler::Chunk`): app code that
174/// `import()` loads on demand.
175#[derive(Debug, Clone)]
176pub struct Chunk {
177    /// Its id (`Screen.js`), as the bundle imports it.
178    pub id: String,
179    /// The code.
180    pub code: BundleCode,
181    /// Source map (JSON), for stack traces.
182    pub source_map: Option<Arc<str>>,
183}
184
185impl Chunk {
186    /// A chunk as JS source.
187    pub fn source(id: impl Into<String>, code: String) -> Self {
188        Self {
189            id: id.into(),
190            code: BundleCode::Source(code),
191            source_map: None,
192        }
193    }
194
195    /// A chunk as bytecode (`nsh_js::compile_chunk_bytecode`).
196    ///
197    /// # Safety
198    ///
199    /// As [`Bundle::bytecode`].
200    pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
201        Self {
202            id: id.into(),
203            code: BundleCode::Bytecode(bytes),
204            source_map: None,
205        }
206    }
207
208    /// Attaches a source map.
209    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
210        self.source_map = Some(map.into());
211        self
212    }
213}
214
215/// What a bundle's code may do.
216#[derive(Debug, Clone)]
217pub struct Policy {
218    /// Run without `eval`, the function constructors and writable shared
219    /// prototypes (see `nsh_js::HostOptions::harden`). On by default; off for
220    /// development bundles.
221    pub harden: bool,
222    /// What the app declared (`nsh.json` `capabilities`); `None`: no
223    /// declaration, everything.
224    pub declared: Option<Capabilities>,
225    /// What the embedding app grants at most; `None`: whatever the app
226    /// declared.
227    pub granted: Option<Capabilities>,
228}
229
230impl Default for Policy {
231    fn default() -> Self {
232        Self {
233            harden: true,
234            declared: None,
235            granted: None,
236        }
237    }
238}
239
240impl Policy {
241    /// Development bundles: `eval` and friends stay (debugging); the
242    /// capabilities are still enforced, so a missing one shows during
243    /// development.
244    pub fn development() -> Self {
245        Self {
246            harden: false,
247            ..Self::default()
248        }
249    }
250
251    /// What the app may reach under this policy.
252    pub fn access(&self) -> Access {
253        Access {
254            declared: self.declared.clone().unwrap_or_else(Capabilities::all),
255            granted: self.granted.clone(),
256        }
257    }
258}
259
260/// The code of a bundle.
261#[derive(Debug, Clone)]
262pub enum BundleCode {
263    /// QuickJS bytecode from `nsh_js::compile_bytecode`.
264    Bytecode(Vec<u8>),
265    /// JS source; slower to start than bytecode.
266    Source(String),
267}
268
269impl Default for Bundle {
270    fn default() -> Self {
271        Self::source(String::new())
272    }
273}
274
275impl Bundle {
276    /// A bytecode bundle.
277    ///
278    /// # Safety
279    ///
280    /// `bytes` must be bytecode from `nsh_js::compile_bytecode` for this
281    /// runtime's `BYTECODE_VERSION`, from a trusted source: QuickJS does not
282    /// validate bytecode, and loading crafted bytecode corrupts memory. Trusted
283    /// are the app's own signed resources, a development server the developer
284    /// pointed the host at, and verified packages ([`Bundle::from_package`]).
285    pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
286        Self {
287            code: BundleCode::Bytecode(bytes),
288            source_map: None,
289            policy: Policy::default(),
290            base_url: None,
291            chunks: Arc::default(),
292            app_id: None,
293            system_paths: nsh_core::access::TrustedPaths::default(),
294            package: None,
295        }
296    }
297
298    /// A JS source bundle.
299    pub fn source(code: String) -> Self {
300        Self {
301            code: BundleCode::Source(code),
302            source_map: None,
303            policy: Policy::default(),
304            base_url: None,
305            chunks: Arc::default(),
306            app_id: None,
307            system_paths: nsh_core::access::TrustedPaths::default(),
308            package: None,
309        }
310    }
311
312    /// Selects trusted source/package and home directory anchors. Supplying a
313    /// path grants nothing by itself: the manifest and host grant must still
314    /// allow the filesystem operation. Only existing absolute directories
315    /// are accepted; unavailable anchors are left unset.
316    pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
317        paths.plugin_dir = trusted_directory(paths.plugin_dir);
318        paths.home_dir = trusted_directory(paths.home_dir);
319        self.system_paths = paths;
320        self
321    }
322
323    /// The app's id ([`Bundle::app_id`]), as `nsh.json` or the dev server
324    /// gives it.
325    pub fn with_app_id(mut self, id: Option<&str>) -> Self {
326        self.app_id = id.map(str::to_owned);
327        self
328    }
329
330    /// Attaches a source map.
331    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
332        self.source_map = Some(map.into());
333        self
334    }
335
336    /// Sets the URL relative request URLs resolve against.
337    pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
338        self.base_url = Some(url.into());
339        self
340    }
341
342    /// Replaces the policy.
343    pub fn with_policy(mut self, policy: Policy) -> Self {
344        self.policy = policy;
345        self
346    }
347
348    /// Adds chunks of a split bundle (see [`Bundle::chunks`]).
349    pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
350        Arc::make_mut(&mut self.chunks).extend(chunks);
351        self
352    }
353
354    /// Reads a JS source bundle written by `nsh build` (`bundle.js`), plus
355    /// `bundle.js.map`, the app's `capabilities.json` and its id
356    /// (`app.json` `"id"`) next to it if present. Bytecode (`bundle.nshc`) is refused: files can be replaced, and
357    /// only [`Bundle::read_trusted`] (the app's own resources) or a verified
358    /// package may load bytecode.
359    pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
360        if path.extension().is_some_and(|e| e == "nshc") {
361            return Err(io::Error::other(
362                "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
363            ));
364        }
365        // SAFETY: not bytecode.
366        unsafe { Self::read_trusted(path) }
367    }
368
369    /// Like [`Bundle::read`], also reading `bundle.nshc` as bytecode.
370    ///
371    /// # Safety
372    ///
373    /// A `.nshc` file must be trusted as [`Bundle::bytecode`] requires (e.g.
374    /// inside the app's own signed bundle).
375    pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
376        let bytes = std::fs::read(path)?;
377        let bundle = if path.extension().is_some_and(|e| e == "nshc") {
378            // SAFETY: guaranteed by the caller.
379            unsafe { Bundle::bytecode(bytes) }
380        } else {
381            Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
382        };
383        let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
384            Ok(map) if !map.is_empty() => bundle.with_source_map(map),
385            _ => bundle,
386        };
387        if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
388            bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
389        }
390        bundle.app_id = read_app_id(&path.with_file_name("app.json"));
391        bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
392            .parent()
393            .map(std::path::Path::to_path_buf);
394        Ok(bundle)
395    }
396}
397
398#[cfg(feature = "js-core")]
399impl Bundle {
400    /// The bundle of a verified package: its bytecode when it was compiled
401    /// for this runtime (else its source), its source map and its declared
402    /// capabilities. What a newer signer wrote that this runtime does not
403    /// know (header fields, files, capabilities) is logged and left out: an
404    /// unknown capability is not granted.
405    pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
406        for ignored in &package.ignored {
407            log::warn!("package {}: ignored {ignored}", package.app.id);
408        }
409        let bundle = match package.bytecode() {
410            // SAFETY: verified: signed by a certified release key, hashed,
411            // and compiled for this runtime.
412            Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
413            None => Bundle::source(package.source.clone()),
414        };
415        let mut bundle = match &package.source_map {
416            Some(map) => bundle.with_source_map(map.clone()),
417            None => bundle,
418        };
419        if let Some(json) = &package.capabilities {
420            let (declared, dropped) = Capabilities::from_json_lenient(json)?;
421            for dropped in dropped {
422                log::warn!("package {}: not granted: {dropped}", package.app.id);
423            }
424            bundle.policy.declared = Some(declared);
425        }
426        bundle.app_id = Some(package.app.id.clone());
427        bundle.package = Some(Arc::new(PackageInfo {
428            id: package.app.id.clone(),
429            name: package.app.name.clone(),
430            version: package.app.version.clone(),
431            build: package.app.build,
432            sha256: package.sha256.clone(),
433        }));
434        Ok(bundle)
435    }
436}
437
438/// The `"id"` of an `app.json` (`nsh build`'s, a packaged app's).
439fn read_app_id(path: &std::path::Path) -> Option<String> {
440    let json: serde_json::Value =
441        serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()?;
442    json.get("id")?.as_str().map(str::to_owned)
443}
444
445/// A verified package, unpacked ([`load_package`], [`verify_package`]).
446#[cfg(feature = "js-core")]
447#[derive(Debug)]
448pub struct LoadedPackage {
449    /// Its bundle.
450    pub bundle: Bundle,
451    /// Where its assets are (`asset:/…`).
452    pub assets: std::path::PathBuf,
453    /// Its app.
454    pub app: nsh_package::App,
455    /// What accepting it records ([`accept_package`]).
456    pub receipt: nsh_package::PackageReceipt,
457}
458
459/// Verifies the package `bytes` with `trust`, writes its assets under
460/// `assets_root` (`<root>/<app id>/<package hash>/`, once per package) and
461/// records its build (older builds of the app are refused from now on):
462/// [`verify_package`], then [`accept_package`].
463#[cfg(feature = "js-core")]
464pub fn load_package(
465    trust: &mut nsh_package::TrustStore,
466    bytes: &[u8],
467    assets_root: &std::path::Path,
468) -> Result<LoadedPackage, String> {
469    let package = verify_package(trust, bytes, assets_root)?;
470    accept_package(trust, &package)?;
471    Ok(package)
472}
473
474/// [`load_package`] without recording the build: the package is verified as
475/// strictly (signature, certificate, revocations, hashes, and its build not
476/// older than the highest accepted) and its assets written, but the builds
477/// accepted before keep verifying. An embedding app runs it, and once it
478/// decided the package is healthy (its first frame drawn, no fatal error for
479/// a while) calls [`accept_package`]; if it fails before, the app can go
480/// back to the package it ran before, which still verifies.
481#[cfg(feature = "js-core")]
482pub fn verify_package(
483    trust: &nsh_package::TrustStore,
484    bytes: &[u8],
485    assets_root: &std::path::Path,
486) -> Result<LoadedPackage, String> {
487    let package = trust
488        .verify(bytes, BYTECODE_VERSION)
489        .map_err(|e| e.to_string())?;
490    let bundle = Bundle::from_package(&package)?;
491    let dir = assets_root.join(&package.app.id).join(&package.sha256);
492    let done = dir.join(".complete");
493    if !done.exists() {
494        let assets = dir.join("assets");
495        for (path, data) in &package.assets {
496            // Paths were checked (relative, no `..`) when the package was read.
497            let dest = assets.join(path);
498            if let Some(parent) = dest.parent() {
499                std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
500            }
501            std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
502        }
503        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
504        std::fs::write(&done, b"").map_err(|e| e.to_string())?;
505    }
506    Ok(LoadedPackage {
507        bundle,
508        assets: dir.join("assets"),
509        receipt: package.receipt(),
510        app: package.app,
511    })
512}
513
514/// Rewrites every `bundle.js:LINE:COL` in `text` (a reported error and its
515/// stack) to the app source position `source_map` (the bundle's) gives,
516/// as the engine does with a bundle's own map: for stacks reported by
517/// packages published without their map (`nsh symbolicate`).
518#[cfg(feature = "js-core")]
519pub fn symbolicate(source_map: &str, text: &str) -> String {
520    symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
521}
522
523/// Records the build of `package` ([`verify_package`]) in `trust`: older
524/// builds of its app are refused from now on. Refused if the package or its
525/// release key was revoked since it was verified.
526#[cfg(feature = "js-core")]
527pub fn accept_package(
528    trust: &mut nsh_package::TrustStore,
529    package: &LoadedPackage,
530) -> Result<(), String> {
531    trust
532        .accept_receipt(&package.receipt)
533        .map_err(|e| e.to_string())
534}
535
536/// Parses capabilities in their JSON form (`capabilities.json`, the dev
537/// protocol, an embedder's grant).
538pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
539    let value: serde_json::Value =
540        serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
541    Capabilities::from_json(&value)
542}
543
544impl Bundle {
545    /// The declared capabilities from their JSON form, if any.
546    pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
547        self.policy.declared = json.map(parse_capabilities).transpose()?;
548        Ok(self)
549    }
550}
551
552/// Receives mount batches on the engine thread. Implementations forward
553/// them to the UI thread.
554pub trait MountSink: Send + 'static {
555    /// Called once per commit, in order.
556    fn submit(&self, batch: MountBatch);
557
558    /// An error of the app, as text (the message and the stack): the
559    /// bundle failed to load, an exception escaped a JS callback, the VM
560    /// was stopped. Errors are always logged; development hosts also show
561    /// them on screen. What [`MountSink::report`] calls unless it is
562    /// implemented.
563    fn report_error(&self, _message: &str) {}
564
565    /// An error of the app, with its parts: what went wrong (whether the
566    /// app can go on), the message, the stack and the package it came
567    /// from. By default, [`MountSink::report_error`] with its text.
568    fn report(&self, error: &AppError) {
569        self.report_error(&error.to_string());
570    }
571
572    /// JS or a component's task asked for a display frame
573    /// (`requestAnimationFrame`, `nsh_core::element::next_frame`), or lists have
574    /// overscan cells left to bind: call [`EngineControl::frame`] at the
575    /// next vsync. Requests are not repeated until that call.
576    fn request_frame(&self) {}
577
578    /// A development update ([`EngineControl::hot_update`]) could not be
579    /// applied in place: reload the latest full bundle.
580    fn hot_update_failed(&self) {}
581
582    /// The engine laid the app out at `size` ([`EngineControl::resize`]):
583    /// called after the commit of the turn that applied the resize (if it
584    /// changed anything, its batch came before), once per turn, with the
585    /// latest size. A platform that waits for the layout at a new size, to
586    /// show it in the frame the window takes the size, stops waiting here.
587    fn resized(&self, _size: Size<Points>) {}
588
589    /// The engine has handled the first `events` events sent with
590    /// [`EngineControl::dispatch_event`]. Called after the commit of the
591    /// turn that handled them (what they changed came before), once per
592    /// turn. A platform holding typed text for the field an event may focus
593    /// gives it to the focused field from here.
594    fn handled(&self, _events: u64) {}
595
596    /// The app imports chunk `id` of a split bundle (`import()`), which its
597    /// [`Bundle`] does not hold: load it and hand it over with
598    /// [`EngineControl::chunk_loaded`] (or [`EngineControl::chunk_failed`]),
599    /// from any thread, and return true. False (the default): this host
600    /// has no chunks to load, and the import fails.
601    fn load_chunk(&self, _id: &str) -> bool {
602        false
603    }
604}
605
606/// Receives what happens to a request started by [`Network::fetch`], in
607/// order, on any thread. After [`FetchTask::cancel`] it may still be called
608/// (the engine then ignores it).
609pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
610
611/// A request in flight, driven from the engine thread.
612pub trait FetchTask: Send {
613    /// The next chunk of a streamed body ([`HttpBody::Stream`]), after
614    /// [`FetchEvent::BodyWanted`].
615    fn send(&mut self, chunk: Vec<u8>);
616    /// A streamed body is complete.
617    fn finish(&mut self);
618    /// Stops (`true`) or resumes (`false`) reading the response body: JS
619    /// does not read what arrived (back pressure). Bytes already on their
620    /// way may still arrive.
621    fn pause(&mut self, paused: bool);
622    /// Aborts the request.
623    fn cancel(self: Box<Self>);
624}
625
626/// The platform's HTTP stack, used by JS `fetch`.
627pub trait Network: Send + Sync + 'static {
628    /// Starts `request`: its response head, then its body in chunks as they
629    /// arrive, are reported to `events`.
630    fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
631}
632
633/// Reads the app's bundled files (`asset:/…` URIs): from the app's
634/// resources, or from the dev server during development. The engine reads
635/// the fonts it registers with it, and answers the app's requests of
636/// `asset:/` URLs (`fetch`) from it.
637pub trait Assets: Send + Sync + 'static {
638    /// The bytes of `uri`. Blocking: the engine calls it on its thread for
639    /// the fonts it registers, and on a thread of the runtime's blocking
640    /// pool for the app's requests (in WebAssembly on its thread).
641    fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
642
643    /// Where `uri` is served, for files [`Assets::read`] does not have at
644    /// hand: the engine downloads them from there with its network stack
645    /// (the web page, which holds only the files it preloaded). `None`, the
646    /// default, when `read` is the only way.
647    fn url(&self, uri: &str) -> Option<String> {
648        let _ = uri;
649        None
650    }
651
652    /// Where `asset:/` URIs resolve, when it is a directory or a URL the
653    /// image loader can read itself: the core's image loads ([`svg`]s)
654    /// then share the platform's cache entries. `None`: through
655    /// [`Assets::read`].
656    ///
657    /// [`svg`]: nsh_core::element::svg
658    #[cfg(not(target_arch = "wasm32"))]
659    fn base(&self) -> Option<nsh_core::image::loader::AssetBase> {
660        None
661    }
662}
663
664/// Engine settings.
665#[derive(Clone)]
666pub struct EngineConfig {
667    /// The app.
668    pub app: App,
669    /// Initial size of the root view.
670    pub viewport: Size<Points>,
671    /// Log per-commit timings (target `nsh::perf`, level info).
672    pub trace: bool,
673    /// The HTTP stack behind `fetch`; without one, requests fail.
674    pub network: Option<Arc<dyn Network>>,
675    /// The host transport for WebSockets, including the browser WebSocket API.
676    pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
677    /// Refuses the app's connections (`net` sockets and both WebSocket
678    /// APIs) with the error it gives for what they connect to, before they
679    /// reach the network: a test's, which reaches it only when the test
680    /// asks (`nsh test`'s `network: "live"`). `None`: they connect.
681    pub refuse_connections: Option<nsh_core::element::RefuseConnections>,
682    /// App-private host filesystem service (for browser storage).
683    pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
684    /// Source of bundled files such as fonts; without one, they fail to load.
685    pub assets: Option<Arc<dyn Assets>>,
686    /// The surface's initial environment (its `window` is `viewport`).
687    pub environment: Environment,
688    /// Height of the platform's screen header bar, normal and with a large
689    /// title (status bar excluded).
690    pub header_heights: (Points, Points),
691    /// The JS VM's resource limits (a JS app's; Rust code has none).
692    pub limits: Limits,
693    /// The UI sets JS imports (`nsh_base::registry()` by default, the app's
694    /// own): their Rust components and modules. A Rust app's
695    /// components need no registration.
696    pub ui_sets: Vec<nsh_core::element::Registry>,
697    /// The tokio runtime the components' async tasks use (timers, IO,
698    /// background work); `None`: one shared by the engines of the process.
699    pub runtime: Option<tokio::runtime::Handle>,
700    /// Where apps keep their data: each app in `<data_dir>/<app id>`
701    /// ([`App::app_id`]; `default` without one), its storage
702    /// (`nsh/storage`) in `storage.json` there. The platform's: the
703    /// system's data directory ([`data_dir`]) for apps of their own,
704    /// `…/nsh` in an embedding app's. `None`: nothing is kept.
705    pub data_dir: Option<std::path::PathBuf>,
706    /// Where the app's caches are kept and how much each keeps: the engine
707    /// opens them in `<root>/<app id>/<kind>` ([`Engine::image_cache`]).
708    /// [`EngineConfig::new`]: none.
709    pub cache: CacheOptions,
710    /// The app's storage, overriding the one [`EngineConfig::data_dir`]
711    /// names (the browser's `localStorage`, an embedder's own); `None`
712    /// with no data directory either: in memory, for the engine's life.
713    pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
714    /// The time the app runs on: the system's, or a manual clock a test
715    /// moves (`nsh_core::time::Clock::manual`), which its timers, frames
716    /// and `Date` follow.
717    pub clock: Clock,
718    /// What the host gives this engine's Rust code, which its UI sets'
719    /// functions and components read while it runs them
720    /// (`nsh_core::element::engine_context`): a host serving several engines
721    /// tells them apart by it.
722    pub context: EngineContext,
723    /// Values of the environment kept whatever the platform reports (a
724    /// test's locale, reduced motion and safe area: `nsh test --target`).
725    pub pinned: EnvironmentPins,
726    /// Serves the app's clipboard calls in place of the platform's
727    /// clipboard (a test's own: `nsh test --target`); `None`: the
728    /// platform's.
729    pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
730    /// The embedding app's channel with the app (`nsh/host`): its launch
731    /// parameters, its events and its handlers of the app's calls and
732    /// posts. A view keeps one for every app it runs; the default is a
733    /// channel of the engine's own, with none of them.
734    pub host: HostChannel,
735    /// Answers the app's picks (`Picker.pickImages`) in place of the
736    /// platform's picker: the embedding app's own picker, or a test's
737    /// files; `None`: the platform's.
738    pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
739    /// Recognizes the app's speech (`Speech.start`) instead of the
740    /// platform's recognizer: the embedding app's own, or a test's fake
741    /// (`nsh_testing`'s). `None` (the default): the platform's, where it
742    /// has one (`Environment::speech`).
743    pub speech: Option<Arc<dyn nsh_core::speech::SpeechBackend>>,
744}
745
746/// Values of the environment an engine keeps whatever its platform reports
747/// ([`EngineConfig::pinned`]); `None` leaves the platform's.
748#[derive(Debug, Clone, Copy, Default, PartialEq)]
749#[non_exhaustive]
750pub struct EnvironmentPins {
751    /// The locale (`Environment::locale`).
752    pub locale: Option<nsh_core::platform::Locale>,
753    /// Whether the user asked for less motion
754    /// (`Environment::reduce_motion`).
755    pub reduce_motion: Option<bool>,
756    /// The safe area insets (`Environment::safe_area`).
757    pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
758}
759
760impl EnvironmentPins {
761    /// `environment` with these values in place of the platform's.
762    pub fn apply(&self, environment: &mut Environment) {
763        if let Some(locale) = self.locale {
764            environment.locale = locale;
765        }
766        if let Some(reduce_motion) = self.reduce_motion {
767            environment.reduce_motion = reduce_motion;
768        }
769        if let Some(safe_area) = self.safe_area {
770            environment.safe_area = safe_area;
771        }
772    }
773}
774
775fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
776    let path = path.filter(|path| path.is_absolute())?;
777    nsh_core::access::canonicalize(&path)
778        .ok()
779        .filter(|path| path.is_dir())
780}
781
782/// Native hosts choose these anchors before any application JavaScript runs.
783#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
784fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
785    let mut paths = bundle.system_paths.clone();
786    paths.plugin_dir = trusted_directory(paths.plugin_dir);
787    paths.home_dir = trusted_directory(paths.home_dir);
788    if paths.home_dir.is_none() {
789        paths.home_dir = ["HOME", "USERPROFILE"]
790            .into_iter()
791            .filter_map(std::env::var_os)
792            .map(std::path::PathBuf::from)
793            .find_map(|path| trusted_directory(Some(path)));
794    }
795    // Local `nsh run` passes its canonical entry directory directly to the
796    // native child process. Remote dev messages never contain this field.
797    // A packaged/hardened bundle cannot inherit a development source anchor.
798    if paths.plugin_dir.is_none() && !bundle.policy.harden {
799        paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
800            .map(std::path::PathBuf::from)
801            .and_then(|path| trusted_directory(Some(path)));
802    }
803    paths
804}
805
806impl EngineConfig {
807    /// `app` on a phone-sized surface (390 × 844 points, iOS's header
808    /// heights) with nothing else: no network, assets, data directory or
809    /// UI sets, the default environment and limits, the shared runtime.
810    /// Set the fields that matter over it (`EngineConfig { ui_sets,
811    /// ..EngineConfig::new(app) }`). There is no `Default`: an engine has
812    /// no app to run by default.
813    pub fn new(app: impl Into<App>) -> Self {
814        Self {
815            app: app.into(),
816            viewport: Size::new(Points(390.0), Points(844.0)),
817            trace: false,
818            network: None,
819            websocket: None,
820            refuse_connections: None,
821            filesystem: None,
822            assets: None,
823            environment: Environment::default(),
824            header_heights: (Points(44.0), Points(96.0)),
825            limits: Limits::default(),
826            ui_sets: Vec::new(),
827            runtime: None,
828            data_dir: None,
829            cache: CacheOptions::off(),
830            storage: None,
831            clock: Clock::system(),
832            context: EngineContext::default(),
833            pinned: EnvironmentPins::default(),
834            clipboard: None,
835            host: HostChannel::default(),
836            picker: None,
837            speech: None,
838        }
839    }
840}
841
842/// The storage of the app `config` runs: [`EngineConfig::storage`], or a
843/// file in its directory of [`EngineConfig::data_dir`].
844fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
845    if let Some(storage) = &config.storage {
846        return Some(storage.clone());
847    }
848    #[cfg(not(target_arch = "wasm32"))]
849    if let Some(root) = &config.data_dir {
850        let dir = root.join(app_dir_name(config.app.app_id()));
851        return Some(FileStorage::open(dir));
852    }
853    None
854}
855
856#[cfg(not(target_arch = "wasm32"))]
857/// The runtime of components' tasks when the embedder gives none: a few
858/// threads, made on first use, shared by every engine (like a thread pool,
859/// it holds no engine's state).
860fn shared_runtime() -> tokio::runtime::Handle {
861    static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
862    RUNTIME
863        .get_or_init(|| {
864            tokio::runtime::Builder::new_multi_thread()
865                .worker_threads(2)
866                .thread_name("nsh-tasks")
867                .enable_all()
868                .build()
869                .expect("the tasks' runtime starts")
870        })
871        .handle()
872        .clone()
873}
874
875impl std::fmt::Debug for EngineConfig {
876    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
877        f.debug_struct("EngineConfig")
878            .field("app", &self.app)
879            .field("viewport", &self.viewport)
880            .field("trace", &self.trace)
881            .field("network", &self.network.is_some())
882            .field("assets", &self.assets.is_some())
883            .field("environment", &self.environment)
884            .field("header_heights", &self.header_heights)
885            .field("limits", &self.limits)
886            .field("ui_sets", &self.ui_sets)
887            .field("clock", &self.clock)
888            .field("context", &self.context)
889            .field("pinned", &self.pinned)
890            .field("clipboard", &self.clipboard.is_some())
891            .field("host", &self.host)
892            .field("picker", &self.picker.is_some())
893            .field("speech", &self.speech.is_some())
894            .finish()
895    }
896}
897
898/// How many times [`EngineControl::advance_clock`] stops for what comes
899/// due at most (sinon's fake timers stop at 1000 for one `runAll`; this
900/// leaves room for a long run of 60 Hz intervals).
901const MAX_ADVANCE_ROUNDS: usize = 100_000;
902
903/// How many times [`EngineControl::flush`] runs what is queued again when
904/// running it queued more (a task woken by another, a request answered at
905/// once): a task that keeps waking itself leaves the engine busy.
906const MAX_FLUSH_ROUNDS: usize = 64;
907
908enum Message {
909    Event(NodeId, EventKind, EventPayload),
910    Scroll(NodeId, Point<Points>, u32),
911    Kept(Vec<NodeId>),
912    InputScroll(NodeId, Point<Points>, Size<Points>, Size<Points>),
913    Zoom(NodeId, f32),
914    ComponentSize(NodeId, Size<Points>),
915    AnimationsFinished(Vec<nsh_core::animation::Finished>),
916    Resize(Size<Points>),
917    /// A component's task was woken: it runs in the loop.
918    Wake,
919    Environment(Environment),
920    RootSize(NodeId, Size<Points>, EdgeInsets),
921    ScreenHeader(NodeId, Option<Points>),
922    Frame,
923    States(NodeId, u16),
924    FontsChanged,
925    Remount,
926    /// An event of a request (by the hop it is for: events of a hop the
927    /// engine left are dropped).
928    Fetch(Requester, u64, FetchEvent),
929    /// Hop `.1` of the request `.2` for a bundled file read it on a
930    /// blocking thread ([`Net::asset`]): its bytes, or why there are none.
931    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
932    AssetRead(Requester, u64, HttpRequest, Result<Vec<u8>, String>),
933    Hot(HotUpdate),
934    /// A chunk [`MountSink::load_chunk`] was asked for, or why it could
935    /// not be loaded (its id and the message).
936    Chunk(Result<Chunk, (String, String)>),
937    Perf(Option<Arc<perf::PerfMonitor>>),
938    /// The embedding app's design tokens.
939    Tokens(Option<Box<Tokens>>),
940    /// The embedding app's event (`nsh/host`'s `host.on`): its name and
941    /// data.
942    HostEvent(String, nsh_core::JsonValue),
943    /// The embedding app's answer to call `.0` (`host.call`).
944    HostReply(u64, Result<nsh_core::JsonValue, String>),
945    /// The embedding app's URL handler answered URL request `id`: it took
946    /// the URL, or the platform opens it.
947    UrlHandled {
948        id: u32,
949        url: String,
950        handled: bool,
951    },
952    /// Moves a manual clock forward by this much, then calls back.
953    Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
954    /// Runs what is queued and due now, then calls back with whether the
955    /// engine is idle ([`EngineControl::flush`]).
956    Flush(Box<dyn FnOnce(bool) + Send>),
957    /// Sent by a dropped [`Engine`] (there is none in WebAssembly).
958    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
959    Shutdown,
960}
961
962/// A development update that replaces the app's changed modules in place,
963/// keeping the JS context, the views and the state of everything else
964/// (made by `nsh_bundler::HotBundle::patch`).
965#[derive(Debug, Clone)]
966pub struct HotUpdate {
967    /// Script name in stack traces, unique per update (e.g. `hot-3.js`).
968    pub name: String,
969    /// The script.
970    pub code: String,
971    /// Its source map (JSON).
972    pub source_map: Option<Arc<str>>,
973}
974
975/// Rounds of "list asks for items -> JS renders them -> layout" folded into
976/// one frame. Bounded so a list that never settles cannot stall the engine;
977/// leftovers continue next frame.
978const MAX_LIST_ROUNDS: usize = 8;
979
980/// The overscan a turn binds: cells until their ops reach this many (about
981/// as many mount items, which the main thread applies in one go) or their
982/// JS takes [`PACED_BIND_TIME`], at least one. A fast scroll asks for a
983/// screen of cells at once and each bind rebuilds a cell's subtree; what
984/// shows (the viewport, the leading edge, cells whose item moved) binds
985/// regardless, the rest on the next display frames.
986const PACED_BIND_OPS: usize = 150;
987/// See [`PACED_BIND_OPS`].
988const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);
989
990/// A cheap, cloneable handle for sending input to the engine from any thread.
991#[derive(Clone)]
992pub struct EngineControl {
993    tx: Sender<Message>,
994}
995
996impl EngineControl {
997    /// Delivers an input event (and its data) to a node.
998    pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
999        let _ = self.tx.send(Message::Event(id, event, payload));
1000    }
1001
1002    /// Reports the content offset of a scroll view or list, and how many
1003    /// scrolls the core asked for (`MountItem::ScrollBy` items and
1004    /// `Command::ScrollTo` commands for the view) were applied before it.
1005    /// Cheap to call on every scroll frame: offsets are coalesced per
1006    /// engine frame.
1007    pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
1008        let _ = self.tx.send(Message::Scroll(id, offset, applied));
1009    }
1010
1011    /// Keeps the virtual list rows holding `nodes` rendered wherever they
1012    /// scroll (`Core::set_kept`): the ends of a text selection. Replaces
1013    /// the last call's; none releases them.
1014    pub fn keep_rendered(&self, nodes: Vec<NodeId>) {
1015        let _ = self.tx.send(Message::Kept(nodes));
1016    }
1017
1018    /// Reports how far a multiline input's text scrolled: its offset, the
1019    /// size of the text it scrolls and of its viewport. Sent while a
1020    /// built-in bar takes the place of its indicator
1021    /// (`InputConfig::replaced`), on every change.
1022    pub fn input_scroll(
1023        &self,
1024        id: NodeId,
1025        offset: Point<Points>,
1026        content: Size<Points>,
1027        viewport: Size<Points>,
1028    ) {
1029        let _ = self
1030            .tx
1031            .send(Message::InputScroll(id, offset, content, viewport));
1032    }
1033
1034    /// Reports the zoom scale of a zoomable scroll view (before the offset
1035    /// the zoom changed); `onScroll` carries it.
1036    pub fn zoom(&self, id: NodeId, scale: f32) {
1037        let _ = self.tx.send(Message::Zoom(id, scale));
1038    }
1039
1040    /// A registered native component's own size (points): it is laid out at
1041    /// it where its style leaves a dimension open.
1042    pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
1043        let _ = self.tx.send(Message::ComponentSize(id, size));
1044    }
1045
1046    /// Reports native animations that finished or were interrupted.
1047    pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
1048        let _ = self.tx.send(Message::AnimationsFinished(finished));
1049    }
1050
1051    /// Resizes the root view.
1052    pub fn resize(&self, size: Size<Points>) {
1053        let _ = self.tx.send(Message::Resize(size));
1054    }
1055
1056    /// Reports a change of the surface's environment (safe area, keyboard,
1057    /// appearance...).
1058    pub fn set_environment(&self, environment: Environment) {
1059        let _ = self.tx.send(Message::Environment(environment));
1060    }
1061
1062    /// The platform presents root `id` (a modal) at `size`, with `insets`
1063    /// of it covered by system UI.
1064    pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
1065        let _ = self.tx.send(Message::RootSize(id, size, insets));
1066    }
1067
1068    /// The platform measured where the content of screen `id` starts below
1069    /// its header (`None`: let the core estimate it).
1070    pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
1071        let _ = self.tx.send(Message::ScreenHeader(id, height));
1072    }
1073
1074    /// Applies a development update in place. When it cannot be applied,
1075    /// [`MountSink::hot_update_failed`] asks the platform to reload.
1076    pub fn hot_update(&self, update: HotUpdate) {
1077        let _ = self.tx.send(Message::Hot(update));
1078    }
1079
1080    /// Hands over the chunk [`MountSink::load_chunk`] asked for: the
1081    /// dynamic imports waiting for it continue.
1082    pub fn chunk_loaded(&self, chunk: Chunk) {
1083        let _ = self.tx.send(Message::Chunk(Ok(chunk)));
1084    }
1085
1086    /// Chunk `id` could not be loaded: the dynamic imports waiting for it
1087    /// fail with `message` (a later import asks for it again).
1088    pub fn chunk_failed(&self, id: String, message: String) {
1089        let _ = self.tx.send(Message::Chunk(Err((id, message))));
1090    }
1091
1092    /// A display frame began, after [`MountSink::request_frame`]: runs the
1093    /// `requestAnimationFrame` callbacks and the tasks waiting for it.
1094    pub fn frame(&self) {
1095        let _ = self.tx.send(Message::Frame);
1096    }
1097
1098    /// Moves the engine's manual clock ([`EngineConfig::clock`]) forward
1099    /// by `by`: the timers and tasks due meanwhile run in the order they
1100    /// come due, each at its time, with what they make due in turn, and the
1101    /// clock's alarms (a response it holds back) go off on the way. Then
1102    /// `done` runs, after the batches of what ran were submitted. With the
1103    /// system's clock it only runs `done`.
1104    pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
1105        let _ = self.tx.send(Message::Advance(by, Box::new(done)));
1106    }
1107
1108    /// Runs everything sent to the engine before it and everything due on
1109    /// its clock now (timers, woken tasks, answers that came at once), with
1110    /// what they queue in turn, without moving the clock. Then `done` runs,
1111    /// after the batches of what ran were submitted, with whether the
1112    /// engine is idle: nothing is left to run and no request waits for
1113    /// the network. False when work keeps coming (a task that keeps waking
1114    /// itself) or a request is in flight, whose answer comes later from
1115    /// elsewhere. A headless driver on a manual clock settles a step with
1116    /// it, instead of waiting for the batches to stop for a while.
1117    pub fn flush(&self, done: impl FnOnce(bool) + Send + 'static) {
1118        let _ = self.tx.send(Message::Flush(Box::new(done)));
1119    }
1120
1121    /// Reports the interaction states of view `id` that the core asked to
1122    /// track ([`nsh_core::MountItem::TrackStates`]; bits of
1123    /// [`nsh_core::tailwind::state`]). Class styles that depend on them
1124    /// (`active:`, `hover:`, `focus:`) update without JS.
1125    pub fn set_states(&self, id: NodeId, states: u16) {
1126        let _ = self.tx.send(Message::States(id, states));
1127    }
1128
1129    /// Fonts the platform loads asynchronously became usable (on the web,
1130    /// a `FontFace` finished loading): text measured with a fallback font
1131    /// is measured again.
1132    pub fn fonts_changed(&self) {
1133        let _ = self.tx.send(Message::FontsChanged);
1134    }
1135
1136    /// The platform's views get everything again and text is measured
1137    /// again: the unit the platform converts values with changed (Android's
1138    /// density). Send the new environment and size too.
1139    pub fn remount(&self) {
1140        let _ = self.tx.send(Message::Remount);
1141    }
1142
1143    /// Records the engine's commits into `monitor` from now on (`None`:
1144    /// stops). Measuring costs nothing while no monitor is installed.
1145    pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
1146        let _ = self.tx.send(Message::Perf(monitor));
1147    }
1148
1149    /// Sets the embedding app's design tokens (`nsh-base`'s theme's),
1150    /// which the app renders with instead of its own (`None`: its own
1151    /// again; [`Core::set_host_tokens`]). Sent from
1152    /// [`Engine::start_with`]'s `setup`, they are in the first frame.
1153    pub fn set_tokens(&self, tokens: Option<Tokens>) {
1154        let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1155    }
1156}
1157
1158#[cfg(not(target_arch = "wasm32"))]
1159/// A running engine. Dropping it stops the thread.
1160pub struct Engine {
1161    control: EngineControl,
1162    thread: Option<std::thread::JoinHandle<()>>,
1163    /// Serializes shutdown with the embedding app's sends.
1164    host: HostChannel,
1165    /// Interrupts running JS when the engine stops.
1166    stop: Arc<std::sync::atomic::AtomicBool>,
1167    /// The app's disk cache of downloaded images.
1168    image_cache: Option<nsh_core::image::DiskCache>,
1169}
1170
1171#[cfg(not(target_arch = "wasm32"))]
1172impl Engine {
1173    /// Starts the engine thread. `make_text_engine` runs on that thread.
1174    pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
1175    where
1176        M: TextEngine + 'static,
1177        F: FnOnce() -> M + Send + 'static,
1178        S: MountSink,
1179    {
1180        Self::start_with(config, make_text_engine, sink, |_| {})
1181    }
1182
1183    /// [`Engine::start`], with `setup` sending input before the engine
1184    /// starts: what it sends (a theme, the environment) is applied before
1185    /// the first frame.
1186    pub fn start_with<M, F, S>(
1187        config: EngineConfig,
1188        make_text_engine: F,
1189        sink: S,
1190        setup: impl FnOnce(&EngineControl),
1191    ) -> io::Result<Engine>
1192    where
1193        M: TextEngine + 'static,
1194        F: FnOnce() -> M + Send + 'static,
1195        S: MountSink,
1196    {
1197        let image_cache = config.cache.open_images(config.app.app_id());
1198        let (tx, rx) = crossbeam_channel::unbounded();
1199        setup(&EngineControl { tx: tx.clone() });
1200        let engine_tx = tx.clone();
1201        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1202        let engine_stop = stop.clone();
1203        let host = config.host.clone();
1204        let thread = std::thread::Builder::new()
1205            .name("nsh-engine".into())
1206            .stack_size(ENGINE_STACK_SIZE)
1207            .spawn(move || run(config, make_text_engine(), sink, engine_tx, rx, engine_stop))?;
1208        Ok(Engine {
1209            control: EngineControl { tx },
1210            thread: Some(thread),
1211            host,
1212            stop,
1213            image_cache,
1214        })
1215    }
1216
1217    /// The disk cache of the images the app downloads
1218    /// ([`EngineConfig::cache`]; `None`: none). The platform's image loader
1219    /// routes the app's `http(s)` images through it.
1220    pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
1221        self.image_cache.clone()
1222    }
1223
1224    /// A handle for sending input from other threads.
1225    pub fn control(&self) -> EngineControl {
1226        self.control.clone()
1227    }
1228}
1229
1230#[cfg(not(target_arch = "wasm32"))]
1231impl Drop for Engine {
1232    fn drop(&mut self) {
1233        // Dropped on the platform's main thread: a script still running is
1234        // aborted rather than waited for.
1235        self.host.shutdown(&self.control.tx, &self.stop);
1236        if let Some(thread) = self.thread.take() {
1237            let _ = thread.join();
1238        }
1239    }
1240}
1241
1242#[cfg(not(target_arch = "wasm32"))]
1243/// The engine thread turns input into frames: it is as latency-critical as
1244/// the UI thread. Without this, Apple platforms may run it on efficiency
1245/// cores at low clock speeds.
1246fn raise_thread_priority() {
1247    #[cfg(target_vendor = "apple")]
1248    // SAFETY: changes the QoS class of the calling thread only.
1249    unsafe {
1250        libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
1251    }
1252}
1253
1254#[cfg(not(target_arch = "wasm32"))]
1255fn run<M: TextEngine + 'static, S: MountSink>(
1256    config: EngineConfig,
1257    text_engine: M,
1258    sink: S,
1259    tx: Sender<Message>,
1260    rx: Receiver<Message>,
1261    stop: Arc<std::sync::atomic::AtomicBool>,
1262) {
1263    raise_thread_priority();
1264    // The thread's time is the engine's from its first line of JS on.
1265    let _clock = config.clock.enter();
1266    let _context = config.context.enter();
1267    let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
1268        return;
1269    };
1270    loop {
1271        let message = match driver.deadline() {
1272            Some(deadline) => match rx.recv_deadline(deadline) {
1273                Ok(message) => Some(message),
1274                Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
1275                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
1276            },
1277            None => match rx.recv() {
1278                Ok(message) => Some(message),
1279                Err(_) => return,
1280            },
1281        };
1282        let started = driver.state.perf.is_some().then(Instant::now);
1283        if let Some(message) = message {
1284            if !driver.handle(message, &rx) {
1285                return;
1286            }
1287            // Coalesce everything already queued into this frame.
1288            while let Ok(message) = rx.try_recv() {
1289                if !driver.handle(message, &rx) {
1290                    return;
1291                }
1292            }
1293        }
1294        driver.turn();
1295        driver.state.record_perf(started);
1296        if rx.is_empty() {
1297            driver.collect_if_idle();
1298        }
1299    }
1300}
1301
1302/// An engine driven by its host's event loop instead of a thread of its
1303/// own: the browser's main thread in WebAssembly, where there are no
1304/// threads to block. Input sent through its [`EngineControl`] is handled
1305/// at the next [`LocalEngine::pump`].
1306pub struct LocalEngine<M: TextEngine + 'static> {
1307    /// Dropped while this engine's context is the thread's. The guard
1308    /// would otherwise end when `drop` returns, before the fields drop.
1309    driver: ManuallyDrop<Driver<M>>,
1310    rx: Receiver<Message>,
1311    control: EngineControl,
1312    /// The host's wake ([`LocalEngine::set_wake`]).
1313    wake: Option<Arc<dyn Fn() + Send + Sync>>,
1314    /// Set while [`LocalEngine::pump`] runs: what it wakes it runs itself,
1315    /// so the host's wake is not called for it.
1316    pumping: Arc<std::sync::atomic::AtomicBool>,
1317}
1318
1319impl<M: TextEngine + 'static> LocalEngine<M> {
1320    /// Starts the app (its first frame goes to `sink` before this returns);
1321    /// `None` if it could not start (reported to `sink`).
1322    pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
1323        let (tx, rx) = crossbeam_channel::unbounded();
1324        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1325        let control = EngineControl { tx: tx.clone() };
1326        let _clock = config.clock.enter();
1327        let _context = config.context.enter();
1328        let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
1329        Some(LocalEngine {
1330            driver: ManuallyDrop::new(driver),
1331            rx,
1332            control,
1333            wake: None,
1334            pumping: Arc::default(),
1335        })
1336    }
1337
1338    /// A handle for sending input.
1339    pub fn control(&self) -> EngineControl {
1340        self.control.clone()
1341    }
1342
1343    /// Calls `wake` when there is work outside a [`pump`](Self::pump): a
1344    /// component task is woken or Rust posts a JS call while no pump runs
1345    /// (a callback of the host's completing what a task waits for, such as
1346    /// a WebSocket message through wasm-bindgen), once per wake-up, or a
1347    /// pump ends with work its bound left. The host then calls `pump` soon,
1348    /// instead of only at the deadline it returned or at the next input.
1349    /// What a pump wakes itself (a task waking another, a reply it hands
1350    /// over) it runs without calling `wake`.
1351    pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
1352        let tx = self.control.tx.clone();
1353        let pumping = self.pumping.clone();
1354        let host = wake.clone();
1355        let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
1356            let _ = tx.send(Message::Wake);
1357            // After the send: a pump that is ending sees the message
1358            // (`pump` clears the flag, then looks at the queue).
1359            if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
1360                host();
1361            }
1362        });
1363        self.driver.state.core.set_task_notify(notify.clone());
1364        self.driver.posts.set_notify(notify);
1365        self.wake = Some(wake);
1366    }
1367
1368    /// Serves `ui_sets` (a superset of the config's, after a UI set or
1369    /// part was registered while the app runs: the web runtime's late
1370    /// gates) to what is mounted from now on.
1371    pub fn extend_ui_sets(&mut self, ui_sets: &[nsh_core::element::Registry]) {
1372        let sets: Vec<_> = nsh_core::runtime::registries()
1373            .iter()
1374            .chain(ui_sets)
1375            .cloned()
1376            .collect();
1377        self.driver
1378            .state
1379            .core
1380            .extend_components(nsh_core::element::Registry::merged(&sets));
1381    }
1382
1383    /// Handles the input sent since the last call, runs what is due
1384    /// (timers, tasks) and commits. Returns when to call again at the
1385    /// latest (sooner if input arrives); `None`: only for input.
1386    pub fn pump(&mut self) -> Option<Instant> {
1387        let _clock = self.driver.clock.enter();
1388        let _context = self.driver.context.enter();
1389        self.pumping
1390            .store(true, std::sync::atomic::Ordering::SeqCst);
1391        // Bounded: messages sent while handling (a task waking another)
1392        // are handled in the same call, a loop that never settles is not.
1393        for _ in 0..4 {
1394            let started = self.driver.state.perf.is_some().then(Instant::now);
1395            while let Ok(message) = self.rx.try_recv() {
1396                self.driver.handle(message, &self.rx);
1397            }
1398            self.driver.turn();
1399            self.driver.state.record_perf(started);
1400            if self.rx.is_empty() {
1401                break;
1402            }
1403        }
1404        self.driver.collect_if_idle();
1405        self.pumping
1406            .store(false, std::sync::atomic::Ordering::SeqCst);
1407        // What the bound left waits for the next pump: soon, not at the
1408        // deadline.
1409        if !self.rx.is_empty()
1410            && let Some(wake) = &self.wake
1411        {
1412            wake();
1413        }
1414        self.driver.deadline()
1415    }
1416}
1417
1418impl<M: TextEngine + 'static> Drop for LocalEngine<M> {
1419    fn drop(&mut self) {
1420        // Cancelling tasks and dropping what they captured reads this
1421        // engine's context. `run` keeps its guard across the driver's
1422        // drop; this path enters for the drop itself.
1423        let _context = self.driver.context.enter();
1424        // SAFETY: `driver` is dropped once, here. `ManuallyDrop` keeps
1425        // the field drop from dropping it again.
1426        unsafe { ManuallyDrop::drop(&mut self.driver) };
1427    }
1428}
1429
1430/// One engine's state and the work of one wake-up, whoever drives it.
1431struct Driver<M: TextEngine + 'static> {
1432    state: State<Rc<M>>,
1433    script: Option<Script>,
1434    sink: Rc<dyn MountSink>,
1435    assets: Option<Arc<dyn Assets>>,
1436    /// A VM stopped for good (out of memory, over a quota) is reported
1437    /// once; its views stay as they were and no JS runs any more.
1438    stopped: bool,
1439    last_gc: Instant,
1440    /// When a message or a due timer last gave the engine work
1441    /// ([`IDLE_GC_QUIET`]).
1442    last_active: Instant,
1443    /// The queue of the JS calls Rust posts: its notify wakes the engine,
1444    /// as the core's task notify does ([`LocalEngine::set_wake`]).
1445    posts: nsh_core::element::Posts,
1446    /// The engine's clock, its thread's ([`Clock::enter`]).
1447    clock: Clock,
1448    /// The host's context, its thread's ([`EngineContext::enter`]).
1449    context: EngineContext,
1450    /// When the last display frame ran, on a clock that moves with the
1451    /// display's frames: the next one comes a frame after it.
1452    last_frame: Option<Instant>,
1453    /// The engine's attachment to the embedding app's channel: its events
1454    /// come here while the engine runs.
1455    _host: host_channel::HostAttachment,
1456}
1457
1458impl<M: TextEngine + 'static> Driver<M> {
1459    /// Sets up the core, starts the app and submits its first frame.
1460    fn start(
1461        mut config: EngineConfig,
1462        text_engine: M,
1463        sink: Rc<dyn MountSink>,
1464        tx: Sender<Message>,
1465        rx: &Receiver<Message>,
1466        stop: Arc<std::sync::atomic::AtomicBool>,
1467    ) -> Option<Self> {
1468        config.pinned.apply(&mut config.environment);
1469        #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
1470        let system_tx = tx.clone();
1471        #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
1472        let host_bridge = config.host.bridge(tx.clone());
1473        let host_tx = tx.clone();
1474        let text_engine = Rc::new(text_engine);
1475        let access = Arc::new(match &config.app {
1476            App::Js(bundle) => bundle.policy.access(),
1477            // Native code is trusted: it reaches what the platform allows.
1478            App::Rust(_) => Policy::default().access(),
1479        });
1480        let mut core = Core::new(text_engine.clone(), config.viewport);
1481        // The runtime's components (`nsh/mobile`'s `TabBar`) and the UI
1482        // sets the host serves.
1483        let sets: Vec<_> = nsh_core::runtime::registries()
1484            .iter()
1485            .chain(&config.ui_sets)
1486            .cloned()
1487            .collect();
1488        core.set_components(nsh_core::element::Registry::merged(&sets));
1489        // The JS calls Rust posts queue in one place, which the core
1490        // releases in order with the ops (a post during a synchronous call)
1491        // and the script runs.
1492        let posts = nsh_core::element::Posts::new();
1493        core.set_posts(posts.clone());
1494        if let App::Js(_) = &config.app {
1495            // Only JS is limited (Rust code is as trusted as the platform).
1496            core.set_max_nodes(config.limits.max_nodes);
1497        }
1498        core.set_access(access.clone());
1499        #[cfg(not(target_arch = "wasm32"))]
1500        core.set_image_context(nsh_core::image::loader::Context {
1501            asset_base: config.assets.as_ref().and_then(|a| a.base()),
1502            read_asset: config.assets.clone().map(|assets| {
1503                Arc::new(move |uri: &str| assets.read(uri)) as nsh_core::image::loader::ReadAsset
1504            }),
1505            access: access.clone(),
1506            // The same cache as the platform's ([`Engine::image_cache`]).
1507            disk: config.cache.open_images(config.app.app_id()),
1508            // The platform's, if it set one ([`nsh_core::image::loader::set_transport`]).
1509            transport: None,
1510        });
1511        core.set_storage(app_storage(&config));
1512        core.set_clipboard(config.clipboard.clone());
1513        core.set_picker(config.picker.clone());
1514        core.set_speech(config.speech.clone());
1515        core.set_font_scale(config.environment.font_scale);
1516        core.set_class_environment(class_environment(&config.environment));
1517        core.set_header_heights(config.header_heights.0, config.header_heights.1);
1518        core.set_safe_area(insets(&config.environment));
1519        core.set_environment(ui_environment(&config.environment, config.viewport));
1520        // WebAssembly has no threads for a runtime: tasks' timers are
1521        // `nsh_core::time`'s there, fired by the driver.
1522        #[cfg(not(target_arch = "wasm32"))]
1523        let runtime = config.runtime.clone().unwrap_or_else(shared_runtime);
1524        #[cfg(not(target_arch = "wasm32"))]
1525        core.set_task_runtime(runtime.clone());
1526        // A Rust app's theme and fonts come with its root (a JS app's from
1527        // its bundle).
1528        if let App::Rust(root) = &config.app {
1529            if let Some(tokens) = root.tokens_ref() {
1530                core.set_tokens(tokens.clone());
1531            }
1532            if let Some(appearance) = root.appearance_ref() {
1533                core.set_appearance(appearance);
1534            }
1535            for font in root.fonts() {
1536                if let Err(err) = core.register_font(font) {
1537                    log::error!("font failed: {err}");
1538                    sink.report(&AppError::new(
1539                        AppErrorKind::Asset,
1540                        &format!("font failed: {err}"),
1541                    ));
1542                }
1543            }
1544        }
1545        // The fonts the UI sets' crates ship, before anything is measured.
1546        let fonts = config
1547            .ui_sets
1548            .iter()
1549            .flat_map(nsh_core::element::Registry::asset_files)
1550            .filter(|file| file.kind == nsh_core::element::AssetKind::Font);
1551        for font in fonts {
1552            let result = match config.assets.as_deref() {
1553                Some(assets) => assets.read(font.uri),
1554                None => Err("this host cannot load assets".to_owned()),
1555            }
1556            .and_then(|data| core.register_font(&data));
1557            if let Err(err) = result {
1558                log::error!("font failed: {}: {err}", font.uri);
1559                let message = format!("font failed: {}: {err}", font.uri);
1560                let package = match &config.app {
1561                    App::Js(bundle) => bundle.package.clone(),
1562                    App::Rust(_) => None,
1563                };
1564                sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
1565            }
1566        }
1567        // A task woken on any thread wakes the loop, and so does a JS call
1568        // Rust queues.
1569        let wake = tx.clone();
1570        core.set_task_notify(Arc::new(move || {
1571            let _ = wake.send(Message::Wake);
1572        }));
1573        let wake = tx.clone();
1574        posts.set_notify(Arc::new(move || {
1575            let _ = wake.send(Message::Wake);
1576        }));
1577        // The embedding app's tokens sent before the start
1578        // (`Engine::start_with`) are there as the bundle evaluates, so its
1579        // first render reads them; the rest comes after it, in order.
1580        let mut early = Vec::new();
1581        while let Ok(message) = rx.try_recv() {
1582            match message {
1583                Message::Tokens(tokens) => core.set_host_tokens(tokens.map(|t| *t)),
1584                message => early.push(message),
1585            }
1586        }
1587        let js_tokens = core.tokens().clone();
1588        let state = State {
1589            core,
1590            js_tokens,
1591            frame_requested: false,
1592            ops: Vec::new(),
1593            binds: Vec::new(),
1594            events: Vec::new(),
1595            trace: config.trace,
1596            perf: None,
1597            perf_commit: perf::CommitTiming::default(),
1598            committed_since_gc: false,
1599            hot: Vec::new(),
1600            scroll_events: FxHashMap::default(),
1601            touch_move: None,
1602            mouse_moves: Vec::new(),
1603            mouse_moved: None,
1604            sets_seen: FxHashMap::default(),
1605            resized: None,
1606            events_handled: 0,
1607            events_reported: 0,
1608            pinned: config.pinned,
1609            host: config.host.clone(),
1610            url_opens: Vec::new(),
1611            net: Net {
1612                network: config.network.clone(),
1613                tx,
1614                queue: NetworkQueue::default(),
1615                inflight: FxHashMap::default(),
1616                tasks: Vec::new(),
1617                abandoned: Vec::new(),
1618                access: access.clone(),
1619                hops: 0,
1620                assets: config.assets.clone(),
1621                #[cfg(not(target_arch = "wasm32"))]
1622                runtime,
1623            },
1624        };
1625
1626        let mut environment = config.environment;
1627        environment.window = config.viewport;
1628        let start = Instant::now();
1629        let mut driver = Driver {
1630            state,
1631            script: None,
1632            sink: sink.clone(),
1633            assets: config.assets.clone(),
1634            stopped: false,
1635            last_gc: Instant::now(),
1636            last_active: Instant::now(),
1637            posts: posts.clone(),
1638            clock: config.clock.clone(),
1639            context: config.context.clone(),
1640            last_frame: None,
1641            _host: config.host.attach(host_tx, rx.clone()),
1642        };
1643        let eval_us = match &config.app {
1644            App::Js(bundle) => {
1645                #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
1646                let system = {
1647                    script::SystemConfig {
1648                        access: (*access).clone(),
1649                        websocket: config.websocket.clone(),
1650                        refuse_connections: config.refuse_connections.clone(),
1651                        filesystem: config.filesystem.clone(),
1652                        data_dir: config
1653                            .data_dir
1654                            .as_ref()
1655                            .map(|root| root.join(app_dir_name(config.app.app_id()))),
1656                        paths: bundle_system_paths(bundle),
1657                        wake: Arc::new(move || {
1658                            let _ = system_tx.send(Message::Wake);
1659                        }),
1660                        host: Rc::new(host_bridge),
1661                    }
1662                };
1663                #[cfg(not(any(
1664                    feature = "js-core",
1665                    all(feature = "browser", target_arch = "wasm32")
1666                )))]
1667                let system = script::SystemConfig;
1668                let (script, eval_us) = Script::start(
1669                    bundle,
1670                    config.limits,
1671                    &config.ui_sets,
1672                    posts,
1673                    &environment,
1674                    driver.state.js_tokens.clone(),
1675                    driver.state.core.theme_tokens(),
1676                    text_engine,
1677                    stop,
1678                    sink,
1679                    system,
1680                )?;
1681                driver.script = Some(script);
1682                eval_us
1683            }
1684            App::Rust(root) => {
1685                driver.state.core.mount_root(root);
1686                0
1687            }
1688        };
1689        let Driver {
1690            state,
1691            script,
1692            sink,
1693            assets,
1694            ..
1695        } = &mut driver;
1696        let script = script.as_ref();
1697        // What was sent before the start (`Engine::start_with`) is in the
1698        // first frame; a move of the clock comes after it.
1699        let mut moves = Vec::new();
1700        let pending = early
1701            .into_iter()
1702            .chain(std::iter::from_fn(|| rx.try_recv().ok()));
1703        for message in pending {
1704            if let Message::Advance(..) | Message::Flush(..) = message {
1705                moves.push(message);
1706            } else if !handle(script, state, message) {
1707                return None;
1708            }
1709        }
1710        // Workers may finish while the first bundle evaluates. Deliver their
1711        // completions even when the startup drain already consumed their wakeup.
1712        if let Some(script) = script {
1713            script.run_system();
1714        }
1715        state.load_fonts(script, assets.as_deref(), &**sink);
1716        if let Some(batch) = state.commit(script) {
1717            if state.trace {
1718                log::info!(
1719                    target: "nsh::perf",
1720                    "first frame: eval {eval_us}µs, total {}µs",
1721                    start.elapsed().as_micros()
1722                );
1723            }
1724            sink.submit(batch);
1725        }
1726        state.report_handled(&**sink);
1727        state.net.pump(script, &mut state.core);
1728        state.load_chunks(script, &**sink);
1729        state.request_frame(script, &**sink);
1730        driver.check_stopped();
1731        for message in moves {
1732            if !driver.handle(message, rx) {
1733                return None;
1734            }
1735        }
1736        Some(driver)
1737    }
1738
1739    /// When the loop wakes next: for the next timer or throttled event
1740    /// (on the system's clock; a manual one moves only when told), or the
1741    /// idle collection (the system's time, whatever the clock).
1742    fn deadline(&self) -> Option<Instant> {
1743        let gc_deadline =
1744            (self.script.is_some() && self.state.committed_since_gc).then(|| self.next_gc());
1745        let due = if self.clock.is_manual() {
1746            None
1747        } else {
1748            self.due()
1749        };
1750        [due, gc_deadline].into_iter().flatten().min()
1751    }
1752
1753    /// When the next timer, task timer or throttled scroll or mouse move
1754    /// is due, on the engine's clock.
1755    fn due(&self) -> Option<Instant> {
1756        [
1757            self.script.as_ref().and_then(Script::next_timer),
1758            self.state.next_scroll_event(),
1759            self.state.next_mouse_move(),
1760            self.state.core.next_task_timer(),
1761        ]
1762        .into_iter()
1763        .flatten()
1764        .min()
1765    }
1766
1767    /// Handles one message; false on shutdown.
1768    fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
1769        self.last_active = Instant::now();
1770        match message {
1771            Message::Advance(by, done) => {
1772                let running = self.advance(by, rx, self.clock.moves_with_frames());
1773                done();
1774                running
1775            }
1776            Message::Flush(done) => {
1777                let running = self.flush(rx);
1778                done(running && self.idle(rx));
1779                running
1780            }
1781            // A test's clock on a real platform: the display's frame moves it
1782            // to the frame's time first (a frame after the last, else now),
1783            // as a headless run's frames do.
1784            Message::Frame if self.clock.moves_with_frames() => {
1785                // The frame runs there, once, as the frames a move runs on
1786                // the way do (whatever the messages handled meanwhile do).
1787                self.state.frame_requested = true;
1788                let by = self.next_frame() - self.clock.now();
1789                self.advance(by, rx, true)
1790            }
1791            message => handle(self.script.as_ref(), &mut self.state, message),
1792        }
1793    }
1794
1795    /// Moves a manual clock forward by `by` ([`EngineControl::advance_clock`]):
1796    /// to each time something comes due on the way, running it (and the
1797    /// messages its alarms sent) before going on; with `frames`, also to
1798    /// each display frame's time ([`nsh_core::time::FRAME`]) while the app
1799    /// waits for frames, running the frame there, as a headless run's
1800    /// display does (a clock that moves with a real display's frames:
1801    /// [`Clock::with_frames`]). False on shutdown.
1802    fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
1803        if !self.clock.is_manual() {
1804            // What the messages before it did is submitted before `done`.
1805            self.turn();
1806            return true;
1807        }
1808        let to = self.clock.now() + by;
1809        for round in 0.. {
1810            // A timer that keeps scheduling itself at once (`setTimeout(f,
1811            // 0)` in `f`) would hold the clock at one time for good.
1812            let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
1813            let next = [self.due(), self.clock.next_alarm(), frame]
1814                .into_iter()
1815                .flatten()
1816                .min()
1817                .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
1818            if round == MAX_ADVANCE_ROUNDS {
1819                log::warn!(
1820                    "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
1821                     a timer keeps scheduling another at once"
1822                );
1823            }
1824            let at = next.unwrap_or(to);
1825            self.clock.advance_to(at);
1826            while let Ok(message) = rx.try_recv() {
1827                if !self.handle(message, rx) {
1828                    return false;
1829                }
1830            }
1831            // Once: what was handled meanwhile may have run it already.
1832            if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
1833                && self.state.frame_requested
1834            {
1835                self.frame();
1836            }
1837            self.turn();
1838            if next.is_none() {
1839                break;
1840            }
1841        }
1842        true
1843    }
1844
1845    /// Runs what is queued and what is due now ([`EngineControl::flush`]),
1846    /// again while that queues more, [`MAX_FLUSH_ROUNDS`] times at most.
1847    /// False on shutdown.
1848    fn flush(&mut self, rx: &Receiver<Message>) -> bool {
1849        let frames = self.clock.moves_with_frames();
1850        for _ in 0..MAX_FLUSH_ROUNDS {
1851            while let Ok(message) = rx.try_recv() {
1852                if !self.handle(message, rx) {
1853                    return false;
1854                }
1855            }
1856            // A manual clock stays where it is: what is due now runs.
1857            if !self.advance(std::time::Duration::ZERO, rx, frames) {
1858                return false;
1859            }
1860            // What a turn queued (a task's wake, a response answered at
1861            // once) runs too, as long as it stops coming.
1862            if rx.is_empty() {
1863                break;
1864            }
1865        }
1866        true
1867    }
1868
1869    /// Whether nothing is left to run: no message queued, nothing due at
1870    /// the clock's time (a timer that keeps scheduling another at once
1871    /// outlasts a flush's rounds) and no request in flight.
1872    fn idle(&self, rx: &Receiver<Message>) -> bool {
1873        let now = self.clock.now();
1874        rx.is_empty()
1875            && self.state.net.idle()
1876            && [self.due(), self.clock.next_alarm()]
1877                .into_iter()
1878                .flatten()
1879                .all(|at| at > now)
1880    }
1881
1882    /// When the next display frame of a clock that moves with the
1883    /// display's frames is: a frame after the last, at the display's pace
1884    /// whatever else comes due meanwhile, else (the first, or after a
1885    /// pause) a frame from now or now.
1886    fn next_frame(&self) -> Instant {
1887        let now = self.clock.now();
1888        self.last_frame
1889            .map_or(now + nsh_core::time::FRAME, |last| {
1890                last + nsh_core::time::FRAME
1891            })
1892            .max(now)
1893    }
1894
1895    /// Runs a display frame of a clock that moves with the display's
1896    /// frames, now.
1897    fn frame(&mut self) {
1898        self.last_frame = Some(self.clock.now());
1899        handle(self.script.as_ref(), &mut self.state, Message::Frame);
1900    }
1901
1902    /// Runs what the handled messages and the time made due, and submits
1903    /// the frame.
1904    fn turn(&mut self) {
1905        let Driver {
1906            state,
1907            script,
1908            sink,
1909            assets,
1910            ..
1911        } = self;
1912        let script = script.as_ref();
1913        if script
1914            .and_then(Script::next_timer)
1915            .is_some_and(|due| due <= nsh_core::time::now())
1916        {
1917            self.last_active = Instant::now();
1918        }
1919        let turn_start = state.trace.then(Instant::now);
1920        state.dispatch_touch_move(script);
1921        if state
1922            .next_mouse_move()
1923            .is_some_and(|due| due <= nsh_core::time::now())
1924        {
1925            state.dispatch_mouse_moves(script);
1926        }
1927        state.dispatch_scroll_events(script);
1928        let hot = std::mem::take(&mut state.hot);
1929        if let Some(script) = script {
1930            for update in hot {
1931                script.hot_update(update, &**sink);
1932            }
1933            script.run_timers(nsh_core::time::now());
1934            script.run_system();
1935        }
1936        state.core.run_component_tasks();
1937        // What JS timers and Rust component tasks took; a Rust component
1938        // renders in the commit.
1939        let tasks = turn_start.map(|s| s.elapsed());
1940        state.load_fonts(script, assets.as_deref(), &**sink);
1941        if let Some(batch) = state.commit(script) {
1942            sink.submit(batch);
1943            if let (Some(start), Some(tasks)) = (turn_start, tasks) {
1944                log::info!(
1945                    target: "nsh::perf",
1946                    "turn: {}µs (timers and tasks {}µs)",
1947                    start.elapsed().as_micros(),
1948                    tasks.as_micros(),
1949                );
1950            }
1951        }
1952        if let Some(size) = state.resized.take() {
1953            sink.resized(size);
1954        }
1955        state.report_handled(&**sink);
1956        state.net.pump(script, &mut state.core);
1957        state.load_chunks(script, &**sink);
1958        state.request_frame(script, &**sink);
1959        self.check_stopped();
1960    }
1961
1962    /// When the next idle collection may run: a second after the last, once
1963    /// the engine has been quiet for [`IDLE_GC_QUIET`] (or at the latest
1964    /// [`IDLE_GC_LONGEST`] after the last).
1965    fn next_gc(&self) -> Instant {
1966        let quiet = (self.last_active + IDLE_GC_QUIET).min(self.last_gc + IDLE_GC_LONGEST);
1967        (self.last_gc + IDLE_GC_INTERVAL).max(quiet)
1968    }
1969
1970    /// Collects cycles when the engine has been idle long enough, so
1971    /// released nodes free their views.
1972    fn collect_if_idle(&mut self) {
1973        if let Some(script) = &self.script
1974            && self.state.committed_since_gc
1975            && Instant::now() >= self.next_gc()
1976        {
1977            let start = self.state.trace.then(Instant::now);
1978            script.collect_garbage();
1979            if let Some(start) = start {
1980                log::info!(target: "nsh::perf", "gc: {}µs", start.elapsed().as_micros());
1981            }
1982            self.last_gc = Instant::now();
1983            self.state.committed_since_gc = false;
1984            if let Some(batch) = self.state.commit(Some(script)) {
1985                self.sink.submit(batch);
1986            }
1987        }
1988    }
1989
1990    fn check_stopped(&mut self) {
1991        if let Some(script) = &self.script
1992            && !self.stopped
1993            && let Some(reason) = script.fatal()
1994        {
1995            self.stopped = true;
1996            script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
1997        }
1998    }
1999}
2000
2001struct ScrollEvent {
2002    x: f32,
2003    y: f32,
2004    content: Size<Points>,
2005    viewport: Size<Points>,
2006    /// The zoom scale.
2007    zoom: f32,
2008    throttle: Duration,
2009    last: Option<Instant>,
2010    /// An offset not reported yet.
2011    pending: bool,
2012}
2013
2014struct State<M: TextEngine> {
2015    core: Core<M>,
2016    /// The design tokens JS has (`token()`): the core's when they were
2017    /// last sent.
2018    js_tokens: Arc<nsh_core::element::Tokens>,
2019    /// What the environment keeps whatever the platform reports
2020    /// ([`EngineConfig::pinned`]).
2021    pinned: EnvironmentPins,
2022    /// A display frame was requested and has not begun yet.
2023    frame_requested: bool,
2024    ops: Vec<Op>,
2025    /// List render requests not yet sent to JS.
2026    binds: Vec<ListBind>,
2027    /// Events raised by the core (e.g. `onLoadMore`, `onLayout`).
2028    events: Vec<JsEvent>,
2029    trace: bool,
2030    /// Where commit timings go ([`EngineControl::set_perf_monitor`]).
2031    perf: Option<Arc<perf::PerfMonitor>>,
2032    /// The core's share of the wake-up being measured (`layout`, `ops`,
2033    /// `items`; `js` is the rest of the wake-up).
2034    perf_commit: perf::CommitTiming,
2035    committed_since_gc: bool,
2036    /// The embedding app's channel: its URL handler sees the app's URLs
2037    /// first.
2038    host: HostChannel,
2039    /// URLs the app asked to open, taken from the core (a reused buffer).
2040    url_opens: Vec<(u32, String)>,
2041    net: Net,
2042    /// Development updates to apply.
2043    hot: Vec<HotUpdate>,
2044    /// `onScroll` events: the latest offset per scroll view, sent once per
2045    /// frame at most (and not more often than the view's throttle).
2046    scroll_events: FxHashMap<NodeId, ScrollEvent>,
2047    /// Touch moves not delivered yet: those queued in one frame become one.
2048    touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
2049    /// Mouse moves not delivered yet: the latest per view, in the order they
2050    /// came; sent once per [`MOUSE_MOVE_INTERVAL`] at most, and before
2051    /// any other event.
2052    mouse_moves: Vec<(NodeId, EventPayload)>,
2053    /// When `mouse_moves` were last delivered.
2054    mouse_moved: Option<Instant>,
2055    /// [`keep_last_sets`]'s buffer, reused.
2056    sets_seen: FxHashMap<(u8, NodeId), usize>,
2057    /// The viewport size a resize set this turn ([`MountSink::resized`]).
2058    resized: Option<Size<Points>>,
2059    /// Events received ([`EngineControl::dispatch_event`]), and the count
2060    /// last reported ([`MountSink::handled`]).
2061    events_handled: u64,
2062    events_reported: u64,
2063}
2064
2065/// Who made a request: JS (`fetch`), or a Rust component's task
2066/// (`nsh_core::element::fetch`, [`Core::take_fetches`]).
2067#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2068enum Requester {
2069    Js(RequestId),
2070    Task(u32),
2071}
2072
2073/// Requests between the app (JS and Rust components' tasks) and the
2074/// platform's network stack.
2075struct Net {
2076    network: Option<Arc<dyn Network>>,
2077    tx: Sender<Message>,
2078    queue: NetworkQueue,
2079    inflight: FxHashMap<Requester, Inflight>,
2080    /// The tasks' requests taken from the core, and those they gave up
2081    /// (reused buffers).
2082    tasks: Vec<(u32, HttpRequest)>,
2083    abandoned: Vec<u32>,
2084    /// What the app may reach.
2085    access: Arc<nsh_core::access::Access>,
2086    /// Hops started so far (the id of the next).
2087    hops: u64,
2088    /// Where requests of `asset:/` URLs are answered from
2089    /// ([`EngineConfig::assets`]).
2090    assets: Option<Arc<dyn Assets>>,
2091    /// The runtime whose blocking pool reads them (the components'
2092    /// tasks').
2093    #[cfg(not(target_arch = "wasm32"))]
2094    runtime: tokio::runtime::Handle,
2095}
2096
2097/// The task of a request for a bundled file while it is read: the read
2098/// finishes on its own, and a cancelled request drops what it gives.
2099struct AssetTask;
2100
2101impl FetchTask for AssetTask {
2102    fn send(&mut self, _: Vec<u8>) {}
2103    fn finish(&mut self) {}
2104    fn pause(&mut self, _: bool) {}
2105    fn cancel(self: Box<Self>) {}
2106}
2107
2108/// Whether `url` names a bundled file (`asset:/…`).
2109fn is_asset(url: &str) -> bool {
2110    url.get(..6)
2111        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("asset:"))
2112}
2113
2114/// Whether the bundled file `url` names stays inside the app's files
2115/// whichever way a host maps `asset:/<path>` to its asset directory: the
2116/// path is relative, and no segment is empty, `.` or `..` (encoded or not)
2117/// or holds a backslash, a NUL or a colon (a Windows drive). Hosts join the
2118/// path to their directory as it comes, so they never see one that
2119/// escapes it.
2120fn is_inside_assets(url: &str) -> bool {
2121    let Some(path) = url.get(6..).and_then(|rest| rest.strip_prefix('/')) else {
2122        return false;
2123    };
2124    path.split('/').all(|segment| {
2125        let segment = segment.to_ascii_lowercase();
2126        let named = !matches!(segment.replace("%2e", ".").as_str(), "" | "." | "..");
2127        let plain = !segment.contains(['\\', '\0', ':'])
2128            && !["%2f", "%5c", "%00", "%3a"]
2129                .iter()
2130                .any(|encoded| segment.contains(encoded));
2131        named && plain
2132    })
2133}
2134
2135/// The media type a bundled file's response carries, from its extension:
2136/// the dev server's (`nsh-dev`'s `content_type`), so a file read from the
2137/// app's files and one downloaded from where a web app serves them answer
2138/// with the same type.
2139fn asset_type(url: &str) -> &'static str {
2140    let name = url.rsplit('/').next().unwrap_or_default();
2141    let extension = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
2142    match extension.as_deref() {
2143        Some("html") => "text/html; charset=utf-8",
2144        Some("js" | "mjs") => "text/javascript; charset=utf-8",
2145        Some("json" | "map") => "application/json",
2146        Some("webmanifest") => "application/manifest+json",
2147        Some("wasm") => "application/wasm",
2148        Some("css") => "text/css; charset=utf-8",
2149        Some("txt") => "text/plain; charset=utf-8",
2150        Some("png") => "image/png",
2151        Some("jpg" | "jpeg") => "image/jpeg",
2152        Some("gif") => "image/gif",
2153        Some("webp") => "image/webp",
2154        Some("avif") => "image/avif",
2155        Some("svg") => "image/svg+xml",
2156        Some("ico") => "image/x-icon",
2157        Some("heic") => "image/heic",
2158        Some("ttf") => "font/ttf",
2159        Some("otf") => "font/otf",
2160        Some("woff") => "font/woff",
2161        Some("woff2") => "font/woff2",
2162        Some("mp4" | "m4v") => "video/mp4",
2163        Some("webm") => "video/webm",
2164        Some("mov") => "video/quicktime",
2165        Some("mp3") => "audio/mpeg",
2166        Some("m4a") => "audio/mp4",
2167        Some("wav") => "audio/wav",
2168        _ => "application/octet-stream",
2169    }
2170}
2171
2172/// A request in flight.
2173struct Inflight {
2174    task: Box<dyn FetchTask>,
2175    /// The hop the task is.
2176    hop: u64,
2177    /// Requests whose redirects the engine follows (to check each hop).
2178    followed: Option<access::Followed>,
2179    /// The bundled file (`asset:/…`) a download is of: a status other than
2180    /// a success fails it, as a file the host does not have does.
2181    asset: Option<String>,
2182}
2183
2184impl Net {
2185    /// Whether no request waits for the network.
2186    fn idle(&self) -> bool {
2187        self.inflight.is_empty()
2188    }
2189
2190    /// Hands what JS and the components' tasks asked of their requests to
2191    /// the network.
2192    fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
2193        let mut abandoned = std::mem::take(&mut self.abandoned);
2194        core.take_fetches(&mut self.tasks, &mut abandoned);
2195        for id in abandoned.drain(..) {
2196            self.cancel(Requester::Task(id));
2197        }
2198        self.abandoned = abandoned;
2199        let mut tasks = std::mem::take(&mut self.tasks);
2200        for (id, request) in tasks.drain(..) {
2201            if let Err(refused) = self.request(Requester::Task(id), request) {
2202                core.fetch_event(id, FetchEvent::Failed(refused.message));
2203            }
2204        }
2205        self.tasks = tasks;
2206        let Some(script) = script else { return };
2207        script.take_network(&mut self.queue);
2208        for (id, op) in std::mem::take(&mut self.queue.ops) {
2209            let who = Requester::Js(id);
2210            match op {
2211                FetchOp::Start(request) => {
2212                    if let Err(refused) = self.request(who, request) {
2213                        script.fetch_refused(id, &refused.message, &refused.url);
2214                    }
2215                }
2216                FetchOp::Send(chunk) => {
2217                    if let Some(i) = self.inflight.get_mut(&who) {
2218                        i.task.send(chunk);
2219                    }
2220                }
2221                FetchOp::Finish => {
2222                    if let Some(i) = self.inflight.get_mut(&who) {
2223                        i.task.finish();
2224                    }
2225                }
2226                FetchOp::Pause(paused) => {
2227                    if let Some(i) = self.inflight.get_mut(&who) {
2228                        i.task.pause(paused);
2229                    }
2230                }
2231                FetchOp::Cancel => self.cancel(who),
2232            }
2233        }
2234    }
2235
2236    /// Aborts `who`'s request.
2237    fn cancel(&mut self, who: Requester) {
2238        if let Some(i) = self.inflight.remove(&who) {
2239            i.task.cancel();
2240        }
2241    }
2242
2243    /// Makes `who`'s request, if the app may (else why not). Bundled files
2244    /// are the app's own: their requests need no capability.
2245    fn request(&mut self, who: Requester, request: HttpRequest) -> Result<(), access::Refused> {
2246        if is_asset(&request.url) {
2247            self.asset(who, request);
2248        } else if self.access.is_unrestricted() {
2249            self.start(who, request, None);
2250        } else if !self.access.allows_http(&request.method, &request.url) {
2251            return Err(access::refused(&request.method, &request.url));
2252        } else if request.follow_redirects {
2253            let hop = access::hop(&request);
2254            let followed = access::Followed { request, hops: 0 };
2255            self.start(who, hop, Some(followed));
2256        } else {
2257            self.start(who, request, None);
2258        }
2259        Ok(())
2260    }
2261
2262    /// Hands one request (or redirect hop) to the network.
2263    fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
2264        self.hops += 1;
2265        let hop = self.hops;
2266        let Some(network) = &self.network else {
2267            let failed = FetchEvent::Failed("this host has no network stack".to_owned());
2268            let _ = self.tx.send(Message::Fetch(id, hop, failed));
2269            return;
2270        };
2271        let tx = self.tx.clone();
2272        let events: FetchEvents = Box::new(move |event| {
2273            let _ = tx.send(Message::Fetch(id, hop, event));
2274        });
2275        let task = network.fetch(request, events);
2276        self.inflight.insert(
2277            id,
2278            Inflight {
2279                task,
2280                hop,
2281                followed,
2282                asset: None,
2283            },
2284        );
2285    }
2286
2287    /// Answers `who`'s request of a bundled file (an `asset:/` URL) from
2288    /// the host's assets: read on the runtime's blocking pool, which reports
2289    /// with [`Message::AssetRead`] (in WebAssembly, which has no threads,
2290    /// here).
2291    fn asset(&mut self, who: Requester, request: HttpRequest) {
2292        self.hops += 1;
2293        let hop = self.hops;
2294        self.inflight.insert(
2295            who,
2296            Inflight {
2297                task: Box::new(AssetTask),
2298                hop,
2299                followed: None,
2300                asset: None,
2301            },
2302        );
2303        // Failed here, before any host reads the file or serves it
2304        // ([`Assets::url`]): a request no host may answer reaches none.
2305        let refused = if !is_inside_assets(&request.url) {
2306            Some(format!(
2307                "{}: bundled files are named by a path inside the app's files",
2308                request.url
2309            ))
2310        } else if !matches!(request.method.as_str(), "GET" | "HEAD") {
2311            Some(format!(
2312                "{} {}: bundled files are read with GET",
2313                request.method, request.url
2314            ))
2315        } else {
2316            None
2317        };
2318        if let Some(refused) = refused {
2319            let _ = self
2320                .tx
2321                .send(Message::Fetch(who, hop, FetchEvent::Failed(refused)));
2322            return;
2323        }
2324        let Some(assets) = &self.assets else {
2325            let failed = Err("this host cannot load assets".to_owned());
2326            self.asset_read(who, hop, request, failed);
2327            return;
2328        };
2329        #[cfg(not(target_arch = "wasm32"))]
2330        {
2331            let assets = assets.clone();
2332            let tx = self.tx.clone();
2333            // The read reports itself; nothing awaits its handle.
2334            drop(self.runtime.spawn_blocking(move || {
2335                let bytes = assets.read(&request.url);
2336                let _ = tx.send(Message::AssetRead(who, hop, request, bytes));
2337            }));
2338        }
2339        #[cfg(target_arch = "wasm32")]
2340        {
2341            let bytes = assets.read(&request.url);
2342            self.asset_read(who, hop, request, bytes);
2343        }
2344    }
2345
2346    /// Hop `hop` of `who`'s request of a bundled file read it: its response,
2347    /// or, when the host has no copy but serves the file at a URL
2348    /// ([`Assets::url`]), the download of it. Only requests [`Net::asset`]
2349    /// let through come here. Dropped when the request was cancelled
2350    /// meanwhile.
2351    fn asset_read(
2352        &mut self,
2353        who: Requester,
2354        hop: u64,
2355        request: HttpRequest,
2356        read: Result<Vec<u8>, String>,
2357    ) {
2358        if self.inflight.get(&who).is_none_or(|i| i.hop != hop) {
2359            return;
2360        }
2361        let events = match read {
2362            Ok(bytes) => {
2363                let head = HttpHead {
2364                    status: 200,
2365                    status_text: "OK".to_owned(),
2366                    headers: vec![
2367                        ("content-length".to_owned(), bytes.len().to_string()),
2368                        (
2369                            "content-type".to_owned(),
2370                            asset_type(&request.url).to_owned(),
2371                        ),
2372                    ],
2373                    url: request.url.clone(),
2374                    ..HttpHead::default()
2375                };
2376                let mut events = vec![FetchEvent::Head(head)];
2377                if request.method == "GET" && !bytes.is_empty() {
2378                    events.push(FetchEvent::Data(bytes));
2379                }
2380                events.push(FetchEvent::End);
2381                events
2382            }
2383            Err(error) => match self.assets.as_ref().and_then(|a| a.url(&request.url)) {
2384                Some(url) => {
2385                    self.inflight.remove(&who);
2386                    let uri = request.url.clone();
2387                    self.start(who, HttpRequest { url, ..request }, None);
2388                    if let Some(download) = self.inflight.get_mut(&who) {
2389                        download.asset = Some(uri);
2390                    }
2391                    return;
2392                }
2393                None => vec![FetchEvent::Failed(error)],
2394            },
2395        };
2396        for event in events {
2397            let _ = self.tx.send(Message::Fetch(who, hop, event));
2398        }
2399    }
2400
2401    /// An event of hop `hop` of request `id`: what JS is told, if anything
2402    /// (`None` for events of hops left behind, and redirects the engine
2403    /// follows; `Err` for a redirect the app may not follow).
2404    fn event(
2405        &mut self,
2406        id: Requester,
2407        hop: u64,
2408        event: FetchEvent,
2409    ) -> Option<Result<FetchEvent, access::Refused>> {
2410        if self.network.is_none() {
2411            return Some(Ok(event));
2412        }
2413        let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
2414        match event {
2415            FetchEvent::Head(mut head) => {
2416                let missing = (inflight.asset.as_ref())
2417                    .filter(|_| !(200..300).contains(&head.status))
2418                    .map(|uri| format!("{uri}: HTTP {}", head.status));
2419                if let Some(missing) = missing {
2420                    if let Some(i) = self.inflight.remove(&id) {
2421                        i.task.cancel();
2422                    }
2423                    return Some(Ok(FetchEvent::Failed(missing)));
2424                }
2425                // A downloaded bundled file answers as one read from the
2426                // app's files: its `asset:/` URL, and a type even where the
2427                // server gave none.
2428                if let Some(uri) = &inflight.asset {
2429                    head.url = uri.clone();
2430                    head.redirected = false;
2431                    if !head
2432                        .headers
2433                        .iter()
2434                        .any(|(name, _)| name.eq_ignore_ascii_case("content-type"))
2435                    {
2436                        head.headers
2437                            .push(("content-type".to_owned(), asset_type(uri).to_owned()));
2438                    }
2439                }
2440                let Some(followed) = &mut inflight.followed else {
2441                    return Some(Ok(FetchEvent::Head(head)));
2442                };
2443                match access::next(&self.access, followed, head) {
2444                    access::Next::Done(head) => Some(Ok(FetchEvent::Head(head))),
2445                    access::Next::Fail(message) => {
2446                        if let Some(i) = self.inflight.remove(&id) {
2447                            i.task.cancel();
2448                        }
2449                        Some(Ok(FetchEvent::Failed(message)))
2450                    }
2451                    access::Next::Refused(refused) => {
2452                        if let Some(i) = self.inflight.remove(&id) {
2453                            i.task.cancel();
2454                        }
2455                        Some(Err(refused))
2456                    }
2457                    access::Next::Hop(request) => {
2458                        let i = self.inflight.remove(&id)?;
2459                        let followed = i.followed;
2460                        i.task.cancel();
2461                        self.start(id, request, followed);
2462                        None
2463                    }
2464                }
2465            }
2466            FetchEvent::End | FetchEvent::Failed(_) => {
2467                self.inflight.remove(&id);
2468                Some(Ok(event))
2469            }
2470            event => Some(Ok(event)),
2471        }
2472    }
2473}
2474
2475impl<M: TextEngine> State<M> {
2476    /// Ends the measured wake-up that began at `started`
2477    /// ([`EngineControl::set_perf_monitor`]).
2478    fn record_perf(&mut self, started: Option<Instant>) {
2479        let (Some(started), Some(monitor)) = (started, &self.perf) else {
2480            return;
2481        };
2482        let busy = started.elapsed();
2483        monitor.record_busy(busy);
2484        let mut commit = std::mem::take(&mut self.perf_commit);
2485        if commit.ops > 0 || commit.items > 0 {
2486            commit.js = busy.saturating_sub(commit.layout);
2487            monitor.record_commit(commit);
2488        }
2489    }
2490
2491    /// Sends the pending touch move.
2492    fn dispatch_touch_move(&mut self, script: Option<&Script>) {
2493        if let Some((id, touch)) = self.touch_move.take()
2494            && let Some(script) = script
2495        {
2496            script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
2497        }
2498    }
2499
2500    /// When the pending `onMouseMove`s are due.
2501    fn next_mouse_move(&self) -> Option<Instant> {
2502        if self.mouse_moves.is_empty() {
2503            return None;
2504        }
2505        Some(
2506            self.mouse_moved
2507                .map_or_else(nsh_core::time::now, |t| t + MOUSE_MOVE_INTERVAL),
2508        )
2509    }
2510
2511    /// Delivers the pending `onMouseMove`s: to the Rust components whose
2512    /// parts they are on, the others to JS.
2513    fn dispatch_mouse_moves(&mut self, script: Option<&Script>) {
2514        if self.mouse_moves.is_empty() {
2515            return;
2516        }
2517        self.mouse_moved = Some(nsh_core::time::now());
2518        for (id, payload) in std::mem::take(&mut self.mouse_moves) {
2519            if self
2520                .core
2521                .component_event(id, EventKind::MouseMove, &payload)
2522            {
2523                continue;
2524            }
2525            if let Some(script) = script {
2526                script.dispatch_event(id, EventKind::MouseMove, &payload);
2527            }
2528        }
2529    }
2530
2531    /// When a throttled `onScroll` is due.
2532    fn next_scroll_event(&self) -> Option<Instant> {
2533        self.scroll_events
2534            .values()
2535            .filter(|e| e.pending)
2536            .filter_map(|e| e.last.map(|t| t + e.throttle))
2537            .min()
2538    }
2539
2540    /// Sends the `onScroll` events that are due.
2541    fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
2542        if self.scroll_events.is_empty() {
2543            return;
2544        }
2545        let now = nsh_core::time::now();
2546        // Views that stopped listening (or are gone).
2547        let core = &self.core;
2548        self.scroll_events
2549            .retain(|&id, _| core.scroll_listener(id).is_some());
2550        for (&id, e) in &mut self.scroll_events {
2551            if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
2552                continue;
2553            }
2554            e.pending = false;
2555            e.last = Some(now);
2556            let n = |v: f32| PayloadValue::Number(v as f64);
2557            let payload = EventPayload::Map(vec![
2558                (
2559                    "offset",
2560                    PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
2561                ),
2562                ("contentSize", PayloadValue::Size(e.content)),
2563                ("size", PayloadValue::Size(e.viewport)),
2564                ("zoomScale", n(e.zoom)),
2565            ]);
2566            // A Rust component's scroll view is the component's.
2567            if !self.core.component_event(id, EventKind::Scroll, &payload)
2568                && let Some(script) = script
2569            {
2570                script.dispatch_event(id, EventKind::Scroll, &payload);
2571            }
2572        }
2573    }
2574
2575    /// Asks the platform for the chunks JS imports and does not have.
2576    fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
2577        let Some(script) = script else { return };
2578        let mut ids = Vec::new();
2579        script.take_chunk_requests(&mut ids);
2580        for id in ids {
2581            if !sink.load_chunk(&id) {
2582                let message = "this host does not load chunks (the app was built split)".to_owned();
2583                let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
2584            }
2585        }
2586    }
2587
2588    /// Tells the platform how many events were handled, once the commit
2589    /// of what they changed is submitted.
2590    fn report_handled(&mut self, sink: &dyn MountSink) {
2591        if self.events_handled != self.events_reported {
2592            self.events_reported = self.events_handled;
2593            sink.handled(self.events_handled);
2594        }
2595    }
2596
2597    /// Asks the platform for a frame when JS or a component's task waits
2598    /// for one.
2599    fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
2600        if !self.frame_requested
2601            && (script.is_some_and(Script::wants_frame)
2602                || self.core.wants_frame()
2603                || (script.is_some() && self.core.has_paced_list_binds()))
2604        {
2605            self.frame_requested = true;
2606            sink.request_frame();
2607        }
2608    }
2609
2610    /// Registers fonts imported by JS. Blocking: text using them must not be
2611    /// measured with a fallback font first.
2612    fn load_fonts(
2613        &mut self,
2614        script: Option<&Script>,
2615        assets: Option<&dyn Assets>,
2616        sink: &dyn MountSink,
2617    ) {
2618        let Some(script) = script else { return };
2619        let mut fonts = Vec::new();
2620        script.take_fonts(&mut fonts);
2621        for uri in fonts {
2622            let result = match assets {
2623                Some(assets) => assets.read(&uri),
2624                None => Err("this host cannot load assets".to_owned()),
2625            }
2626            .and_then(|data| self.core.register_font(&data));
2627            if let Err(err) = result {
2628                script.report(
2629                    sink,
2630                    AppErrorKind::Asset,
2631                    "font failed",
2632                    &format!("{uri}: {err}"),
2633                );
2634            }
2635        }
2636    }
2637
2638    /// Produces one frame: applies JS ops, lays out, and lets lists pull
2639    /// the items they need, merging everything into a single batch.
2640    /// Hands the URLs the app asked to open to the embedding app's URL
2641    /// handler, or, without one, to the platform ([`nsh_core::open_url`]);
2642    /// true when the platform has one to open (the core's commit sends it).
2643    fn open_urls(&mut self) -> bool {
2644        self.core.take_url_opens(&mut self.url_opens);
2645        let mut platform = false;
2646        for (id, url) in self.url_opens.drain(..) {
2647            if self.host.open_url(id, url.clone(), &self.net.tx).is_none() {
2648                self.core.open_url_on_platform(id, url);
2649                platform = true;
2650            }
2651        }
2652        platform
2653    }
2654
2655    fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
2656        let start = Instant::now();
2657        let mut merged: Option<MountBatch> = None;
2658        let mut commits = 0;
2659        let mut op_count = 0;
2660        let mut js = std::time::Duration::ZERO;
2661        // The overscan bound this turn ([`PACED_BIND_OPS`]).
2662        let mut paced = PacedBinds::default();
2663        for _ in 0..MAX_LIST_ROUNDS {
2664            // Requests from the previous round (or frame) first.
2665            let js_start = Instant::now();
2666            // Without JS, lists bind nowhere (Rust components' lists bind in
2667            // the core).
2668            let binds = self.binds.drain(..);
2669            if let Some(script) = script {
2670                for bind in binds {
2671                    script.bind_list(bind.list, &bind.binds);
2672                }
2673                script.take_ops(&mut self.ops);
2674                let mut binds = Vec::new();
2675                while paced.left() && self.core.has_paced_list_binds() {
2676                    let start = Instant::now();
2677                    let ops = self.ops.len();
2678                    self.core.take_paced_list_binds(1, &mut binds);
2679                    for bind in binds.drain(..) {
2680                        paced.cells += bind.binds.len();
2681                        script.bind_list(bind.list, &bind.binds);
2682                    }
2683                    script.take_ops(&mut self.ops);
2684                    paced.ops += self.ops.len() - ops;
2685                    paced.time += start.elapsed();
2686                }
2687            } else {
2688                drop(binds);
2689            }
2690            // The JS calls Rust queued (callbacks' posts), in order, before
2691            // the events: a task's posts come before its result.
2692            if let Some(script) = script {
2693                script.run_posted();
2694            }
2695            // The core's events (layouts, ends reached, ...) on a Rust
2696            // component's nodes are the component's; the rest are JS's, in
2697            // order with Rust components' events and calls' results.
2698            for event in self.events.drain(..) {
2699                match event {
2700                    JsEvent::Event(id, event, payload) => {
2701                        if !self.core.component_event(id, event, &payload)
2702                            && let Some(script) = script
2703                        {
2704                            script.dispatch_event(id, event, &payload);
2705                        }
2706                    }
2707                    JsEvent::LayoutListener {
2708                        host,
2709                        id,
2710                        listener,
2711                        frame,
2712                    } => {
2713                        self.core.component_layout(host, id, &listener, frame);
2714                    }
2715                    // Without JS nothing waits for them.
2716                    other => {
2717                        if let Some(script) = script {
2718                            script.deliver(other);
2719                        }
2720                    }
2721                }
2722            }
2723            if let Some(script) = script {
2724                script.take_ops(&mut self.ops);
2725            }
2726            js += js_start.elapsed();
2727            op_count += self.ops.len();
2728            // A stop drops the rest of the ops, releasing what they hold
2729            // for Rust classes.
2730            let mut ops = self.ops.drain(..);
2731            while let Some(op) = ops.next() {
2732                match self.core.apply(op) {
2733                    Ok(()) => {}
2734                    Err(err) if err.is_fatal() => {
2735                        self.core.discard_ops(ops.by_ref());
2736                        let Some(script) = script else { break };
2737                        script.stop(match err {
2738                            ApplyError::TooManyNodes(max) => {
2739                                format!("the app created more than {max} nodes and was stopped")
2740                            }
2741                            other => {
2742                                format!("the app sent an invalid op ({other:?}) and was stopped")
2743                            }
2744                        });
2745                        break;
2746                    }
2747                    Err(err) => log::error!("invalid op: {err:?}"),
2748                }
2749            }
2750            drop(ops);
2751            if let Some(batch) = self.core.commit() {
2752                commits += 1;
2753                match &mut merged {
2754                    Some(m) => extend_frame(&mut m.items, batch.items),
2755                    None => merged = Some(batch),
2756                }
2757            }
2758            self.core.take_list_binds(&mut self.binds);
2759            self.core.take_events(&mut self.events);
2760            // URLs the platform opens go out in another round.
2761            let urls = self.open_urls();
2762            // Posts the ops queued (in program order) run in another round.
2763            let posted = script.is_some_and(Script::has_posted);
2764            // New tokens (the app's theme, the embedding app's) reach what
2765            // read them in JS, whose ops come in another round.
2766            let retheme = match script {
2767                Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
2768                    self.js_tokens = self.core.tokens().clone();
2769                    script.set_tokens(self.js_tokens.clone());
2770                    true
2771                }
2772                _ => false,
2773            };
2774            let more_paced = script.is_some() && paced.left() && self.core.has_paced_list_binds();
2775            // What waited for the app's answer to the events just taken runs
2776            // in the next round, once JS has handled them, and shows in this
2777            // batch.
2778            let answers = self.core.has_due_answers();
2779            if self.binds.is_empty()
2780                && self.events.is_empty()
2781                && !posted
2782                && !retheme
2783                && !more_paced
2784                && !urls
2785                && !answers
2786            {
2787                break;
2788            }
2789        }
2790        if commits > 1
2791            && let Some(batch) = &mut merged
2792        {
2793            keep_last_sets(&mut batch.items, &mut self.sets_seen);
2794        }
2795        self.committed_since_gc |= op_count > 0;
2796        if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
2797            let c = &mut self.perf_commit;
2798            c.layout += start.elapsed().saturating_sub(js);
2799            c.ops += op_count as u32;
2800            c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
2801        }
2802        if self.trace && (op_count > 0 || merged.is_some()) {
2803            log::info!(
2804                target: "nsh::perf",
2805                "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
2806                start.elapsed().as_micros(),
2807                js.as_micros(),
2808                merged.as_ref().map_or(0, |b| b.items.len()),
2809                self.core.node_count(),
2810            );
2811        }
2812        merged
2813    }
2814}
2815
2816fn insets(env: &Environment) -> EdgeInsets {
2817    env.safe_area
2818}
2819
2820/// What Rust components read from the environment.
2821fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::element::Environment {
2822    nsh_core::element::Environment {
2823        window,
2824        safe_area: insets(env),
2825        title_bar: env.title_bar,
2826        keyboard_height: env.keyboard_height,
2827        keyboard_duration: env.keyboard_duration,
2828        dark: env.color_scheme == ColorScheme::Dark,
2829        font_scale: env.font_scale,
2830        reduce_motion: env.reduce_motion,
2831        screen_reader: env.screen_reader,
2832        rtl: env.rtl,
2833        pixel_ratio: env.pixel_ratio,
2834        os: env.os,
2835        os_version: env.os_version,
2836        idiom: env.idiom,
2837        locale: env.locale,
2838        apple_keyboard: env.apple_keyboard,
2839        host: env.host,
2840        lifecycle: env.lifecycle,
2841        screen_color: env.screen_color,
2842        file_requests: env.file_requests,
2843        speech: env.speech,
2844        web_input: env.web_input,
2845    }
2846}
2847
2848/// What class variants read from the environment.
2849fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
2850    nsh_core::tailwind::ClassEnvironment {
2851        dark: env.color_scheme == ColorScheme::Dark,
2852        platform: if env.os == Os::Web {
2853            nsh_core::tailwind::Platform::Web
2854        } else if cfg!(target_os = "android") {
2855            nsh_core::tailwind::Platform::Android
2856        } else {
2857            nsh_core::tailwind::Platform::Ios
2858        },
2859        reduce_motion: env.reduce_motion,
2860    }
2861}
2862
2863/// Returns false on shutdown.
2864fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
2865    match message {
2866        Message::Event(id, event, mut payload) => {
2867            state.events_handled += 1;
2868            if state.trace {
2869                log::info!(target: "nsh::perf", "event {event:?} on view {id}");
2870            }
2871            // Mouse moves wait for the frame, the latest per view; any other
2872            // event comes after the moves before it (a view hears where the
2873            // mouse went before it hears it leave).
2874            if event == EventKind::MouseMove {
2875                match state.mouse_moves.iter_mut().find(|(v, _)| *v == id) {
2876                    Some((_, pending)) => *pending = payload,
2877                    None => state.mouse_moves.push((id, payload)),
2878                }
2879                return true;
2880            }
2881            state.dispatch_mouse_moves(script);
2882            // The core tracks input text for layout and to recognize stale
2883            // values (from JS and from Rust components alike).
2884            if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
2885                state.core.input_changed(id, text, *count);
2886            }
2887            // The platform knows the caret in the input, the core where
2888            // the input is.
2889            if event == EventKind::CaretMove {
2890                state.core.locate_caret(id, &mut payload);
2891            }
2892            if event == EventKind::Paste {
2893                payload = payload.into_paste();
2894            }
2895            // Events on a Rust component's parts are the component's.
2896            if state.core.component_event(id, event, &payload) {
2897                return true;
2898            }
2899            if let EventPayload::Touch(touch) = payload {
2900                if touch.phase == nsh_core::TouchPhase::Move {
2901                    match &mut state.touch_move {
2902                        Some((_, pending)) => pending.merge_move(*touch),
2903                        None => state.touch_move = Some((id, touch)),
2904                    }
2905                    return true;
2906                }
2907                // Moves before a start, end or cancel go first.
2908                state.dispatch_touch_move(script);
2909                if let Some(script) = script {
2910                    script.dispatch_event(id, event, &EventPayload::Touch(touch));
2911                }
2912                return true;
2913            }
2914            let Some(script) = script else { return true };
2915            let start = state.trace.then(Instant::now);
2916            script.dispatch_event(id, event, &payload);
2917            if let Some(start) = start {
2918                // The handler, its microtasks and the decode of what it
2919                // committed.
2920                log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
2921            }
2922        }
2923        Message::Scroll(id, offset, applied) => {
2924            state.core.set_scroll_offset(id, offset, applied);
2925            let (x, y) = (offset.x.0, offset.y.0);
2926            if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
2927                let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
2928                    x,
2929                    y,
2930                    content,
2931                    viewport,
2932                    zoom,
2933                    throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
2934                    last: None,
2935                    pending: true,
2936                });
2937                (event.x, event.y, event.content, event.viewport, event.zoom) =
2938                    (x, y, content, viewport, zoom);
2939                event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
2940                event.pending = true;
2941            }
2942        }
2943        Message::Kept(nodes) => state.core.set_kept(&nodes),
2944        Message::InputScroll(id, offset, content, viewport) => {
2945            state.core.set_input_scroll(id, offset, content, viewport);
2946        }
2947        Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
2948        Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
2949        Message::AnimationsFinished(mut finished) => {
2950            // The components' animations end in the core, JS's in JS.
2951            state.core.animations_finished(&mut finished);
2952            if let Some(script) = script {
2953                script.animations_finished(&finished);
2954            }
2955        }
2956        Message::Resize(size) => {
2957            state.core.set_viewport(size);
2958            state.resized = Some(size);
2959        }
2960        Message::Wake => {}
2961        Message::Environment(mut env) => {
2962            state.pinned.apply(&mut env);
2963            state.core.set_font_scale(env.font_scale);
2964            state.core.set_class_environment(class_environment(&env));
2965            state.core.set_safe_area(insets(&env));
2966            let window = env.window;
2967            state.core.set_environment(ui_environment(&env, window));
2968            if let Some(script) = script {
2969                script.set_environment(&env);
2970            }
2971        }
2972        Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
2973        Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
2974        Message::Frame => {
2975            state.frame_requested = false;
2976            state.core.run_frame(nsh_core::time::now());
2977            if let Some(script) = script {
2978                script.run_frame();
2979            }
2980        }
2981        Message::States(id, states) => state.core.set_states(id, states),
2982        Message::FontsChanged => state.core.fonts_changed(),
2983        Message::Remount => state.core.remount(),
2984        Message::Fetch(who, hop, event) => match (who, state.net.event(who, hop, event)) {
2985            (_, None) => {}
2986            (Requester::Js(id), Some(event)) => {
2987                if let Some(script) = script {
2988                    match event {
2989                        Ok(event) => script.fetch_event(id, event),
2990                        Err(refused) => script.fetch_refused(id, &refused.message, &refused.url),
2991                    }
2992                }
2993            }
2994            (Requester::Task(id), Some(event)) => {
2995                let event = event.unwrap_or_else(|refused| FetchEvent::Failed(refused.message));
2996                if !state.core.fetch_event(id, event) {
2997                    state.net.cancel(who);
2998                }
2999            }
3000        },
3001        Message::AssetRead(who, hop, request, read) => {
3002            state.net.asset_read(who, hop, request, read)
3003        }
3004        Message::Hot(update) => state.hot.push(update),
3005        Message::Chunk(chunk) => {
3006            if let Some(script) = script {
3007                script.chunk(chunk);
3008            }
3009        }
3010        Message::Perf(monitor) => {
3011            state.perf = monitor;
3012            state.perf_commit = perf::CommitTiming::default();
3013        }
3014        Message::Tokens(tokens) => {
3015            state.core.set_host_tokens(tokens.map(|t| *t));
3016            if let Some(script) = script {
3017                script.set_theme_tokens(state.core.theme_tokens());
3018            }
3019        }
3020        // A Rust app has no `nsh/host`: what the host sends it goes.
3021        Message::HostEvent(name, data) => {
3022            if let Some(script) = script {
3023                script.host_event(&name, data);
3024            }
3025        }
3026        Message::HostReply(id, result) => {
3027            if let Some(script) = script {
3028                script.host_reply(id, result);
3029            }
3030        }
3031        Message::UrlHandled { id, url, handled } => {
3032            if handled {
3033                state.core.answer_open_url(id, true);
3034            } else {
3035                state.core.open_url_on_platform(id, url);
3036            }
3037        }
3038        // The driver handles it ([`Driver::handle`]), and keeps the ones
3039        // sent before it started for after the first frame.
3040        Message::Advance(..) | Message::Flush(..) => unreachable!("the driver moves the clock"),
3041        Message::Shutdown => return false,
3042    }
3043    true
3044}
3045
3046/// What a turn spent binding overscan cells.
3047#[derive(Default)]
3048struct PacedBinds {
3049    cells: usize,
3050    ops: usize,
3051    time: std::time::Duration,
3052}
3053
3054impl PacedBinds {
3055    /// Whether the turn may bind another: at least one, then within the
3056    /// budget.
3057    fn left(&self) -> bool {
3058        self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
3059    }
3060}
3061
3062/// Appends a commit's items to the frame's. A scroll view's content size
3063/// that the frame already sets is updated to the later size (unless the
3064/// view scrolls in between): a row relaid over two commits must not send
3065/// the platform a transient size, which clamps the offset before the
3066/// content grows back (a list jumping when a row expands).
3067fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
3068    use nsh_core::MountItem;
3069    let start = frame.len();
3070    frame.extend(items);
3071    for k in start..frame.len() {
3072        let MountItem::ScrollContent { id, size } = frame[k] else {
3073            continue;
3074        };
3075        let earlier = frame[..k].iter().rposition(|m| {
3076            matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
3077        });
3078        if let Some(j) = earlier
3079            && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
3080        {
3081            *s = size;
3082        }
3083    }
3084}
3085
3086/// Of the items of a frame merged from several commits that set one part
3087/// of a view whole (its frame, style, text, ...), keeps the last: the
3088/// platform would apply each in one pass, and a list's rounds (binds, then
3089/// the paced ones) relay and restyle the same cells. Once per turn, with
3090/// `last` the reused buffer.
3091fn keep_last_sets(frame: &mut Vec<nsh_core::MountItem>, last: &mut FxHashMap<(u8, NodeId), usize>) {
3092    last.clear();
3093    let mut repeated = false;
3094    for (k, item) in frame.iter().enumerate() {
3095        if let Some(key) = sets_whole(item) {
3096            repeated |= last.insert(key, k).is_some();
3097        }
3098    }
3099    if !repeated {
3100        return;
3101    }
3102    let mut k = 0;
3103    frame.retain(|item| {
3104        k += 1;
3105        sets_whole(item).is_none_or(|key| last[&key] == k - 1)
3106    });
3107}
3108
3109/// The part of a view an item sets whole, and the view: of two such items
3110/// the later is all the view ends up with.
3111fn sets_whole(item: &nsh_core::MountItem) -> Option<(u8, nsh_core::NodeId)> {
3112    use nsh_core::MountItem;
3113    Some(match *item {
3114        MountItem::Frame { id, .. } => (0, id),
3115        MountItem::Overflow { id, .. } => (1, id),
3116        MountItem::ViewStyle { id, .. } => (2, id),
3117        MountItem::Text { id, .. } => (3, id),
3118        MountItem::Events { id, .. } => (4, id),
3119        MountItem::Image { id, .. } => (5, id),
3120        _ => return None,
3121    })
3122}
3123
3124#[cfg(test)]
3125mod tests {
3126    #[test]
3127    fn pinned_values_hold_whatever_the_platform_reports() {
3128        let pins = super::EnvironmentPins {
3129            locale: nsh_core::platform::Locale::parse("de-DE"),
3130            reduce_motion: Some(true),
3131            ..Default::default()
3132        };
3133        let mut reported = super::Environment {
3134            locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
3135            font_scale: 1.5,
3136            ..Default::default()
3137        };
3138        pins.apply(&mut reported);
3139        assert_eq!(reported.locale.as_str(), "de-DE");
3140        assert!(reported.reduce_motion);
3141        // What is not pinned stays the platform's.
3142        assert_eq!(reported.font_scale, 1.5);
3143        assert_eq!(reported.safe_area, Default::default());
3144    }
3145
3146    #[test]
3147    fn bundle_default_has_no_application_selected_path_anchors() {
3148        let bundle = super::Bundle::default();
3149        assert!(bundle.system_paths.plugin_dir.is_none());
3150        assert!(bundle.system_paths.home_dir.is_none());
3151        assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
3152    }
3153
3154    #[test]
3155    fn bundle_trusted_paths_reject_relative_and_missing_directories() {
3156        let mut paths = nsh_core::access::TrustedPaths::default();
3157        paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
3158        paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
3159        let bundle = super::Bundle::default().with_system_paths(paths);
3160        assert!(bundle.system_paths.plugin_dir.is_none());
3161        assert!(bundle.system_paths.home_dir.is_none());
3162        assert!(
3163            super::trusted_directory(Some(std::path::PathBuf::from(
3164                "/nsh-nonexistent-anchor-never-created"
3165            )))
3166            .is_none()
3167        );
3168    }
3169
3170    #[test]
3171    fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
3172        let root = std::env::var_os("TMPDIR")
3173            .map(std::path::PathBuf::from)
3174            .unwrap_or_else(|| {
3175                std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
3176                    .join(".cache/nsh-benchs-test-tmp")
3177            });
3178        assert!(root.is_absolute() && !root.starts_with("/tmp"));
3179        let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
3180        std::fs::create_dir_all(&directory).unwrap();
3181        let path = directory.join("bundle.js");
3182        std::fs::write(&path, "export default null;").unwrap();
3183        let bundle = super::Bundle::read(&path).unwrap();
3184        assert_eq!(
3185            bundle.system_paths.plugin_dir,
3186            Some(nsh_core::access::canonicalize(&directory).unwrap())
3187        );
3188        assert!(bundle.system_paths.home_dir.is_none());
3189        std::fs::remove_dir_all(directory).unwrap();
3190    }
3191
3192    #[test]
3193    fn rust_environment_preserves_native_title_bar_insets() {
3194        use super::{Edges, Points};
3195        let title_bar = Edges {
3196            top: Points(42.0),
3197            left: Points(78.0),
3198            right: Points(138.0),
3199            bottom: Points(0.0),
3200        };
3201        let environment = super::Environment {
3202            title_bar,
3203            ..Default::default()
3204        };
3205        assert_eq!(
3206            super::ui_environment(
3207                &environment,
3208                nsh_core::Size::new(Points(840.0), Points(630.0))
3209            )
3210            .title_bar,
3211            title_bar
3212        );
3213    }
3214
3215    use nsh_core::{MountItem, Points, Size};
3216
3217    #[test]
3218    fn a_frame_sends_a_scroll_views_last_content_size() {
3219        let content = |height| MountItem::ScrollContent {
3220            id: 2,
3221            size: Size::new(Points(390.0), height),
3222        };
3223        let heights = |frame: &[MountItem]| -> Vec<f32> {
3224            frame
3225                .iter()
3226                .filter_map(|m| match m {
3227                    MountItem::ScrollContent { size, .. } => Some(size.height.0),
3228                    _ => None,
3229                })
3230                .collect()
3231        };
3232        let mut frame = vec![content(Points(313.0))];
3233        super::extend_frame(&mut frame, vec![content(Points(544.0))]);
3234        assert_eq!(heights(&frame), [544.0, 544.0]);
3235        // A scroll in between keeps the size it scrolled against.
3236        let mut frame = vec![
3237            content(Points(313.0)),
3238            MountItem::ScrollBy {
3239                id: 2,
3240                dx: Points(0.0),
3241                dy: Points(10.0),
3242            },
3243        ];
3244        super::extend_frame(&mut frame, vec![content(Points(544.0))]);
3245        assert_eq!(heights(&frame), [313.0, 544.0]);
3246    }
3247
3248    #[test]
3249    fn a_frame_sends_a_views_last_frame_once() {
3250        use nsh_core::{Bounds, Point};
3251        let at = |id, y| MountItem::Frame {
3252            id,
3253            frame: Bounds::new(
3254                Point::new(Points(0.0), Points(y)),
3255                Size::new(Points(10.0), Points(10.0)),
3256            ),
3257        };
3258        let mut frame = vec![
3259            MountItem::Create {
3260                id: 4,
3261                kind: nsh_core::ViewKind::View,
3262            },
3263            at(4, 0.0),
3264            at(6, 0.0),
3265        ];
3266        super::extend_frame(&mut frame, vec![at(4, 50.0)]);
3267        super::keep_last_sets(&mut frame, &mut Default::default());
3268        assert!(matches!(frame[0], MountItem::Create { id: 4, .. }));
3269        let frames: Vec<_> = frame
3270            .iter()
3271            .filter_map(|m| match m {
3272                MountItem::Frame { id, frame } => Some((*id, frame.origin.y.0)),
3273                _ => None,
3274            })
3275            .collect();
3276        assert_eq!(frames, [(6, 0.0), (4, 50.0)]);
3277    }
3278}