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;
19mod host_channel;
20mod local_storage;
21#[cfg(not(target_arch = "wasm32"))]
22pub mod logging;
23#[cfg(feature = "net")]
24pub mod net;
25pub mod perf;
26mod script;
27#[cfg_attr(not(feature = "shader"), path = "shader_off.rs")]
28pub mod shader;
29mod shader_frame;
30#[cfg(all(feature = "shader", any(target_vendor = "apple", windows)))]
31#[cfg_attr(windows, path = "shader_surfaces_windows.rs")]
32mod shader_surfaces;
33#[cfg(not(target_arch = "wasm32"))]
34mod storage;
35#[cfg(feature = "js-core")]
36mod symbolicate;
37#[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
38pub mod updates;
39
40#[cfg(test)]
43#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
44mod unit_scan;
45
46#[cfg(test)]
47#[test]
48fn public_api_is_typed() {
49 unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
50}
51
52use std::{io, mem::ManuallyDrop, rc::Rc, sync::Arc, time::Duration};
53
54pub use app_directory::app_dir_name;
55use crossbeam_channel::{Receiver, Sender};
56pub use local_storage::local_storage_prefix;
57use nsh_core::{
58 ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
59 PayloadValue, TextEngine, element::JsEvent, platform::content_type, time::Instant,
60};
61pub use nsh_core::{
62 JsonValue,
63 access::{Access, Capabilities},
64 element::{EngineContext, Root, Tokens},
65 geometry::{self, Bounds, Edges, Point, Points, Size},
66 js::{HostLimits, Limits},
67 main_thread::MainThreadTask,
68 platform::{
69 ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HourCycle, HttpBody,
70 HttpCache, HttpHead, HttpRequest, Idiom, Languages, Lifecycle, Locale, LocaleSettings,
71 MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday,
72 },
73 storage::{StorageBackend, StorageChange},
74 time::Clock,
75};
76#[cfg(feature = "js-core")]
77pub use nsh_js::BYTECODE_VERSION;
78#[cfg(feature = "js-core")]
79#[doc(hidden)]
80pub use nsh_js::with_inline_root;
81#[cfg(feature = "js-core")]
83pub use nsh_package as package;
84use rustc_hash::FxHashMap;
85#[cfg(not(target_arch = "wasm32"))]
86pub use storage::{FileStorage, resolve_data_dir, support_dir};
87
88pub use crate::{
89 cache::{ByteSize, CacheLocation, CacheOptions, CachePolicy},
90 error::{AppError, AppErrorKind, PackageInfo},
91 host_channel::{HostCall, HostChannel, HostReply, OpenUrlRequest},
92};
93use crate::{
94 host_channel::HostRefusal,
95 script::{NetworkQueue, RequestId, Script},
96};
97
98#[cfg(not(target_arch = "wasm32"))]
99const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
103
104const PERF_STATS_INTERVAL: Duration = Duration::from_secs(1);
107const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
111
112const IDLE_GC_QUIET: Duration = Duration::from_millis(300);
119
120const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);
122
123const MOUSE_MOVE_INTERVAL: Duration = Duration::from_millis(8);
127
128#[derive(Debug, Clone)]
130#[allow(
131 clippy::large_enum_variant,
132 reason = "one app per surface; keep the public constructor API without allocation"
133)]
134pub enum App {
135 Rust(Root),
137 Js(Bundle),
139}
140
141impl From<Bundle> for App {
142 fn from(bundle: Bundle) -> Self {
143 App::Js(bundle)
144 }
145}
146
147impl App {
148 pub fn app_id(&self) -> Option<&str> {
150 match self {
151 App::Rust(root) => root.app_id_ref(),
152 App::Js(bundle) => bundle.app_id.as_deref(),
153 }
154 }
155
156 pub fn main_window(&self) -> Option<&nsh_core::desktop::MainWindowOptions> {
161 match self {
162 App::Rust(root) => root.main_window_ref(),
163 App::Js(bundle) => bundle.main_window.as_ref(),
164 }
165 }
166
167 pub fn application(&self) -> Option<&nsh_core::desktop::ApplicationOptions> {
171 match self {
172 App::Rust(root) => root.application_ref(),
173 App::Js(bundle) => bundle.application.as_ref(),
174 }
175 }
176
177 pub fn app_info(&self) -> Option<&nsh_core::platform::AppInfo> {
181 match self {
182 App::Rust(root) => root.app_info_ref(),
183 App::Js(_) => None,
184 }
185 }
186
187 pub fn url_schemes(&self) -> &[String] {
190 self.links().schemes()
191 }
192
193 pub fn links(&self) -> &nsh_core::url_scheme::AppLinks {
196 match self {
197 App::Rust(root) => root.links_ref(),
198 App::Js(bundle) => &bundle.links,
199 }
200 }
201}
202
203impl From<Root> for App {
204 fn from(root: Root) -> Self {
205 App::Rust(root)
206 }
207}
208
209#[derive(Debug, Clone)]
211#[non_exhaustive]
212pub struct Bundle {
213 pub code: BundleCode,
215 pub source_map: Option<Arc<str>>,
217 pub policy: Policy,
219 pub base_url: Option<Arc<str>>,
222 pub chunks: Arc<Vec<Chunk>>,
226 pub app_id: Option<String>,
229 pub links: nsh_core::url_scheme::AppLinks,
235 pub system_paths: nsh_core::access::TrustedPaths,
239 pub package: Option<Arc<PackageInfo>>,
242 pub updater_config: Option<Arc<[u8]>>,
248 pub trial: Option<Arc<dyn Trial>>,
252 pub main_window: Option<nsh_core::desktop::MainWindowOptions>,
257 pub application: Option<nsh_core::desktop::ApplicationOptions>,
261}
262
263pub const TRIAL_PERIOD: Duration = Duration::from_secs(10);
266
267pub trait Trial: Send + Sync + std::fmt::Debug + 'static {
271 fn healthy(&self);
274 fn failed(&self, error: &AppError);
276}
277
278#[derive(Debug, Clone)]
281pub struct Chunk {
282 pub id: String,
284 pub code: BundleCode,
286 pub source_map: Option<Arc<str>>,
288}
289
290impl Chunk {
291 pub fn source(id: impl Into<String>, code: String) -> Self {
293 Self {
294 id: id.into(),
295 code: BundleCode::Source(code),
296 source_map: None,
297 }
298 }
299
300 pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
306 Self {
307 id: id.into(),
308 code: BundleCode::Bytecode(bytes),
309 source_map: None,
310 }
311 }
312
313 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
315 self.source_map = Some(map.into());
316 self
317 }
318}
319
320#[derive(Debug, Clone)]
322pub struct Policy {
323 pub harden: bool,
327 pub declared: Option<Capabilities>,
330 pub granted: Option<Capabilities>,
333}
334
335impl Default for Policy {
336 fn default() -> Self {
337 Self {
338 harden: true,
339 declared: None,
340 granted: None,
341 }
342 }
343}
344
345impl Policy {
346 pub fn development() -> Self {
350 Self {
351 harden: false,
352 ..Self::default()
353 }
354 }
355
356 pub fn access(&self) -> Access {
358 Access {
359 declared: self.declared.clone().unwrap_or_else(Capabilities::all),
360 granted: self.granted.clone(),
361 }
362 }
363}
364
365#[derive(Debug, Clone)]
367pub enum BundleCode {
368 Bytecode(Vec<u8>),
370 Source(String),
372}
373
374impl Default for Bundle {
375 fn default() -> Self {
376 Self::source(String::new())
377 }
378}
379
380impl Bundle {
381 pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
391 Self {
392 code: BundleCode::Bytecode(bytes),
393 source_map: None,
394 policy: Policy::default(),
395 base_url: None,
396 chunks: Arc::default(),
397 app_id: None,
398 links: nsh_core::url_scheme::AppLinks::default(),
399 system_paths: nsh_core::access::TrustedPaths::default(),
400 package: None,
401 updater_config: None,
402 trial: None,
403 main_window: None,
404 application: None,
405 }
406 }
407
408 pub fn source(code: String) -> Self {
410 Self {
411 code: BundleCode::Source(code),
412 source_map: None,
413 policy: Policy::default(),
414 base_url: None,
415 chunks: Arc::default(),
416 app_id: None,
417 links: nsh_core::url_scheme::AppLinks::default(),
418 system_paths: nsh_core::access::TrustedPaths::default(),
419 package: None,
420 updater_config: None,
421 trial: None,
422 main_window: None,
423 application: None,
424 }
425 }
426
427 pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
432 paths.plugin_dir = trusted_directory(paths.plugin_dir);
433 paths.home_dir = trusted_directory(paths.home_dir);
434 self.system_paths = paths;
435 self
436 }
437
438 pub fn with_app_id(mut self, id: Option<&str>) -> Self {
441 self.app_id = id.map(str::to_owned);
442 self
443 }
444
445 pub fn with_main_window(mut self, json: Option<&str>) -> Self {
449 self.main_window = json.and_then(|json| {
450 let parsed = serde_json::from_str(json)
451 .map_err(|e| e.to_string())
452 .and_then(|v| nsh_core::desktop::MainWindowOptions::from_json(&v));
453 parsed.map_err(|e| log::warn!("nsh.json window: {e}")).ok()
454 });
455 self
456 }
457
458 pub fn with_application(mut self, json: Option<&str>) -> Self {
462 self.application = json.and_then(|json| {
463 let parsed = serde_json::from_str(json)
464 .map_err(|e| e.to_string())
465 .and_then(|v| nsh_core::desktop::ApplicationOptions::from_json(&v));
466 parsed
467 .map_err(|e| log::warn!("nsh.json application: {e}"))
468 .ok()
469 });
470 self
471 }
472
473 pub fn with_url_schemes(
476 mut self,
477 schemes: impl IntoIterator<Item = impl Into<String>>,
478 ) -> Self {
479 self.links.set_schemes(schemes);
480 self
481 }
482
483 pub fn with_links(mut self, links: nsh_core::url_scheme::AppLinks) -> Self {
485 self.links = links;
486 self
487 }
488
489 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
491 self.source_map = Some(map.into());
492 self
493 }
494
495 pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
500 self.base_url = Some(url.into());
501 self
502 }
503
504 pub fn with_policy(mut self, policy: Policy) -> Self {
506 self.policy = policy;
507 self
508 }
509
510 pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
512 Arc::make_mut(&mut self.chunks).extend(chunks);
513 self
514 }
515
516 pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
523 if path.extension().is_some_and(|e| e == "nshc") {
524 return Err(io::Error::other(
525 "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
526 ));
527 }
528 unsafe { Self::read_trusted(path) }
530 }
531
532 pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
539 let bytes = std::fs::read(path)?;
540 let bundle = if path.extension().is_some_and(|e| e == "nshc") {
541 unsafe { Bundle::bytecode(bytes) }
543 } else {
544 Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
545 };
546 let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
547 Ok(map) if !map.is_empty() => bundle.with_source_map(map),
548 _ => bundle,
549 };
550 if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
551 bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
552 }
553 let info = read_app_json(&path.with_file_name("app.json"));
554 bundle.app_id = info
555 .as_ref()
556 .and_then(|info| info.get("id")?.as_str().map(str::to_owned));
557 if let Some(window) = info.as_ref().and_then(|info| info.get("window")) {
558 bundle.main_window = Some(
559 nsh_core::desktop::MainWindowOptions::from_json(window)
560 .map_err(|e| io::Error::other(format!("app.json: {e}")))?,
561 );
562 }
563 if let Some(application) = info.as_ref().and_then(|info| info.get("application")) {
564 bundle.application = Some(
565 nsh_core::desktop::ApplicationOptions::from_json(application)
566 .map_err(|e| io::Error::other(format!("app.json: {e}")))?,
567 );
568 }
569 if let Some(info) = &info {
570 let (links, ignored) = nsh_core::url_scheme::AppLinks::from_json_lenient(info);
572 for what in ignored {
573 log::warn!("app.json: {what}, ignored");
574 }
575 bundle.links = links;
576 }
577 if info
579 .as_ref()
580 .is_some_and(nsh_core::file_type::declares_file_types)
581 {
582 let schemes = bundle.links.schemes().to_vec();
583 bundle.links.set_schemes(
584 schemes
585 .into_iter()
586 .chain([nsh_core::file_type::FILE_SCHEME.to_owned()]),
587 );
588 }
589 bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
590 .parent()
591 .map(std::path::Path::to_path_buf);
592 Ok(bundle)
593 }
594}
595
596#[cfg(feature = "js-core")]
597impl Bundle {
598 pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
604 for ignored in &package.ignored {
605 log::warn!("package {}: ignored {ignored}", package.app.id);
606 }
607 let bundle = match package.bytecode() {
608 Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
611 None => Bundle::source(package.source.clone()),
612 };
613 let mut bundle = match &package.source_map {
614 Some(map) => bundle.with_source_map(map.clone()),
615 None => bundle,
616 };
617 if let Some(json) = &package.capabilities {
618 let (declared, dropped) = Capabilities::from_json_lenient(json)?;
619 for dropped in dropped {
620 log::warn!("package {}: not granted: {dropped}", package.app.id);
621 }
622 bundle.policy.declared = Some(declared);
623 }
624 bundle.app_id = Some(package.app.id.clone());
625 bundle.package = Some(Arc::new(PackageInfo {
626 id: package.app.id.clone(),
627 name: package.app.name.clone(),
628 version: package.app.version.clone(),
629 build: package.app.build,
630 sha256: package.sha256.clone(),
631 }));
632 Ok(bundle)
633 }
634}
635
636fn read_app_json(path: &std::path::Path) -> Option<serde_json::Value> {
639 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
640}
641
642#[cfg(feature = "js-core")]
644#[derive(Debug)]
645pub struct LoadedPackage {
646 pub bundle: Bundle,
648 pub assets: std::path::PathBuf,
650 pub app: nsh_package::App,
652 pub receipt: nsh_package::PackageReceipt,
654}
655
656#[cfg(feature = "js-core")]
661pub fn load_package(
662 trust: &mut nsh_package::TrustStore,
663 bytes: &[u8],
664 assets_root: &std::path::Path,
665) -> Result<LoadedPackage, String> {
666 let package = verify_package(trust, bytes, assets_root)?;
667 accept_package(trust, &package)?;
668 Ok(package)
669}
670
671#[cfg(feature = "js-core")]
679pub fn verify_package(
680 trust: &nsh_package::TrustStore,
681 bytes: &[u8],
682 assets_root: &std::path::Path,
683) -> Result<LoadedPackage, String> {
684 let package = trust
685 .verify(bytes, BYTECODE_VERSION)
686 .map_err(|e| e.to_string())?;
687 let bundle = Bundle::from_package(&package)?;
688 let dir = assets_root.join(&package.app.id).join(&package.sha256);
689 let done = dir.join(".complete");
690 if !done.exists() {
691 let assets = dir.join("assets");
692 for (path, data) in &package.assets {
693 let dest = assets.join(path);
695 if let Some(parent) = dest.parent() {
696 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
697 }
698 std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
699 }
700 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
701 std::fs::write(&done, b"").map_err(|e| e.to_string())?;
702 }
703 Ok(LoadedPackage {
704 bundle,
705 assets: dir.join("assets"),
706 receipt: package.receipt(),
707 app: package.app,
708 })
709}
710
711#[cfg(feature = "js-core")]
716pub fn symbolicate(source_map: &str, text: &str) -> String {
717 symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
718}
719
720#[cfg(feature = "js-core")]
724pub fn accept_package(
725 trust: &mut nsh_package::TrustStore,
726 package: &LoadedPackage,
727) -> Result<(), String> {
728 trust
729 .accept_receipt(&package.receipt)
730 .map_err(|e| e.to_string())
731}
732
733pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
739 let value: serde_json::Value =
740 serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
741 let (capabilities, dropped) = Capabilities::from_json_lenient(&value)?;
742 for dropped in dropped {
743 log::warn!("not granted: {dropped} (unknown to this NSH)");
744 }
745 Ok(capabilities)
746}
747
748impl Bundle {
749 pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
751 self.policy.declared = json.map(parse_capabilities).transpose()?;
752 Ok(self)
753 }
754}
755
756pub trait MountSink: Send + 'static {
759 fn submit(&self, batch: MountBatch);
761
762 fn needs_content_height(&self) -> bool {
764 false
765 }
766
767 fn submit_with_content_height(&self, batch: MountBatch, _content_height: Option<Points>) {
774 if !batch.items.is_empty() {
775 self.submit(batch);
776 }
777 }
778
779 fn needs_tree_order(&self) -> bool {
782 false
783 }
784
785 fn needs_projected_states(&self) -> bool {
789 false
790 }
791
792 fn report_error(&self, _message: &str) {}
798
799 fn report(&self, error: &AppError) {
803 self.report_error(&error.to_string());
804 }
805
806 fn request_frame(&self) {}
811
812 fn hot_update_failed(&self) {}
815
816 fn run_on_main_thread(&self, task: MainThreadTask) {
822 task.run();
823 }
824
825 fn resized(&self, _size: Size<Points>) {}
831
832 fn root_resized(&self, _id: NodeId, _size: Size<Points>) {}
839
840 fn handled(&self, _events: u64) {}
846
847 fn load_chunk(&self, _id: &str) -> bool {
853 false
854 }
855}
856
857pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
861
862pub trait FetchTask: Send {
864 fn send(&mut self, chunk: Vec<u8>);
867 fn finish(&mut self);
869 fn pause(&mut self, paused: bool);
873 fn cancel(self: Box<Self>);
875}
876
877struct UpdaterOverNetwork {
880 network: Arc<dyn Network>,
881 assets: Option<Arc<dyn Assets>>,
882 config: Option<Arc<[u8]>>,
884 running: Option<Arc<PackageInfo>>,
886}
887
888impl UpdaterOverNetwork {
889 fn host(
892 network: Option<Arc<dyn Network>>,
893 assets: Option<Arc<dyn Assets>>,
894 bundle: &Bundle,
895 ) -> Option<Arc<dyn nsh_core::runtime::UpdaterHost>> {
896 if assets.is_none() && bundle.updater_config.is_none() {
897 return None;
898 }
899 Some(Arc::new(UpdaterOverNetwork {
900 network: network?,
901 assets,
902 config: bundle.updater_config.clone(),
903 running: bundle.package.clone(),
904 }))
905 }
906}
907
908impl UpdaterOverNetwork {
909 fn of(
911 network: Option<Arc<dyn Network>>,
912 assets: Option<Arc<dyn Assets>>,
913 ) -> Option<Arc<dyn nsh_core::runtime::UpdaterHost>> {
914 Some(Arc::new(UpdaterOverNetwork {
915 network: network?,
916 assets: Some(assets?),
917 config: None,
918 running: None,
919 }))
920 }
921}
922
923impl nsh_core::runtime::UpdaterHost for UpdaterOverNetwork {
924 fn config(&self) -> Option<Vec<u8>> {
925 if let Some(config) = &self.config {
926 return Some(config.to_vec());
927 }
928 self.assets.as_ref()?.read("asset:/nsh-updater.json").ok()
930 }
931
932 fn running_package(&self) -> Option<nsh_core::runtime::PackageVersion> {
933 let running = self.running.as_ref()?;
934 let mut version = nsh_core::runtime::PackageVersion::default();
935 version.version = running.version.clone();
936 version.build = running.build;
937 Some(version)
938 }
939
940 fn runs_packages(&self) -> bool {
941 cfg!(all(feature = "js-core", not(target_arch = "wasm32")))
942 }
943
944 #[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
945 fn verify_package(
946 &self,
947 file: &std::path::Path,
948 updates: &std::path::Path,
949 app_id: &str,
950 roots: &[String],
951 newer_than: u64,
952 ) -> Result<nsh_core::runtime::PackageVersion, String> {
953 let app = updates::verify_download(file, updates, app_id, roots, newer_than)?;
954 let mut version = nsh_core::runtime::PackageVersion::default();
955 version.version = app.version;
956 version.build = app.build;
957 Ok(version)
958 }
959
960 fn get(
961 &self,
962 url: &str,
963 from: u64,
964 sink: nsh_core::runtime::UpdaterSink<'_>,
965 ) -> Result<(), String> {
966 const MAX_REDIRECTS: usize = 20;
967 let mut current = url.to_owned();
968 for hops in 0..=MAX_REDIRECTS {
969 let (tx, rx) = std::sync::mpsc::channel();
970 let events: FetchEvents = Box::new(move |event| {
971 let _ = tx.send(event);
972 });
973 let mut request =
976 HttpRequest::new("GET", ¤t).header("Accept-Encoding", "identity");
977 if from > 0 {
978 request = request.header("Range", format!("bytes={from}-"));
979 }
980 request.follow_redirects = false;
984 let task = self.network.fetch(request, events);
985
986 let mut expected_body: Option<u64> = None;
987 let mut received_body: u64 = 0;
988 let mut redirect_to: Option<String> = None;
989 let mut at = 0u64;
991 let mut total: Option<u64> = None;
992
993 let outcome = loop {
994 match rx.recv() {
995 Ok(FetchEvent::Head(head)) => {
996 if matches!(head.status, 301 | 302 | 303 | 307 | 308)
997 && let Some(location) = updater_header(&head.headers, "location")
998 {
999 if hops == MAX_REDIRECTS {
1000 break Err("too many redirects".to_owned());
1001 }
1002 let base = if head.url.is_empty() {
1003 current.as_str()
1004 } else {
1005 head.url.as_str()
1006 };
1007 let next = nsh_core::access::resolve_reference(base, location.trim());
1008 if !is_updater_url(&next) {
1009 break Err(format!("redirect to non-HTTPS URL {next:?}"));
1010 }
1011 redirect_to = Some(next);
1012 break Ok(());
1013 }
1014 let content_length = updater_header(&head.headers, "content-length")
1015 .and_then(|value| value.trim().parse::<u64>().ok());
1016 if from > 0 && head.status == 206 {
1017 let valid = updater_header(&head.headers, "content-range")
1018 .and_then(parse_content_range)
1019 .filter(|range| {
1020 range.start == from
1021 && content_length.is_none_or(|cl| cl == range.len)
1022 });
1023 match valid {
1024 Some(range) => {
1025 expected_body = Some(range.len);
1026 at = range.start;
1027 total = range.total;
1028 }
1029 None => break Ok(()),
1031 }
1032 } else if from > 0 && head.status == 416 {
1033 break Ok(());
1034 } else if head.status == 200 {
1035 expected_body = content_length;
1036 total = content_length;
1037 } else {
1038 break Err(format!("HTTP {}", head.status));
1039 }
1040 }
1041 Ok(FetchEvent::Data(chunk)) => {
1042 if chunk.is_empty() {
1043 continue;
1044 }
1045 received_body = received_body.saturating_add(chunk.len() as u64);
1046 if let Err(e) = sink(at, &chunk, total) {
1047 break Err(e);
1048 }
1049 at = at.saturating_add(chunk.len() as u64);
1050 }
1051 Ok(FetchEvent::End) => {
1052 if let Some(expected) = expected_body
1053 && received_body < expected
1054 {
1055 break Err(format!(
1056 "truncated response ({received_body} of {expected} bytes)"
1057 ));
1058 }
1059 break Ok(());
1060 }
1061 Ok(FetchEvent::Failed(e)) => break Err(e),
1062 Ok(FetchEvent::BodyWanted) => {}
1063 Err(_) => break Err("the network stack went away".to_owned()),
1064 }
1065 };
1066 task.cancel();
1067 outcome?;
1068 if let Some(next) = redirect_to {
1069 current = next;
1070 continue;
1071 }
1072 return Ok(());
1073 }
1074 Err("too many redirects".to_owned())
1075 }
1076}
1077
1078fn updater_header<'a>(headers: &'a [(String, String)], target: &str) -> Option<&'a str> {
1080 headers
1081 .iter()
1082 .find(|(name, _)| name.eq_ignore_ascii_case(target))
1083 .map(|(_, value)| value.as_str())
1084}
1085
1086#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1088struct ContentRange {
1089 start: u64,
1090 len: u64,
1091 total: Option<u64>,
1092}
1093
1094fn parse_content_range(value: &str) -> Option<ContentRange> {
1095 let parse_digits = |s: &str| -> Option<u64> {
1096 (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
1097 .then(|| s.parse().ok())
1098 .flatten()
1099 };
1100 let (unit, rest) = value.trim().split_once(' ')?;
1101 if !unit.eq_ignore_ascii_case("bytes") {
1102 return None;
1103 }
1104 let (range, total) = rest.trim_start().split_once('/')?;
1105 let (start, end) = range.split_once('-')?;
1106 let start = parse_digits(start)?;
1107 let end = parse_digits(end)?;
1108 if start > end {
1109 return None;
1110 }
1111 let len = end.checked_sub(start)?.checked_add(1)?;
1112 let total = if total == "*" {
1113 None
1114 } else {
1115 let total = parse_digits(total)?;
1116 if end >= total {
1117 return None;
1118 }
1119 Some(total)
1120 };
1121 Some(ContentRange { start, len, total })
1122}
1123
1124fn is_updater_url(url: &str) -> bool {
1126 let Some(parts) = nsh_core::access::parse_url(url) else {
1127 return false;
1128 };
1129 parts.scheme == "https"
1130 || (parts.scheme == "http"
1131 && matches!(
1132 parts.host.as_str(),
1133 "127.0.0.1" | "localhost" | "::1" | "[::1]"
1134 ))
1135}
1136
1137pub trait Network: Send + Sync + 'static {
1139 fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
1142}
1143
1144pub trait Assets: Send + Sync + 'static {
1149 fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
1153
1154 fn url(&self, uri: &str) -> Option<String> {
1159 let _ = uri;
1160 None
1161 }
1162
1163 #[cfg(not(target_arch = "wasm32"))]
1170 fn base(&self) -> Option<nsh_core::image::loader::AssetBase> {
1171 None
1172 }
1173}
1174
1175#[derive(Clone)]
1177pub struct EngineConfig {
1178 pub app: App,
1180 pub viewport: Size<Points>,
1182 pub trace: bool,
1184 pub content_culling: bool,
1188 pub network: Option<Arc<dyn Network>>,
1190 pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
1192 pub refuse_connections: Option<nsh_core::element::RefuseConnections>,
1197 pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
1199 pub assets: Option<Arc<dyn Assets>>,
1201 pub environment: Environment,
1203 pub header_heights: (Points, Points),
1206 pub limits: Limits,
1208 pub ui_sets: Vec<nsh_core::element::Registry>,
1212 pub runtime: Option<tokio::runtime::Handle>,
1215 #[doc(hidden)]
1226 pub support_dir: Option<std::path::PathBuf>,
1227 pub data_dir: Option<std::path::PathBuf>,
1232 pub cache: CacheOptions,
1236 pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
1241 pub clock: Clock,
1245 pub context: EngineContext,
1250 pub pinned: EnvironmentPins,
1253 pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
1257 pub host: HostChannel,
1262 pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
1266 pub audio: Option<Arc<dyn nsh_core::audio::AudioBackend>>,
1271 pub windows: Option<Arc<dyn nsh_core::desktop::WindowBackend>>,
1277 pub login_item: Option<Arc<dyn nsh_core::desktop::LoginItemBackend>>,
1282}
1283
1284#[derive(Debug, Clone, Copy, Default, PartialEq)]
1287#[non_exhaustive]
1288pub struct EnvironmentPins {
1289 pub locale: Option<nsh_core::platform::Locale>,
1291 pub languages: Option<nsh_core::platform::Languages>,
1293 pub hour_cycle: Option<nsh_core::platform::HourCycle>,
1295 pub first_day_of_week: Option<nsh_core::platform::Weekday>,
1297 pub measurement_system: Option<nsh_core::platform::MeasurementSystem>,
1299 pub temperature_unit: Option<nsh_core::platform::TemperatureUnit>,
1301 pub time_zone: Option<nsh_core::platform::TimeZone>,
1303 pub reduce_motion: Option<bool>,
1306 pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
1308}
1309
1310impl EnvironmentPins {
1311 pub fn apply(&self, environment: &mut Environment) {
1313 if let Some(locale) = self.locale {
1314 environment.locale = locale;
1315 }
1316 let settings = &mut environment.locale_settings;
1317 if let Some(languages) = self.languages {
1318 settings.languages = languages;
1319 }
1320 if let Some(time_zone) = self.time_zone {
1321 settings.time_zone = time_zone;
1322 }
1323 if let Some(hour_cycle) = self.hour_cycle {
1324 settings.hour_cycle = hour_cycle;
1325 }
1326 if let Some(day) = self.first_day_of_week {
1327 settings.first_day_of_week = day;
1328 }
1329 if let Some(system) = self.measurement_system {
1330 settings.measurement_system = system;
1331 }
1332 if let Some(unit) = self.temperature_unit {
1333 settings.temperature_unit = unit;
1334 }
1335 if let Some(reduce_motion) = self.reduce_motion {
1336 environment.reduce_motion = reduce_motion;
1337 }
1338 if let Some(safe_area) = self.safe_area {
1339 environment.safe_area = safe_area;
1340 }
1341 }
1342}
1343
1344fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
1345 let path = path.filter(|path| path.is_absolute())?;
1346 nsh_core::access::canonicalize(&path)
1347 .ok()
1348 .filter(|path| path.is_dir())
1349}
1350
1351fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
1354 system_paths(bundle.system_paths.clone(), !bundle.policy.harden)
1355}
1356
1357fn system_paths(
1360 mut paths: nsh_core::access::TrustedPaths,
1361 development: bool,
1362) -> nsh_core::access::TrustedPaths {
1363 paths.plugin_dir = trusted_directory(paths.plugin_dir);
1364 paths.home_dir = trusted_directory(paths.home_dir);
1365 if paths.home_dir.is_none() {
1366 paths.home_dir = ["HOME", "USERPROFILE"]
1367 .into_iter()
1368 .filter_map(std::env::var_os)
1369 .map(std::path::PathBuf::from)
1370 .find_map(|path| trusted_directory(Some(path)));
1371 }
1372 if paths.plugin_dir.is_none() && development {
1376 paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
1377 .map(std::path::PathBuf::from)
1378 .and_then(|path| trusted_directory(Some(path)));
1379 }
1380 paths
1381}
1382
1383impl EngineConfig {
1384 pub fn new(app: impl Into<App>) -> Self {
1391 Self {
1392 app: app.into(),
1393 viewport: Size::new(Points(390.0), Points(844.0)),
1394 trace: false,
1395 content_culling: false,
1396 network: None,
1397 websocket: None,
1398 refuse_connections: None,
1399 filesystem: None,
1400 assets: None,
1401 environment: Environment::default(),
1402 header_heights: (Points(44.0), Points(96.0)),
1403 limits: Limits::default(),
1404 ui_sets: Vec::new(),
1405 runtime: None,
1406 support_dir: None,
1407 data_dir: None,
1408 cache: CacheOptions::off(),
1409 storage: None,
1410 clock: Clock::system(),
1411 context: EngineContext::default(),
1412 pinned: EnvironmentPins::default(),
1413 clipboard: None,
1414 host: HostChannel::default(),
1415 picker: None,
1416 audio: None,
1417 windows: None,
1418 login_item: None,
1419 }
1420 }
1421
1422 pub fn main_window_placement(
1430 &self,
1431 displays: &[nsh_core::desktop::Display],
1432 ) -> Option<nsh_core::desktop::WindowPlacement> {
1433 let options = self.app.main_window()?;
1434 let storage = app_storage(self)?;
1435 options.kept_placement(&*storage, displays)
1436 }
1437}
1438
1439fn data_dir(config: &EngineConfig) -> Option<std::path::PathBuf> {
1442 config.data_dir.clone().or_else(|| {
1443 config
1444 .support_dir
1445 .as_ref()
1446 .map(|root| root.join(app_dir_name(config.app.app_id())))
1447 })
1448}
1449
1450fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
1453 if let Some(storage) = &config.storage {
1454 return Some(storage.clone());
1455 }
1456 #[cfg(not(target_arch = "wasm32"))]
1457 if let Some(dir) = data_dir(config) {
1458 return Some(FileStorage::open(dir));
1459 }
1460 None
1461}
1462
1463#[cfg(not(target_arch = "wasm32"))]
1464fn shared_runtime() -> tokio::runtime::Handle {
1468 static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
1469 RUNTIME
1470 .get_or_init(|| {
1471 tokio::runtime::Builder::new_multi_thread()
1472 .worker_threads(2)
1473 .thread_name("nsh-tasks")
1474 .enable_all()
1475 .build()
1476 .expect("the tasks' runtime starts")
1477 })
1478 .handle()
1479 .clone()
1480}
1481
1482impl std::fmt::Debug for EngineConfig {
1483 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1484 f.debug_struct("EngineConfig")
1485 .field("app", &self.app)
1486 .field("viewport", &self.viewport)
1487 .field("trace", &self.trace)
1488 .field("content_culling", &self.content_culling)
1489 .field("network", &self.network.is_some())
1490 .field("assets", &self.assets.is_some())
1491 .field("environment", &self.environment)
1492 .field("header_heights", &self.header_heights)
1493 .field("limits", &self.limits)
1494 .field("ui_sets", &self.ui_sets)
1495 .field("clock", &self.clock)
1496 .field("context", &self.context)
1497 .field("pinned", &self.pinned)
1498 .field("clipboard", &self.clipboard.is_some())
1499 .field("host", &self.host)
1500 .field("picker", &self.picker.is_some())
1501 .field("audio", &self.audio.is_some())
1502 .field("login_item", &self.login_item.is_some())
1503 .field("windows", &self.windows.is_some())
1504 .finish()
1505 }
1506}
1507
1508const MAX_ADVANCE_ROUNDS: usize = 100_000;
1512
1513const MAX_FLUSH_ROUNDS: usize = 64;
1517
1518enum Message {
1519 Event(NodeId, EventKind, EventPayload),
1520 Scroll(NodeId, Point<Points>, u32),
1521 KeyScrolled(NodeId, nsh_core::scroll::KeyMove),
1522 Kept(Vec<NodeId>),
1523 ContentCulling(bool),
1524 InputScroll(NodeId, Point<Points>, Size<Points>, Size<Points>),
1525 InputComposing(NodeId, Option<String>),
1526 Zoom(NodeId, f32),
1527 ComponentSize(NodeId, Size<Points>),
1528 AnimationsFinished(Vec<nsh_core::animation::Finished>),
1529 Resize(Size<Points>),
1530 Wake,
1532 Environment(Box<Environment>),
1536 ShadersUnavailable,
1539 Displays(Arc<[nsh_core::desktop::Display]>),
1541 RootSize(NodeId, Size<Points>, EdgeInsets),
1542 OverlayArea(Option<nsh_core::Bounds<Points>>),
1545 PressBeyondRoot(nsh_core::Point<Points>),
1547 PressOnNative(NodeId, nsh_core::Point<Points>),
1549 ScreenHeader(NodeId, Option<Points>),
1550 Frame,
1551 States(NodeId, u16),
1552 ReleaseStates(NodeId, u16, std::time::Duration),
1553 Modality(nsh_core::platform::InputModality),
1554 FontsChanged,
1555 Remount,
1556 Fetch(Requester, u64, FetchEvent),
1559 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1562 AssetRead(Requester, u64, HttpRequest, Result<Vec<u8>, String>),
1563 Hot(HotUpdate),
1564 Chunk(Result<Chunk, (String, String)>),
1567 Perf(Option<Arc<perf::PerfMonitor>>),
1568 Tokens(Option<Box<Tokens>>),
1570 HostFont(Vec<u8>),
1573 HostEvent(String, nsh_core::JsonValue),
1576 HostReply(u64, Result<nsh_core::JsonValue, String>),
1578 CoreHostReply(u64, Result<nsh_core::JsonValue, String>),
1582 UrlHandled {
1585 id: u32,
1586 url: String,
1587 handled: bool,
1588 },
1589 Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
1591 Flush(Box<dyn FnOnce(bool, Option<Instant>) + Send>),
1595 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1597 Shutdown,
1598}
1599
1600#[derive(Debug, Clone)]
1604pub struct HotUpdate {
1605 pub name: String,
1607 pub code: String,
1609 pub source_map: Option<Arc<str>>,
1611}
1612
1613const MAX_LIST_ROUNDS: usize = 8;
1617
1618const PACED_BIND_OPS: usize = 150;
1625const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);
1627
1628#[derive(Clone)]
1630pub struct EngineControl {
1631 tx: Sender<Message>,
1632 modality: Arc<std::sync::atomic::AtomicU8>,
1635 downloads: nsh_core::webview::downloads::DownloadCleanup,
1639}
1640
1641impl EngineControl {
1642 pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
1644 self.downloads.dispatch(id, event, &payload);
1650 let _ = self.tx.send(Message::Event(id, event, payload));
1651 }
1652
1653 pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
1659 let _ = self.tx.send(Message::Scroll(id, offset, applied));
1660 }
1661
1662 pub fn key_scrolled(&self, id: NodeId, key_move: nsh_core::scroll::KeyMove) {
1667 let _ = self.tx.send(Message::KeyScrolled(id, key_move));
1668 }
1669
1670 pub fn keep_rendered(&self, nodes: Vec<NodeId>) {
1674 let _ = self.tx.send(Message::Kept(nodes));
1675 }
1676
1677 pub fn set_content_culling(&self, enabled: bool) {
1682 let _ = self.tx.send(Message::ContentCulling(enabled));
1683 }
1684
1685 pub fn input_scroll(
1690 &self,
1691 id: NodeId,
1692 offset: Point<Points>,
1693 content: Size<Points>,
1694 viewport: Size<Points>,
1695 ) {
1696 let _ = self
1697 .tx
1698 .send(Message::InputScroll(id, offset, content, viewport));
1699 }
1700
1701 pub fn input_composing(&self, id: NodeId, shown: Option<String>) {
1706 let _ = self.tx.send(Message::InputComposing(id, shown));
1707 }
1708
1709 pub fn zoom(&self, id: NodeId, scale: f32) {
1712 let _ = self.tx.send(Message::Zoom(id, scale));
1713 }
1714
1715 pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
1718 let _ = self.tx.send(Message::ComponentSize(id, size));
1719 }
1720
1721 pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
1723 let _ = self.tx.send(Message::AnimationsFinished(finished));
1724 }
1725
1726 pub fn resize(&self, size: Size<Points>) {
1728 let _ = self.tx.send(Message::Resize(size));
1729 }
1730
1731 pub fn set_environment(&self, environment: Environment) {
1734 let _ = self.tx.send(Message::Environment(Box::new(environment)));
1735 }
1736
1737 pub fn shaders_unavailable(&self) {
1742 let _ = self.tx.send(Message::ShadersUnavailable);
1743 }
1744
1745 pub fn set_displays(&self, displays: Vec<nsh_core::desktop::Display>) {
1749 let _ = self.tx.send(Message::Displays(displays.into()));
1750 }
1751
1752 pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
1756 let _ = self.tx.send(Message::RootSize(id, size, insets));
1757 }
1758
1759 pub fn set_overlay_area(&self, area: Option<nsh_core::Bounds<Points>>) {
1764 let _ = self.tx.send(Message::OverlayArea(area));
1765 }
1766
1767 pub fn press_beyond_root(&self, page: nsh_core::Point<Points>) {
1772 let _ = self.tx.send(Message::PressBeyondRoot(page));
1773 }
1774
1775 pub fn press_on_native(&self, id: NodeId, page: nsh_core::Point<Points>) {
1780 let _ = self.tx.send(Message::PressOnNative(id, page));
1781 }
1782
1783 pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
1786 let _ = self.tx.send(Message::ScreenHeader(id, height));
1787 }
1788
1789 pub fn hot_update(&self, update: HotUpdate) {
1792 let _ = self.tx.send(Message::Hot(update));
1793 }
1794
1795 pub fn chunk_loaded(&self, chunk: Chunk) {
1798 let _ = self.tx.send(Message::Chunk(Ok(chunk)));
1799 }
1800
1801 pub fn chunk_failed(&self, id: String, message: String) {
1804 let _ = self.tx.send(Message::Chunk(Err((id, message))));
1805 }
1806
1807 pub fn frame(&self) {
1810 let _ = self.tx.send(Message::Frame);
1811 }
1812
1813 pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
1820 let _ = self.tx.send(Message::Advance(by, Box::new(done)));
1821 }
1822
1823 pub fn flush(&self, done: impl FnOnce(bool) + Send + 'static) {
1833 self.flush_until_due(move |idle, _| done(idle));
1834 }
1835
1836 #[doc(hidden)]
1842 pub fn flush_until_due(&self, done: impl FnOnce(bool, Option<Instant>) + Send + 'static) {
1843 let _ = self.tx.send(Message::Flush(Box::new(done)));
1844 }
1845
1846 pub fn set_input_modality(&self, modality: nsh_core::platform::InputModality) {
1853 use std::sync::atomic::Ordering;
1854 let code = match modality {
1855 nsh_core::platform::InputModality::Keyboard => 1,
1856 nsh_core::platform::InputModality::Pointer => 2,
1857 };
1858 if self.modality.swap(code, Ordering::Relaxed) != code {
1859 let _ = self.tx.send(Message::Modality(modality));
1860 }
1861 }
1862
1863 pub fn set_states(&self, id: NodeId, states: u16) {
1868 let _ = self.tx.send(Message::States(id, states));
1869 }
1870
1871 pub fn release_states_after(&self, id: NodeId, states: u16, hold: std::time::Duration) {
1876 let _ = self.tx.send(Message::ReleaseStates(id, states, hold));
1877 }
1878
1879 pub fn fonts_changed(&self) {
1883 let _ = self.tx.send(Message::FontsChanged);
1884 }
1885
1886 pub fn remount(&self) {
1890 let _ = self.tx.send(Message::Remount);
1891 }
1892
1893 pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
1896 let _ = self.tx.send(Message::Perf(monitor));
1897 }
1898
1899 pub fn set_tokens(&self, tokens: Option<Tokens>) {
1904 let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1905 }
1906
1907 pub fn register_font(&self, data: Vec<u8>) {
1912 let _ = self.tx.send(Message::HostFont(data));
1913 }
1914}
1915
1916#[cfg(not(target_arch = "wasm32"))]
1917pub struct Engine {
1919 control: EngineControl,
1920 thread: Option<std::thread::JoinHandle<()>>,
1921 host: HostChannel,
1923 stop: Arc<std::sync::atomic::AtomicBool>,
1925 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1928 image_cache: Option<nsh_core::image::DiskCache>,
1930 media_files: Arc<nsh_core::access::MediaFiles>,
1932}
1933
1934#[cfg(not(target_arch = "wasm32"))]
1935impl Engine {
1936 pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
1938 where
1939 M: TextEngine + 'static,
1940 F: FnOnce() -> M + Send + 'static,
1941 S: MountSink,
1942 {
1943 Self::start_with(config, make_text_engine, sink, |_| {})
1944 }
1945
1946 pub fn start_with<M, F, S>(
1950 config: EngineConfig,
1951 make_text_engine: F,
1952 sink: S,
1953 setup: impl FnOnce(&EngineControl),
1954 ) -> io::Result<Engine>
1955 where
1956 M: TextEngine + 'static,
1957 F: FnOnce() -> M + Send + 'static,
1958 S: MountSink,
1959 {
1960 let image_cache = config.cache.open_images(config.app.app_id());
1961 let media_files = Arc::new(media_files(&config, &app_access(&config.app)));
1962 let (tx, rx) = crossbeam_channel::unbounded();
1963 let modality = Arc::default();
1964 let downloads = nsh_core::webview::downloads::DownloadCleanup::new();
1965 setup(&EngineControl {
1966 tx: tx.clone(),
1967 modality: Arc::clone(&modality),
1968 downloads: downloads.clone(),
1969 });
1970 let engine_tx = tx.clone();
1971 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1972 let engine_stop = stop.clone();
1973 let quit_listeners = Arc::new(std::sync::atomic::AtomicBool::new(false));
1974 let engine_quit_listeners = quit_listeners.clone();
1975 let host = config.host.clone();
1976 let engine_downloads = downloads.clone();
1977 let thread = std::thread::Builder::new()
1978 .name("nsh-engine".into())
1979 .stack_size(ENGINE_STACK_SIZE)
1980 .spawn(move || {
1981 run(
1982 config,
1983 make_text_engine(),
1984 sink,
1985 (engine_tx, rx),
1986 engine_stop,
1987 engine_quit_listeners,
1988 engine_downloads,
1989 )
1990 })?;
1991 Ok(Engine {
1992 control: EngineControl {
1993 tx,
1994 modality,
1995 downloads,
1996 },
1997 thread: Some(thread),
1998 host,
1999 stop,
2000 quit_listeners,
2001 image_cache,
2002 media_files,
2003 })
2004 }
2005
2006 pub fn media_files(&self) -> Arc<nsh_core::access::MediaFiles> {
2011 self.media_files.clone()
2012 }
2013
2014 pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
2018 self.image_cache.clone()
2019 }
2020
2021 pub fn control(&self) -> EngineControl {
2023 self.control.clone()
2024 }
2025}
2026
2027#[cfg(not(target_arch = "wasm32"))]
2028impl Drop for Engine {
2029 fn drop(&mut self) {
2030 if self
2034 .quit_listeners
2035 .load(std::sync::atomic::Ordering::Relaxed)
2036 {
2037 self.host.request_shutdown(&self.control.tx);
2038 let deadline = Instant::now() + QUIT_TIMEOUT + QUIT_GRACE;
2039 while self.thread.as_ref().is_some_and(|t| !t.is_finished())
2040 && Instant::now() < deadline
2041 {
2042 std::thread::sleep(Duration::from_millis(1));
2043 }
2044 }
2045 self.host.shutdown(&self.control.tx, &self.stop);
2046 if let Some(thread) = self.thread.take() {
2047 let _ = thread.join();
2048 }
2049 }
2050}
2051
2052#[cfg(not(target_arch = "wasm32"))]
2053fn raise_thread_priority() {
2057 #[cfg(target_vendor = "apple")]
2058 unsafe {
2060 libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
2061 }
2062}
2063
2064#[cfg(not(target_arch = "wasm32"))]
2066use nsh_core::element::desktop::QUIT_TIMEOUT;
2067
2068#[cfg(not(target_arch = "wasm32"))]
2071const QUIT_GRACE: Duration = Duration::from_millis(20);
2072
2073const RESIZE_BURST_GAP: Duration = Duration::from_millis(120);
2076
2077#[cfg(not(target_arch = "wasm32"))]
2078fn run<M: TextEngine + 'static, S: MountSink>(
2079 config: EngineConfig,
2080 text_engine: M,
2081 sink: S,
2082 messages: (Sender<Message>, Receiver<Message>),
2083 stop: Arc<std::sync::atomic::AtomicBool>,
2084 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
2085 downloads: nsh_core::webview::downloads::DownloadCleanup,
2086) {
2087 let (tx, rx) = messages;
2088 raise_thread_priority();
2089 let _clock = config.clock.enter();
2091 let _context = config.context.enter();
2092 let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
2093 return;
2094 };
2095 driver.state.core.set_download_cleanup(downloads);
2096 driver.quit_listeners = quit_listeners;
2097 driver.sync_quit_listeners();
2098 drive(&mut driver, &rx);
2099 driver.quit(&rx);
2100 if let Some(trial) = &driver.trial {
2102 trial.healthy();
2103 }
2104}
2105
2106fn start_trial(trial: Arc<dyn Trial>) {
2109 #[cfg(not(target_arch = "wasm32"))]
2110 {
2111 let spawned = std::thread::Builder::new()
2112 .name("nsh-trial".into())
2113 .spawn(move || {
2114 std::thread::sleep(TRIAL_PERIOD);
2115 trial.healthy();
2116 });
2117 if let Err(err) = spawned {
2118 log::error!("cannot time the app's trial: {err}");
2119 }
2120 }
2121 #[cfg(target_arch = "wasm32")]
2123 drop(trial);
2124}
2125
2126#[cfg(not(target_arch = "wasm32"))]
2128fn drive<M: TextEngine + 'static>(driver: &mut Driver<M>, rx: &Receiver<Message>) {
2129 loop {
2130 let message = match driver.deadline() {
2131 Some(deadline) => match rx.recv_deadline(deadline) {
2132 Ok(message) => Some(message),
2133 Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
2134 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
2135 },
2136 None => match rx.recv() {
2137 Ok(message) => Some(message),
2138 Err(_) => return,
2139 },
2140 };
2141 let started = driver.state.perf.is_some().then(Instant::now);
2142 if let Some(message) = message {
2143 if !driver.handle(message, rx) {
2144 return;
2145 }
2146 while let Ok(message) = rx.try_recv() {
2148 if !driver.handle(message, rx) {
2149 return;
2150 }
2151 }
2152 }
2153 driver.turn();
2154 driver.state.record_perf(started);
2155 driver.read_perf_stats();
2156 if rx.is_empty() {
2157 driver.collect_if_idle();
2158 }
2159 }
2160}
2161
2162pub struct LocalEngine<M: TextEngine + 'static> {
2167 driver: ManuallyDrop<Driver<M>>,
2170 rx: Receiver<Message>,
2171 control: EngineControl,
2172 wake: Option<Arc<dyn Fn() + Send + Sync>>,
2174 pumping: Arc<std::sync::atomic::AtomicBool>,
2177 quit_started: bool,
2179}
2180
2181impl<M: TextEngine + 'static> LocalEngine<M> {
2182 pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
2185 Self::start_with(config, text_engine, sink, |_| {})
2186 }
2187
2188 pub fn start_with<S: MountSink>(
2192 config: EngineConfig,
2193 text_engine: M,
2194 sink: S,
2195 setup: impl FnOnce(&EngineControl),
2196 ) -> Option<Self> {
2197 let (tx, rx) = crossbeam_channel::unbounded();
2198 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
2199 let downloads = nsh_core::webview::downloads::DownloadCleanup::new();
2200 let control = EngineControl {
2201 tx: tx.clone(),
2202 modality: Arc::default(),
2203 downloads: downloads.clone(),
2204 };
2205 setup(&control);
2206 let _clock = config.clock.enter();
2207 let _context = config.context.enter();
2208 let mut driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
2209 driver.state.core.set_download_cleanup(downloads);
2210 Some(LocalEngine {
2211 driver: ManuallyDrop::new(driver),
2212 rx,
2213 control,
2214 wake: None,
2215 pumping: Arc::default(),
2216 quit_started: false,
2217 })
2218 }
2219
2220 pub fn control(&self) -> EngineControl {
2222 self.control.clone()
2223 }
2224
2225 pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
2234 let tx = self.control.tx.clone();
2235 let pumping = self.pumping.clone();
2236 let host = wake.clone();
2237 let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
2238 let _ = tx.send(Message::Wake);
2239 if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
2242 host();
2243 }
2244 });
2245 self.driver.state.core.set_task_notify(notify.clone());
2246 self.driver.posts.set_notify(notify);
2247 self.wake = Some(wake);
2248 }
2249
2250 pub fn extend_ui_sets(&mut self, ui_sets: &[nsh_core::element::Registry]) {
2254 let sets: Vec<_> = nsh_core::runtime::registries()
2255 .iter()
2256 .chain(ui_sets)
2257 .cloned()
2258 .collect();
2259 self.driver
2260 .state
2261 .core
2262 .extend_components(nsh_core::element::Registry::merged(&sets));
2263 }
2264
2265 #[doc(hidden)]
2281 pub fn key_event(
2282 &mut self,
2283 id: NodeId,
2284 kind: EventKind,
2285 mut payload: EventPayload,
2286 stroke: Option<nsh_core::keymap::Keystroke>,
2287 ) -> bool {
2288 let _clock = self.driver.clock.enter();
2289 let _context = self.driver.context.enter();
2290 let prevented = match &mut payload {
2291 EventPayload::Key(event) => {
2292 event.default_prevented = self.driver.state.core.key_captured(id, stroke.as_ref());
2293 event.default_prevented
2294 }
2295 _ => false,
2296 };
2297 self.driver
2298 .handle(Message::Event(id, kind, payload), &self.rx);
2299 prevented
2300 }
2301
2302 #[doc(hidden)]
2307 pub fn key_interest(&self, id: NodeId) -> bool {
2308 self.driver.state.core.key_interest(id)
2309 }
2310
2311 pub fn pump(&mut self) -> Option<Instant> {
2315 let _clock = self.driver.clock.enter();
2316 let _context = self.driver.context.enter();
2317 self.pumping
2318 .store(true, std::sync::atomic::Ordering::SeqCst);
2319 for _ in 0..4 {
2322 let started = self.driver.state.perf.is_some().then(Instant::now);
2323 while let Ok(message) = self.rx.try_recv() {
2324 self.driver.handle(message, &self.rx);
2325 }
2326 self.driver.turn();
2327 self.driver.state.record_perf(started);
2328 if self.rx.is_empty() {
2329 break;
2330 }
2331 }
2332 self.driver.read_perf_stats();
2333 self.driver.collect_if_idle();
2334 self.pumping
2335 .store(false, std::sync::atomic::Ordering::SeqCst);
2336 if !self.rx.is_empty()
2339 && let Some(wake) = &self.wake
2340 {
2341 wake();
2342 }
2343 self.driver.deadline()
2344 }
2345
2346 #[doc(hidden)]
2354 pub fn start_quit(&mut self) {
2355 if std::mem::replace(&mut self.quit_started, true) {
2356 return;
2357 }
2358 {
2359 let _clock = self.driver.clock.enter();
2360 let _context = self.driver.context.enter();
2361 if !self.driver.state.core.has_quit_listeners() {
2362 return;
2363 }
2364 self.driver.state.core.start_quit();
2365 }
2366 self.pump();
2367 }
2368}
2369
2370impl<M: TextEngine + 'static> Drop for LocalEngine<M> {
2371 fn drop(&mut self) {
2372 let _context = self.driver.context.enter();
2376 unsafe { ManuallyDrop::drop(&mut self.driver) };
2379 }
2380}
2381
2382struct Driver<M: TextEngine + 'static> {
2384 state: State<Rc<M>>,
2385 script: Option<Script>,
2386 sink: Rc<dyn MountSink>,
2387 assets: Option<Arc<dyn Assets>>,
2388 stopped: bool,
2391 last_gc: Instant,
2392 last_active: Instant,
2395 posts: nsh_core::element::Posts,
2398 clock: Clock,
2400 context: EngineContext,
2402 last_frame: Option<Instant>,
2405 _host: host_channel::HostAttachment,
2408 #[cfg(not(target_arch = "wasm32"))]
2412 trial: Option<Arc<dyn Trial>>,
2413 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
2415 quitting: bool,
2418}
2419
2420impl<M: TextEngine + 'static> Driver<M> {
2421 fn start(
2423 mut config: EngineConfig,
2424 text_engine: M,
2425 sink: Rc<dyn MountSink>,
2426 tx: Sender<Message>,
2427 rx: &Receiver<Message>,
2428 stop: Arc<std::sync::atomic::AtomicBool>,
2429 ) -> Option<Self> {
2430 config.pinned.apply(&mut config.environment);
2431 drawn_shaders(&mut config.environment, false);
2432 let trial = match &config.app {
2433 App::Js(bundle) => bundle.trial.clone(),
2434 App::Rust(_) => None,
2435 };
2436 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2437 let system_tx = tx.clone();
2438 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2439 let host_bridge = config.host.bridge(tx.clone());
2440 let host_tx = tx.clone();
2441 let text_engine = Rc::new(text_engine);
2442 let access = Arc::new(app_access(&config.app));
2443 let mut core = Core::new(text_engine.clone(), config.viewport);
2444 let mode = config
2449 .app
2450 .application()
2451 .map(|options| options.quit_mode)
2452 .unwrap_or_default();
2453 core.set_quit_mode(mode);
2454 core.set_content_culling(config.content_culling);
2455 core.set_tree_order_tracking(sink.needs_tree_order());
2456 core.set_projected_state_mounting(sink.needs_projected_states());
2457 let sets: Vec<_> = nsh_core::runtime::registries()
2460 .iter()
2461 .chain(&config.ui_sets)
2462 .cloned()
2463 .collect();
2464 core.set_components(nsh_core::element::Registry::merged(&sets));
2465 let posts = nsh_core::element::Posts::new();
2469 core.set_posts(posts.clone());
2470 if let App::Js(_) = &config.app {
2471 core.set_max_nodes(config.limits.max_nodes);
2473 }
2474 core.set_access(access.clone());
2475 if let App::Js(bundle) = &config.app {
2476 core.set_base_url(bundle.base_url.clone());
2478 }
2479 let media_files = Arc::new(media_files(&config, &access));
2482 core.set_media_files(media_files.clone());
2483 #[cfg(not(target_arch = "wasm32"))]
2484 core.set_image_context(nsh_core::image::loader::Context {
2485 asset_base: config.assets.as_ref().and_then(|a| a.base()),
2486 read_asset: config.assets.clone().map(|assets| {
2487 Arc::new(move |uri: &str| assets.read(uri)) as nsh_core::image::loader::ReadAsset
2488 }),
2489 access: access.clone(),
2490 media_files,
2491 disk: config.cache.open_images(config.app.app_id()),
2493 transport: None,
2495 });
2496 core.set_storage(app_storage(&config));
2497 core.set_data_dir(data_dir(&config));
2498 core.set_updater(match &config.app {
2501 App::Js(bundle) => {
2502 UpdaterOverNetwork::host(config.network.clone(), config.assets.clone(), bundle)
2503 }
2504 App::Rust(_) => UpdaterOverNetwork::of(config.network.clone(), config.assets.clone()),
2505 });
2506 core.set_clipboard(config.clipboard.clone());
2507 core.set_picker(config.picker.clone());
2508 core.set_app_links(config.app.links().clone());
2509 core.set_app_info(config.app.app_info().cloned());
2510 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2512 let app_url = core.app_url_cell();
2513 core.set_audio(config.audio.clone());
2514 core.set_window_backend(config.windows.clone());
2515 core.set_login_item(config.login_item.clone());
2516 core.set_font_scale(config.environment.font_scale);
2517 core.set_class_environment(class_environment(&config.environment));
2518 core.set_header_heights(config.header_heights.0, config.header_heights.1);
2519 core.set_safe_area(insets(&config.environment));
2520 core.set_environment(ui_environment(&config.environment, config.viewport));
2521 if let Some(window) = config.app.main_window() {
2524 core.set_main_window(window);
2525 }
2526 #[cfg(not(target_arch = "wasm32"))]
2529 let runtime = config.runtime.clone().unwrap_or_else(shared_runtime);
2530 #[cfg(not(target_arch = "wasm32"))]
2531 core.set_task_runtime(runtime.clone());
2532 if let App::Rust(root) = &config.app {
2535 if let Some(tokens) = root.tokens_ref() {
2536 core.set_tokens(tokens.clone());
2537 }
2538 if let Some(appearance) = root.appearance_ref() {
2539 core.set_appearance(appearance);
2540 }
2541 if let Some(translations) = root.translations_ref() {
2542 core.set_translations(translations.clone());
2543 }
2544 for font in root.fonts() {
2545 if let Err(err) = core.register_font(font) {
2546 log::error!("font failed: {err}");
2547 sink.report(&AppError::new(
2548 AppErrorKind::Asset,
2549 &format!("font failed: {err}"),
2550 ));
2551 }
2552 }
2553 }
2554 let os = config.environment.os;
2557 let fonts = config
2558 .ui_sets
2559 .iter()
2560 .flat_map(nsh_core::element::Registry::scoped_asset_files)
2561 .filter(|(targets, _)| targets.is_empty() || targets.contains(&os))
2562 .map(|(_, file)| file)
2563 .filter(|file| file.kind == nsh_core::element::AssetKind::Font);
2564 for font in fonts {
2565 let result = match config.assets.as_deref() {
2566 Some(assets) => assets.read(font.uri),
2567 None => Err("this host cannot load assets".to_owned()),
2568 }
2569 .and_then(|data| core.register_font(&data));
2570 if let Err(err) = result {
2571 log::error!("font failed: {}: {err}", font.uri);
2572 let message = format!("font failed: {}: {err}", font.uri);
2573 let package = match &config.app {
2574 App::Js(bundle) => bundle.package.clone(),
2575 App::Rust(_) => None,
2576 };
2577 sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
2578 }
2579 }
2580 let wake = tx.clone();
2583 core.set_task_notify(Arc::new(move || {
2584 let _ = wake.send(Message::Wake);
2585 }));
2586 let wake = tx.clone();
2587 posts.set_notify(Arc::new(move || {
2588 let _ = wake.send(Message::Wake);
2589 }));
2590 let mut early = Vec::new();
2597 let mut displays: Arc<[nsh_core::desktop::Display]> = Arc::from(Vec::new());
2598 while let Ok(message) = rx.try_recv() {
2599 match message {
2600 Message::Tokens(tokens) => core.set_host_tokens(tokens.map(|t| *t)),
2601 Message::HostFont(data) => {
2602 if let Err(err) = core.register_font(&data) {
2603 log::error!("font failed: {err}");
2604 }
2605 }
2606 Message::Displays(list) => {
2607 core.set_displays(list.clone());
2608 displays = list;
2609 }
2610 Message::Event(nsh_core::ROOT_ID, EventKind::UrlScheme, payload) => {
2611 core.component_event(nsh_core::ROOT_ID, EventKind::UrlScheme, &payload);
2612 }
2613 message => early.push(message),
2614 }
2615 }
2616 let js_tokens = core.tokens().clone();
2617 let state = State {
2618 core,
2619 published_content_height: None,
2620 js_tokens,
2621 frame_requested: false,
2622 frame_turn: false,
2623 frames_seen: false,
2624 ops: Vec::new(),
2625 binds: Vec::new(),
2626 events: Vec::new(),
2627 trace: config.trace,
2628 perf: None,
2629 perf_stats_at: None,
2630 perf_commit: perf::CommitTiming::default(),
2631 committed_since_gc: false,
2632 hot: Vec::new(),
2633 scroll_events: FxHashMap::default(),
2634 touch_move: None,
2635 mouse_moves: Vec::new(),
2636 mouse_moved: None,
2637 key_path: Vec::new(),
2638 sets_seen: FxHashMap::default(),
2639 resized: None,
2640 roots_resized: Vec::new(),
2641 resize_burst_ends: None,
2642 window_state: WindowStateReport {
2643 shown: config.environment.window_state,
2644 ..WindowStateReport::default()
2645 },
2646 events_handled: 0,
2647 events_reported: 0,
2648 pinned: config.pinned,
2649 environment: config.environment,
2650 shaders_unavailable: false,
2651 app_locale: None,
2652 host: config.host.clone(),
2653 url_opens: Vec::new(),
2654 host_requests: Vec::new(),
2655 net: Net {
2656 network: config.network.clone(),
2657 tx,
2658 queue: NetworkQueue::default(),
2659 inflight: FxHashMap::default(),
2660 tasks: Vec::new(),
2661 abandoned: Vec::new(),
2662 access: access.clone(),
2663 hops: 0,
2664 assets: config.assets.clone(),
2665 #[cfg(not(target_arch = "wasm32"))]
2666 runtime,
2667 },
2668 };
2669
2670 let mut environment = config.environment;
2671 environment.window = config.viewport;
2672 let start = Instant::now();
2673 let mut driver = Driver {
2674 state,
2675 script: None,
2676 sink: sink.clone(),
2677 assets: config.assets.clone(),
2678 stopped: false,
2679 last_gc: Instant::now(),
2680 last_active: Instant::now(),
2681 posts: posts.clone(),
2682 clock: config.clock.clone(),
2683 context: config.context.clone(),
2684 last_frame: None,
2685 _host: config.host.attach(host_tx, rx.clone()),
2686 #[cfg(not(target_arch = "wasm32"))]
2687 trial: trial.clone(),
2688 quit_listeners: Arc::default(),
2689 quitting: false,
2690 };
2691 let eval_us = match &config.app {
2692 App::Js(bundle) => {
2693 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2694 let system = {
2695 script::SystemConfig {
2696 access: (*access).clone(),
2697 websocket: config.websocket.clone(),
2698 refuse_connections: config.refuse_connections.clone(),
2699 filesystem: config.filesystem.clone(),
2700 updater: UpdaterOverNetwork::host(
2701 config.network.clone(),
2702 config.assets.clone(),
2703 bundle,
2704 ),
2705 app_url: app_url.clone(),
2706 data_dir: data_dir(&config),
2707 paths: bundle_system_paths(bundle),
2708 wake: Arc::new(move || {
2709 let _ = system_tx.send(Message::Wake);
2710 }),
2711 host: Rc::new(host_bridge),
2712 lazy_rows: config.content_culling,
2713 }
2714 };
2715 #[cfg(not(any(
2716 feature = "js-core",
2717 all(feature = "browser", target_arch = "wasm32")
2718 )))]
2719 let system = script::SystemConfig;
2720 let (script, eval_us) = Script::start(
2721 bundle,
2722 config.limits,
2723 &config.ui_sets,
2724 posts,
2725 &environment,
2726 &displays,
2727 driver.state.js_tokens.clone(),
2728 driver.state.core.theme_tokens(),
2729 text_engine,
2730 stop,
2731 sink,
2732 system,
2733 )?;
2734 driver.script = Some(script);
2735 eval_us
2736 }
2737 App::Rust(root) => {
2738 driver.state.core.mount_root(root);
2739 0
2740 }
2741 };
2742 let Driver {
2743 state,
2744 script,
2745 sink,
2746 assets,
2747 ..
2748 } = &mut driver;
2749 let script = script.as_ref();
2750 let mut moves = Vec::new();
2753 let pending = early
2754 .into_iter()
2755 .chain(std::iter::from_fn(|| rx.try_recv().ok()));
2756 for message in pending {
2757 if let Message::Advance(..) | Message::Flush(..) = message {
2758 moves.push(message);
2759 } else if !handle(script, state, message) {
2760 return None;
2761 }
2762 }
2763 if let Some(script) = script {
2766 script.run_system();
2767 }
2768 state.load_fonts(script, assets.as_deref(), &**sink);
2769 if script.is_some() {
2772 state.core.mount_opened_windows();
2773 }
2774 let batch = state.commit(script);
2775 if state.submit_mount(&**sink, batch) && state.trace {
2776 log::info!(
2777 target: "nsh::perf",
2778 "first frame: eval {eval_us}µs, total {}µs",
2779 start.elapsed().as_micros()
2780 );
2781 }
2782 state.run_on_main_thread(&**sink);
2783 if let Some(trial) = trial {
2784 start_trial(trial);
2785 }
2786 if let Some(size) = state.resized.take() {
2790 sink.resized(size);
2791 }
2792 for (id, size) in state.roots_resized.drain(..) {
2793 sink.root_resized(id, size);
2794 }
2795 state.report_handled(&**sink);
2796 state.net.pump(script, &mut state.core);
2797 state.load_chunks(script, &**sink);
2798 state.request_frame(script, &**sink);
2799 driver.check_stopped();
2800 for message in moves {
2801 if !driver.handle(message, rx) {
2802 return None;
2803 }
2804 }
2805 Some(driver)
2806 }
2807
2808 fn deadline(&self) -> Option<Instant> {
2812 let gc_deadline =
2813 (self.script.is_some() && self.state.committed_since_gc).then(|| self.next_gc());
2814 let due = if self.clock.is_manual() {
2815 None
2816 } else {
2817 self.due()
2818 };
2819 [due, gc_deadline, self.state.perf_stats_at]
2820 .into_iter()
2821 .flatten()
2822 .min()
2823 }
2824
2825 fn read_perf_stats(&mut self) {
2828 let Some(at) = self.state.perf_stats_at else {
2829 return;
2830 };
2831 let now = Instant::now();
2832 if now < at {
2833 return;
2834 }
2835 self.state.perf_stats_at = Some(now + PERF_STATS_INTERVAL);
2836 let Some(stats) = self.state.perf.as_ref().map(|m| m.snapshot().stats()) else {
2837 return;
2838 };
2839 self.state.core.set_perf_stats(Some(stats));
2840 if let Some(script) = &self.script {
2841 script.set_perf_stats(Some(&stats));
2842 }
2843 let batch = self.state.commit(self.script.as_ref());
2844 self.state.submit_mount(&*self.sink, batch);
2845 self.state.run_on_main_thread(&*self.sink);
2846 }
2847
2848 fn due(&self) -> Option<Instant> {
2851 [
2852 self.script.as_ref().and_then(Script::next_timer),
2853 self.state.next_scroll_event(),
2854 self.state.next_mouse_move(),
2855 self.state.core.next_task_timer(),
2856 self.state.core.next_state_timer(),
2857 self.state.core.download_deadline(),
2858 self.state.resize_burst_ends,
2859 self.state.window_state.settles,
2860 ]
2861 .into_iter()
2862 .flatten()
2863 .min()
2864 }
2865
2866 fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
2868 self.last_active = Instant::now();
2869 match message {
2870 Message::Advance(by, done) => {
2871 let running = self.advance(by, rx, self.clock.moves_with_frames());
2872 done();
2873 running
2874 }
2875 Message::Flush(done) => {
2876 let running = self.flush(rx);
2877 let due = [self.due(), self.clock.next_alarm()]
2878 .into_iter()
2879 .flatten()
2880 .min();
2881 done(running && self.idle(rx), due);
2882 running
2883 }
2884 Message::Frame if self.clock.moves_with_frames() => {
2888 self.state.frame_requested = true;
2891 let by = self.next_frame() - self.clock.now();
2892 self.advance(by, rx, true)
2893 }
2894 message => handle(self.script.as_ref(), &mut self.state, message),
2895 }
2896 }
2897
2898 fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
2906 if !self.clock.is_manual() {
2907 self.turn();
2909 return true;
2910 }
2911 let to = self.clock.now() + by;
2912 for round in 0.. {
2913 let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
2916 let next = [self.due(), self.clock.next_alarm(), frame]
2917 .into_iter()
2918 .flatten()
2919 .min()
2920 .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
2921 if round == MAX_ADVANCE_ROUNDS {
2922 log::warn!(
2923 "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
2924 a timer keeps scheduling another at once"
2925 );
2926 }
2927 let at = next.unwrap_or(to);
2928 self.clock.advance_to(at);
2929 while let Ok(message) = rx.try_recv() {
2930 if !self.handle(message, rx) {
2931 return false;
2932 }
2933 }
2934 if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
2936 && self.state.frame_requested
2937 {
2938 self.frame();
2939 }
2940 self.turn();
2941 if next.is_none() {
2942 break;
2943 }
2944 }
2945 true
2946 }
2947
2948 fn flush(&mut self, rx: &Receiver<Message>) -> bool {
2952 let frames = self.clock.moves_with_frames();
2953 for _ in 0..MAX_FLUSH_ROUNDS {
2954 while let Ok(message) = rx.try_recv() {
2955 if !self.handle(message, rx) {
2956 return false;
2957 }
2958 }
2959 if !self.advance(std::time::Duration::ZERO, rx, frames) {
2961 return false;
2962 }
2963 if rx.is_empty() {
2966 break;
2967 }
2968 }
2969 true
2970 }
2971
2972 fn idle(&self, rx: &Receiver<Message>) -> bool {
2976 let now = self.clock.now();
2977 rx.is_empty()
2978 && self.state.net.idle()
2979 && [self.due(), self.clock.next_alarm()]
2980 .into_iter()
2981 .flatten()
2982 .all(|at| at > now)
2983 }
2984
2985 fn next_frame(&self) -> Instant {
2990 let now = self.clock.now();
2991 self.last_frame
2992 .map_or(now + nsh_core::time::FRAME, |last| {
2993 last + nsh_core::time::FRAME
2994 })
2995 .max(now)
2996 }
2997
2998 fn frame(&mut self) {
3001 self.last_frame = Some(self.clock.now());
3002 handle(self.script.as_ref(), &mut self.state, Message::Frame);
3003 }
3004
3005 fn turn(&mut self) {
3008 let Driver {
3009 state,
3010 script,
3011 sink,
3012 assets,
3013 ..
3014 } = self;
3015 let script = script.as_ref();
3016 if script
3017 .and_then(Script::next_timer)
3018 .is_some_and(|due| due <= nsh_core::time::now())
3019 {
3020 self.last_active = Instant::now();
3021 }
3022 state.core.expire_state_timers(nsh_core::time::now());
3023 if state
3024 .resize_burst_ends
3025 .is_some_and(|ends| ends <= nsh_core::time::now())
3026 {
3027 state.resize_burst_ends = None;
3028 state.core.set_resizing(false);
3029 }
3030 if state
3031 .window_state
3032 .settles
3033 .is_some_and(|due| due <= nsh_core::time::now())
3034 && let Some(env) = state.window_state.reported
3035 {
3036 state.window_state.settles = None;
3037 state.window_state.shown = env.window_state;
3038 apply_environment(script, state, env);
3039 }
3040 let turn_start = state.trace.then(Instant::now);
3041 state.dispatch_touch_move(script);
3042 if state
3043 .next_mouse_move()
3044 .is_some_and(|due| due <= nsh_core::time::now())
3045 {
3046 state.dispatch_mouse_moves(script);
3047 }
3048 state.dispatch_scroll_events(script);
3049 let hot = std::mem::take(&mut state.hot);
3050 if let Some(script) = script {
3051 for update in hot {
3052 script.hot_update(update, &**sink);
3053 }
3054 script.run_timers(nsh_core::time::now());
3055 script.run_system();
3056 }
3057 state.core.run_component_tasks();
3058 let tasks = turn_start.map(|s| s.elapsed());
3061 state.load_fonts(script, assets.as_deref(), &**sink);
3062 let batch = state.commit(script);
3063 if !self.quitting
3064 && state.submit_mount(&**sink, batch)
3065 && let (Some(start), Some(tasks)) = (turn_start, tasks)
3066 {
3067 log::info!(
3068 target: "nsh::perf",
3069 "turn: {}µs (timers and tasks {}µs)",
3070 start.elapsed().as_micros(),
3071 tasks.as_micros(),
3072 );
3073 }
3074 state.run_on_main_thread(&**sink);
3075 if let Some(size) = state.resized.take() {
3076 sink.resized(size);
3077 }
3078 for (id, size) in state.roots_resized.drain(..) {
3079 sink.root_resized(id, size);
3080 }
3081 state.report_handled(&**sink);
3082 state.net.pump(script, &mut state.core);
3083 state.load_chunks(script, &**sink);
3084 state.request_frame(script, &**sink);
3085 self.check_stopped();
3086 self.sync_quit_listeners();
3087 }
3088
3089 fn sync_quit_listeners(&self) {
3091 self.quit_listeners.store(
3092 self.state.core.has_quit_listeners(),
3093 std::sync::atomic::Ordering::Relaxed,
3094 );
3095 }
3096
3097 #[cfg(not(target_arch = "wasm32"))]
3102 fn quit(&mut self, rx: &Receiver<Message>) {
3103 if !self.state.core.has_quit_listeners() {
3104 return;
3105 }
3106 let deadline = Instant::now() + QUIT_TIMEOUT;
3107 self.quitting = true;
3108 self.state.core.start_quit();
3109 let mut kept = Vec::new();
3110 loop {
3111 self.turn();
3112 if !self.state.core.quit_pending() || self.stopped {
3113 break;
3114 }
3115 let wake = self.deadline().map_or(deadline, |at| at.min(deadline));
3116 match rx.recv_deadline(wake) {
3117 Ok(Message::Shutdown) => {}
3118 Ok(message @ Message::HostEvent(..)) => kept.push(message),
3119 Ok(message) => {
3120 self.handle(message, rx);
3121 }
3122 Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
3123 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => break,
3124 }
3125 if Instant::now() >= deadline {
3126 log::warn!(
3127 "the app's quit listeners did not finish in {} ms",
3128 QUIT_TIMEOUT.as_millis()
3129 );
3130 break;
3131 }
3132 }
3133 for message in kept {
3134 let _ = self.state.net.tx.send(message);
3135 }
3136 }
3137
3138 fn next_gc(&self) -> Instant {
3142 let quiet = (self.last_active + IDLE_GC_QUIET).min(self.last_gc + IDLE_GC_LONGEST);
3143 (self.last_gc + IDLE_GC_INTERVAL).max(quiet)
3144 }
3145
3146 fn collect_if_idle(&mut self) {
3149 if let Some(script) = &self.script
3150 && self.state.committed_since_gc
3151 && Instant::now() >= self.next_gc()
3152 {
3153 let start = self.state.trace.then(Instant::now);
3154 script.collect_garbage();
3155 if let Some(start) = start {
3156 log::info!(target: "nsh::perf", "gc: {}µs", start.elapsed().as_micros());
3157 }
3158 if let Some(monitor) = &self.state.perf {
3161 let (js_heap, js_objects) = script.heap_usage();
3162 monitor.set_memory(perf::MemorySample {
3163 js_heap,
3164 js_objects,
3165 nodes: self.state.core.node_count() as u64,
3166 node_ids: self.state.core.node_id_room() as u64,
3167 });
3168 }
3169 self.last_gc = Instant::now();
3170 self.state.committed_since_gc = false;
3171 let batch = self.state.commit(Some(script));
3172 self.state.submit_mount(&*self.sink, batch);
3173 self.state.run_on_main_thread(&*self.sink);
3174 }
3175 }
3176
3177 fn check_stopped(&mut self) {
3178 if let Some(script) = &self.script
3179 && !self.stopped
3180 && let Some(reason) = script.fatal()
3181 {
3182 self.stopped = true;
3183 script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
3184 }
3185 }
3186}
3187
3188struct ScrollEvent {
3189 x: f32,
3190 y: f32,
3191 content: Size<Points>,
3192 viewport: Size<Points>,
3193 zoom: f32,
3195 throttle: Duration,
3196 last: Option<Instant>,
3197 pending: bool,
3199}
3200
3201struct State<M: TextEngine> {
3202 core: Core<M>,
3203 published_content_height: Option<Points>,
3204 js_tokens: Arc<nsh_core::element::Tokens>,
3207 pinned: EnvironmentPins,
3210 environment: Environment,
3212 shaders_unavailable: bool,
3215 app_locale: Option<nsh_core::platform::Locale>,
3217 frame_requested: bool,
3219 frame_turn: bool,
3222 frames_seen: bool,
3226 ops: Vec<Op>,
3227 binds: Vec<ListBind>,
3229 events: Vec<JsEvent>,
3231 trace: bool,
3232 perf: Option<Arc<perf::PerfMonitor>>,
3234 perf_stats_at: Option<Instant>,
3237 perf_commit: perf::CommitTiming,
3240 committed_since_gc: bool,
3241 host: HostChannel,
3244 url_opens: Vec<(u32, String)>,
3246 host_requests: Vec<nsh_core::host_channel::HostRequest>,
3249 net: Net,
3250 hot: Vec<HotUpdate>,
3252 scroll_events: FxHashMap<NodeId, ScrollEvent>,
3255 touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
3257 mouse_moves: Vec<(NodeId, EventPayload)>,
3261 mouse_moved: Option<Instant>,
3263 key_path: Vec<NodeId>,
3266 sets_seen: FxHashMap<(u8, NodeId, u32), usize>,
3268 resized: Option<Size<Points>>,
3270 roots_resized: Vec<(NodeId, Size<Points>)>,
3273 resize_burst_ends: Option<Instant>,
3276 window_state: WindowStateReport,
3279 events_handled: u64,
3282 events_reported: u64,
3283}
3284
3285#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3288enum Requester {
3289 Js(RequestId),
3290 Task(u32),
3291}
3292
3293struct Net {
3296 network: Option<Arc<dyn Network>>,
3297 tx: Sender<Message>,
3298 queue: NetworkQueue,
3299 inflight: FxHashMap<Requester, Inflight>,
3300 tasks: Vec<(u32, HttpRequest)>,
3303 abandoned: Vec<u32>,
3304 access: Arc<nsh_core::access::Access>,
3306 hops: u64,
3308 assets: Option<Arc<dyn Assets>>,
3311 #[cfg(not(target_arch = "wasm32"))]
3314 runtime: tokio::runtime::Handle,
3315}
3316
3317struct AssetTask;
3320
3321impl FetchTask for AssetTask {
3322 fn send(&mut self, _: Vec<u8>) {}
3323 fn finish(&mut self) {}
3324 fn pause(&mut self, _: bool) {}
3325 fn cancel(self: Box<Self>) {}
3326}
3327
3328fn is_asset(url: &str) -> bool {
3331 url.get(..6)
3332 .is_some_and(|scheme| scheme.eq_ignore_ascii_case("asset:"))
3333}
3334
3335fn asset_response_url(url: &str) -> String {
3341 let rest = url.get(6..).unwrap_or_default();
3342 format!("asset:{}", rest.split('#').next().unwrap_or_default())
3343}
3344
3345fn asset_file(url: &str) -> &str {
3350 url.split('?').next().unwrap_or_default()
3351}
3352
3353struct Inflight {
3355 task: Box<dyn FetchTask>,
3356 hop: u64,
3358 followed: Option<access::Followed>,
3360 asset: Option<String>,
3364}
3365
3366impl Net {
3367 fn idle(&self) -> bool {
3369 self.inflight.is_empty()
3370 }
3371
3372 fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
3375 let mut abandoned = std::mem::take(&mut self.abandoned);
3376 core.take_fetches(&mut self.tasks, &mut abandoned);
3377 for id in abandoned.drain(..) {
3378 self.cancel(Requester::Task(id));
3379 }
3380 self.abandoned = abandoned;
3381 let mut tasks = std::mem::take(&mut self.tasks);
3382 for (id, request) in tasks.drain(..) {
3383 if let Err(refused) = self.request(Requester::Task(id), request) {
3384 core.fetch_refused(id, refused.message, refused.url);
3385 }
3386 }
3387 self.tasks = tasks;
3388 let Some(script) = script else { return };
3389 script.take_network(&mut self.queue);
3390 for (id, op) in std::mem::take(&mut self.queue.ops) {
3391 let who = Requester::Js(id);
3392 match op {
3393 FetchOp::Start(request) => {
3394 if let Err(refused) = self.request(who, request) {
3395 script.fetch_refused(id, &refused.message, &refused.url);
3396 }
3397 }
3398 FetchOp::Send(chunk) => {
3399 if let Some(i) = self.inflight.get_mut(&who) {
3400 i.task.send(chunk);
3401 }
3402 }
3403 FetchOp::Finish => {
3404 if let Some(i) = self.inflight.get_mut(&who) {
3405 i.task.finish();
3406 }
3407 }
3408 FetchOp::Pause(paused) => {
3409 if let Some(i) = self.inflight.get_mut(&who) {
3410 i.task.pause(paused);
3411 }
3412 }
3413 FetchOp::Cancel => self.cancel(who),
3414 }
3415 }
3416 }
3417
3418 fn cancel(&mut self, who: Requester) {
3420 if let Some(i) = self.inflight.remove(&who) {
3421 i.task.cancel();
3422 }
3423 }
3424
3425 fn request(&mut self, who: Requester, mut request: HttpRequest) -> Result<(), access::Refused> {
3428 if is_asset(&request.url) {
3429 self.asset(who, request);
3430 return Ok(());
3431 }
3432 if self.access.is_unrestricted() {
3433 self.start(who, request, None);
3434 return Ok(());
3435 }
3436 match self.access.http_url(&request.method, &request.url) {
3439 Some(url) => request.url = url.into_owned(),
3440 None => return Err(access::refused(&request.method, &request.url)),
3441 }
3442 if request.follow_redirects {
3443 let hop = access::hop(&request);
3444 let followed = access::Followed { request, hops: 0 };
3445 self.start(who, hop, Some(followed));
3446 } else {
3447 self.start(who, request, None);
3448 }
3449 Ok(())
3450 }
3451
3452 fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
3454 self.hops += 1;
3455 let hop = self.hops;
3456 let Some(network) = &self.network else {
3457 let failed = FetchEvent::Failed("this host has no network stack".to_owned());
3458 let _ = self.tx.send(Message::Fetch(id, hop, failed));
3459 return;
3460 };
3461 let tx = self.tx.clone();
3462 let events: FetchEvents = Box::new(move |event| {
3463 let _ = tx.send(Message::Fetch(id, hop, event));
3464 });
3465 let task = network.fetch(request, events);
3466 self.inflight.insert(
3467 id,
3468 Inflight {
3469 task,
3470 hop,
3471 followed,
3472 asset: None,
3473 },
3474 );
3475 }
3476
3477 fn asset(&mut self, who: Requester, mut request: HttpRequest) {
3482 request.url = asset_response_url(&request.url);
3483 let file = asset_file(&request.url).to_owned();
3484 self.hops += 1;
3485 let hop = self.hops;
3486 self.inflight.insert(
3487 who,
3488 Inflight {
3489 task: Box::new(AssetTask),
3490 hop,
3491 followed: None,
3492 asset: None,
3493 },
3494 );
3495 let refused = if !nsh_core::access::is_inside_assets(&file) {
3498 Some(format!(
3499 "{}: bundled files are named by a path inside the app's files",
3500 request.url
3501 ))
3502 } else if !matches!(request.method.as_str(), "GET" | "HEAD") {
3503 Some(format!(
3504 "{} {}: bundled files are read with GET",
3505 request.method, request.url
3506 ))
3507 } else {
3508 None
3509 };
3510 if let Some(refused) = refused {
3511 let _ = self
3512 .tx
3513 .send(Message::Fetch(who, hop, FetchEvent::Failed(refused)));
3514 return;
3515 }
3516 let Some(assets) = &self.assets else {
3517 let failed = Err("this host cannot load assets".to_owned());
3518 self.asset_read(who, hop, request, failed);
3519 return;
3520 };
3521 #[cfg(not(target_arch = "wasm32"))]
3522 {
3523 let assets = assets.clone();
3524 let tx = self.tx.clone();
3525 drop(self.runtime.spawn_blocking(move || {
3527 let bytes = assets.read(&file);
3528 let _ = tx.send(Message::AssetRead(who, hop, request, bytes));
3529 }));
3530 }
3531 #[cfg(target_arch = "wasm32")]
3532 {
3533 let bytes = assets.read(&file);
3534 self.asset_read(who, hop, request, bytes);
3535 }
3536 }
3537
3538 fn asset_read(
3544 &mut self,
3545 who: Requester,
3546 hop: u64,
3547 request: HttpRequest,
3548 read: Result<Vec<u8>, String>,
3549 ) {
3550 if self.inflight.get(&who).is_none_or(|i| i.hop != hop) {
3551 return;
3552 }
3553 let events = match read {
3554 Ok(bytes) => {
3555 let head = HttpHead {
3556 status: 200,
3557 status_text: "OK".to_owned(),
3558 headers: vec![
3559 ("content-length".to_owned(), bytes.len().to_string()),
3560 (
3561 "content-type".to_owned(),
3562 content_type(asset_file(&request.url)).to_owned(),
3563 ),
3564 ],
3565 url: request.url.clone(),
3566 ..HttpHead::default()
3567 };
3568 let mut events = vec![FetchEvent::Head(head)];
3569 if request.method == "GET" && !bytes.is_empty() {
3570 events.push(FetchEvent::Data(bytes));
3571 }
3572 events.push(FetchEvent::End);
3573 events
3574 }
3575 Err(error) => {
3576 match (self.assets.as_ref()).and_then(|a| a.url(asset_file(&request.url))) {
3577 Some(url) => {
3578 self.inflight.remove(&who);
3579 let uri = request.url.clone();
3580 self.start(who, HttpRequest { url, ..request }, None);
3581 if let Some(download) = self.inflight.get_mut(&who) {
3582 download.asset = Some(uri);
3583 }
3584 return;
3585 }
3586 None => vec![FetchEvent::Failed(error)],
3587 }
3588 }
3589 };
3590 for event in events {
3591 let _ = self.tx.send(Message::Fetch(who, hop, event));
3592 }
3593 }
3594
3595 fn event(
3599 &mut self,
3600 id: Requester,
3601 hop: u64,
3602 event: FetchEvent,
3603 ) -> Option<Result<FetchEvent, access::Refused>> {
3604 if self.network.is_none() {
3605 return Some(Ok(event));
3606 }
3607 let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
3608 match event {
3609 FetchEvent::Head(mut head) => {
3610 let missing = (inflight.asset.as_ref())
3611 .filter(|_| !(200..300).contains(&head.status))
3612 .map(|uri| format!("{uri}: HTTP {}", head.status));
3613 if let Some(missing) = missing {
3614 if let Some(i) = self.inflight.remove(&id) {
3615 i.task.cancel();
3616 }
3617 return Some(Ok(FetchEvent::Failed(missing)));
3618 }
3619 if let Some(uri) = &inflight.asset {
3623 head.url = uri.clone();
3624 head.redirected = false;
3625 if !head
3626 .headers
3627 .iter()
3628 .any(|(name, _)| name.eq_ignore_ascii_case("content-type"))
3629 {
3630 let file_type = content_type(asset_file(uri)).to_owned();
3631 head.headers.push(("content-type".to_owned(), file_type));
3632 }
3633 }
3634 let Some(followed) = &mut inflight.followed else {
3635 return Some(Ok(FetchEvent::Head(head)));
3636 };
3637 match access::next(&self.access, followed, head) {
3638 access::Next::Done(head) => Some(Ok(FetchEvent::Head(head))),
3639 access::Next::Fail(message) => {
3640 if let Some(i) = self.inflight.remove(&id) {
3641 i.task.cancel();
3642 }
3643 Some(Ok(FetchEvent::Failed(message)))
3644 }
3645 access::Next::Refused(refused) => {
3646 if let Some(i) = self.inflight.remove(&id) {
3647 i.task.cancel();
3648 }
3649 Some(Err(refused))
3650 }
3651 access::Next::Hop(request) => {
3652 let i = self.inflight.remove(&id)?;
3653 let followed = i.followed;
3654 i.task.cancel();
3655 self.start(id, request, followed);
3656 None
3657 }
3658 }
3659 }
3660 FetchEvent::End | FetchEvent::Failed(_) => {
3661 self.inflight.remove(&id);
3662 Some(Ok(event))
3663 }
3664 event => Some(Ok(event)),
3665 }
3666 }
3667}
3668
3669impl<M: TextEngine> State<M> {
3670 fn record_perf(&mut self, started: Option<Instant>) {
3673 let (Some(started), Some(monitor)) = (started, &self.perf) else {
3674 return;
3675 };
3676 let busy = started.elapsed();
3677 monitor.record_busy(busy);
3678 let mut commit = std::mem::take(&mut self.perf_commit);
3679 if commit.ops > 0 || commit.items > 0 {
3680 commit.js = busy.saturating_sub(commit.layout);
3681 monitor.record_commit(commit);
3682 }
3683 }
3684
3685 fn dispatch_touch_move(&mut self, script: Option<&Script>) {
3687 if let Some((id, touch)) = self.touch_move.take()
3688 && let Some(script) = script
3689 {
3690 script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
3691 }
3692 }
3693
3694 fn next_mouse_move(&self) -> Option<Instant> {
3696 if self.mouse_moves.is_empty() {
3697 return None;
3698 }
3699 Some(
3700 self.mouse_moved
3701 .map_or_else(nsh_core::time::now, |t| t + MOUSE_MOVE_INTERVAL),
3702 )
3703 }
3704
3705 fn dispatch_mouse_moves(&mut self, script: Option<&Script>) {
3708 if self.mouse_moves.is_empty() {
3709 return;
3710 }
3711 self.mouse_moved = Some(nsh_core::time::now());
3712 for (id, payload) in std::mem::take(&mut self.mouse_moves) {
3713 if self
3714 .core
3715 .component_event(id, EventKind::MouseMove, &payload)
3716 {
3717 continue;
3718 }
3719 if let Some(script) = script {
3720 script.dispatch_event(id, EventKind::MouseMove, &payload);
3721 }
3722 }
3723 }
3724
3725 fn next_scroll_event(&self) -> Option<Instant> {
3727 self.scroll_events
3728 .values()
3729 .filter(|e| e.pending)
3730 .filter_map(|e| e.last.map(|t| t + e.throttle))
3731 .min()
3732 }
3733
3734 fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
3736 if self.scroll_events.is_empty() {
3737 return;
3738 }
3739 let now = nsh_core::time::now();
3740 let core = &self.core;
3742 self.scroll_events
3743 .retain(|&id, _| core.scroll_listener(id).is_some());
3744 for (&id, e) in &mut self.scroll_events {
3745 if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
3746 continue;
3747 }
3748 e.pending = false;
3749 e.last = Some(now);
3750 let n = |v: f32| PayloadValue::Number(v as f64);
3751 let payload = EventPayload::Map(vec![
3752 (
3753 "offset",
3754 PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
3755 ),
3756 ("contentSize", PayloadValue::Size(e.content)),
3757 ("size", PayloadValue::Size(e.viewport)),
3758 ("zoomScale", n(e.zoom)),
3759 ]);
3760 if !self.core.component_event(id, EventKind::Scroll, &payload)
3762 && let Some(script) = script
3763 {
3764 script.dispatch_event(id, EventKind::Scroll, &payload);
3765 }
3766 }
3767 }
3768
3769 fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
3771 let Some(script) = script else { return };
3772 let mut ids = Vec::new();
3773 script.take_chunk_requests(&mut ids);
3774 for id in ids {
3775 if !sink.load_chunk(&id) {
3776 let message = "this host does not load chunks (the app was built split)".to_owned();
3777 let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
3778 }
3779 }
3780 }
3781
3782 fn report_handled(&mut self, sink: &dyn MountSink) {
3785 if self.events_handled != self.events_reported {
3786 self.events_reported = self.events_handled;
3787 sink.handled(self.events_handled);
3788 }
3789 }
3790
3791 fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
3794 if !self.frame_requested
3795 && (script.is_some_and(Script::wants_frame)
3796 || self.core.wants_frame()
3797 || self.core.has_paced_mounts()
3798 || (script.is_some() && self.core.has_paced_list_binds()))
3799 {
3800 self.frame_requested = true;
3801 sink.request_frame();
3802 }
3803 }
3804
3805 fn run_on_main_thread(&mut self, sink: &dyn MountSink) {
3808 for task in self.core.take_main_thread_tasks() {
3809 sink.run_on_main_thread(task);
3810 }
3811 }
3812
3813 fn load_fonts(
3816 &mut self,
3817 script: Option<&Script>,
3818 assets: Option<&dyn Assets>,
3819 sink: &dyn MountSink,
3820 ) {
3821 let Some(script) = script else { return };
3822 let mut fonts = Vec::new();
3823 script.take_fonts(&mut fonts);
3824 for uri in fonts {
3825 let result = match assets {
3826 Some(assets) => assets.read(&uri),
3827 None => Err("this host cannot load assets".to_owned()),
3828 }
3829 .and_then(|data| self.core.register_font(&data));
3830 if let Err(err) = result {
3831 script.report(
3832 sink,
3833 AppErrorKind::Asset,
3834 "font failed",
3835 &format!("{uri}: {err}"),
3836 );
3837 }
3838 }
3839 }
3840
3841 fn open_urls(&mut self) -> bool {
3847 self.core.take_url_opens(&mut self.url_opens);
3848 let mut platform = false;
3849 for (id, url) in self.url_opens.drain(..) {
3850 if self.host.open_url(id, url.clone(), &self.net.tx).is_none() {
3851 self.core.open_url_on_platform(id, url);
3852 platform = true;
3853 }
3854 }
3855 platform
3856 }
3857
3858 fn host_requests(&mut self) -> bool {
3865 let mut more = self.core.release_host_events();
3866 self.core.take_host_requests(&mut self.host_requests);
3867 for request in self.host_requests.drain(..) {
3868 match self.host.start_request(request, &self.net.tx) {
3869 Ok(()) => {}
3870 Err(HostRefusal::NoHandler(id, error)) => self.core.answer_host(id, Err(error)),
3871 Err(HostRefusal::Unconfigured(request)) => {
3872 self.core.host_request_on_platform(request);
3873 more = true;
3874 }
3875 }
3876 }
3877 more
3878 }
3879
3880 fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
3881 let start = Instant::now();
3882 let mut merged: Option<MountBatch> = None;
3883 let mut commits = 0;
3884 let mut op_count = 0;
3885 let mut js = std::time::Duration::ZERO;
3886 let mut paced = PacedBinds::default();
3888 let frame = std::mem::take(&mut self.frame_turn) || !self.frames_seen;
3893 self.core.begin_mount_turn();
3894 if !frame {
3895 self.core.hold_paced_mounts();
3896 }
3897 for _ in 0..MAX_LIST_ROUNDS {
3898 let js_start = Instant::now();
3900 let binds = self.binds.drain(..);
3903 if let Some(script) = script {
3904 script.take_ops(&mut self.ops);
3910 let unapplied = !self.ops.is_empty();
3911 for bind in binds {
3912 script.bind_list(bind.list, &bind.binds);
3913 }
3914 script.take_ops(&mut self.ops);
3915 let mut binds = Vec::new();
3916 while frame && !unapplied && paced.left() && self.core.has_paced_list_binds() {
3917 let start = Instant::now();
3918 let ops = self.ops.len();
3919 self.core.take_paced_list_binds(1, &mut binds);
3920 for bind in binds.drain(..) {
3921 paced.cells += bind.binds.len();
3922 script.bind_list(bind.list, &bind.binds);
3923 }
3924 script.take_ops(&mut self.ops);
3925 paced.ops += self.ops.len() - ops;
3926 paced.time += start.elapsed();
3927 }
3928 } else {
3929 drop(binds);
3930 }
3931 if let Some(script) = script {
3934 script.run_posted();
3935 }
3936 for event in self.events.drain(..) {
3940 match event {
3941 JsEvent::Event(id, event, payload) => {
3942 if matches!(event, EventKind::KeyDown | EventKind::KeyUp) {
3943 dispatch_key(
3944 script,
3945 &mut self.core,
3946 &mut self.key_path,
3947 id,
3948 event,
3949 &payload,
3950 );
3951 } else if !self.core.component_event(id, event, &payload)
3952 && let Some(script) = script
3953 {
3954 script.dispatch_event(id, event, &payload);
3955 }
3956 }
3957 JsEvent::LayoutListener {
3958 host,
3959 id,
3960 listener,
3961 frame,
3962 } => {
3963 self.core.component_layout(host, id, &listener, frame);
3964 }
3965 other => {
3967 if let Some(script) = script {
3968 script.deliver(other);
3969 }
3970 }
3971 }
3972 }
3973 if let Some(script) = script {
3974 script.take_ops(&mut self.ops);
3975 }
3976 js += js_start.elapsed();
3977 op_count += self.ops.len();
3978 let mut ops = self.ops.drain(..);
3981 while let Some(op) = ops.next() {
3982 match self.core.apply(op) {
3983 Ok(()) => {}
3984 Err(err) if err.is_fatal() => {
3985 self.core.discard_ops(ops.by_ref());
3986 let Some(script) = script else { break };
3987 script.stop(match err {
3988 ApplyError::TooManyNodes(max) => {
3989 format!("the app created more than {max} nodes and was stopped")
3990 }
3991 ApplyError::TooDeep(max) => {
3992 format!("the app nested views more than {max} deep and was stopped")
3993 }
3994 other => {
3995 format!("the app sent an invalid op ({other:?}) and was stopped")
3996 }
3997 });
3998 break;
3999 }
4000 Err(err) => log::error!("invalid op: {err:?}"),
4001 }
4002 }
4003 drop(ops);
4004 release_spare_ops(&mut self.ops);
4005 if let Some(batch) = self.core.commit() {
4006 commits += 1;
4007 match &mut merged {
4008 Some(m) => extend_frame(&mut m.items, batch.items),
4009 None => merged = Some(batch),
4010 }
4011 }
4012 self.core.take_list_binds(&mut self.binds);
4013 self.core.take_events(&mut self.events);
4014 let urls = self.open_urls();
4016 let host = self.host_requests();
4019 let posted = script.is_some_and(Script::has_posted);
4021 let retheme = match script {
4024 Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
4025 self.js_tokens = self.core.tokens().clone();
4026 script.set_tokens(self.js_tokens.clone());
4027 true
4028 }
4029 _ => false,
4030 };
4031 let relocale = match self.core.take_locale_request() {
4034 Some(locale) => {
4035 self.app_locale = locale;
4036 apply_environment(script, self, self.environment);
4037 true
4038 }
4039 None => false,
4040 };
4041 let more_paced = script.is_some() && paced.left() && self.core.has_paced_list_binds();
4042 let answers = self.core.has_due_answers();
4046 if self.binds.is_empty()
4047 && self.events.is_empty()
4048 && !posted
4049 && !retheme
4050 && !relocale
4051 && !more_paced
4052 && !urls
4053 && !host
4054 && !answers
4055 {
4056 break;
4057 }
4058 }
4059 if commits > 1
4060 && let Some(batch) = &mut merged
4061 {
4062 keep_last_sets(&mut batch.items, &mut self.sets_seen);
4063 }
4064 self.committed_since_gc |= op_count > 0;
4065 if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
4066 let c = &mut self.perf_commit;
4067 c.layout += start.elapsed().saturating_sub(js);
4068 c.ops += op_count as u32;
4069 c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
4070 }
4071 if self.trace && (op_count > 0 || merged.is_some()) {
4072 log::info!(
4073 target: "nsh::perf",
4074 "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
4075 start.elapsed().as_micros(),
4076 js.as_micros(),
4077 merged.as_ref().map_or(0, |b| b.items.len()),
4078 self.core.node_count(),
4079 );
4080 }
4081 merged
4082 }
4083
4084 fn submit_mount(&mut self, sink: &dyn MountSink, batch: Option<MountBatch>) -> bool {
4086 if sink.needs_content_height() {
4087 let height = self.core.content_height();
4088 if batch.is_some() || height != self.published_content_height {
4089 sink.submit_with_content_height(batch.unwrap_or_default(), height);
4090 self.published_content_height = height;
4091 return true;
4092 }
4093 } else if let Some(batch) = batch {
4094 sink.submit(batch);
4095 return true;
4096 }
4097 false
4098 }
4099}
4100
4101fn insets(env: &Environment) -> EdgeInsets {
4102 env.safe_area
4103}
4104
4105fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::element::Environment {
4107 nsh_core::element::Environment {
4108 window,
4109 horizontal_size_class: env.horizontal_size_class,
4110 vertical_size_class: env.vertical_size_class,
4111 safe_area: insets(env),
4112 title_bar: env.title_bar,
4113 window_state: env.window_state,
4114 keyboard_height: env.keyboard_height,
4115 keyboard_duration: env.keyboard_duration,
4116 dark: env.color_scheme == ColorScheme::Dark,
4117 font_scale: env.font_scale,
4118 reduce_motion: env.reduce_motion,
4119 screen_reader: env.screen_reader,
4120 reads_active_descendants: env.reads_active_descendants,
4121 rtl: env.rtl,
4122 pixel_ratio: env.pixel_ratio,
4123 os: env.os,
4124 platform: env.platform,
4125 os_version: env.os_version,
4126 idiom: env.idiom,
4127 locale: env.locale,
4128 locale_settings: env.locale_settings,
4129 apple_keyboard: env.apple_keyboard,
4130 ctrl_for_command: env.ctrl_for_command,
4131 host: env.host,
4132 lifecycle: env.lifecycle,
4133 wake_count: env.wake_count,
4134 network: env.network,
4135 screen_color: env.screen_color,
4136 clipboard_write_result: env.clipboard_write_result,
4137 canvas_render: env.canvas_render,
4138 share: env.share,
4139 app_settings: env.app_settings,
4140 auth_session: env.auth_session,
4141 scheme_links: env.scheme_links(),
4142 file_requests: env.file_requests,
4143 notifications: env.notifications,
4144 audio: env.audio,
4145 tab_bar: env.tab_bar,
4146 cell: env.cell,
4147 web_input: env.web_input,
4148 web_evaluate: env.web_evaluate,
4149 web_views: env.web_views,
4150 webview_requests: env.webview_requests,
4151 shaders: env.shaders,
4152 }
4153}
4154
4155fn drawn_shaders(env: &mut Environment, unavailable: bool) {
4159 env.shaders &= env.cell.is_none() && !unavailable && !shader::no_gpu();
4160}
4161
4162fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
4164 nsh_core::tailwind::ClassEnvironment {
4165 dark: env.color_scheme == ColorScheme::Dark,
4166 platform: match env.os {
4167 Os::Web => nsh_core::tailwind::Platform::Web,
4168 Os::Android => nsh_core::tailwind::Platform::Android,
4169 _ => nsh_core::tailwind::Platform::Ios,
4170 },
4171 reduce_motion: env.reduce_motion,
4172 pointer: if env.desktop() {
4173 nsh_core::tailwind::Pointer::Fine
4174 } else {
4175 nsh_core::tailwind::Pointer::Coarse
4176 },
4177 terminal: env.idiom == Idiom::Terminal,
4178 }
4179}
4180
4181const WINDOW_SETTLE: Duration = Duration::from_millis(150);
4184
4185#[derive(Default)]
4190struct WindowStateReport {
4191 shown: Option<nsh_core::desktop::WindowState>,
4193 reported: Option<Environment>,
4195 settles: Option<Instant>,
4197}
4198
4199impl WindowStateReport {
4200 fn report(&mut self, mut env: Environment, now: Instant) -> Environment {
4203 let next = env.window_state;
4204 let moving = match (&self.shown, &next) {
4205 (Some(shown), Some(next)) => shown != next && moved_only(shown, next),
4206 _ => false,
4207 };
4208 if moving {
4209 let moved = self.reported.map(|r| r.window_state) != Some(next);
4212 if moved || self.settles.is_none() {
4213 self.settles = Some(now + WINDOW_SETTLE);
4214 }
4215 self.reported = Some(env);
4216 env.window_state = self.shown;
4217 } else {
4218 self.reported = None;
4219 self.settles = None;
4220 self.shown = next;
4221 }
4222 env
4223 }
4224}
4225
4226fn moved_only(
4230 shown: &nsh_core::desktop::WindowState,
4231 next: &nsh_core::desktop::WindowState,
4232) -> bool {
4233 shown.mode == next.mode
4234 && shown.placement.mode == next.placement.mode
4235 && shown.minimized == next.minimized
4236 && shown.visible == next.visible
4237 && shown.focused == next.focused
4238 && shown.display == next.display
4239 && shown.scale_factor == next.scale_factor
4240}
4241
4242fn apply_environment<M: TextEngine>(
4244 script: Option<&Script>,
4245 state: &mut State<M>,
4246 env: Environment,
4247) {
4248 state.environment = env;
4249 let mut env = env;
4250 if let Some(locale) = state.app_locale {
4253 env.locale = locale;
4254 env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
4255 }
4256 state.core.set_font_scale(env.font_scale);
4257 state.core.set_class_environment(class_environment(&env));
4258 state.core.set_safe_area(insets(&env));
4259 let window = env.window;
4260 state.core.set_environment(ui_environment(&env, window));
4261 if let Some(script) = script {
4262 script.set_environment(&env);
4263 }
4264}
4265
4266fn dispatch_key<M: TextEngine>(
4271 script: Option<&Script>,
4272 core: &mut nsh_core::Core<M>,
4273 path: &mut Vec<NodeId>,
4274 id: NodeId,
4275 event: EventKind,
4276 payload: &EventPayload,
4277) {
4278 core.key_path(id, path);
4279 for node in path.iter().copied() {
4280 core.component_event(node, event, payload);
4281 if core.listens(node, event)
4284 && let Some(script) = script
4285 {
4286 script.dispatch_event(node, event, payload);
4287 }
4288 }
4289 path.clear();
4290}
4291
4292fn press_outside<M: TextEngine>(
4296 script: Option<&Script>,
4297 core: &mut nsh_core::Core<M>,
4298 pressed: Vec<(NodeId, EventPayload)>,
4299) {
4300 for (overlay, payload) in pressed {
4301 if !core.component_event(overlay, EventKind::PressOutside, &payload)
4302 && let Some(script) = script
4303 {
4304 script.dispatch_event(overlay, EventKind::PressOutside, &payload);
4305 }
4306 }
4307}
4308
4309fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
4311 match message {
4312 Message::Event(id, event, mut payload) => {
4313 state.events_handled += 1;
4314 if let EventPayload::Window(window) = &payload
4317 && matches!(**window, nsh_core::desktop::WindowEvent::Reopen)
4318 {
4319 state.core.reopened();
4320 }
4321 if state.trace {
4322 log::info!(target: "nsh::perf", "event {event:?} on view {id}");
4323 }
4324 if event == EventKind::MouseMove {
4330 match state.mouse_moves.iter_mut().find(|(v, _)| *v == id) {
4331 Some((_, pending)) => *pending = payload,
4332 None => state.mouse_moves.push((id, payload)),
4333 }
4334 return true;
4335 }
4336 if !matches!(&payload, EventPayload::Touch(t) if t.phase == nsh_core::TouchPhase::Move)
4337 {
4338 state.dispatch_mouse_moves(script);
4339 }
4340 if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
4343 state.core.input_changed(id, text, *count);
4344 }
4345 if event == EventKind::CaretMove {
4348 state.core.locate_caret(id, &mut payload);
4349 }
4350 if event == EventKind::SelectionChange {
4351 state.core.locate_selection(id, &mut payload);
4352 }
4353 if event == EventKind::Paste {
4354 payload = payload.into_paste();
4355 state.core.limit_paste(id, &mut payload);
4356 }
4357 if let EventPayload::ContextMenu(menu) = &payload {
4362 let pressed = state.core.context_menu_presses_outside(id, menu);
4363 press_outside(script, &mut state.core, pressed);
4364 }
4365 if matches!(event, EventKind::KeyDown | EventKind::KeyUp) {
4369 dispatch_key(
4370 script,
4371 &mut state.core,
4372 &mut state.key_path,
4373 id,
4374 event,
4375 &payload,
4376 );
4377 return true;
4378 }
4379 if state.core.component_event(id, event, &payload) {
4381 return true;
4382 }
4383 if let EventPayload::Touch(touch) = payload {
4384 if touch.phase == nsh_core::TouchPhase::Move {
4385 match &mut state.touch_move {
4386 Some((_, pending)) => pending.merge_move(*touch),
4387 None => state.touch_move = Some((id, touch)),
4388 }
4389 return true;
4390 }
4391 state.dispatch_touch_move(script);
4393 if let Some(script) = script {
4394 script.dispatch_event(id, event, &EventPayload::Touch(touch));
4395 }
4396 return true;
4397 }
4398 let Some(script) = script else { return true };
4399 let start = state.trace.then(Instant::now);
4400 script.dispatch_event(id, event, &payload);
4401 if let Some(start) = start {
4402 log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
4405 }
4406 }
4407 Message::Scroll(id, offset, applied) => {
4408 state.core.set_scroll_offset(id, offset, applied);
4409 let (x, y) = (offset.x.0, offset.y.0);
4410 if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
4411 let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
4412 x,
4413 y,
4414 content,
4415 viewport,
4416 zoom,
4417 throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
4418 last: None,
4419 pending: true,
4420 });
4421 (event.x, event.y, event.content, event.viewport, event.zoom) =
4422 (x, y, content, viewport, zoom);
4423 event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
4424 event.pending = true;
4425 }
4426 }
4427 Message::KeyScrolled(id, key_move) => state.core.key_scrolled(id, key_move),
4428 Message::Kept(nodes) => state.core.set_kept(&nodes),
4429 Message::ContentCulling(enabled) => {
4430 state.core.set_content_culling(enabled);
4431 if let Some(script) = script {
4432 script.set_lazy_rows(enabled);
4433 }
4434 }
4435 Message::InputScroll(id, offset, content, viewport) => {
4436 state.core.set_input_scroll(id, offset, content, viewport);
4437 }
4438 Message::InputComposing(id, shown) => state.core.input_composing(id, shown.as_deref()),
4439 Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
4440 Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
4441 Message::AnimationsFinished(mut finished) => {
4442 state.core.animations_finished(&mut finished);
4444 if let Some(script) = script {
4445 script.animations_finished(&finished);
4446 }
4447 }
4448 Message::Resize(size) => {
4449 if !nsh_core::time::manual() {
4452 let now = nsh_core::time::now();
4453 if state.resize_burst_ends.is_some_and(|ends| now < ends) {
4454 state.core.set_resizing(true);
4455 }
4456 state.resize_burst_ends = Some(now + RESIZE_BURST_GAP);
4457 }
4458 state.core.set_viewport(size);
4459 state.resized = Some(size);
4460 }
4461 Message::Wake => {}
4462 Message::Environment(mut env) => {
4463 state.pinned.apply(&mut env);
4464 drawn_shaders(&mut env, state.shaders_unavailable);
4465 let env = state.window_state.report(*env, nsh_core::time::now());
4466 apply_environment(script, state, env);
4467 }
4468 Message::ShadersUnavailable => {
4469 state.shaders_unavailable = true;
4470 if state.environment.shaders {
4471 let env = Environment {
4472 shaders: false,
4473 ..state.environment
4474 };
4475 apply_environment(script, state, env);
4476 }
4477 }
4478 Message::Displays(displays) => {
4479 state.core.set_displays(displays.clone());
4480 if let Some(script) = script {
4481 script.set_displays(&displays);
4482 }
4483 }
4484 Message::RootSize(id, size, insets) => {
4485 state.core.set_root_size(id, size, insets);
4486 match state.roots_resized.iter_mut().find(|(i, _)| *i == id) {
4487 Some((_, latest)) => *latest = size,
4488 None => state.roots_resized.push((id, size)),
4489 }
4490 }
4491 Message::OverlayArea(area) => state.core.set_overlay_area(area),
4492 Message::PressBeyondRoot(page) => {
4493 let pressed = state.core.presses_beyond_root(page);
4494 press_outside(script, &mut state.core, pressed);
4495 }
4496 Message::PressOnNative(id, page) => {
4497 let pressed = state.core.presses_on_native(id, page);
4498 press_outside(script, &mut state.core, pressed);
4499 }
4500 Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
4501 Message::Frame => {
4502 state.frame_requested = false;
4503 state.frame_turn = true;
4504 state.frames_seen = true;
4505 state.core.run_frame(nsh_core::time::now());
4506 if let Some(script) = script {
4507 script.run_frame();
4508 }
4509 }
4510 Message::States(id, states) => state.core.set_states(id, states),
4511 Message::ReleaseStates(id, states, hold) => {
4512 state.core.release_states_after(id, states, hold);
4513 }
4514 Message::Modality(modality) => state.core.set_input_modality(modality),
4515 Message::FontsChanged => state.core.fonts_changed(),
4516 Message::Remount => state.core.remount(),
4517 Message::Fetch(who, hop, event) => match (who, state.net.event(who, hop, event)) {
4518 (_, None) => {}
4519 (Requester::Js(id), Some(event)) => {
4520 if let Some(script) = script {
4521 match event {
4522 Ok(event) => script.fetch_event(id, event),
4523 Err(refused) => script.fetch_refused(id, &refused.message, &refused.url),
4524 }
4525 }
4526 }
4527 (Requester::Task(id), Some(Ok(event))) => {
4528 if !state.core.fetch_event(id, event) {
4529 state.net.cancel(who);
4530 }
4531 }
4532 (Requester::Task(id), Some(Err(refused))) => {
4535 state.core.fetch_refused(id, refused.message, refused.url)
4536 }
4537 },
4538 Message::AssetRead(who, hop, request, read) => {
4539 state.net.asset_read(who, hop, request, read)
4540 }
4541 Message::Hot(update) => state.hot.push(update),
4542 Message::Chunk(chunk) => {
4543 if let Some(script) = script {
4544 script.chunk(chunk);
4545 }
4546 }
4547 Message::Perf(monitor) => {
4548 state.core.set_perf_monitor(monitor.is_some());
4549 if let Some(script) = script {
4550 script.set_fps_enabled(monitor.is_some());
4551 }
4552 state.perf_stats_at = monitor
4554 .as_ref()
4555 .map(|_| Instant::now() + PERF_STATS_INTERVAL);
4556 if monitor.is_none() {
4557 state.core.set_perf_stats(None);
4558 if let Some(script) = script {
4559 script.set_perf_stats(None);
4560 }
4561 }
4562 state.perf = monitor;
4563 state.perf_commit = perf::CommitTiming::default();
4564 }
4565 Message::Tokens(tokens) => {
4566 state.core.set_host_tokens(tokens.map(|t| *t));
4567 if let Some(script) = script {
4568 script.set_theme_tokens(state.core.theme_tokens());
4569 }
4570 }
4571 Message::HostFont(data) => {
4572 if let Err(err) = state.core.register_font(&data) {
4573 log::error!("font failed: {err}");
4574 }
4575 }
4576 Message::HostEvent(name, data) => {
4578 state.core.host_event(&name, &data);
4579 if let Some(script) = script {
4580 script.host_event(&name, data);
4581 }
4582 }
4583 Message::HostReply(id, result) => {
4584 if let Some(script) = script {
4585 script.host_reply(id, result);
4586 }
4587 }
4588 Message::CoreHostReply(id, result) => state.core.answer_host(
4589 id,
4590 result.map_err(nsh_core::host_channel::HostError::Failed),
4591 ),
4592 Message::UrlHandled { id, url, handled } => {
4593 if handled {
4594 state.core.answer_open_url(id, true);
4595 } else {
4596 state.core.open_url_on_platform(id, url);
4597 }
4598 }
4599 Message::Advance(..) | Message::Flush(..) => unreachable!("the driver moves the clock"),
4602 Message::Shutdown => return false,
4603 }
4604 true
4605}
4606
4607#[derive(Default)]
4609struct PacedBinds {
4610 cells: usize,
4611 ops: usize,
4612 time: std::time::Duration,
4613}
4614
4615impl PacedBinds {
4616 fn left(&self) -> bool {
4619 self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
4620 }
4621}
4622
4623fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
4629 use nsh_core::MountItem;
4630 let start = frame.len();
4631 frame.extend(items);
4632 for k in start..frame.len() {
4633 let MountItem::ScrollContent { id, size } = frame[k] else {
4634 continue;
4635 };
4636 let earlier = frame[..k].iter().rposition(|m| {
4637 matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
4638 });
4639 if let Some(j) = earlier
4640 && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
4641 {
4642 *s = size;
4643 }
4644 }
4645}
4646
4647fn keep_last_sets(
4656 frame: &mut Vec<nsh_core::MountItem>,
4657 last: &mut FxHashMap<(u8, NodeId, u32), usize>,
4658) {
4659 last.clear();
4660 let mut repeated = false;
4661 let mut run = 0;
4662 for (k, item) in frame.iter().enumerate() {
4663 run += matches!(item, nsh_core::MountItem::LayoutAnimation(_)) as u32;
4664 if let Some(key) = sets_whole(item, run) {
4665 repeated |= last.insert(key, k).is_some();
4666 }
4667 }
4668 if !repeated {
4669 return;
4670 }
4671 let (mut k, mut run) = (0, 0);
4672 frame.retain(|item| {
4673 k += 1;
4674 run += matches!(item, nsh_core::MountItem::LayoutAnimation(_)) as u32;
4675 sets_whole(item, run).is_none_or(|key| last[&key] == k - 1)
4676 });
4677}
4678
4679fn sets_whole(item: &nsh_core::MountItem, run: u32) -> Option<(u8, nsh_core::NodeId, u32)> {
4683 use nsh_core::MountItem;
4684 Some(match *item {
4685 MountItem::Frame { id, .. } => (0, id, run),
4686 MountItem::Overflow { id, .. } => (1, id, 0),
4687 MountItem::ViewStyle { id, .. } => (2, id, 0),
4688 MountItem::Text { id, .. } => (3, id, 0),
4689 MountItem::Events { id, .. } => (4, id, 0),
4690 MountItem::Image { id, .. } => (5, id, 0),
4691 _ => return None,
4692 })
4693}
4694
4695const RETAINED_OPS: usize = 16 * 1024;
4697
4698fn release_spare_ops(ops: &mut Vec<Op>) {
4703 debug_assert!(ops.is_empty());
4704 if ops.capacity() > RETAINED_OPS {
4705 ops.shrink_to(RETAINED_OPS);
4706 }
4707}
4708
4709fn app_access(app: &App) -> Access {
4713 match app {
4714 App::Js(bundle) => bundle.policy.access(),
4715 App::Rust(root) => Policy {
4716 declared: root.capabilities_ref().cloned(),
4717 ..Policy::default()
4718 }
4719 .access(),
4720 }
4721}
4722
4723fn media_files(config: &EngineConfig, access: &Access) -> nsh_core::access::MediaFiles {
4726 match &config.app {
4727 App::Js(bundle) => nsh_core::access::MediaFiles::new(
4728 access,
4729 data_dir(config).as_deref(),
4730 &bundle_system_paths(bundle),
4731 nsh_core::access::native_files(config.environment.os),
4732 ),
4733 App::Rust(root) if root.capabilities_ref().is_some() => nsh_core::access::MediaFiles::new(
4734 access,
4735 data_dir(config).as_deref(),
4736 &system_paths(nsh_core::access::TrustedPaths::default(), false),
4737 nsh_core::access::native_files(config.environment.os),
4738 ),
4739 App::Rust(_) => nsh_core::access::MediaFiles::default(),
4740 }
4741}
4742
4743#[cfg(test)]
4744mod tests {
4745 #[cfg(feature = "js-core")]
4746 #[test]
4747 fn an_apps_directory_is_its_own_or_the_one_named_by_its_id() {
4748 let app = || super::Bundle::source(String::new()).with_app_id(Some("com.a"));
4749 let mut config = super::EngineConfig::new(app());
4750 assert_eq!(super::data_dir(&config), None);
4751 config.support_dir = Some("/data".into());
4752 assert_eq!(
4753 super::data_dir(&config),
4754 Some(std::path::Path::new("/data").join("com.a"))
4755 );
4756 config.data_dir = Some("/home/a/.myapp".into());
4759 assert_eq!(super::data_dir(&config), Some("/home/a/.myapp".into()));
4760 config.app = app().with_app_id(Some("com.b")).into();
4761 assert_eq!(super::data_dir(&config), Some("/home/a/.myapp".into()));
4762 config.data_dir = None;
4763 assert_eq!(
4764 super::data_dir(&config),
4765 Some(std::path::Path::new("/data").join("com.b"))
4766 );
4767 config.support_dir = None;
4768 assert_eq!(super::data_dir(&config), None);
4769 }
4770
4771 #[test]
4772 fn an_emptied_op_buffer_gives_back_what_a_large_commit_grew() {
4773 let mut ops: Vec<super::Op> = Vec::with_capacity(super::RETAINED_OPS * 8);
4774 super::release_spare_ops(&mut ops);
4775 assert!(ops.capacity() <= super::RETAINED_OPS);
4776 let mut ops: Vec<super::Op> = Vec::with_capacity(1024);
4778 super::release_spare_ops(&mut ops);
4779 assert_eq!(ops.capacity(), 1024);
4780 }
4781
4782 #[test]
4783 fn moves_settle_and_changes_of_mode_do_not() {
4784 use nsh_core::{
4785 desktop::{DisplayId, WindowMode, WindowPlacement, WindowState},
4786 geometry::{Bounds, point, px, size},
4787 };
4788 let rect = |x: f32| Bounds::new(point(px(x), px(0.0)), size(px(800.0), px(600.0)));
4789 let a = WindowState::new(
4790 rect(0.0),
4791 WindowPlacement::new(WindowMode::Normal, rect(0.0)),
4792 );
4793 let mut moved = a;
4794 moved.bounds = rect(10.0);
4795 moved.placement = WindowPlacement::new(WindowMode::Normal, rect(10.0));
4796 assert!(super::moved_only(&a, &moved));
4797 let mut maximized = a;
4798 maximized.mode = WindowMode::Maximized;
4799 maximized.placement = WindowPlacement::new(WindowMode::Maximized, rect(0.0));
4800 assert!(!super::moved_only(&a, &maximized));
4801 let mut minimized = a;
4802 minimized.minimized = true;
4803 assert!(!super::moved_only(&a, &minimized));
4804 let mut hidden = a;
4805 hidden.visible = false;
4806 assert!(!super::moved_only(&a, &hidden));
4807 let mut elsewhere = a;
4808 elsewhere.display = Some(DisplayId(2));
4809 assert!(!super::moved_only(&a, &elsewhere));
4810 }
4811
4812 #[test]
4813 fn pinned_values_hold_whatever_the_platform_reports() {
4814 let pins = super::EnvironmentPins {
4815 locale: nsh_core::platform::Locale::parse("de-DE"),
4816 reduce_motion: Some(true),
4817 ..Default::default()
4818 };
4819 let mut reported = super::Environment {
4820 locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
4821 font_scale: 1.5,
4822 ..Default::default()
4823 };
4824 pins.apply(&mut reported);
4825 assert_eq!(reported.locale.as_str(), "de-DE");
4826 assert!(reported.reduce_motion);
4827 assert_eq!(reported.font_scale, 1.5);
4829 assert_eq!(reported.safe_area, Default::default());
4830 }
4831
4832 #[test]
4833 fn bundle_default_has_no_application_selected_path_anchors() {
4834 let bundle = super::Bundle::default();
4835 assert!(bundle.system_paths.plugin_dir.is_none());
4836 assert!(bundle.system_paths.home_dir.is_none());
4837 assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
4838 }
4839
4840 #[test]
4841 fn bundle_trusted_paths_reject_relative_and_missing_directories() {
4842 let mut paths = nsh_core::access::TrustedPaths::default();
4843 paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
4844 paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
4845 let bundle = super::Bundle::default().with_system_paths(paths);
4846 assert!(bundle.system_paths.plugin_dir.is_none());
4847 assert!(bundle.system_paths.home_dir.is_none());
4848 assert!(
4849 super::trusted_directory(Some(std::path::PathBuf::from(
4850 "/nsh-nonexistent-anchor-never-created"
4851 )))
4852 .is_none()
4853 );
4854 }
4855
4856 #[test]
4857 fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
4858 let root = std::env::var_os("TMPDIR")
4859 .map(std::path::PathBuf::from)
4860 .unwrap_or_else(|| {
4861 std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
4862 .join(".cache/nsh-benchs-test-tmp")
4863 });
4864 assert!(root.is_absolute() && !root.starts_with("/tmp"));
4865 let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
4866 std::fs::create_dir_all(&directory).unwrap();
4867 let path = directory.join("bundle.js");
4868 std::fs::write(&path, "export default null;").unwrap();
4869 let bundle = super::Bundle::read(&path).unwrap();
4870 assert_eq!(
4871 bundle.system_paths.plugin_dir,
4872 Some(nsh_core::access::canonicalize(&directory).unwrap())
4873 );
4874 assert!(bundle.system_paths.home_dir.is_none());
4875 std::fs::remove_dir_all(directory).unwrap();
4876 }
4877
4878 #[test]
4879 fn rust_environment_preserves_native_title_bar_insets() {
4880 use super::{Edges, Points};
4881 let title_bar = Edges {
4882 top: Points(42.0),
4883 left: Points(78.0),
4884 right: Points(138.0),
4885 bottom: Points(0.0),
4886 };
4887 let environment = super::Environment {
4888 title_bar,
4889 ..Default::default()
4890 };
4891 assert_eq!(
4892 super::ui_environment(
4893 &environment,
4894 nsh_core::Size::new(Points(840.0), Points(630.0))
4895 )
4896 .title_bar,
4897 title_bar
4898 );
4899 }
4900
4901 use nsh_core::{MountItem, Points, Size};
4902
4903 #[test]
4904 fn a_frame_sends_a_scroll_views_last_content_size() {
4905 let content = |height| MountItem::ScrollContent {
4906 id: 2,
4907 size: Size::new(Points(390.0), height),
4908 };
4909 let heights = |frame: &[MountItem]| -> Vec<f32> {
4910 frame
4911 .iter()
4912 .filter_map(|m| match m {
4913 MountItem::ScrollContent { size, .. } => Some(size.height.0),
4914 _ => None,
4915 })
4916 .collect()
4917 };
4918 let mut frame = vec![content(Points(313.0))];
4919 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
4920 assert_eq!(heights(&frame), [544.0, 544.0]);
4921 let mut frame = vec![
4923 content(Points(313.0)),
4924 MountItem::ScrollBy {
4925 id: 2,
4926 dx: Points(0.0),
4927 dy: Points(10.0),
4928 },
4929 ];
4930 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
4931 assert_eq!(heights(&frame), [313.0, 544.0]);
4932 }
4933
4934 #[test]
4935 fn a_frame_sends_a_views_last_frame_once() {
4936 use nsh_core::{Bounds, Point};
4937 let at = |id, y| MountItem::Frame {
4938 id,
4939 frame: Bounds::new(
4940 Point::new(Points(0.0), Points(y)),
4941 Size::new(Points(10.0), Points(10.0)),
4942 ),
4943 };
4944 let mut frame = vec![
4945 MountItem::Create {
4946 id: 4,
4947 kind: nsh_core::ViewKind::View,
4948 },
4949 at(4, 0.0),
4950 at(6, 0.0),
4951 ];
4952 super::extend_frame(&mut frame, vec![at(4, 50.0)]);
4953 super::keep_last_sets(&mut frame, &mut Default::default());
4954 assert!(matches!(frame[0], MountItem::Create { id: 4, .. }));
4955 let frames: Vec<_> = frame
4956 .iter()
4957 .filter_map(|m| match m {
4958 MountItem::Frame { id, frame } => Some((*id, frame.origin.y.0)),
4959 _ => None,
4960 })
4961 .collect();
4962 assert_eq!(frames, [(6, 0.0), (4, 50.0)]);
4963
4964 let animation = |update| {
4967 MountItem::LayoutAnimation(nsh_core::LayoutAnimation {
4968 update,
4969 ..Default::default()
4970 })
4971 };
4972 let eased = nsh_core::LayoutAnimation::EASE_IN_EASE_OUT.update;
4973 let mut frame = vec![animation(None), at(4, 50.0), animation(eased), at(4, 0.0)];
4974 super::extend_frame(&mut frame, vec![at(4, 20.0)]);
4975 super::keep_last_sets(&mut frame, &mut Default::default());
4976 let frames: Vec<_> = frame
4977 .iter()
4978 .filter_map(|m| match m {
4979 MountItem::Frame { frame, .. } => Some(frame.origin.y.0),
4980 _ => None,
4981 })
4982 .collect();
4983 assert_eq!(frames, [50.0, 20.0]);
4984 }
4985}
4986
4987#[cfg(test)]
4988mod download_cleanup_tests {
4989 use super::*;
4993
4994 #[test]
4995 fn an_end_queued_into_a_dead_engine_cleans_its_staging_only() {
4996 let dir = std::env::temp_dir().join(format!(
4997 "nsh-engine-download-cleanup-{}",
4998 std::process::id()
4999 ));
5000 let _ = std::fs::remove_dir_all(&dir);
5001 std::fs::create_dir_all(&dir).unwrap();
5002 let leaf = dir.join("out.bin");
5003 std::fs::write(&leaf, b"partial").unwrap();
5004
5005 let cleanup = nsh_core::webview::DownloadCleanup::new();
5006 cleanup.register_staging(7, "d1", dir.clone(), leaf.clone());
5007
5008 let (tx, rx) = crossbeam_channel::unbounded();
5009 let control = EngineControl {
5010 tx,
5011 modality: Arc::default(),
5012 downloads: cleanup.clone(),
5013 };
5014 drop(rx);
5015
5016 control.dispatch_event(
5017 7,
5018 EventKind::DownloadEnd,
5019 nsh_core::webview::download_end(&nsh_core::webview::DownloadEnd {
5020 id: "d1".into(),
5021 outcome: nsh_core::webview::DownloadOutcome::Finished { bytes: 3 },
5022 }),
5023 );
5024 cleanup.close();
5026
5027 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
5028 while dir.exists() {
5029 assert!(
5030 std::time::Instant::now() < deadline,
5031 "the dead engine's staging directory was not cleaned"
5032 );
5033 std::thread::sleep(std::time::Duration::from_millis(2));
5034 }
5035 }
5036}
5037
5038#[cfg(test)]
5039mod updater_range_tests {
5040 use std::sync::Mutex;
5041
5042 use nsh_core::runtime::UpdaterHost as _;
5043
5044 use super::*;
5045
5046 #[test]
5047 fn parses_content_range_headers() {
5048 assert_eq!(
5049 parse_content_range("bytes 0-9/10"),
5050 Some(ContentRange {
5051 start: 0,
5052 len: 10,
5053 total: Some(10),
5054 })
5055 );
5056 assert_eq!(
5057 parse_content_range("BYTES 100-199/500"),
5058 Some(ContentRange {
5059 start: 100,
5060 len: 100,
5061 total: Some(500),
5062 })
5063 );
5064 assert_eq!(
5065 parse_content_range(" bytes 5-9/* "),
5066 Some(ContentRange {
5067 start: 5,
5068 len: 5,
5069 total: None,
5070 })
5071 );
5072 for bad in [
5073 "",
5074 "bytes */10",
5075 "items 0-9/10",
5076 "bytes 10-5/20",
5077 "bytes 0-10/10",
5078 "bytes +0-9/10",
5079 "bytes 0-9/10, 12-15/10",
5080 "bytes 0-18446744073709551615/*",
5081 ] {
5082 assert_eq!(parse_content_range(bad), None, "{bad:?}");
5083 }
5084 }
5085
5086 #[test]
5087 fn updater_urls_allow_https_and_loopback_only() {
5088 assert!(is_updater_url(
5089 "https://objects.githubusercontent.com/a.tar.gz"
5090 ));
5091 assert!(is_updater_url("http://127.0.0.1:8080/a.tar.gz"));
5092 assert!(is_updater_url("http://localhost/a.tar.gz"));
5093 assert!(is_updater_url("http://[::1]:8080/a.tar.gz"));
5094 assert!(!is_updater_url("http://example.com/a.tar.gz"));
5095 assert!(!is_updater_url("http://localhost.evil.dev/a.tar.gz"));
5096 assert!(!is_updater_url("file:///etc/passwd"));
5097 }
5098
5099 struct NoopTask;
5100 impl FetchTask for NoopTask {
5101 fn send(&mut self, _: Vec<u8>) {}
5102 fn finish(&mut self) {}
5103 fn pause(&mut self, _: bool) {}
5104 fn cancel(self: Box<Self>) {}
5105 }
5106
5107 type MockHandler = Box<dyn Fn(&HttpRequest) -> Vec<FetchEvent> + Send + Sync>;
5108
5109 struct MockNetwork {
5110 seen: Mutex<Vec<HttpRequest>>,
5111 handler: MockHandler,
5112 }
5113
5114 impl Network for MockNetwork {
5115 fn fetch(&self, request: HttpRequest, mut events: FetchEvents) -> Box<dyn FetchTask> {
5116 self.seen.lock().unwrap().push(request.clone());
5117 for event in (self.handler)(&request) {
5118 events(event);
5119 }
5120 Box::new(NoopTask)
5121 }
5122 }
5123
5124 fn host_with(
5125 handler: impl Fn(&HttpRequest) -> Vec<FetchEvent> + Send + Sync + 'static,
5126 ) -> (Arc<MockNetwork>, UpdaterOverNetwork) {
5127 let net = Arc::new(MockNetwork {
5128 seen: Mutex::new(Vec::new()),
5129 handler: Box::new(handler),
5130 });
5131 let host = UpdaterOverNetwork {
5132 network: net.clone(),
5133 assets: None,
5134 config: None,
5135 running: None,
5136 };
5137 (net, host)
5138 }
5139
5140 fn collect(
5141 host: &UpdaterOverNetwork,
5142 url: &str,
5143 from: u64,
5144 ) -> Result<(Vec<String>, Vec<u8>), String> {
5145 let mut events = Vec::new();
5146 let mut body = Vec::new();
5147 let mut next_at: Option<u64> = None;
5148 host.get(url, from, &mut |at, bytes, total| {
5149 assert!(!bytes.is_empty());
5150 if let Some(expected) = next_at {
5151 assert_eq!(at, expected);
5152 } else {
5153 let kind = if at == 0 { "full" } else { "partial" };
5154 events.push(format!("{kind}:{total:?}"));
5155 }
5156 next_at = Some(at + bytes.len() as u64);
5157 body.extend_from_slice(bytes);
5158 Ok(())
5159 })?;
5160 if body.is_empty() && from > 0 {
5161 events.push("unsatisfiable".into());
5162 }
5163 Ok((events, body))
5164 }
5165
5166 #[test]
5167 fn updater_over_network_follows_redirects_and_validates_ranges() {
5168 let (net, host) = host_with(|req| match req.url.as_str() {
5169 "https://github.com/o/r/releases/latest/download/a.tar.gz" => vec![
5170 FetchEvent::Head(HttpHead {
5171 status: 302,
5172 url: req.url.clone(),
5173 headers: vec![(
5174 "Location".into(),
5175 "https://cdn.example.com/assets/a.tar.gz".into(),
5176 )],
5177 ..Default::default()
5178 }),
5179 FetchEvent::End,
5180 ],
5181 "https://cdn.example.com/assets/a.tar.gz" => {
5182 let range = updater_header(&req.headers, "range");
5183 if range == Some("bytes=4-") {
5184 vec![
5185 FetchEvent::Head(HttpHead {
5186 status: 206,
5187 url: req.url.clone(),
5188 headers: vec![
5189 ("Content-Range".into(), "bytes 4-9/10".into()),
5190 ("Content-Length".into(), "6".into()),
5191 ],
5192 ..Default::default()
5193 }),
5194 FetchEvent::Data(Vec::new()),
5195 FetchEvent::Data(b"45".to_vec()),
5196 FetchEvent::Data(b"6789".to_vec()),
5197 FetchEvent::End,
5198 ]
5199 } else {
5200 vec![
5201 FetchEvent::Head(HttpHead {
5202 status: 200,
5203 url: req.url.clone(),
5204 headers: vec![("Content-Length".into(), "10".into())],
5205 ..Default::default()
5206 }),
5207 FetchEvent::Data(b"0123456789".to_vec()),
5208 FetchEvent::End,
5209 ]
5210 }
5211 }
5212 "https://downgrade.example.com/a" => vec![
5213 FetchEvent::Head(HttpHead {
5214 status: 302,
5215 url: req.url.clone(),
5216 headers: vec![("Location".into(), "http://insecure.example.com/a".into())],
5217 ..Default::default()
5218 }),
5219 FetchEvent::End,
5220 ],
5221 "https://bad-range.example.com/wrong-start" => vec![
5222 FetchEvent::Head(HttpHead {
5223 status: 206,
5224 url: req.url.clone(),
5225 headers: vec![
5226 ("Content-Range".into(), "bytes 0-9/10".into()),
5227 ("Content-Length".into(), "10".into()),
5228 ],
5229 ..Default::default()
5230 }),
5231 FetchEvent::Data(b"0123456789".to_vec()),
5232 FetchEvent::End,
5233 ],
5234 "https://bad-range.example.com/416" => vec![
5235 FetchEvent::Head(HttpHead {
5236 status: 416,
5237 url: req.url.clone(),
5238 headers: vec![("Content-Range".into(), "bytes */10".into())],
5239 ..Default::default()
5240 }),
5241 FetchEvent::End,
5242 ],
5243 "https://bad-range.example.com/truncated" => vec![
5244 FetchEvent::Head(HttpHead {
5245 status: 206,
5246 url: req.url.clone(),
5247 headers: vec![
5248 ("Content-Range".into(), "bytes 4-9/10".into()),
5249 ("Content-Length".into(), "6".into()),
5250 ],
5251 ..Default::default()
5252 }),
5253 FetchEvent::Data(b"45".to_vec()),
5254 FetchEvent::End,
5255 ],
5256 "https://bad-range.example.com/204" => vec![
5257 FetchEvent::Head(HttpHead {
5258 status: 204,
5259 url: req.url.clone(),
5260 ..Default::default()
5261 }),
5262 FetchEvent::End,
5263 ],
5264 _ => vec![FetchEvent::Failed("unexpected url".into())],
5265 });
5266
5267 let (events, body) = collect(
5269 &host,
5270 "https://github.com/o/r/releases/latest/download/a.tar.gz",
5271 4,
5272 )
5273 .unwrap();
5274 assert_eq!(events, ["partial:Some(10)"]);
5275 assert_eq!(body, b"456789");
5276 let seen = net.seen.lock().unwrap().clone();
5277 assert_eq!(seen.len(), 2);
5278 for req in &seen {
5279 assert!(!req.follow_redirects);
5280 assert_eq!(
5281 updater_header(&req.headers, "accept-encoding"),
5282 Some("identity")
5283 );
5284 assert_eq!(updater_header(&req.headers, "range"), Some("bytes=4-"));
5285 }
5286
5287 net.seen.lock().unwrap().clear();
5289 let (events, body) = collect(&host, "https://cdn.example.com/assets/a.tar.gz", 0).unwrap();
5290 assert_eq!(events, ["full:Some(10)"]);
5291 assert_eq!(body, b"0123456789");
5292 let seen = net.seen.lock().unwrap();
5293 assert_eq!(updater_header(&seen[0].headers, "range"), None);
5294 assert_eq!(
5295 updater_header(&seen[0].headers, "accept-encoding"),
5296 Some("identity")
5297 );
5298 drop(seen);
5299
5300 let err = collect(&host, "https://downgrade.example.com/a", 4).unwrap_err();
5302 assert!(err.contains("non-HTTPS"), "{err}");
5303
5304 let (events, body) =
5306 collect(&host, "https://bad-range.example.com/wrong-start", 4).unwrap();
5307 assert_eq!(events, ["unsatisfiable"]);
5308 assert!(body.is_empty());
5309
5310 let (events, body) = collect(&host, "https://bad-range.example.com/416", 10).unwrap();
5312 assert_eq!(events, ["unsatisfiable"]);
5313 assert!(body.is_empty());
5314
5315 let err = collect(&host, "https://bad-range.example.com/truncated", 4).unwrap_err();
5317 assert!(err.contains("truncated"), "{err}");
5318
5319 let err = collect(&host, "https://bad-range.example.com/204", 4).unwrap_err();
5321 assert_eq!(err, "HTTP 204");
5322 }
5323
5324 #[cfg(all(feature = "net", not(target_arch = "wasm32")))]
5325 #[test]
5326 fn updater_over_network_resumes_over_ureq_across_redirect() {
5327 use std::{
5328 io::{BufRead as _, BufReader, Write as _},
5329 net::TcpListener,
5330 };
5331
5332 let payload = b"0123456789abcdefghijklmnopqrstuvwxyz".to_vec();
5333 let asset_listener = TcpListener::bind("127.0.0.1:0").unwrap();
5334 let asset_port = asset_listener.local_addr().unwrap().port();
5335 let redirect_listener = TcpListener::bind("127.0.0.1:0").unwrap();
5336 let redirect_port = redirect_listener.local_addr().unwrap().port();
5337
5338 let served = payload.clone();
5339 std::thread::spawn(move || {
5340 for stream in asset_listener.incoming() {
5341 let Ok(stream) = stream else { return };
5342 let mut reader = BufReader::new(stream);
5343 let mut line = String::new();
5344 if reader.read_line(&mut line).is_err() {
5345 continue;
5346 }
5347 let mut range_header = None;
5348 let mut accept_encoding = None;
5349 loop {
5350 let mut h = String::new();
5351 if reader.read_line(&mut h).is_err() || h.trim().is_empty() {
5352 break;
5353 }
5354 if let Some((k, v)) = h.split_once(':') {
5355 if k.trim().eq_ignore_ascii_case("range") {
5356 range_header = Some(v.trim().to_owned());
5357 } else if k.trim().eq_ignore_ascii_case("accept-encoding") {
5358 accept_encoding = Some(v.trim().to_owned());
5359 }
5360 }
5361 }
5362 assert_eq!(accept_encoding.as_deref(), Some("identity"));
5363 let s = reader.get_mut();
5364 if let Some(start) = range_header
5365 .as_deref()
5366 .and_then(|r| r.strip_prefix("bytes="))
5367 .and_then(|r| r.strip_suffix('-'))
5368 .and_then(|r| r.parse::<usize>().ok())
5369 {
5370 if start >= served.len() {
5371 let _ = write!(
5372 s,
5373 "HTTP/1.1 416 Range Not Satisfiable\r\nContent-Range: bytes */{}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
5374 served.len()
5375 );
5376 } else {
5377 let slice = &served[start..];
5378 let _ = write!(
5379 s,
5380 "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes {start}-{}/{}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
5381 served.len() - 1,
5382 served.len(),
5383 slice.len()
5384 );
5385 let _ = s.write_all(slice);
5386 }
5387 } else {
5388 let _ = write!(
5389 s,
5390 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
5391 served.len()
5392 );
5393 let _ = s.write_all(&served);
5394 }
5395 }
5396 });
5397
5398 std::thread::spawn(move || {
5399 for stream in redirect_listener.incoming() {
5400 let Ok(stream) = stream else { return };
5401 let mut reader = BufReader::new(stream);
5402 let mut line = String::new();
5403 if reader.read_line(&mut line).is_err() {
5404 continue;
5405 }
5406 loop {
5407 let mut h = String::new();
5408 if reader.read_line(&mut h).is_err() || h.trim().is_empty() {
5409 break;
5410 }
5411 }
5412 let _ = write!(
5413 reader.get_mut(),
5414 "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{asset_port}/app.tar.gz\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
5415 );
5416 }
5417 });
5418
5419 let host = UpdaterOverNetwork {
5420 network: crate::net::network(),
5421 assets: None,
5422 config: None,
5423 running: None,
5424 };
5425 let url = format!("http://127.0.0.1:{redirect_port}/latest/app.tar.gz");
5426
5427 let (events, body) = collect(&host, &url, 10).unwrap();
5428 assert_eq!(events, [format!("partial:Some({})", payload.len())]);
5429 assert_eq!(body, &payload[10..]);
5430
5431 let (events, body) = collect(&host, &url, payload.len() as u64).unwrap();
5432 assert_eq!(events, ["unsatisfiable"]);
5433 assert!(body.is_empty());
5434 }
5435}