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