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