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`). Each wake-up (input event, timer,
6//! resize) runs the app's code (component tasks; JS and its microtasks),
7//! applies what JS committed, lays out, and hands one [`MountBatch`] to the
8//! platform through a [`MountSink`]. The platform thread never blocks on
9//! the engine.
10
11mod access;
12mod app_directory;
13mod error;
14mod local_storage;
15#[cfg(feature = "net")]
16pub mod net;
17pub mod perf;
18mod script;
19#[cfg(not(target_arch = "wasm32"))]
20mod storage;
21#[cfg(feature = "js")]
22mod symbolicate;
23
24// The typed API check (docs/dev/geometry.md, "Typed API"): the scan is
25// nsh-core's; this crate's lists are `unitless.txt` and `untyped.txt`.
26#[cfg(test)]
27#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
28mod unit_scan;
29
30#[cfg(test)]
31#[test]
32fn public_api_is_typed() {
33    unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
34}
35
36use std::{io, rc::Rc, sync::Arc, time::Duration};
37
38pub use app_directory::app_dir_name;
39use crossbeam_channel::{Receiver, Sender};
40pub use local_storage::local_storage_prefix;
41use nsh_core::{
42    ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
43    PayloadValue, TextEngine, time::Instant, ui::JsEvent,
44};
45pub use nsh_core::{
46    access::{Access, Capabilities},
47    geometry::{self, Bounds, Edges, Point, Points, Size},
48    js::{HostLimits, Limits},
49    platform::{
50        ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HttpBody, HttpHead,
51        HttpRequest, Idiom, Locale, Os,
52    },
53    storage::{StorageBackend, StorageChange},
54    time::Clock,
55    ui::{Root, Tokens},
56};
57#[cfg(feature = "js")]
58pub use nsh_js::BYTECODE_VERSION;
59/// Signed packages, release-key certificates, revocations and trust stores.
60#[cfg(feature = "js")]
61pub use nsh_package as package;
62use rustc_hash::FxHashMap;
63#[cfg(not(target_arch = "wasm32"))]
64pub use storage::{FileStorage, data_dir};
65
66pub use crate::error::{AppError, AppErrorKind, PackageInfo};
67use crate::script::{NetworkQueue, RequestId, Script};
68
69#[cfg(not(target_arch = "wasm32"))]
70/// Stack size of the engine thread. QuickJS recursion (and deep Solid
71/// component trees) needs more than the 512 KiB default of secondary
72/// threads on Apple platforms.
73const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
74
75/// Minimum time between idle cycle collections. QuickJS frees acyclic
76/// garbage immediately; only cycles (such as detached node subtrees, whose
77/// parent/child links reference each other) wait for the collector.
78const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
79
80/// The shortest time between two deliveries of mouse motion: a frame at
81/// 120 Hz. Mice report moves far more often (up to 1000 Hz), and a handler
82/// that redraws a crosshair needs no more than one per frame.
83const HOVER_MOVE_INTERVAL: Duration = Duration::from_millis(8);
84
85/// The app an engine runs.
86#[derive(Debug, Clone)]
87#[allow(
88    clippy::large_enum_variant,
89    reason = "one app per surface; keep the public constructor API without allocation"
90)]
91pub enum App {
92    /// A Rust app: its root component, mounted as the surface's content.
93    Rust(Root),
94    /// A JS app (feature `js`).
95    Js(Bundle),
96}
97
98impl From<Bundle> for App {
99    fn from(bundle: Bundle) -> Self {
100        App::Js(bundle)
101    }
102}
103
104impl App {
105    /// The app's id (`nsh.json` `"id"`), when it carries one.
106    pub fn app_id(&self) -> Option<&str> {
107        match self {
108            App::Rust(root) => root.app_id_ref(),
109            App::Js(bundle) => bundle.app_id.as_deref(),
110        }
111    }
112}
113
114impl From<Root> for App {
115    fn from(root: Root) -> Self {
116        App::Rust(root)
117    }
118}
119
120/// An app bundle: its code plus, in development, a source map.
121#[derive(Debug, Clone)]
122#[non_exhaustive]
123pub struct Bundle {
124    /// The code.
125    pub code: BundleCode,
126    /// Source map (JSON) used to show app source locations in stack traces.
127    pub source_map: Option<Arc<str>>,
128    /// What the code may do.
129    pub policy: Policy,
130    /// What relative request URLs resolve against (the page's URL on the
131    /// web); `None`: they are invalid.
132    pub base_url: Option<Arc<str>>,
133    /// The chunks of a split bundle that come with it (`import()` loads
134    /// them without asking the platform); those missing are asked of
135    /// [`MountSink::load_chunk`]. Shared by the bundle's clones.
136    pub chunks: Arc<Vec<Chunk>>,
137    /// The sandbox's hardening as bytecode (`nsh_js::compile_harden`),
138    /// for a runtime without QuickJS' parser (the web runtime of published
139    /// apps); `None`: compiled when the policy hardens. Set it with
140    /// [`Bundle::with_harden_bytecode`].
141    pub harden_bytecode: Option<Arc<Vec<u8>>>,
142    /// The app's id (`nsh.json` `"id"`; a signed package's verified one):
143    /// it names where the app keeps its data (`nsh/storage`).
144    pub app_id: Option<String>,
145    /// Trusted filesystem anchors selected by the native host, never decoded
146    /// from application code, its manifest or a development server message.
147    /// Missing anchors deny relative and corresponding placeholder grants.
148    pub system_paths: nsh_core::access::TrustedPaths,
149    /// The signed package the bundle came from ([`Bundle::from_package`]),
150    /// named in the app's errors ([`AppError::package`]).
151    pub package: Option<Arc<PackageInfo>>,
152}
153
154/// A chunk of a split bundle (`nsh_bundler::Chunk`): app code that
155/// `import()` loads on demand.
156#[derive(Debug, Clone)]
157pub struct Chunk {
158    /// Its id (`Screen.js`), as the bundle imports it.
159    pub id: String,
160    /// The code.
161    pub code: BundleCode,
162    /// Source map (JSON), for stack traces.
163    pub source_map: Option<Arc<str>>,
164}
165
166impl Chunk {
167    /// A chunk as JS source.
168    pub fn source(id: impl Into<String>, code: String) -> Self {
169        Self {
170            id: id.into(),
171            code: BundleCode::Source(code),
172            source_map: None,
173        }
174    }
175
176    /// A chunk as bytecode (`nsh_js::compile_chunk_bytecode`).
177    ///
178    /// # Safety
179    ///
180    /// As [`Bundle::bytecode`].
181    pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
182        Self {
183            id: id.into(),
184            code: BundleCode::Bytecode(bytes),
185            source_map: None,
186        }
187    }
188
189    /// Attaches a source map.
190    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
191        self.source_map = Some(map.into());
192        self
193    }
194}
195
196/// What a bundle's code may do.
197#[derive(Debug, Clone)]
198pub struct Policy {
199    /// Run without `eval`, the function constructors and writable shared
200    /// prototypes (see `nsh_js::HostOptions::harden`). On by default; off for
201    /// development bundles.
202    pub harden: bool,
203    /// What the app declared (`nsh.json` `capabilities`); `None`: no
204    /// declaration, everything.
205    pub declared: Option<Capabilities>,
206    /// What the embedding app grants at most; `None`: whatever the app
207    /// declared.
208    pub granted: Option<Capabilities>,
209}
210
211impl Default for Policy {
212    fn default() -> Self {
213        Self {
214            harden: true,
215            declared: None,
216            granted: None,
217        }
218    }
219}
220
221impl Policy {
222    /// Development bundles: `eval` and friends stay (debugging); the
223    /// capabilities are still enforced, so a missing one shows during
224    /// development.
225    pub fn development() -> Self {
226        Self {
227            harden: false,
228            ..Self::default()
229        }
230    }
231
232    /// What the app may reach under this policy.
233    pub fn access(&self) -> Access {
234        Access {
235            declared: self.declared.clone().unwrap_or_else(Capabilities::all),
236            granted: self.granted.clone(),
237        }
238    }
239}
240
241/// The code of a bundle.
242#[derive(Debug, Clone)]
243pub enum BundleCode {
244    /// QuickJS bytecode from `nsh_js::compile_bytecode`.
245    Bytecode(Vec<u8>),
246    /// JS source; slower to start than bytecode.
247    Source(String),
248}
249
250impl Default for Bundle {
251    fn default() -> Self {
252        Self::source(String::new())
253    }
254}
255
256impl Bundle {
257    /// A bytecode bundle.
258    ///
259    /// # Safety
260    ///
261    /// `bytes` must be bytecode from `nsh_js::compile_bytecode` for this
262    /// runtime's `BYTECODE_VERSION`, from a trusted source: QuickJS does not
263    /// validate bytecode, and loading crafted bytecode corrupts memory. Trusted
264    /// are the app's own signed resources, a development server the developer
265    /// pointed the host at, and verified packages ([`Bundle::from_package`]).
266    pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
267        Self {
268            code: BundleCode::Bytecode(bytes),
269            source_map: None,
270            policy: Policy::default(),
271            base_url: None,
272            chunks: Arc::default(),
273            harden_bytecode: None,
274            app_id: None,
275            system_paths: nsh_core::access::TrustedPaths::default(),
276            package: None,
277        }
278    }
279
280    /// A JS source bundle.
281    pub fn source(code: String) -> Self {
282        Self {
283            code: BundleCode::Source(code),
284            source_map: None,
285            policy: Policy::default(),
286            base_url: None,
287            chunks: Arc::default(),
288            harden_bytecode: None,
289            app_id: None,
290            system_paths: nsh_core::access::TrustedPaths::default(),
291            package: None,
292        }
293    }
294
295    /// Selects trusted source/package and home directory anchors. Supplying a
296    /// path grants nothing by itself: the manifest and host grant must still
297    /// allow the filesystem operation. Only existing absolute directories
298    /// are accepted; unavailable anchors are left unset.
299    pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
300        paths.plugin_dir = trusted_directory(paths.plugin_dir);
301        paths.home_dir = trusted_directory(paths.home_dir);
302        self.system_paths = paths;
303        self
304    }
305
306    /// The app's id ([`Bundle::app_id`]), as `nsh.json` or the dev server
307    /// gives it.
308    pub fn with_app_id(mut self, id: Option<&str>) -> Self {
309        self.app_id = id.map(str::to_owned);
310        self
311    }
312
313    /// Attaches a source map.
314    pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
315        self.source_map = Some(map.into());
316        self
317    }
318
319    /// Sets the URL relative request URLs resolve against.
320    pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
321        self.base_url = Some(url.into());
322        self
323    }
324
325    /// Hardens with `bytes` ([`Bundle::harden_bytecode`]).
326    ///
327    /// # Safety
328    ///
329    /// As [`Bundle::bytecode`]: `bytes` comes from `nsh_js::compile_harden`
330    /// of this runtime's `BYTECODE_VERSION`, from a trusted source.
331    pub unsafe fn with_harden_bytecode(mut self, bytes: Vec<u8>) -> Self {
332        self.harden_bytecode = Some(Arc::new(bytes));
333        self
334    }
335
336    /// Replaces the policy.
337    pub fn with_policy(mut self, policy: Policy) -> Self {
338        self.policy = policy;
339        self
340    }
341
342    /// Adds chunks of a split bundle (see [`Bundle::chunks`]).
343    pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
344        Arc::make_mut(&mut self.chunks).extend(chunks);
345        self
346    }
347
348    /// Reads a JS source bundle written by `nsh build` (`bundle.js`), plus
349    /// `bundle.js.map`, the app's `capabilities.json` and its id
350    /// (`app.json` `"id"`) next to it if present. Bytecode (`bundle.nshc`) is refused: files can be replaced, and
351    /// only [`Bundle::read_trusted`] (the app's own resources) or a verified
352    /// package may load bytecode.
353    pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
354        if path.extension().is_some_and(|e| e == "nshc") {
355            return Err(io::Error::other(
356                "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
357            ));
358        }
359        // SAFETY: not bytecode.
360        unsafe { Self::read_trusted(path) }
361    }
362
363    /// Like [`Bundle::read`], also reading `bundle.nshc` as bytecode.
364    ///
365    /// # Safety
366    ///
367    /// A `.nshc` file must be trusted as [`Bundle::bytecode`] requires (e.g.
368    /// inside the app's own signed bundle).
369    pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
370        let bytes = std::fs::read(path)?;
371        let bundle = if path.extension().is_some_and(|e| e == "nshc") {
372            // SAFETY: guaranteed by the caller.
373            unsafe { Bundle::bytecode(bytes) }
374        } else {
375            Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
376        };
377        let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
378            Ok(map) if !map.is_empty() => bundle.with_source_map(map),
379            _ => bundle,
380        };
381        if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
382            bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
383        }
384        bundle.app_id = read_app_id(&path.with_file_name("app.json"));
385        bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
386            .parent()
387            .map(std::path::Path::to_path_buf);
388        Ok(bundle)
389    }
390}
391
392#[cfg(feature = "js")]
393impl Bundle {
394    /// The bundle of a verified package: its bytecode when it was compiled
395    /// for this runtime (else its source), its source map and its declared
396    /// capabilities. What a newer signer wrote that this runtime does not
397    /// know (header fields, files, capabilities) is logged and left out: an
398    /// unknown capability is not granted.
399    pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
400        for ignored in &package.ignored {
401            log::warn!("package {}: ignored {ignored}", package.app.id);
402        }
403        let bundle = match package.bytecode() {
404            // SAFETY: verified: signed by a certified release key, hashed,
405            // and compiled for this runtime.
406            Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
407            None => Bundle::source(package.source.clone()),
408        };
409        let mut bundle = match &package.source_map {
410            Some(map) => bundle.with_source_map(map.clone()),
411            None => bundle,
412        };
413        if let Some(json) = &package.capabilities {
414            let (declared, dropped) = Capabilities::from_json_lenient(json)?;
415            for dropped in dropped {
416                log::warn!("package {}: not granted: {dropped}", package.app.id);
417            }
418            bundle.policy.declared = Some(declared);
419        }
420        bundle.app_id = Some(package.app.id.clone());
421        bundle.package = Some(Arc::new(PackageInfo {
422            id: package.app.id.clone(),
423            name: package.app.name.clone(),
424            version: package.app.version.clone(),
425            build: package.app.build,
426            sha256: package.sha256.clone(),
427        }));
428        Ok(bundle)
429    }
430}
431
432/// The `"id"` of an `app.json` (`nsh build`'s, a packaged app's).
433fn read_app_id(path: &std::path::Path) -> Option<String> {
434    let json: serde_json::Value =
435        serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()?;
436    json.get("id")?.as_str().map(str::to_owned)
437}
438
439/// A verified package, unpacked ([`load_package`], [`verify_package`]).
440#[cfg(feature = "js")]
441#[derive(Debug)]
442pub struct LoadedPackage {
443    /// Its bundle.
444    pub bundle: Bundle,
445    /// Where its assets are (`asset:/…`).
446    pub assets: std::path::PathBuf,
447    /// Its app.
448    pub app: nsh_package::App,
449    /// What accepting it records ([`accept_package`]).
450    pub receipt: nsh_package::PackageReceipt,
451}
452
453/// Verifies the package `bytes` with `trust`, writes its assets under
454/// `assets_root` (`<root>/<app id>/<package hash>/`, once per package) and
455/// records its build (older builds of the app are refused from now on):
456/// [`verify_package`], then [`accept_package`].
457#[cfg(feature = "js")]
458pub fn load_package(
459    trust: &mut nsh_package::TrustStore,
460    bytes: &[u8],
461    assets_root: &std::path::Path,
462) -> Result<LoadedPackage, String> {
463    let package = verify_package(trust, bytes, assets_root)?;
464    accept_package(trust, &package)?;
465    Ok(package)
466}
467
468/// [`load_package`] without recording the build: the package is verified as
469/// strictly (signature, certificate, revocations, hashes, and its build not
470/// older than the highest accepted) and its assets written, but the builds
471/// accepted before keep verifying. An embedding app runs it, and once it
472/// decided the package is healthy (its first frame drawn, no fatal error for
473/// a while) calls [`accept_package`]; if it fails before, the app can go
474/// back to the package it ran before, which still verifies.
475#[cfg(feature = "js")]
476pub fn verify_package(
477    trust: &nsh_package::TrustStore,
478    bytes: &[u8],
479    assets_root: &std::path::Path,
480) -> Result<LoadedPackage, String> {
481    let package = trust
482        .verify(bytes, BYTECODE_VERSION)
483        .map_err(|e| e.to_string())?;
484    let bundle = Bundle::from_package(&package)?;
485    let dir = assets_root.join(&package.app.id).join(&package.sha256);
486    let done = dir.join(".complete");
487    if !done.exists() {
488        let assets = dir.join("assets");
489        for (path, data) in &package.assets {
490            // Paths were checked (relative, no `..`) when the package was read.
491            let dest = assets.join(path);
492            if let Some(parent) = dest.parent() {
493                std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
494            }
495            std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
496        }
497        std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
498        std::fs::write(&done, b"").map_err(|e| e.to_string())?;
499    }
500    Ok(LoadedPackage {
501        bundle,
502        assets: dir.join("assets"),
503        receipt: package.receipt(),
504        app: package.app,
505    })
506}
507
508/// Rewrites every `bundle.js:LINE:COL` in `text` (a reported error and its
509/// stack) to the app source position `source_map` (the bundle's) gives,
510/// as the engine does with a bundle's own map: for stacks reported by
511/// packages published without their map (`nsh symbolicate`).
512#[cfg(feature = "js")]
513pub fn symbolicate(source_map: &str, text: &str) -> String {
514    symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
515}
516
517/// Records the build of `package` ([`verify_package`]) in `trust`: older
518/// builds of its app are refused from now on. Refused if the package or its
519/// release key was revoked since it was verified.
520#[cfg(feature = "js")]
521pub fn accept_package(
522    trust: &mut nsh_package::TrustStore,
523    package: &LoadedPackage,
524) -> Result<(), String> {
525    trust
526        .accept_receipt(&package.receipt)
527        .map_err(|e| e.to_string())
528}
529
530/// Parses capabilities in their JSON form (`capabilities.json`, the dev
531/// protocol, an embedder's grant).
532pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
533    let value: serde_json::Value =
534        serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
535    Capabilities::from_json(&value)
536}
537
538impl Bundle {
539    /// The declared capabilities from their JSON form, if any.
540    pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
541        self.policy.declared = json.map(parse_capabilities).transpose()?;
542        Ok(self)
543    }
544}
545
546/// Receives mount batches on the engine thread. Implementations forward
547/// them to the UI thread.
548pub trait MountSink: Send + 'static {
549    /// Called once per commit, in order.
550    fn submit(&self, batch: MountBatch);
551
552    /// An error of the app, as text (the message and the stack): the
553    /// bundle failed to load, an exception escaped a JS callback, the VM
554    /// was stopped. Errors are always logged; development hosts also show
555    /// them on screen. What [`MountSink::report`] calls unless it is
556    /// implemented.
557    fn report_error(&self, _message: &str) {}
558
559    /// An error of the app, with its parts: what went wrong (whether the
560    /// app can go on), the message, the stack and the package it came
561    /// from. By default, [`MountSink::report_error`] with its text.
562    fn report(&self, error: &AppError) {
563        self.report_error(&error.to_string());
564    }
565
566    /// JS or a component's task asked for a display frame
567    /// (`requestAnimationFrame`, `ui::ambient::next_frame`): call
568    /// [`EngineControl::frame`] at the next vsync. Requests are not repeated
569    /// until that call.
570    fn request_frame(&self) {}
571
572    /// A development update ([`EngineControl::hot_update`]) could not be
573    /// applied in place: reload the latest full bundle.
574    fn hot_update_failed(&self) {}
575
576    /// The engine laid the app out at `size` ([`EngineControl::resize`]):
577    /// called after the commit of the turn that applied the resize (if it
578    /// changed anything, its batch came before), once per turn, with the
579    /// latest size. A platform that waits for the layout at a new size, to
580    /// show it in the frame the window takes the size, stops waiting here.
581    fn resized(&self, _size: Size<Points>) {}
582
583    /// The app imports chunk `id` of a split bundle (`import()`), which its
584    /// [`Bundle`] does not hold: load it and hand it over with
585    /// [`EngineControl::chunk_loaded`] (or [`EngineControl::chunk_failed`]),
586    /// from any thread, and return true. False (the default): this host
587    /// has no chunks to load, and the import fails.
588    fn load_chunk(&self, _id: &str) -> bool {
589        false
590    }
591}
592
593/// Receives what happens to a request started by [`Network::fetch`], in
594/// order, on any thread. After [`FetchTask::cancel`] it may still be called
595/// (the engine then ignores it).
596pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
597
598/// A request in flight, driven from the engine thread.
599pub trait FetchTask: Send {
600    /// The next chunk of a streamed body ([`HttpBody::Stream`]), after
601    /// [`FetchEvent::BodyWanted`].
602    fn send(&mut self, chunk: Vec<u8>);
603    /// A streamed body is complete.
604    fn finish(&mut self);
605    /// Stops (`true`) or resumes (`false`) reading the response body: JS
606    /// does not read what arrived (back pressure). Bytes already on their
607    /// way may still arrive.
608    fn pause(&mut self, paused: bool);
609    /// Aborts the request.
610    fn cancel(self: Box<Self>);
611}
612
613/// The platform's HTTP stack, used by JS `fetch`.
614pub trait Network: Send + Sync + 'static {
615    /// Starts `request`: its response head, then its body in chunks as they
616    /// arrive, are reported to `events`.
617    fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
618}
619
620/// Reads the app's bundled files (`asset:/…` URIs): from the app's
621/// resources, or from the dev server during development.
622pub trait Assets: Send + Sync + 'static {
623    /// The bytes of `uri`. Blocking; called on the engine thread.
624    fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
625}
626
627/// Engine settings.
628#[derive(Clone)]
629pub struct EngineConfig {
630    /// The app.
631    pub app: App,
632    /// Initial size of the root view.
633    pub viewport: Size<Points>,
634    /// Log per-commit timings (target `nsh::perf`, level info).
635    pub trace: bool,
636    /// The HTTP stack behind `fetch`; without one, requests fail.
637    pub network: Option<Arc<dyn Network>>,
638    /// The host transport for WebSockets, including the browser WebSocket API.
639    pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
640    /// App-private host filesystem service (for browser storage).
641    pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
642    /// Source of bundled files such as fonts; without one, they fail to load.
643    pub assets: Option<Arc<dyn Assets>>,
644    /// The surface's initial environment (its `window` is `viewport`).
645    pub environment: Environment,
646    /// Height of the platform's screen header bar, normal and with a large
647    /// title (status bar excluded).
648    pub header_heights: (Points, Points),
649    /// The JS VM's resource limits (a JS app's; Rust code has none).
650    pub limits: Limits,
651    /// The UI sets JS imports (`nsh_base::registry()` by default, the app's
652    /// own): their Rust components and modules. A Rust app's
653    /// components need no registration.
654    pub ui_sets: Vec<nsh_core::ui::Registry>,
655    /// The tokio runtime the components' async tasks use (timers, IO,
656    /// background work); `None`: one shared by the engines of the process.
657    pub runtime: Option<tokio::runtime::Handle>,
658    /// Where apps keep their data: each app in `<data_dir>/<app id>`
659    /// ([`App::app_id`]; `default` without one), its storage
660    /// (`nsh/storage`) in `storage.json` there. The platform's: the
661    /// system's data directory ([`data_dir`]) for apps of their own,
662    /// `…/nsh` in an embedding app's. `None`: nothing is kept.
663    pub data_dir: Option<std::path::PathBuf>,
664    /// The app's storage, overriding the one [`EngineConfig::data_dir`]
665    /// names (the browser's `localStorage`, an embedder's own); `None`
666    /// with no data directory either: in memory, for the engine's life.
667    pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
668    /// The time the app runs on: the system's, or a manual clock a test
669    /// moves (`nsh_core::time::Clock::manual`), which its timers, frames
670    /// and `Date` follow.
671    pub clock: Clock,
672    /// Values of the environment kept whatever the platform reports (a
673    /// test's locale, reduced motion and safe area: `nsh test --target`).
674    pub pinned: EnvironmentPins,
675    /// Serves the app's clipboard calls in place of the platform's
676    /// clipboard (a test's own: `nsh test --target`); `None`: the
677    /// platform's.
678    pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
679}
680
681/// Values of the environment an engine keeps whatever its platform reports
682/// ([`EngineConfig::pinned`]); `None` leaves the platform's.
683#[derive(Debug, Clone, Copy, Default, PartialEq)]
684#[non_exhaustive]
685pub struct EnvironmentPins {
686    /// The locale (`Environment::locale`).
687    pub locale: Option<nsh_core::platform::Locale>,
688    /// Whether the user asked for less motion
689    /// (`Environment::reduce_motion`).
690    pub reduce_motion: Option<bool>,
691    /// The safe area insets (`Environment::safe_area`).
692    pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
693}
694
695impl EnvironmentPins {
696    /// `environment` with these values in place of the platform's.
697    pub fn apply(&self, environment: &mut Environment) {
698        if let Some(locale) = self.locale {
699            environment.locale = locale;
700        }
701        if let Some(reduce_motion) = self.reduce_motion {
702            environment.reduce_motion = reduce_motion;
703        }
704        if let Some(safe_area) = self.safe_area {
705            environment.safe_area = safe_area;
706        }
707    }
708}
709
710fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
711    let path = path.filter(|path| path.is_absolute())?;
712    nsh_core::access::canonicalize(&path)
713        .ok()
714        .filter(|path| path.is_dir())
715}
716
717/// Native hosts choose these anchors before any application JavaScript runs.
718#[cfg(feature = "js")]
719fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
720    let mut paths = bundle.system_paths.clone();
721    paths.plugin_dir = trusted_directory(paths.plugin_dir);
722    paths.home_dir = trusted_directory(paths.home_dir);
723    if paths.home_dir.is_none() {
724        paths.home_dir = ["HOME", "USERPROFILE"]
725            .into_iter()
726            .filter_map(std::env::var_os)
727            .map(std::path::PathBuf::from)
728            .find_map(|path| trusted_directory(Some(path)));
729    }
730    // Local `nsh run` passes its canonical entry directory directly to the
731    // native child process. Remote dev messages never contain this field.
732    // A packaged/hardened bundle cannot inherit a development source anchor.
733    if paths.plugin_dir.is_none() && !bundle.policy.harden {
734        paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
735            .map(std::path::PathBuf::from)
736            .and_then(|path| trusted_directory(Some(path)));
737    }
738    paths
739}
740
741impl EngineConfig {
742    /// `app` on a phone-sized surface (390 × 844 points, iOS's header
743    /// heights) with nothing else: no network, assets, data directory or
744    /// UI sets, the default environment and limits, the shared runtime.
745    /// Set the fields that matter over it (`EngineConfig { ui_sets,
746    /// ..EngineConfig::new(app) }`). There is no `Default`: an engine has
747    /// no app to run by default.
748    pub fn new(app: impl Into<App>) -> Self {
749        Self {
750            app: app.into(),
751            viewport: Size::new(Points(390.0), Points(844.0)),
752            trace: false,
753            network: None,
754            websocket: None,
755            filesystem: None,
756            assets: None,
757            environment: Environment::default(),
758            header_heights: (Points(44.0), Points(96.0)),
759            limits: Limits::default(),
760            ui_sets: Vec::new(),
761            runtime: None,
762            data_dir: None,
763            storage: None,
764            clock: Clock::system(),
765            pinned: EnvironmentPins::default(),
766            clipboard: None,
767        }
768    }
769}
770
771/// The storage of the app `config` runs: [`EngineConfig::storage`], or a
772/// file in its directory of [`EngineConfig::data_dir`].
773fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
774    if let Some(storage) = &config.storage {
775        return Some(storage.clone());
776    }
777    #[cfg(not(target_arch = "wasm32"))]
778    if let Some(root) = &config.data_dir {
779        let dir = root.join(app_dir_name(config.app.app_id()));
780        return Some(FileStorage::open(dir));
781    }
782    None
783}
784
785#[cfg(not(target_arch = "wasm32"))]
786/// The runtime of components' tasks when the embedder gives none: a few
787/// threads, made on first use, shared by every engine (like a thread pool,
788/// it holds no engine's state).
789fn shared_runtime() -> tokio::runtime::Handle {
790    static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
791    RUNTIME
792        .get_or_init(|| {
793            tokio::runtime::Builder::new_multi_thread()
794                .worker_threads(2)
795                .thread_name("nsh-tasks")
796                .enable_all()
797                .build()
798                .expect("the tasks' runtime starts")
799        })
800        .handle()
801        .clone()
802}
803
804impl std::fmt::Debug for EngineConfig {
805    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
806        f.debug_struct("EngineConfig")
807            .field("app", &self.app)
808            .field("viewport", &self.viewport)
809            .field("trace", &self.trace)
810            .field("network", &self.network.is_some())
811            .field("assets", &self.assets.is_some())
812            .field("environment", &self.environment)
813            .field("header_heights", &self.header_heights)
814            .field("limits", &self.limits)
815            .field("ui_sets", &self.ui_sets)
816            .field("clock", &self.clock)
817            .field("pinned", &self.pinned)
818            .field("clipboard", &self.clipboard.is_some())
819            .finish()
820    }
821}
822
823/// How many times [`EngineControl::advance_clock`] stops for what comes
824/// due at most (sinon's fake timers stop at 1000 for one `runAll`; this
825/// leaves room for a long run of 60 Hz intervals).
826const MAX_ADVANCE_ROUNDS: usize = 100_000;
827
828enum Message {
829    Event(NodeId, EventKind, EventPayload),
830    Scroll(NodeId, Point<Points>, u32),
831    Zoom(NodeId, f32),
832    ComponentSize(NodeId, Size<Points>),
833    AnimationsFinished(Vec<nsh_core::animation::Finished>),
834    Resize(Size<Points>),
835    /// A component's task was woken: it runs in the loop.
836    Wake,
837    Environment(Environment),
838    RootSize(NodeId, Size<Points>, EdgeInsets),
839    ScreenHeader(NodeId, Option<Points>),
840    Frame,
841    States(NodeId, u8),
842    FontsChanged,
843    /// An event of a request (by the hop it is for: events of a hop the
844    /// engine left are dropped).
845    Fetch(Requester, u64, FetchEvent),
846    Hot(HotUpdate),
847    /// A chunk [`MountSink::load_chunk`] was asked for, or why it could
848    /// not be loaded (its id and the message).
849    Chunk(Result<Chunk, (String, String)>),
850    Perf(Option<Arc<perf::PerfMonitor>>),
851    /// The embedding app's design tokens.
852    Tokens(Option<Box<Tokens>>),
853    /// Moves a manual clock forward by this much, then calls back.
854    Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
855    /// Sent by a dropped [`Engine`] (there is none in WebAssembly).
856    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
857    Shutdown,
858}
859
860/// A development update that replaces the app's changed modules in place,
861/// keeping the JS context, the views and the state of everything else
862/// (made by `nsh_bundler::HotBundle::patch`).
863#[derive(Debug, Clone)]
864pub struct HotUpdate {
865    /// Script name in stack traces, unique per update (e.g. `hot-3.js`).
866    pub name: String,
867    /// The script.
868    pub code: String,
869    /// Its source map (JSON).
870    pub source_map: Option<Arc<str>>,
871}
872
873/// Rounds of "list asks for items -> JS renders them -> layout" folded into
874/// one frame. Bounded so a list that never settles cannot stall the engine;
875/// leftovers continue next frame.
876const MAX_LIST_ROUNDS: usize = 8;
877
878/// A cheap, cloneable handle for sending input to the engine from any thread.
879#[derive(Clone)]
880pub struct EngineControl {
881    tx: Sender<Message>,
882}
883
884impl EngineControl {
885    /// Delivers an input event (and its data) to a node.
886    pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
887        let _ = self.tx.send(Message::Event(id, event, payload));
888    }
889
890    /// Reports the content offset of a scroll view or list, and how many
891    /// scrolls the core asked for (`MountItem::ScrollBy` items and
892    /// `Command::ScrollTo` commands for the view) were applied before it.
893    /// Cheap to call on every scroll frame: offsets are coalesced per
894    /// engine frame.
895    pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
896        let _ = self.tx.send(Message::Scroll(id, offset, applied));
897    }
898
899    /// Reports the zoom scale of a zoomable scroll view (before the offset
900    /// the zoom changed); `onScroll` carries it.
901    pub fn zoom(&self, id: NodeId, scale: f32) {
902        let _ = self.tx.send(Message::Zoom(id, scale));
903    }
904
905    /// A registered native component's own size (points): it is laid out at
906    /// it where its style leaves a dimension open.
907    pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
908        let _ = self.tx.send(Message::ComponentSize(id, size));
909    }
910
911    /// Reports native animations that finished or were interrupted.
912    pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
913        let _ = self.tx.send(Message::AnimationsFinished(finished));
914    }
915
916    /// Resizes the root view.
917    pub fn resize(&self, size: Size<Points>) {
918        let _ = self.tx.send(Message::Resize(size));
919    }
920
921    /// Reports a change of the surface's environment (safe area, keyboard,
922    /// appearance...).
923    pub fn set_environment(&self, environment: Environment) {
924        let _ = self.tx.send(Message::Environment(environment));
925    }
926
927    /// The platform presents root `id` (a modal) at `size`, with `insets`
928    /// of it covered by system UI.
929    pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
930        let _ = self.tx.send(Message::RootSize(id, size, insets));
931    }
932
933    /// The platform measured where the content of screen `id` starts below
934    /// its header (`None`: let the core estimate it).
935    pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
936        let _ = self.tx.send(Message::ScreenHeader(id, height));
937    }
938
939    /// Applies a development update in place. When it cannot be applied,
940    /// [`MountSink::hot_update_failed`] asks the platform to reload.
941    pub fn hot_update(&self, update: HotUpdate) {
942        let _ = self.tx.send(Message::Hot(update));
943    }
944
945    /// Hands over the chunk [`MountSink::load_chunk`] asked for: the
946    /// dynamic imports waiting for it continue.
947    pub fn chunk_loaded(&self, chunk: Chunk) {
948        let _ = self.tx.send(Message::Chunk(Ok(chunk)));
949    }
950
951    /// Chunk `id` could not be loaded: the dynamic imports waiting for it
952    /// fail with `message` (a later import asks for it again).
953    pub fn chunk_failed(&self, id: String, message: String) {
954        let _ = self.tx.send(Message::Chunk(Err((id, message))));
955    }
956
957    /// A display frame began, after [`MountSink::request_frame`]: runs the
958    /// `requestAnimationFrame` callbacks and the tasks waiting for it.
959    pub fn frame(&self) {
960        let _ = self.tx.send(Message::Frame);
961    }
962
963    /// Moves the engine's manual clock ([`EngineConfig::clock`]) forward
964    /// by `by`: the timers and tasks due meanwhile run in the order they
965    /// come due, each at its time, with what they make due in turn, and the
966    /// clock's alarms (a response it holds back) go off on the way. Then
967    /// `done` runs, after the batches of what ran were submitted. With the
968    /// system's clock it only runs `done`.
969    pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
970        let _ = self.tx.send(Message::Advance(by, Box::new(done)));
971    }
972
973    /// Reports the interaction states of view `id` that the core asked to
974    /// track ([`nsh_core::MountItem::TrackStates`]; bits of
975    /// [`nsh_core::tailwind::state`]). Class styles that depend on them
976    /// (`active:`, `hover:`, `focus:`) update without JS.
977    pub fn set_states(&self, id: NodeId, states: u8) {
978        let _ = self.tx.send(Message::States(id, states));
979    }
980
981    /// Fonts the platform loads asynchronously became usable (on the web,
982    /// a `FontFace` finished loading): text measured with a fallback font
983    /// is measured again.
984    pub fn fonts_changed(&self) {
985        let _ = self.tx.send(Message::FontsChanged);
986    }
987
988    /// Records the engine's commits into `monitor` from now on (`None`:
989    /// stops). Measuring costs nothing while no monitor is installed.
990    pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
991        let _ = self.tx.send(Message::Perf(monitor));
992    }
993
994    /// Sets the embedding app's design tokens (`nsh-base`'s theme's),
995    /// which the app renders with instead of its own (`None`: its own
996    /// again; [`Core::set_host_tokens`]). Sent from
997    /// [`Engine::start_with`]'s `setup`, they are in the first frame.
998    pub fn set_tokens(&self, tokens: Option<Tokens>) {
999        let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1000    }
1001}
1002
1003#[cfg(not(target_arch = "wasm32"))]
1004/// A running engine. Dropping it stops the thread.
1005pub struct Engine {
1006    control: EngineControl,
1007    thread: Option<std::thread::JoinHandle<()>>,
1008    /// Interrupts running JS when the engine stops.
1009    stop: Arc<std::sync::atomic::AtomicBool>,
1010}
1011
1012#[cfg(not(target_arch = "wasm32"))]
1013impl Engine {
1014    /// Starts the engine thread. `make_text_engine` runs on that thread.
1015    pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
1016    where
1017        M: TextEngine + 'static,
1018        F: FnOnce() -> M + Send + 'static,
1019        S: MountSink,
1020    {
1021        Self::start_with(config, make_text_engine, sink, |_| {})
1022    }
1023
1024    /// [`Engine::start`], with `setup` sending input before the engine
1025    /// starts: what it sends (a theme, the environment) is applied before
1026    /// the first frame.
1027    pub fn start_with<M, F, S>(
1028        config: EngineConfig,
1029        make_text_engine: F,
1030        sink: S,
1031        setup: impl FnOnce(&EngineControl),
1032    ) -> io::Result<Engine>
1033    where
1034        M: TextEngine + 'static,
1035        F: FnOnce() -> M + Send + 'static,
1036        S: MountSink,
1037    {
1038        let (tx, rx) = crossbeam_channel::unbounded();
1039        setup(&EngineControl { tx: tx.clone() });
1040        let engine_tx = tx.clone();
1041        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1042        let engine_stop = stop.clone();
1043        let thread = std::thread::Builder::new()
1044            .name("nsh-engine".into())
1045            .stack_size(ENGINE_STACK_SIZE)
1046            .spawn(move || run(config, make_text_engine(), sink, engine_tx, rx, engine_stop))?;
1047        Ok(Engine {
1048            control: EngineControl { tx },
1049            thread: Some(thread),
1050            stop,
1051        })
1052    }
1053
1054    /// A handle for sending input from other threads.
1055    pub fn control(&self) -> EngineControl {
1056        self.control.clone()
1057    }
1058}
1059
1060#[cfg(not(target_arch = "wasm32"))]
1061impl Drop for Engine {
1062    fn drop(&mut self) {
1063        // Dropped on the platform's main thread: a script still running is
1064        // aborted rather than waited for.
1065        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
1066        let _ = self.control.tx.send(Message::Shutdown);
1067        if let Some(thread) = self.thread.take() {
1068            let _ = thread.join();
1069        }
1070    }
1071}
1072
1073#[cfg(not(target_arch = "wasm32"))]
1074/// The engine thread turns input into frames: it is as latency-critical as
1075/// the UI thread. Without this, Apple platforms may run it on efficiency
1076/// cores at low clock speeds.
1077fn raise_thread_priority() {
1078    #[cfg(target_vendor = "apple")]
1079    // SAFETY: changes the QoS class of the calling thread only.
1080    unsafe {
1081        libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
1082    }
1083}
1084
1085#[cfg(not(target_arch = "wasm32"))]
1086fn run<M: TextEngine + 'static, S: MountSink>(
1087    config: EngineConfig,
1088    text_engine: M,
1089    sink: S,
1090    tx: Sender<Message>,
1091    rx: Receiver<Message>,
1092    stop: Arc<std::sync::atomic::AtomicBool>,
1093) {
1094    raise_thread_priority();
1095    // The thread's time is the engine's from its first line of JS on.
1096    let _clock = config.clock.enter();
1097    let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
1098        return;
1099    };
1100    loop {
1101        let message = match driver.deadline() {
1102            Some(deadline) => match rx.recv_deadline(deadline) {
1103                Ok(message) => Some(message),
1104                Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
1105                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
1106            },
1107            None => match rx.recv() {
1108                Ok(message) => Some(message),
1109                Err(_) => return,
1110            },
1111        };
1112        let started = driver.state.perf.is_some().then(Instant::now);
1113        if let Some(message) = message {
1114            if !driver.handle(message, &rx) {
1115                return;
1116            }
1117            // Coalesce everything already queued into this frame.
1118            while let Ok(message) = rx.try_recv() {
1119                if !driver.handle(message, &rx) {
1120                    return;
1121                }
1122            }
1123        }
1124        driver.turn();
1125        driver.state.record_perf(started);
1126        if rx.is_empty() {
1127            driver.collect_if_idle();
1128        }
1129    }
1130}
1131
1132/// An engine driven by its host's event loop instead of a thread of its
1133/// own: the browser's main thread in WebAssembly, where there are no
1134/// threads to block. Input sent through its [`EngineControl`] is handled
1135/// at the next [`LocalEngine::pump`].
1136pub struct LocalEngine<M: TextEngine + 'static> {
1137    driver: Driver<M>,
1138    rx: Receiver<Message>,
1139    control: EngineControl,
1140    /// The host's wake ([`LocalEngine::set_wake`]).
1141    wake: Option<Arc<dyn Fn() + Send + Sync>>,
1142    /// Set while [`LocalEngine::pump`] runs: what it wakes it runs itself,
1143    /// so the host's wake is not called for it.
1144    pumping: Arc<std::sync::atomic::AtomicBool>,
1145}
1146
1147impl<M: TextEngine + 'static> LocalEngine<M> {
1148    /// Starts the app (its first frame goes to `sink` before this returns);
1149    /// `None` if it could not start (reported to `sink`).
1150    pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
1151        let (tx, rx) = crossbeam_channel::unbounded();
1152        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1153        let control = EngineControl { tx: tx.clone() };
1154        let _clock = config.clock.enter();
1155        let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
1156        Some(LocalEngine {
1157            driver,
1158            rx,
1159            control,
1160            wake: None,
1161            pumping: Arc::default(),
1162        })
1163    }
1164
1165    /// A handle for sending input.
1166    pub fn control(&self) -> EngineControl {
1167        self.control.clone()
1168    }
1169
1170    /// Calls `wake` when there is work outside a [`pump`](Self::pump): a
1171    /// component task is woken or Rust posts a JS call while no pump runs
1172    /// (a callback of the host's completing what a task waits for, such as
1173    /// a WebSocket message through wasm-bindgen), once per wake-up, or a
1174    /// pump ends with work its bound left. The host then calls `pump` soon,
1175    /// instead of only at the deadline it returned or at the next input.
1176    /// What a pump wakes itself (a task waking another, a reply it hands
1177    /// over) it runs without calling `wake`.
1178    pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
1179        let tx = self.control.tx.clone();
1180        let pumping = self.pumping.clone();
1181        let host = wake.clone();
1182        let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
1183            let _ = tx.send(Message::Wake);
1184            // After the send: a pump that is ending sees the message
1185            // (`pump` clears the flag, then looks at the queue).
1186            if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
1187                host();
1188            }
1189        });
1190        self.driver.state.core.set_task_notify(notify.clone());
1191        self.driver.posts.set_notify(notify);
1192        self.wake = Some(wake);
1193    }
1194
1195    /// Handles the input sent since the last call, runs what is due
1196    /// (timers, tasks) and commits. Returns when to call again at the
1197    /// latest (sooner if input arrives); `None`: only for input.
1198    pub fn pump(&mut self) -> Option<Instant> {
1199        let _clock = self.driver.clock.enter();
1200        self.pumping
1201            .store(true, std::sync::atomic::Ordering::SeqCst);
1202        // Bounded: messages sent while handling (a task waking another)
1203        // are handled in the same call, a loop that never settles is not.
1204        for _ in 0..4 {
1205            let started = self.driver.state.perf.is_some().then(Instant::now);
1206            while let Ok(message) = self.rx.try_recv() {
1207                self.driver.handle(message, &self.rx);
1208            }
1209            self.driver.turn();
1210            self.driver.state.record_perf(started);
1211            if self.rx.is_empty() {
1212                break;
1213            }
1214        }
1215        self.driver.collect_if_idle();
1216        self.pumping
1217            .store(false, std::sync::atomic::Ordering::SeqCst);
1218        // What the bound left waits for the next pump: soon, not at the
1219        // deadline.
1220        if !self.rx.is_empty()
1221            && let Some(wake) = &self.wake
1222        {
1223            wake();
1224        }
1225        self.driver.deadline()
1226    }
1227}
1228
1229/// One engine's state and the work of one wake-up, whoever drives it.
1230struct Driver<M: TextEngine + 'static> {
1231    state: State<Rc<M>>,
1232    script: Option<Script>,
1233    sink: Rc<dyn MountSink>,
1234    assets: Option<Arc<dyn Assets>>,
1235    /// A VM stopped for good (out of memory, over a quota) is reported
1236    /// once; its views stay as they were and no JS runs any more.
1237    stopped: bool,
1238    last_gc: Instant,
1239    /// The queue of the JS calls Rust posts: its notify wakes the engine,
1240    /// as the core's task notify does ([`LocalEngine::set_wake`]).
1241    posts: nsh_core::ui::Posts,
1242    /// The engine's clock, its thread's ([`Clock::enter`]).
1243    clock: Clock,
1244    /// When the last display frame ran, on a clock that moves with the
1245    /// display's frames: the next one comes a frame after it.
1246    last_frame: Option<Instant>,
1247}
1248
1249impl<M: TextEngine + 'static> Driver<M> {
1250    /// Sets up the core, starts the app and submits its first frame.
1251    fn start(
1252        mut config: EngineConfig,
1253        text_engine: M,
1254        sink: Rc<dyn MountSink>,
1255        tx: Sender<Message>,
1256        rx: &Receiver<Message>,
1257        stop: Arc<std::sync::atomic::AtomicBool>,
1258    ) -> Option<Self> {
1259        config.pinned.apply(&mut config.environment);
1260        #[cfg(feature = "js")]
1261        let system_tx = tx.clone();
1262        let text_engine = Rc::new(text_engine);
1263        let access = Arc::new(match &config.app {
1264            App::Js(bundle) => bundle.policy.access(),
1265            // Native code is trusted: it reaches what the platform allows.
1266            App::Rust(_) => Policy::default().access(),
1267        });
1268        let mut core = Core::new(text_engine.clone(), config.viewport);
1269        core.set_components(nsh_core::ui::Registry::merged(&config.ui_sets));
1270        // The JS calls Rust posts queue in one place, which the core
1271        // releases in order with the ops (a post during a synchronous call)
1272        // and the script runs.
1273        let posts = nsh_core::ui::Posts::new();
1274        core.set_posts(posts.clone());
1275        if let App::Js(_) = &config.app {
1276            // Only JS is limited (Rust code is as trusted as the platform).
1277            core.set_max_nodes(config.limits.max_nodes);
1278        }
1279        core.set_access(access.clone());
1280        core.set_storage(app_storage(&config));
1281        core.set_clipboard(config.clipboard.clone());
1282        core.set_font_scale(config.environment.font_scale);
1283        core.set_class_environment(class_environment(&config.environment));
1284        core.set_header_heights(config.header_heights.0, config.header_heights.1);
1285        core.set_safe_area(insets(&config.environment));
1286        core.set_environment(ui_environment(&config.environment, config.viewport));
1287        // WebAssembly has no threads for a runtime: tasks' timers are
1288        // `nsh_core::time`'s there, fired by the driver.
1289        #[cfg(not(target_arch = "wasm32"))]
1290        core.set_task_runtime(config.runtime.clone().unwrap_or_else(shared_runtime));
1291        // A Rust app's theme and fonts come with its root (a JS app's from
1292        // its bundle).
1293        if let App::Rust(root) = &config.app {
1294            if let Some(tokens) = root.tokens_ref() {
1295                core.set_tokens(tokens.clone());
1296            }
1297            if let Some(appearance) = root.appearance_ref() {
1298                core.set_appearance(appearance);
1299            }
1300            for font in root.fonts() {
1301                if let Err(err) = core.register_font(font) {
1302                    log::error!("font failed: {err}");
1303                    sink.report(&AppError::new(
1304                        AppErrorKind::Asset,
1305                        &format!("font failed: {err}"),
1306                    ));
1307                }
1308            }
1309        }
1310        // The fonts the UI sets' crates ship, before anything is measured.
1311        let fonts = config
1312            .ui_sets
1313            .iter()
1314            .flat_map(nsh_core::ui::Registry::asset_files)
1315            .filter(|file| file.kind == nsh_core::ui::AssetKind::Font);
1316        for font in fonts {
1317            let result = match config.assets.as_deref() {
1318                Some(assets) => assets.read(font.uri),
1319                None => Err("this host cannot load assets".to_owned()),
1320            }
1321            .and_then(|data| core.register_font(&data));
1322            if let Err(err) = result {
1323                log::error!("font failed: {}: {err}", font.uri);
1324                let message = format!("font failed: {}: {err}", font.uri);
1325                let package = match &config.app {
1326                    App::Js(bundle) => bundle.package.clone(),
1327                    App::Rust(_) => None,
1328                };
1329                sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
1330            }
1331        }
1332        // A task woken on any thread wakes the loop, and so does a JS call
1333        // Rust queues.
1334        let wake = tx.clone();
1335        core.set_task_notify(Arc::new(move || {
1336            let _ = wake.send(Message::Wake);
1337        }));
1338        let wake = tx.clone();
1339        posts.set_notify(Arc::new(move || {
1340            let _ = wake.send(Message::Wake);
1341        }));
1342        let js_tokens = core.tokens().clone();
1343        let state = State {
1344            core,
1345            js_tokens,
1346            frame_requested: false,
1347            ops: Vec::new(),
1348            binds: Vec::new(),
1349            events: Vec::new(),
1350            trace: config.trace,
1351            perf: None,
1352            perf_commit: perf::CommitTiming::default(),
1353            committed_since_gc: false,
1354            hot: Vec::new(),
1355            scroll_events: FxHashMap::default(),
1356            touch_move: None,
1357            hover_moves: Vec::new(),
1358            hover_moved: None,
1359            resized: None,
1360            pinned: config.pinned,
1361            net: Net {
1362                network: config.network.clone(),
1363                tx,
1364                queue: NetworkQueue::default(),
1365                inflight: FxHashMap::default(),
1366                tasks: Vec::new(),
1367                abandoned: Vec::new(),
1368                access: access.clone(),
1369                hops: 0,
1370            },
1371        };
1372
1373        let mut environment = config.environment;
1374        environment.window = config.viewport;
1375        let start = Instant::now();
1376        let mut driver = Driver {
1377            state,
1378            script: None,
1379            sink: sink.clone(),
1380            assets: config.assets.clone(),
1381            stopped: false,
1382            last_gc: Instant::now(),
1383            posts: posts.clone(),
1384            clock: config.clock.clone(),
1385            last_frame: None,
1386        };
1387        let eval_us = match &config.app {
1388            App::Js(bundle) => {
1389                #[cfg(feature = "js")]
1390                let system = {
1391                    script::SystemConfig {
1392                        access: (*access).clone(),
1393                        websocket: config.websocket.clone(),
1394                        filesystem: config.filesystem.clone(),
1395                        data_dir: config
1396                            .data_dir
1397                            .as_ref()
1398                            .map(|root| root.join(app_dir_name(config.app.app_id()))),
1399                        paths: bundle_system_paths(bundle),
1400                        wake: Arc::new(move || {
1401                            let _ = system_tx.send(Message::Wake);
1402                        }),
1403                    }
1404                };
1405                #[cfg(not(feature = "js"))]
1406                let system = script::SystemConfig;
1407                let (script, eval_us) = Script::start(
1408                    bundle,
1409                    config.limits,
1410                    &config.ui_sets,
1411                    posts,
1412                    &environment,
1413                    driver.state.js_tokens.clone(),
1414                    text_engine,
1415                    stop,
1416                    sink,
1417                    system,
1418                )?;
1419                driver.script = Some(script);
1420                eval_us
1421            }
1422            App::Rust(root) => {
1423                driver.state.core.mount_root(root);
1424                0
1425            }
1426        };
1427        let Driver {
1428            state,
1429            script,
1430            sink,
1431            assets,
1432            ..
1433        } = &mut driver;
1434        let script = script.as_ref();
1435        // What was sent before the start (`Engine::start_with`) is in the
1436        // first frame; a move of the clock comes after it.
1437        let mut moves = Vec::new();
1438        while let Ok(message) = rx.try_recv() {
1439            if let Message::Advance(..) = message {
1440                moves.push(message);
1441            } else if !handle(script, state, message) {
1442                return None;
1443            }
1444        }
1445        // Workers may finish while the first bundle evaluates. Deliver their
1446        // completions even when the startup drain already consumed their wakeup.
1447        if let Some(script) = script {
1448            script.run_system();
1449        }
1450        state.load_fonts(script, assets.as_deref(), &**sink);
1451        if let Some(batch) = state.commit(script) {
1452            if state.trace {
1453                log::info!(
1454                    target: "nsh::perf",
1455                    "first frame: eval {eval_us}µs, total {}µs",
1456                    start.elapsed().as_micros()
1457                );
1458            }
1459            sink.submit(batch);
1460        }
1461        state.net.pump(script, &mut state.core);
1462        state.load_chunks(script, &**sink);
1463        state.request_frame(script, &**sink);
1464        driver.check_stopped();
1465        for message in moves {
1466            if !driver.handle(message, rx) {
1467                return None;
1468            }
1469        }
1470        Some(driver)
1471    }
1472
1473    /// When the loop wakes next: for the next timer or throttled event
1474    /// (on the system's clock; a manual one moves only when told), or the
1475    /// idle collection (the system's time, whatever the clock).
1476    fn deadline(&self) -> Option<Instant> {
1477        let gc_deadline = (self.script.is_some() && self.state.committed_since_gc)
1478            .then(|| self.last_gc + IDLE_GC_INTERVAL);
1479        let due = if self.clock.is_manual() {
1480            None
1481        } else {
1482            self.due()
1483        };
1484        [due, gc_deadline].into_iter().flatten().min()
1485    }
1486
1487    /// When the next timer, task timer or throttled scroll or hover event
1488    /// is due, on the engine's clock.
1489    fn due(&self) -> Option<Instant> {
1490        [
1491            self.script.as_ref().and_then(Script::next_timer),
1492            self.state.next_scroll_event(),
1493            self.state.next_hover_move(),
1494            self.state.core.next_task_timer(),
1495        ]
1496        .into_iter()
1497        .flatten()
1498        .min()
1499    }
1500
1501    /// Handles one message; false on shutdown.
1502    fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
1503        match message {
1504            Message::Advance(by, done) => {
1505                let running = self.advance(by, rx, self.clock.moves_with_frames());
1506                done();
1507                running
1508            }
1509            // A test's clock on a real platform: the display's frame moves it
1510            // to the frame's time first (a frame after the last, else now),
1511            // as a headless run's frames do.
1512            Message::Frame if self.clock.moves_with_frames() => {
1513                // The frame runs there, once, as the frames a move runs on
1514                // the way do (whatever the messages handled meanwhile do).
1515                self.state.frame_requested = true;
1516                let by = self.next_frame() - self.clock.now();
1517                self.advance(by, rx, true)
1518            }
1519            message => handle(self.script.as_ref(), &mut self.state, message),
1520        }
1521    }
1522
1523    /// Moves a manual clock forward by `by` ([`EngineControl::advance_clock`]):
1524    /// to each time something comes due on the way, running it (and the
1525    /// messages its alarms sent) before going on; with `frames`, also to
1526    /// each display frame's time ([`nsh_core::time::FRAME`]) while the app
1527    /// waits for frames, running the frame there, as a headless run's
1528    /// display does (a clock that moves with a real display's frames:
1529    /// [`Clock::with_frames`]). False on shutdown.
1530    fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
1531        if !self.clock.is_manual() {
1532            // What the messages before it did is submitted before `done`.
1533            self.turn();
1534            return true;
1535        }
1536        let to = self.clock.now() + by;
1537        for round in 0.. {
1538            // A timer that keeps scheduling itself at once (`setTimeout(f,
1539            // 0)` in `f`) would hold the clock at one time for good.
1540            let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
1541            let next = [self.due(), self.clock.next_alarm(), frame]
1542                .into_iter()
1543                .flatten()
1544                .min()
1545                .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
1546            if round == MAX_ADVANCE_ROUNDS {
1547                log::warn!(
1548                    "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
1549                     a timer keeps scheduling another at once"
1550                );
1551            }
1552            let at = next.unwrap_or(to);
1553            self.clock.advance_to(at);
1554            while let Ok(message) = rx.try_recv() {
1555                if !self.handle(message, rx) {
1556                    return false;
1557                }
1558            }
1559            // Once: what was handled meanwhile may have run it already.
1560            if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
1561                && self.state.frame_requested
1562            {
1563                self.frame();
1564            }
1565            self.turn();
1566            if next.is_none() {
1567                break;
1568            }
1569        }
1570        true
1571    }
1572
1573    /// When the next display frame of a clock that moves with the
1574    /// display's frames is: a frame after the last, at the display's pace
1575    /// whatever else comes due meanwhile, else (the first, or after a
1576    /// pause) a frame from now or now.
1577    fn next_frame(&self) -> Instant {
1578        let now = self.clock.now();
1579        self.last_frame
1580            .map_or(now + nsh_core::time::FRAME, |last| {
1581                last + nsh_core::time::FRAME
1582            })
1583            .max(now)
1584    }
1585
1586    /// Runs a display frame of a clock that moves with the display's
1587    /// frames, now.
1588    fn frame(&mut self) {
1589        self.last_frame = Some(self.clock.now());
1590        handle(self.script.as_ref(), &mut self.state, Message::Frame);
1591    }
1592
1593    /// Runs what the handled messages and the time made due, and submits
1594    /// the frame.
1595    fn turn(&mut self) {
1596        let Driver {
1597            state,
1598            script,
1599            sink,
1600            assets,
1601            ..
1602        } = self;
1603        let script = script.as_ref();
1604        let turn_start = state.trace.then(Instant::now);
1605        state.dispatch_touch_move(script);
1606        if state
1607            .next_hover_move()
1608            .is_some_and(|due| due <= nsh_core::time::now())
1609        {
1610            state.dispatch_hover_moves(script);
1611        }
1612        state.dispatch_scroll_events(script);
1613        let hot = std::mem::take(&mut state.hot);
1614        if let Some(script) = script {
1615            for update in hot {
1616                script.hot_update(update, &**sink);
1617            }
1618            script.run_timers(nsh_core::time::now());
1619            script.run_system();
1620        }
1621        state.core.run_component_tasks();
1622        // What JS timers and Rust component tasks took; a Rust component
1623        // renders in the commit.
1624        let tasks = turn_start.map(|s| s.elapsed());
1625        state.load_fonts(script, assets.as_deref(), &**sink);
1626        if let Some(batch) = state.commit(script) {
1627            sink.submit(batch);
1628            if let (Some(start), Some(tasks)) = (turn_start, tasks) {
1629                log::info!(
1630                    target: "nsh::perf",
1631                    "turn: {}µs (timers and tasks {}µs)",
1632                    start.elapsed().as_micros(),
1633                    tasks.as_micros(),
1634                );
1635            }
1636        }
1637        if let Some(size) = state.resized.take() {
1638            sink.resized(size);
1639        }
1640        state.net.pump(script, &mut state.core);
1641        state.load_chunks(script, &**sink);
1642        state.request_frame(script, &**sink);
1643        self.check_stopped();
1644    }
1645
1646    /// Collects cycles when the engine has been idle long enough, so
1647    /// released nodes free their views.
1648    fn collect_if_idle(&mut self) {
1649        if let Some(script) = &self.script
1650            && self.state.committed_since_gc
1651            && self.last_gc.elapsed() >= IDLE_GC_INTERVAL
1652        {
1653            script.collect_garbage();
1654            self.last_gc = Instant::now();
1655            self.state.committed_since_gc = false;
1656            if let Some(batch) = self.state.commit(Some(script)) {
1657                self.sink.submit(batch);
1658            }
1659        }
1660    }
1661
1662    fn check_stopped(&mut self) {
1663        if let Some(script) = &self.script
1664            && !self.stopped
1665            && let Some(reason) = script.fatal()
1666        {
1667            self.stopped = true;
1668            script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
1669        }
1670    }
1671}
1672
1673struct ScrollEvent {
1674    x: f32,
1675    y: f32,
1676    content: Size<Points>,
1677    viewport: Size<Points>,
1678    /// The zoom scale.
1679    zoom: f32,
1680    throttle: Duration,
1681    last: Option<Instant>,
1682    /// An offset not reported yet.
1683    pending: bool,
1684}
1685
1686struct State<M: TextEngine> {
1687    core: Core<M>,
1688    /// The design tokens JS has (`token()`): the core's when they were
1689    /// last sent.
1690    js_tokens: Arc<nsh_core::ui::Tokens>,
1691    /// What the environment keeps whatever the platform reports
1692    /// ([`EngineConfig::pinned`]).
1693    pinned: EnvironmentPins,
1694    /// A display frame was requested and has not begun yet.
1695    frame_requested: bool,
1696    ops: Vec<Op>,
1697    /// List render requests not yet sent to JS.
1698    binds: Vec<ListBind>,
1699    /// Events raised by the core (e.g. `onLoadMore`, `onLayout`).
1700    events: Vec<JsEvent>,
1701    trace: bool,
1702    /// Where commit timings go ([`EngineControl::set_perf_monitor`]).
1703    perf: Option<Arc<perf::PerfMonitor>>,
1704    /// The core's share of the wake-up being measured (`layout`, `ops`,
1705    /// `items`; `js` is the rest of the wake-up).
1706    perf_commit: perf::CommitTiming,
1707    committed_since_gc: bool,
1708    net: Net,
1709    /// Development updates to apply.
1710    hot: Vec<HotUpdate>,
1711    /// `onScroll` events: the latest offset per scroll view, sent once per
1712    /// frame at most (and not more often than the view's throttle).
1713    scroll_events: FxHashMap<NodeId, ScrollEvent>,
1714    /// Touch moves not delivered yet: those queued in one frame become one.
1715    touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
1716    /// Hover and mouse moves not delivered yet: the latest per view, in the order
1717    /// they came; sent once per [`HOVER_MOVE_INTERVAL`] at most, and before
1718    /// any other event.
1719    hover_moves: Vec<(NodeId, EventKind, EventPayload)>,
1720    /// When `hover_moves` were last delivered.
1721    hover_moved: Option<Instant>,
1722    /// The viewport size a resize set this turn ([`MountSink::resized`]).
1723    resized: Option<Size<Points>>,
1724}
1725
1726/// Who made a request: JS (`fetch`), or a Rust component's task
1727/// (`nsh_core::ui::fetch`, [`Core::take_fetches`]).
1728#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1729enum Requester {
1730    Js(RequestId),
1731    Task(u32),
1732}
1733
1734/// Requests between the app (JS and Rust components' tasks) and the
1735/// platform's network stack.
1736struct Net {
1737    network: Option<Arc<dyn Network>>,
1738    tx: Sender<Message>,
1739    queue: NetworkQueue,
1740    inflight: FxHashMap<Requester, Inflight>,
1741    /// The tasks' requests taken from the core, and those they gave up
1742    /// (reused buffers).
1743    tasks: Vec<(u32, HttpRequest)>,
1744    abandoned: Vec<u32>,
1745    /// What the app may reach.
1746    access: Arc<nsh_core::access::Access>,
1747    /// Hops started so far (the id of the next).
1748    hops: u64,
1749}
1750
1751/// A request in flight.
1752struct Inflight {
1753    task: Box<dyn FetchTask>,
1754    /// The hop the task is.
1755    hop: u64,
1756    /// Requests whose redirects the engine follows (to check each hop).
1757    followed: Option<access::Followed>,
1758}
1759
1760impl Net {
1761    /// Hands what JS and the components' tasks asked of their requests to
1762    /// the network.
1763    fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
1764        let mut abandoned = std::mem::take(&mut self.abandoned);
1765        core.take_fetches(&mut self.tasks, &mut abandoned);
1766        for id in abandoned.drain(..) {
1767            self.cancel(Requester::Task(id));
1768        }
1769        self.abandoned = abandoned;
1770        let mut tasks = std::mem::take(&mut self.tasks);
1771        for (id, request) in tasks.drain(..) {
1772            if let Err(refused) = self.request(Requester::Task(id), request) {
1773                core.fetch_event(id, FetchEvent::Failed(refused));
1774            }
1775        }
1776        self.tasks = tasks;
1777        let Some(script) = script else { return };
1778        script.take_network(&mut self.queue);
1779        for (id, op) in std::mem::take(&mut self.queue.ops) {
1780            let who = Requester::Js(id);
1781            match op {
1782                FetchOp::Start(request) => {
1783                    if let Err(refused) = self.request(who, request) {
1784                        script.fetch_event(id, FetchEvent::Failed(refused));
1785                    }
1786                }
1787                FetchOp::Send(chunk) => {
1788                    if let Some(i) = self.inflight.get_mut(&who) {
1789                        i.task.send(chunk);
1790                    }
1791                }
1792                FetchOp::Finish => {
1793                    if let Some(i) = self.inflight.get_mut(&who) {
1794                        i.task.finish();
1795                    }
1796                }
1797                FetchOp::Pause(paused) => {
1798                    if let Some(i) = self.inflight.get_mut(&who) {
1799                        i.task.pause(paused);
1800                    }
1801                }
1802                FetchOp::Cancel => self.cancel(who),
1803            }
1804        }
1805    }
1806
1807    /// Aborts `who`'s request.
1808    fn cancel(&mut self, who: Requester) {
1809        if let Some(i) = self.inflight.remove(&who) {
1810            i.task.cancel();
1811        }
1812    }
1813
1814    /// Makes `who`'s request, if the app may (else why not).
1815    fn request(&mut self, who: Requester, request: HttpRequest) -> Result<(), String> {
1816        if self.access.is_unrestricted() {
1817            self.start(who, request, None);
1818        } else if !self.access.allows_http(&request.method, &request.url) {
1819            return Err(access::refused(&request.method, &request.url));
1820        } else if request.follow_redirects {
1821            let hop = access::hop(&request);
1822            let followed = access::Followed { request, hops: 0 };
1823            self.start(who, hop, Some(followed));
1824        } else {
1825            self.start(who, request, None);
1826        }
1827        Ok(())
1828    }
1829
1830    /// Hands one request (or redirect hop) to the network.
1831    fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
1832        self.hops += 1;
1833        let hop = self.hops;
1834        let Some(network) = &self.network else {
1835            let failed = FetchEvent::Failed("this host has no network stack".to_owned());
1836            let _ = self.tx.send(Message::Fetch(id, hop, failed));
1837            return;
1838        };
1839        let tx = self.tx.clone();
1840        let events: FetchEvents = Box::new(move |event| {
1841            let _ = tx.send(Message::Fetch(id, hop, event));
1842        });
1843        let task = network.fetch(request, events);
1844        self.inflight.insert(
1845            id,
1846            Inflight {
1847                task,
1848                hop,
1849                followed,
1850            },
1851        );
1852    }
1853
1854    /// An event of hop `hop` of request `id`: what JS is told, if anything
1855    /// (`None` for events of hops left behind, and redirects the engine
1856    /// follows).
1857    fn event(&mut self, id: Requester, hop: u64, event: FetchEvent) -> Option<FetchEvent> {
1858        if self.network.is_none() {
1859            return Some(event);
1860        }
1861        let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
1862        match event {
1863            FetchEvent::Head(head) => {
1864                let Some(followed) = &mut inflight.followed else {
1865                    return Some(FetchEvent::Head(head));
1866                };
1867                match access::next(&self.access, followed, head) {
1868                    access::Next::Done(head) => Some(FetchEvent::Head(head)),
1869                    access::Next::Fail(message) => {
1870                        if let Some(i) = self.inflight.remove(&id) {
1871                            i.task.cancel();
1872                        }
1873                        Some(FetchEvent::Failed(message))
1874                    }
1875                    access::Next::Hop(request) => {
1876                        let i = self.inflight.remove(&id)?;
1877                        let followed = i.followed;
1878                        i.task.cancel();
1879                        self.start(id, request, followed);
1880                        None
1881                    }
1882                }
1883            }
1884            FetchEvent::End | FetchEvent::Failed(_) => {
1885                self.inflight.remove(&id);
1886                Some(event)
1887            }
1888            event => Some(event),
1889        }
1890    }
1891}
1892
1893impl<M: TextEngine> State<M> {
1894    /// Ends the measured wake-up that began at `started`
1895    /// ([`EngineControl::set_perf_monitor`]).
1896    fn record_perf(&mut self, started: Option<Instant>) {
1897        let (Some(started), Some(monitor)) = (started, &self.perf) else {
1898            return;
1899        };
1900        let busy = started.elapsed();
1901        monitor.record_busy(busy);
1902        let mut commit = std::mem::take(&mut self.perf_commit);
1903        if commit.ops > 0 || commit.items > 0 {
1904            commit.js = busy.saturating_sub(commit.layout);
1905            monitor.record_commit(commit);
1906        }
1907    }
1908
1909    /// Sends the pending touch move.
1910    fn dispatch_touch_move(&mut self, script: Option<&Script>) {
1911        if let Some((id, touch)) = self.touch_move.take()
1912            && let Some(script) = script
1913        {
1914            script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
1915        }
1916    }
1917
1918    /// When the pending `onHoverMove`s are due.
1919    fn next_hover_move(&self) -> Option<Instant> {
1920        if self.hover_moves.is_empty() {
1921            return None;
1922        }
1923        Some(
1924            self.hover_moved
1925                .map_or_else(nsh_core::time::now, |t| t + HOVER_MOVE_INTERVAL),
1926        )
1927    }
1928
1929    /// Delivers the pending `onHoverMove`s: to the Rust components whose
1930    /// parts they are on, the others to JS.
1931    fn dispatch_hover_moves(&mut self, script: Option<&Script>) {
1932        if self.hover_moves.is_empty() {
1933            return;
1934        }
1935        self.hover_moved = Some(nsh_core::time::now());
1936        for (id, kind, payload) in std::mem::take(&mut self.hover_moves) {
1937            if self.core.component_event(id, kind, &payload) {
1938                continue;
1939            }
1940            if let Some(script) = script {
1941                script.dispatch_event(id, kind, &payload);
1942            }
1943        }
1944    }
1945
1946    /// When a throttled `onScroll` is due.
1947    fn next_scroll_event(&self) -> Option<Instant> {
1948        self.scroll_events
1949            .values()
1950            .filter(|e| e.pending)
1951            .filter_map(|e| e.last.map(|t| t + e.throttle))
1952            .min()
1953    }
1954
1955    /// Sends the `onScroll` events that are due.
1956    fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
1957        if self.scroll_events.is_empty() {
1958            return;
1959        }
1960        let now = nsh_core::time::now();
1961        // Views that stopped listening (or are gone).
1962        let core = &self.core;
1963        self.scroll_events
1964            .retain(|&id, _| core.scroll_listener(id).is_some());
1965        for (&id, e) in &mut self.scroll_events {
1966            if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
1967                continue;
1968            }
1969            e.pending = false;
1970            e.last = Some(now);
1971            let n = |v: f32| PayloadValue::Number(v as f64);
1972            let payload = EventPayload::Map(vec![
1973                (
1974                    "offset",
1975                    PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
1976                ),
1977                ("contentSize", PayloadValue::Size(e.content)),
1978                ("size", PayloadValue::Size(e.viewport)),
1979                ("zoomScale", n(e.zoom)),
1980            ]);
1981            // A Rust component's scroll view is the component's.
1982            if !self.core.component_event(id, EventKind::Scroll, &payload)
1983                && let Some(script) = script
1984            {
1985                script.dispatch_event(id, EventKind::Scroll, &payload);
1986            }
1987        }
1988    }
1989
1990    /// Asks the platform for the chunks JS imports and does not have.
1991    fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
1992        let Some(script) = script else { return };
1993        let mut ids = Vec::new();
1994        script.take_chunk_requests(&mut ids);
1995        for id in ids {
1996            if !sink.load_chunk(&id) {
1997                let message = "this host does not load chunks (the app was built split)".to_owned();
1998                let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
1999            }
2000        }
2001    }
2002
2003    /// Asks the platform for a frame when JS or a component's task waits
2004    /// for one.
2005    fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
2006        if !self.frame_requested
2007            && (script.is_some_and(Script::wants_frame) || self.core.wants_frame())
2008        {
2009            self.frame_requested = true;
2010            sink.request_frame();
2011        }
2012    }
2013
2014    /// Registers fonts imported by JS. Blocking: text using them must not be
2015    /// measured with a fallback font first.
2016    fn load_fonts(
2017        &mut self,
2018        script: Option<&Script>,
2019        assets: Option<&dyn Assets>,
2020        sink: &dyn MountSink,
2021    ) {
2022        let Some(script) = script else { return };
2023        let mut fonts = Vec::new();
2024        script.take_fonts(&mut fonts);
2025        for uri in fonts {
2026            let result = match assets {
2027                Some(assets) => assets.read(&uri),
2028                None => Err("this host cannot load assets".to_owned()),
2029            }
2030            .and_then(|data| self.core.register_font(&data));
2031            if let Err(err) = result {
2032                script.report(
2033                    sink,
2034                    AppErrorKind::Asset,
2035                    "font failed",
2036                    &format!("{uri}: {err}"),
2037                );
2038            }
2039        }
2040    }
2041
2042    /// Produces one frame: applies JS ops, lays out, and lets lists pull
2043    /// the items they need, merging everything into a single batch.
2044    fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
2045        let start = Instant::now();
2046        let mut merged: Option<MountBatch> = None;
2047        let mut op_count = 0;
2048        let mut js = std::time::Duration::ZERO;
2049        for _ in 0..MAX_LIST_ROUNDS {
2050            // Requests from the previous round (or frame) first.
2051            let js_start = Instant::now();
2052            // Without JS, lists bind nowhere (Rust components' lists bind in
2053            // the core).
2054            let binds = self.binds.drain(..);
2055            if let Some(script) = script {
2056                for bind in binds {
2057                    script.bind_list(bind.list, &bind.binds);
2058                }
2059            } else {
2060                drop(binds);
2061            }
2062            // The JS calls Rust queued (callbacks' posts), in order, before
2063            // the events: a task's posts come before its result.
2064            if let Some(script) = script {
2065                script.run_posted();
2066            }
2067            // The core's events (layouts, ends reached, ...) on a Rust
2068            // component's nodes are the component's; the rest are JS's, in
2069            // order with Rust components' events and calls' results.
2070            for event in self.events.drain(..) {
2071                match event {
2072                    JsEvent::Event(id, event, payload) => {
2073                        if !self.core.component_event(id, event, &payload)
2074                            && let Some(script) = script
2075                        {
2076                            script.dispatch_event(id, event, &payload);
2077                        }
2078                    }
2079                    // Without JS nothing waits for them.
2080                    other => {
2081                        if let Some(script) = script {
2082                            script.deliver(other);
2083                        }
2084                    }
2085                }
2086            }
2087            if let Some(script) = script {
2088                script.take_ops(&mut self.ops);
2089            }
2090            js += js_start.elapsed();
2091            op_count += self.ops.len();
2092            // A stop drops the rest of the ops, releasing what they hold
2093            // for Rust classes.
2094            let mut ops = self.ops.drain(..);
2095            while let Some(op) = ops.next() {
2096                match self.core.apply(op) {
2097                    Ok(()) => {}
2098                    Err(err) if err.is_fatal() => {
2099                        self.core.discard_ops(ops.by_ref());
2100                        let Some(script) = script else { break };
2101                        script.stop(match err {
2102                            ApplyError::TooManyNodes(max) => {
2103                                format!("the app created more than {max} nodes and was stopped")
2104                            }
2105                            other => {
2106                                format!("the app sent an invalid op ({other:?}) and was stopped")
2107                            }
2108                        });
2109                        break;
2110                    }
2111                    Err(err) => log::error!("invalid op: {err:?}"),
2112                }
2113            }
2114            if let Some(batch) = self.core.commit() {
2115                match &mut merged {
2116                    Some(m) => extend_frame(&mut m.items, batch.items),
2117                    None => merged = Some(batch),
2118                }
2119            }
2120            self.core.take_list_binds(&mut self.binds);
2121            self.core.take_events(&mut self.events);
2122            // Posts the ops queued (in program order) run in another round.
2123            let posted = script.is_some_and(Script::has_posted);
2124            // New tokens (the app's theme, the embedding app's) reach what
2125            // read them in JS, whose ops come in another round.
2126            let retheme = match script {
2127                Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
2128                    self.js_tokens = self.core.tokens().clone();
2129                    script.set_tokens(self.js_tokens.clone());
2130                    true
2131                }
2132                _ => false,
2133            };
2134            if self.binds.is_empty() && self.events.is_empty() && !posted && !retheme {
2135                break;
2136            }
2137        }
2138        self.committed_since_gc |= op_count > 0;
2139        if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
2140            let c = &mut self.perf_commit;
2141            c.layout += start.elapsed().saturating_sub(js);
2142            c.ops += op_count as u32;
2143            c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
2144        }
2145        if self.trace && (op_count > 0 || merged.is_some()) {
2146            log::info!(
2147                target: "nsh::perf",
2148                "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
2149                start.elapsed().as_micros(),
2150                js.as_micros(),
2151                merged.as_ref().map_or(0, |b| b.items.len()),
2152                self.core.node_count(),
2153            );
2154        }
2155        merged
2156    }
2157}
2158
2159fn insets(env: &Environment) -> EdgeInsets {
2160    env.safe_area
2161}
2162
2163/// What Rust components read from the environment.
2164fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::ui::Environment {
2165    nsh_core::ui::Environment {
2166        window,
2167        safe_area: insets(env),
2168        title_bar: env.title_bar,
2169        keyboard_height: env.keyboard_height,
2170        keyboard_duration: env.keyboard_duration,
2171        dark: env.color_scheme == ColorScheme::Dark,
2172        font_scale: env.font_scale,
2173        reduce_motion: env.reduce_motion,
2174        screen_reader: env.screen_reader,
2175        rtl: env.rtl,
2176        pixel_ratio: env.pixel_ratio,
2177        os: env.os,
2178        os_version: env.os_version,
2179        idiom: env.idiom,
2180        locale: env.locale,
2181        apple_keyboard: env.apple_keyboard,
2182    }
2183}
2184
2185/// What class variants read from the environment.
2186fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
2187    nsh_core::tailwind::ClassEnvironment {
2188        dark: env.color_scheme == ColorScheme::Dark,
2189        platform: if env.os == Os::Web {
2190            nsh_core::tailwind::Platform::Web
2191        } else if cfg!(target_os = "android") {
2192            nsh_core::tailwind::Platform::Android
2193        } else {
2194            nsh_core::tailwind::Platform::Ios
2195        },
2196        reduce_motion: env.reduce_motion,
2197    }
2198}
2199
2200/// Returns false on shutdown.
2201fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
2202    match message {
2203        Message::Event(id, event, payload) => {
2204            if state.trace {
2205                log::info!(target: "nsh::perf", "event {event:?} on view {id}");
2206            }
2207            // Hover moves wait for the frame, the latest per view; any other
2208            // event comes after the moves before it (a view hears where the
2209            // mouse went before it hears it leave).
2210            if event == EventKind::MouseMove
2211                || (event == EventKind::HoverMove && matches!(payload, EventPayload::Hover(_)))
2212            {
2213                match state
2214                    .hover_moves
2215                    .iter_mut()
2216                    .find(|(v, kind, _)| *v == id && *kind == event)
2217                {
2218                    Some((_, _, pending)) => *pending = payload,
2219                    None => state.hover_moves.push((id, event, payload)),
2220                }
2221                return true;
2222            }
2223            state.dispatch_hover_moves(script);
2224            // The core tracks input text for layout and to recognize stale
2225            // values (from JS and from Rust components alike).
2226            if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
2227                state.core.input_changed(id, text, *count);
2228            }
2229            // Events on a Rust component's parts are the component's.
2230            if state.core.component_event(id, event, &payload) {
2231                return true;
2232            }
2233            if let EventPayload::Touch(touch) = payload {
2234                if touch.phase == nsh_core::TouchPhase::Move {
2235                    match &mut state.touch_move {
2236                        Some((_, pending)) => pending.merge_move(*touch),
2237                        None => state.touch_move = Some((id, touch)),
2238                    }
2239                    return true;
2240                }
2241                // Moves before a start, end or cancel go first.
2242                state.dispatch_touch_move(script);
2243                if let Some(script) = script {
2244                    script.dispatch_event(id, event, &EventPayload::Touch(touch));
2245                }
2246                return true;
2247            }
2248            let Some(script) = script else { return true };
2249            let start = state.trace.then(Instant::now);
2250            script.dispatch_event(id, event, &payload);
2251            if let Some(start) = start {
2252                // The handler, its microtasks and the decode of what it
2253                // committed.
2254                log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
2255            }
2256        }
2257        Message::Scroll(id, offset, applied) => {
2258            state.core.set_scroll_offset(id, offset, applied);
2259            let (x, y) = (offset.x.0, offset.y.0);
2260            if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
2261                let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
2262                    x,
2263                    y,
2264                    content,
2265                    viewport,
2266                    zoom,
2267                    throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
2268                    last: None,
2269                    pending: true,
2270                });
2271                (event.x, event.y, event.content, event.viewport, event.zoom) =
2272                    (x, y, content, viewport, zoom);
2273                event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
2274                event.pending = true;
2275            }
2276        }
2277        Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
2278        Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
2279        Message::AnimationsFinished(mut finished) => {
2280            // The components' animations end in the core, JS's in JS.
2281            state.core.animations_finished(&mut finished);
2282            if let Some(script) = script {
2283                script.animations_finished(&finished);
2284            }
2285        }
2286        Message::Resize(size) => {
2287            state.core.set_viewport(size);
2288            state.resized = Some(size);
2289        }
2290        Message::Wake => {}
2291        Message::Environment(mut env) => {
2292            state.pinned.apply(&mut env);
2293            state.core.set_font_scale(env.font_scale);
2294            state.core.set_class_environment(class_environment(&env));
2295            state.core.set_safe_area(insets(&env));
2296            let window = env.window;
2297            state.core.set_environment(ui_environment(&env, window));
2298            if let Some(script) = script {
2299                script.set_environment(&env);
2300            }
2301        }
2302        Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
2303        Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
2304        Message::Frame => {
2305            state.frame_requested = false;
2306            state.core.run_frame(nsh_core::time::now());
2307            if let Some(script) = script {
2308                script.run_frame();
2309            }
2310        }
2311        Message::States(id, states) => state.core.set_states(id, states),
2312        Message::FontsChanged => state.core.fonts_changed(),
2313        Message::Fetch(who, hop, event) => {
2314            if let Some(event) = state.net.event(who, hop, event) {
2315                match who {
2316                    Requester::Js(id) => {
2317                        if let Some(script) = script {
2318                            script.fetch_event(id, event);
2319                        }
2320                    }
2321                    Requester::Task(id) => {
2322                        if !state.core.fetch_event(id, event) {
2323                            state.net.cancel(who);
2324                        }
2325                    }
2326                }
2327            }
2328        }
2329        Message::Hot(update) => state.hot.push(update),
2330        Message::Chunk(chunk) => {
2331            if let Some(script) = script {
2332                script.chunk(chunk);
2333            }
2334        }
2335        Message::Perf(monitor) => {
2336            state.perf = monitor;
2337            state.perf_commit = perf::CommitTiming::default();
2338        }
2339        Message::Tokens(tokens) => state.core.set_host_tokens(tokens.map(|t| *t)),
2340        // The driver handles it ([`Driver::handle`]), and keeps the ones
2341        // sent before it started for after the first frame.
2342        Message::Advance(..) => unreachable!("the driver moves the clock"),
2343        Message::Shutdown => return false,
2344    }
2345    true
2346}
2347
2348/// Appends a commit's items to the frame's. A scroll view's content size
2349/// that the frame already sets is updated to the later size (unless the
2350/// view scrolls in between): a row relaid over two commits must not send
2351/// the platform a transient size, which clamps the offset before the
2352/// content grows back (a list jumping when a row expands).
2353fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
2354    use nsh_core::MountItem;
2355    let start = frame.len();
2356    frame.extend(items);
2357    for k in start..frame.len() {
2358        let MountItem::ScrollContent { id, size } = frame[k] else {
2359            continue;
2360        };
2361        let earlier = frame[..k].iter().rposition(|m| {
2362            matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
2363        });
2364        if let Some(j) = earlier
2365            && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
2366        {
2367            *s = size;
2368        }
2369    }
2370}
2371
2372#[cfg(test)]
2373mod tests {
2374    #[test]
2375    fn pinned_values_hold_whatever_the_platform_reports() {
2376        let pins = super::EnvironmentPins {
2377            locale: nsh_core::platform::Locale::parse("de-DE"),
2378            reduce_motion: Some(true),
2379            ..Default::default()
2380        };
2381        let mut reported = super::Environment {
2382            locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
2383            font_scale: 1.5,
2384            ..Default::default()
2385        };
2386        pins.apply(&mut reported);
2387        assert_eq!(reported.locale.as_str(), "de-DE");
2388        assert!(reported.reduce_motion);
2389        // What is not pinned stays the platform's.
2390        assert_eq!(reported.font_scale, 1.5);
2391        assert_eq!(reported.safe_area, Default::default());
2392    }
2393
2394    #[test]
2395    fn bundle_default_has_no_application_selected_path_anchors() {
2396        let bundle = super::Bundle::default();
2397        assert!(bundle.system_paths.plugin_dir.is_none());
2398        assert!(bundle.system_paths.home_dir.is_none());
2399        assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
2400    }
2401
2402    #[test]
2403    fn bundle_trusted_paths_reject_relative_and_missing_directories() {
2404        let mut paths = nsh_core::access::TrustedPaths::default();
2405        paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
2406        paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
2407        let bundle = super::Bundle::default().with_system_paths(paths);
2408        assert!(bundle.system_paths.plugin_dir.is_none());
2409        assert!(bundle.system_paths.home_dir.is_none());
2410        assert!(
2411            super::trusted_directory(Some(std::path::PathBuf::from(
2412                "/nsh-nonexistent-anchor-never-created"
2413            )))
2414            .is_none()
2415        );
2416    }
2417
2418    #[test]
2419    fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
2420        let root = std::env::var_os("TMPDIR")
2421            .map(std::path::PathBuf::from)
2422            .unwrap_or_else(|| {
2423                std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
2424                    .join(".cache/nsh-benchs-test-tmp")
2425            });
2426        assert!(root.is_absolute() && !root.starts_with("/tmp"));
2427        let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
2428        std::fs::create_dir_all(&directory).unwrap();
2429        let path = directory.join("bundle.js");
2430        std::fs::write(&path, "export default null;").unwrap();
2431        let bundle = super::Bundle::read(&path).unwrap();
2432        assert_eq!(
2433            bundle.system_paths.plugin_dir,
2434            Some(nsh_core::access::canonicalize(&directory).unwrap())
2435        );
2436        assert!(bundle.system_paths.home_dir.is_none());
2437        std::fs::remove_dir_all(directory).unwrap();
2438    }
2439
2440    #[test]
2441    fn rust_environment_preserves_native_title_bar_insets() {
2442        use super::{Edges, Points};
2443        let title_bar = Edges {
2444            top: Points(42.0),
2445            left: Points(78.0),
2446            right: Points(138.0),
2447            bottom: Points(0.0),
2448        };
2449        let environment = super::Environment {
2450            title_bar,
2451            ..Default::default()
2452        };
2453        assert_eq!(
2454            super::ui_environment(
2455                &environment,
2456                nsh_core::Size::new(Points(840.0), Points(630.0))
2457            )
2458            .title_bar,
2459            title_bar
2460        );
2461    }
2462
2463    use nsh_core::{MountItem, Points, Size};
2464
2465    #[test]
2466    fn a_frame_sends_a_scroll_views_last_content_size() {
2467        let content = |height| MountItem::ScrollContent {
2468            id: 2,
2469            size: Size::new(Points(390.0), height),
2470        };
2471        let heights = |frame: &[MountItem]| -> Vec<f32> {
2472            frame
2473                .iter()
2474                .filter_map(|m| match m {
2475                    MountItem::ScrollContent { size, .. } => Some(size.height.0),
2476                    _ => None,
2477                })
2478                .collect()
2479        };
2480        let mut frame = vec![content(Points(313.0))];
2481        super::extend_frame(&mut frame, vec![content(Points(544.0))]);
2482        assert_eq!(heights(&frame), [544.0, 544.0]);
2483        // A scroll in between keeps the size it scrolled against.
2484        let mut frame = vec![
2485            content(Points(313.0)),
2486            MountItem::ScrollBy {
2487                id: 2,
2488                dx: Points(0.0),
2489                dy: Points(10.0),
2490            },
2491        ];
2492        super::extend_frame(&mut frame, vec![content(Points(544.0))]);
2493        assert_eq!(heights(&frame), [313.0, 544.0]);
2494    }
2495}