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