Skip to main content

nsh_engine/
lib.rs

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