1#[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#[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#[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#[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"))]
106const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
110
111const PERF_STATS_INTERVAL: Duration = Duration::from_secs(1);
114const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
118
119const IDLE_GC_QUIET: Duration = Duration::from_millis(300);
126
127const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);
129
130const IDLE_GC_LONGEST_ANIMATING: Duration = Duration::from_secs(30);
138
139const ANIMATING_GAP: Duration = Duration::from_millis(100);
142
143const MOUSE_MOVE_INTERVAL: Duration = Duration::from_millis(8);
147
148#[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 Rust(Root),
157 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 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 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 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 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 pub fn url_schemes(&self) -> &[String] {
210 self.links().schemes()
211 }
212
213 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#[derive(Debug, Clone)]
231#[non_exhaustive]
232pub struct Bundle {
233 pub code: BundleCode,
235 pub source_map: Option<Arc<str>>,
237 pub policy: Policy,
239 pub base_url: Option<Arc<str>>,
242 pub chunks: Arc<Vec<Chunk>>,
246 pub app_id: Option<String>,
249 pub links: nsh_core::url_scheme::AppLinks,
255 pub system_paths: nsh_core::access::TrustedPaths,
259 pub package: Option<Arc<PackageInfo>>,
262 pub updater_config: Option<Arc<[u8]>>,
268 pub trial: Option<Arc<dyn Trial>>,
272 pub main_window: Option<nsh_core::desktop::MainWindowOptions>,
277 pub application: Option<nsh_core::desktop::ApplicationOptions>,
281}
282
283pub const TRIAL_PERIOD: Duration = Duration::from_secs(10);
286
287pub trait Trial: Send + Sync + std::fmt::Debug + 'static {
291 fn healthy(&self);
294 fn failed(&self, error: &AppError);
296}
297
298#[derive(Debug, Clone)]
301pub struct Chunk {
302 pub id: String,
304 pub code: BundleCode,
306 pub source_map: Option<Arc<str>>,
308}
309
310impl Chunk {
311 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 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 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#[derive(Debug, Clone)]
342pub struct Policy {
343 pub harden: bool,
347 pub declared: Option<Capabilities>,
350 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 pub fn development() -> Self {
370 Self {
371 harden: false,
372 ..Self::default()
373 }
374 }
375
376 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#[derive(Debug, Clone)]
387pub enum BundleCode {
388 Bytecode(Vec<u8>),
390 Source(String),
392}
393
394impl Default for Bundle {
395 fn default() -> Self {
396 Self::source(String::new())
397 }
398}
399
400impl Bundle {
401 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 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 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 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 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 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 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 pub fn with_links(mut self, links: nsh_core::url_scheme::AppLinks) -> Self {
505 self.links = links;
506 self
507 }
508
509 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 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 pub fn with_policy(mut self, policy: Policy) -> Self {
526 self.policy = policy;
527 self
528 }
529
530 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 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 unsafe { Self::read_trusted(path) }
550 }
551
552 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 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 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 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 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 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
656fn 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#[cfg(feature = "js-core")]
664#[derive(Debug)]
665pub struct LoadedPackage {
666 pub bundle: Bundle,
668 pub assets: std::path::PathBuf,
670 pub app: nsh_package::App,
672 pub receipt: nsh_package::PackageReceipt,
674}
675
676#[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#[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 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#[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#[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
753pub 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 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
776pub trait MountSink: Send + 'static {
779 fn submit(&self, batch: MountBatch);
781
782 fn needs_content_height(&self) -> bool {
784 false
785 }
786
787 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 fn needs_tree_order(&self) -> bool {
802 false
803 }
804
805 fn needs_projected_states(&self) -> bool {
809 false
810 }
811
812 fn report_error(&self, _message: &str) {}
818
819 fn report(&self, error: &AppError) {
823 self.report_error(&error.to_string());
824 }
825
826 fn request_frame(&self) {}
831
832 fn hot_update_failed(&self) {}
835
836 fn run_on_main_thread(&self, task: MainThreadTask) {
842 task.run();
843 }
844
845 fn resized(&self, _size: Size<Points>) {}
851
852 fn root_resized(&self, _id: NodeId, _size: Size<Points>) {}
859
860 fn handled(&self, _events: u64) {}
866
867 fn load_chunk(&self, _id: &str) -> bool {
873 false
874 }
875}
876
877pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
881
882pub trait FetchTask: Send {
884 fn send(&mut self, chunk: Vec<u8>);
887 fn finish(&mut self);
889 fn pause(&mut self, paused: bool);
893 fn cancel(self: Box<Self>);
895}
896
897struct UpdaterOverNetwork {
900 network: Arc<dyn Network>,
901 assets: Option<Arc<dyn Assets>>,
902 config: Option<Arc<[u8]>>,
904 running: Option<Arc<PackageInfo>>,
906}
907
908impl UpdaterOverNetwork {
909 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 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 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 let mut request =
999 HttpRequest::new("GET", ¤t).header("Accept-Encoding", "identity");
1000 if from > 0 {
1001 request = request.header("Range", format!("bytes={from}-"));
1002 }
1003 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 let mut at = 0u64;
1015 let mut total: Option<u64> = None;
1016
1017 let outcome = loop {
1018 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 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
1117const 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
1125fn 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#[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
1171fn 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
1184fn 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
1201pub trait Network: Send + Sync + 'static {
1203 fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
1206}
1207
1208pub trait Assets: Send + Sync + 'static {
1213 fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
1217
1218 fn url(&self, uri: &str) -> Option<String> {
1223 let _ = uri;
1224 None
1225 }
1226
1227 #[cfg(not(target_arch = "wasm32"))]
1234 fn base(&self) -> Option<nsh_core::image::loader::AssetBase> {
1235 None
1236 }
1237}
1238
1239#[derive(Clone)]
1241pub struct EngineConfig {
1242 pub app: App,
1244 pub viewport: Size<Points>,
1246 pub trace: bool,
1248 pub content_culling: bool,
1252 pub network: Option<Arc<dyn Network>>,
1254 pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
1256 pub refuse_connections: Option<nsh_core::element::RefuseConnections>,
1261 pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
1263 pub assets: Option<Arc<dyn Assets>>,
1265 pub environment: Environment,
1267 pub header_heights: (Points, Points),
1270 pub limits: Limits,
1272 pub ui_sets: Vec<nsh_core::element::Registry>,
1276 pub runtime: Option<tokio::runtime::Handle>,
1279 #[doc(hidden)]
1290 pub support_dir: Option<std::path::PathBuf>,
1291 pub data_dir: Option<std::path::PathBuf>,
1296 pub cache: CacheOptions,
1300 pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
1305 pub clock: Clock,
1309 pub context: EngineContext,
1314 pub pinned: EnvironmentPins,
1317 pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
1321 pub host: HostChannel,
1326 pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
1330 pub audio: Option<Arc<dyn nsh_core::audio::AudioBackend>>,
1335 pub windows: Option<Arc<dyn nsh_core::desktop::WindowBackend>>,
1341 pub login_item: Option<Arc<dyn nsh_core::desktop::LoginItemBackend>>,
1346}
1347
1348#[derive(Debug, Clone, Copy, Default, PartialEq)]
1351#[non_exhaustive]
1352pub struct EnvironmentPins {
1353 pub locale: Option<nsh_core::platform::Locale>,
1355 pub languages: Option<nsh_core::platform::Languages>,
1357 pub hour_cycle: Option<nsh_core::platform::HourCycle>,
1359 pub first_day_of_week: Option<nsh_core::platform::Weekday>,
1361 pub measurement_system: Option<nsh_core::platform::MeasurementSystem>,
1363 pub temperature_unit: Option<nsh_core::platform::TemperatureUnit>,
1365 pub time_zone: Option<nsh_core::platform::TimeZone>,
1367 pub reduce_motion: Option<bool>,
1370 pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
1372}
1373
1374impl EnvironmentPins {
1375 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
1415fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
1418 system_paths(bundle.system_paths.clone(), !bundle.policy.harden)
1419}
1420
1421fn 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 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 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 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
1503fn 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
1514fn 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"))]
1528fn 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
1572const MAX_ADVANCE_ROUNDS: usize = 100_000;
1576
1577const 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 Wake,
1596 Environment(Box<Environment>),
1600 ShadersUnavailable,
1603 Displays(Arc<[nsh_core::desktop::Display]>),
1605 RootSize(NodeId, Size<Points>, EdgeInsets),
1606 OverlayArea(Option<nsh_core::Bounds<Points>>),
1609 PressBeyondRoot(nsh_core::Point<Points>),
1611 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 Fetch(Requester, u64, FetchEvent),
1623 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1626 AssetRead(Requester, u64, HttpRequest, Result<Vec<u8>, String>),
1627 Hot(HotUpdate),
1628 Chunk(Result<Chunk, (String, String)>),
1631 Perf(Option<Arc<perf::PerfMonitor>>),
1632 Tokens(Option<Box<Tokens>>),
1634 HostFont(Vec<u8>),
1637 HostEvent(String, nsh_core::JsonValue),
1640 CallerEvent(String, nsh_core::JsonValue),
1643 HostReply(u64, Result<nsh_core::JsonValue, String>),
1645 CoreHostReply(u64, Result<nsh_core::JsonValue, String>),
1649 UrlHandled {
1652 id: u32,
1653 url: String,
1654 handled: bool,
1655 },
1656 Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
1658 Flush(Box<dyn FnOnce(bool, Option<Instant>) + Send>),
1662 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1664 Shutdown,
1665}
1666
1667#[derive(Debug, Clone)]
1671pub struct HotUpdate {
1672 pub name: String,
1674 pub code: String,
1676 pub source_map: Option<Arc<str>>,
1678}
1679
1680const MAX_LIST_ROUNDS: usize = 8;
1684
1685const PACED_BIND_OPS: usize = 150;
1692const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);
1694
1695#[derive(Clone)]
1697pub struct EngineControl {
1698 tx: Sender<Message>,
1699 modality: Arc<std::sync::atomic::AtomicU8>,
1702 downloads: nsh_core::webview::downloads::DownloadCleanup,
1706}
1707
1708impl EngineControl {
1709 pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
1711 self.downloads.dispatch(id, event, &payload);
1717 let _ = self.tx.send(Message::Event(id, event, payload));
1718 }
1719
1720 pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
1726 let _ = self.tx.send(Message::Scroll(id, offset, applied));
1727 }
1728
1729 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 pub fn keep_rendered(&self, nodes: Vec<NodeId>) {
1741 let _ = self.tx.send(Message::Kept(nodes));
1742 }
1743
1744 pub fn set_content_culling(&self, enabled: bool) {
1749 let _ = self.tx.send(Message::ContentCulling(enabled));
1750 }
1751
1752 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 pub fn input_composing(&self, id: NodeId, shown: Option<String>) {
1773 let _ = self.tx.send(Message::InputComposing(id, shown));
1774 }
1775
1776 pub fn zoom(&self, id: NodeId, scale: f32) {
1779 let _ = self.tx.send(Message::Zoom(id, scale));
1780 }
1781
1782 pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
1785 let _ = self.tx.send(Message::ComponentSize(id, size));
1786 }
1787
1788 pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
1790 let _ = self.tx.send(Message::AnimationsFinished(finished));
1791 }
1792
1793 pub fn resize(&self, size: Size<Points>) {
1795 let _ = self.tx.send(Message::Resize(size));
1796 }
1797
1798 pub fn set_environment(&self, environment: Environment) {
1801 let _ = self.tx.send(Message::Environment(Box::new(environment)));
1802 }
1803
1804 pub fn shaders_unavailable(&self) {
1809 let _ = self.tx.send(Message::ShadersUnavailable);
1810 }
1811
1812 pub fn set_displays(&self, displays: Vec<nsh_core::desktop::Display>) {
1816 let _ = self.tx.send(Message::Displays(displays.into()));
1817 }
1818
1819 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 pub fn set_overlay_area(&self, area: Option<nsh_core::Bounds<Points>>) {
1831 let _ = self.tx.send(Message::OverlayArea(area));
1832 }
1833
1834 pub fn press_beyond_root(&self, page: nsh_core::Point<Points>) {
1839 let _ = self.tx.send(Message::PressBeyondRoot(page));
1840 }
1841
1842 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 pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
1853 let _ = self.tx.send(Message::ScreenHeader(id, height));
1854 }
1855
1856 pub fn hot_update(&self, update: HotUpdate) {
1859 let _ = self.tx.send(Message::Hot(update));
1860 }
1861
1862 pub fn chunk_loaded(&self, chunk: Chunk) {
1865 let _ = self.tx.send(Message::Chunk(Ok(chunk)));
1866 }
1867
1868 pub fn chunk_failed(&self, id: String, message: String) {
1871 let _ = self.tx.send(Message::Chunk(Err((id, message))));
1872 }
1873
1874 pub fn frame(&self) {
1877 let _ = self.tx.send(Message::Frame);
1878 }
1879
1880 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 pub fn flush(&self, done: impl FnOnce(bool) + Send + 'static) {
1900 self.flush_until_due(move |idle, _| done(idle));
1901 }
1902
1903 #[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 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 pub fn set_states(&self, id: NodeId, states: u16) {
1935 let _ = self.tx.send(Message::States(id, states));
1936 }
1937
1938 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 pub fn fonts_changed(&self) {
1950 let _ = self.tx.send(Message::FontsChanged);
1951 }
1952
1953 pub fn remount(&self) {
1957 let _ = self.tx.send(Message::Remount);
1958 }
1959
1960 pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
1963 let _ = self.tx.send(Message::Perf(monitor));
1964 }
1965
1966 pub fn set_tokens(&self, tokens: Option<Tokens>) {
1971 let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1972 }
1973
1974 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"))]
1984pub struct Engine {
1986 control: EngineControl,
1987 thread: Option<std::thread::JoinHandle<()>>,
1988 host: HostChannel,
1990 stop: Arc<std::sync::atomic::AtomicBool>,
1992 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1995 image_cache: Option<nsh_core::image::DiskCache>,
1997 media_files: Arc<nsh_core::access::MediaFiles>,
1999}
2000
2001#[cfg(not(target_arch = "wasm32"))]
2002impl Engine {
2003 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 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 pub fn media_files(&self) -> Arc<nsh_core::access::MediaFiles> {
2078 self.media_files.clone()
2079 }
2080
2081 pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
2085 self.image_cache.clone()
2086 }
2087
2088 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 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"))]
2120fn raise_thread_priority() {
2124 #[cfg(target_vendor = "apple")]
2125 unsafe {
2127 libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
2128 }
2129}
2130
2131fn 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#[cfg(not(target_arch = "wasm32"))]
2149use nsh_core::element::desktop::QUIT_TIMEOUT;
2150
2151#[cfg(not(target_arch = "wasm32"))]
2154const QUIT_GRACE: Duration = Duration::from_millis(20);
2155
2156const 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 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 if let Some(trial) = &driver.trial {
2187 trial.healthy();
2188 }
2189 with_autorelease_pool(|| drop(driver));
2190}
2191
2192fn 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 #[cfg(target_arch = "wasm32")]
2209 drop(trial);
2210}
2211
2212#[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 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
2254pub struct LocalEngine<M: TextEngine + 'static> {
2259 driver: ManuallyDrop<Driver<M>>,
2262 rx: Receiver<Message>,
2263 control: EngineControl,
2264 wake: Option<Arc<dyn Fn() + Send + Sync>>,
2266 pumping: Arc<std::sync::atomic::AtomicBool>,
2269 quit_started: bool,
2271}
2272
2273impl<M: TextEngine + 'static> LocalEngine<M> {
2274 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 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 pub fn control(&self) -> EngineControl {
2316 self.control.clone()
2317 }
2318
2319 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 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 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 #[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 #[doc(hidden)]
2404 pub fn key_interest(&self, id: NodeId) -> bool {
2405 self.driver.state.core.key_interest(id)
2406 }
2407
2408 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 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 if !self.rx.is_empty()
2440 && let Some(wake) = &self.wake
2441 {
2442 wake();
2443 }
2444 self.driver.deadline()
2445 }
2446
2447 #[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 let _context = self.driver.context.enter();
2477 with_autorelease_pool(|| {
2478 unsafe { ManuallyDrop::drop(&mut self.driver) };
2481 });
2482 }
2483}
2484
2485struct 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 stopped: bool,
2494 last_gc: Instant,
2495 last_active: Instant,
2498 last_display_frame: Option<Instant>,
2501 posts: nsh_core::element::Posts,
2504 clock: Clock,
2506 context: EngineContext,
2508 last_frame: Option<Instant>,
2511 _host: host_channel::HostAttachment,
2514 #[cfg(not(target_arch = "wasm32"))]
2518 trial: Option<Arc<dyn Trial>>,
2519 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
2521 quitting: bool,
2524}
2525
2526impl<M: TextEngine + 'static> Driver<M> {
2527 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 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 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 let posts = nsh_core::element::Posts::new();
2578 core.set_posts(posts.clone());
2579 if let App::Js(_) = &config.app {
2580 core.set_max_nodes(config.limits.max_nodes);
2582 }
2583 core.set_access(access.clone());
2584 if let App::Js(bundle) = &config.app {
2585 core.set_base_url(bundle.base_url.clone());
2587 }
2588 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 disk: config.cache.open_images(config.app.app_id()),
2602 transport: None,
2604 });
2605 core.set_storage(app_storage(&config));
2606 core.set_data_dir(data_dir(&config));
2607 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 #[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 if let Some(window) = config.app.main_window() {
2633 core.set_main_window(window);
2634 }
2635 #[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 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 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 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 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 #[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 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 if let Some(script) = script {
2881 script.run_system();
2882 }
2883 state.load_fonts(script, assets.as_deref(), &**sink);
2884 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 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 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 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 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 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 Message::Frame if self.clock.moves_with_frames() => {
3006 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 fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
3024 if !self.clock.is_manual() {
3025 with_autorelease_pool(|| self.turn());
3027 return true;
3028 }
3029 let to = self.clock.now() + by;
3030 for round in 0.. {
3031 let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
3034 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 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 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 if !self.advance(std::time::Duration::ZERO, rx, frames) {
3089 return false;
3090 }
3091 if rx.is_empty() {
3094 break;
3095 }
3096 }
3097 true
3098 }
3099
3100 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 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 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 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 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 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 #[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 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 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 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 zoom: f32,
3345 throttle: Duration,
3346 last: Option<Instant>,
3347 pending: bool,
3349}
3350
3351struct State<M: TextEngine> {
3352 core: Core<M>,
3353 published_content_height: Option<Points>,
3354 js_tokens: Arc<nsh_core::element::Tokens>,
3357 pinned: EnvironmentPins,
3360 environment: Environment,
3362 shaders_unavailable: bool,
3365 app_locale: Option<nsh_core::platform::Locale>,
3367 frame_requested: bool,
3369 frame_turn: bool,
3372 frames_seen: bool,
3376 ops: Vec<Op>,
3377 binds: Vec<ListBind>,
3379 events: Vec<JsEvent>,
3381 trace: bool,
3382 perf: Option<Arc<perf::PerfMonitor>>,
3384 perf_stats_at: Option<Instant>,
3387 perf_commit: perf::CommitTiming,
3390 committed_since_gc: bool,
3391 host: HostChannel,
3394 url_opens: Vec<(u32, String)>,
3396 host_requests: Vec<nsh_core::host_channel::HostRequest>,
3399 net: Net,
3400 hot: Vec<HotUpdate>,
3402 scroll_events: FxHashMap<NodeId, ScrollEvent>,
3405 touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
3407 mouse_moves: Vec<(NodeId, EventPayload)>,
3411 mouse_moved: Option<Instant>,
3413 key_path: Vec<NodeId>,
3416 sets_seen: FxHashMap<(u8, NodeId, u32), usize>,
3418 resized: Option<Size<Points>>,
3420 roots_resized: Vec<(NodeId, Size<Points>)>,
3423 resize_burst_ends: Option<Instant>,
3426 window_state: WindowStateReport,
3429 events_handled: u64,
3432 events_reported: u64,
3433}
3434
3435#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3438enum Requester {
3439 Js(RequestId),
3440 Task(u32),
3441}
3442
3443struct Net {
3446 network: Option<Arc<dyn Network>>,
3447 tx: Sender<Message>,
3448 queue: NetworkQueue,
3449 inflight: FxHashMap<Requester, Inflight>,
3450 tasks: Vec<(u32, HttpRequest)>,
3453 abandoned: Vec<u32>,
3454 access: Arc<nsh_core::access::Access>,
3456 hops: u64,
3458 assets: Option<Arc<dyn Assets>>,
3461 #[cfg(not(target_arch = "wasm32"))]
3464 runtime: tokio::runtime::Handle,
3465}
3466
3467struct 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
3478fn is_asset(url: &str) -> bool {
3481 url.get(..6)
3482 .is_some_and(|scheme| scheme.eq_ignore_ascii_case("asset:"))
3483}
3484
3485fn 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
3495fn asset_file(url: &str) -> &str {
3500 url.split('?').next().unwrap_or_default()
3501}
3502
3503struct Inflight {
3505 task: Box<dyn FetchTask>,
3506 hop: u64,
3508 followed: Option<access::Followed>,
3510 asset: Option<String>,
3514}
3515
3516impl Net {
3517 fn idle(&self) -> bool {
3519 self.inflight.is_empty()
3520 }
3521
3522 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 fn cancel(&mut self, who: Requester) {
3570 if let Some(i) = self.inflight.remove(&who) {
3571 i.task.cancel();
3572 }
3573 }
3574
3575 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let mut paced = PacedBinds::default();
4051 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 let js_start = Instant::now();
4063 let binds = self.binds.drain(..);
4066 if let Some(script) = script {
4067 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 if let Some(script) = script {
4097 script.run_posted();
4098 }
4099 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 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 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 let urls = self.open_urls();
4179 let host = self.host_requests();
4182 let posted = script.is_some_and(Script::has_posted);
4184 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 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 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 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
4268fn 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
4317fn drawn_shaders(env: &mut Environment, unavailable: bool) {
4321 env.shaders &= env.cell.is_none() && !unavailable && !shader::no_gpu();
4322}
4323
4324fn 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
4343const WINDOW_SETTLE: Duration = Duration::from_millis(150);
4346
4347#[derive(Default)]
4352struct WindowStateReport {
4353 shown: Option<nsh_core::desktop::WindowState>,
4355 reported: Option<Environment>,
4357 settles: Option<Instant>,
4359}
4360
4361impl WindowStateReport {
4362 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 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
4388fn 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
4404fn 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 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
4428fn 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 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
4454fn 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
4471fn 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 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 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 if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
4505 state.core.input_changed(id, text, *count);
4506 }
4507 if event == EventKind::CaretMove {
4510 state.core.locate_caret(id, &mut payload);
4511 }
4512 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 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 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 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 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 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 state.core.animations_finished(&mut finished);
4614 if let Some(script) = script {
4615 script.animations_finished(&finished);
4616 }
4617 }
4618 Message::Resize(size) => {
4619 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 (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 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 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 Message::Advance(..) | Message::Flush(..) => unreachable!("the driver moves the clock"),
4772 Message::Shutdown => return false,
4773 }
4774 true
4775}
4776
4777#[derive(Default)]
4779struct PacedBinds {
4780 cells: usize,
4781 ops: usize,
4782 time: std::time::Duration,
4783}
4784
4785impl PacedBinds {
4786 fn left(&self) -> bool {
4789 self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
4790 }
4791}
4792
4793fn 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
4817fn 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
4849fn 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
4865const RETAINED_OPS: usize = 16 * 1024;
4867
4868fn 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
4879fn 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
4893fn 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 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 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 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 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 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 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 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 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 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 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 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 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 let err = collect(&host, "https://downgrade.example.com/a", 4).unwrap_err();
5541 assert!(err.contains("non-HTTPS"), "{err}");
5542
5543 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 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 let err = collect(&host, "https://bad-range.example.com/truncated", 4).unwrap_err();
5556 assert!(err.contains("truncated"), "{err}");
5557
5558 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 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_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 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 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 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}