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 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")]
80pub use nsh_package as package;
81use rustc_hash::FxHashMap;
82#[cfg(not(target_arch = "wasm32"))]
83pub use storage::{FileStorage, resolve_data_dir, support_dir};
84
85use crate::script::{NetworkQueue, RequestId, Script};
86pub use crate::{
87 cache::{ByteSize, CacheLocation, CacheOptions, CachePolicy},
88 error::{AppError, AppErrorKind, PackageInfo},
89 host_channel::{HostCall, HostChannel, HostReply, OpenUrlRequest},
90};
91
92#[cfg(not(target_arch = "wasm32"))]
93const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
97
98const PERF_STATS_INTERVAL: Duration = Duration::from_secs(1);
101const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
105
106const IDLE_GC_QUIET: Duration = Duration::from_millis(300);
113
114const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);
116
117const MOUSE_MOVE_INTERVAL: Duration = Duration::from_millis(8);
121
122#[derive(Debug, Clone)]
124#[allow(
125 clippy::large_enum_variant,
126 reason = "one app per surface; keep the public constructor API without allocation"
127)]
128pub enum App {
129 Rust(Root),
131 Js(Bundle),
133}
134
135impl From<Bundle> for App {
136 fn from(bundle: Bundle) -> Self {
137 App::Js(bundle)
138 }
139}
140
141impl App {
142 pub fn app_id(&self) -> Option<&str> {
144 match self {
145 App::Rust(root) => root.app_id_ref(),
146 App::Js(bundle) => bundle.app_id.as_deref(),
147 }
148 }
149
150 pub fn main_window(&self) -> Option<&nsh_core::desktop::MainWindowOptions> {
155 match self {
156 App::Rust(root) => root.main_window_ref(),
157 App::Js(bundle) => bundle.main_window.as_ref(),
158 }
159 }
160
161 pub fn url_schemes(&self) -> &[String] {
164 match self {
165 App::Rust(root) => root.url_schemes_ref(),
166 App::Js(bundle) => &bundle.url_schemes,
167 }
168 }
169}
170
171impl From<Root> for App {
172 fn from(root: Root) -> Self {
173 App::Rust(root)
174 }
175}
176
177#[derive(Debug, Clone)]
179#[non_exhaustive]
180pub struct Bundle {
181 pub code: BundleCode,
183 pub source_map: Option<Arc<str>>,
185 pub policy: Policy,
187 pub base_url: Option<Arc<str>>,
190 pub chunks: Arc<Vec<Chunk>>,
194 pub app_id: Option<String>,
197 pub url_schemes: Vec<String>,
202 pub system_paths: nsh_core::access::TrustedPaths,
206 pub package: Option<Arc<PackageInfo>>,
209 pub updater_config: Option<Arc<[u8]>>,
215 pub trial: Option<Arc<dyn Trial>>,
219 pub main_window: Option<nsh_core::desktop::MainWindowOptions>,
224}
225
226pub const TRIAL_PERIOD: Duration = Duration::from_secs(10);
229
230pub trait Trial: Send + Sync + std::fmt::Debug + 'static {
234 fn healthy(&self);
237 fn failed(&self, error: &AppError);
239}
240
241#[derive(Debug, Clone)]
244pub struct Chunk {
245 pub id: String,
247 pub code: BundleCode,
249 pub source_map: Option<Arc<str>>,
251}
252
253impl Chunk {
254 pub fn source(id: impl Into<String>, code: String) -> Self {
256 Self {
257 id: id.into(),
258 code: BundleCode::Source(code),
259 source_map: None,
260 }
261 }
262
263 pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
269 Self {
270 id: id.into(),
271 code: BundleCode::Bytecode(bytes),
272 source_map: None,
273 }
274 }
275
276 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
278 self.source_map = Some(map.into());
279 self
280 }
281}
282
283#[derive(Debug, Clone)]
285pub struct Policy {
286 pub harden: bool,
290 pub declared: Option<Capabilities>,
293 pub granted: Option<Capabilities>,
296}
297
298impl Default for Policy {
299 fn default() -> Self {
300 Self {
301 harden: true,
302 declared: None,
303 granted: None,
304 }
305 }
306}
307
308impl Policy {
309 pub fn development() -> Self {
313 Self {
314 harden: false,
315 ..Self::default()
316 }
317 }
318
319 pub fn access(&self) -> Access {
321 Access {
322 declared: self.declared.clone().unwrap_or_else(Capabilities::all),
323 granted: self.granted.clone(),
324 }
325 }
326}
327
328#[derive(Debug, Clone)]
330pub enum BundleCode {
331 Bytecode(Vec<u8>),
333 Source(String),
335}
336
337impl Default for Bundle {
338 fn default() -> Self {
339 Self::source(String::new())
340 }
341}
342
343impl Bundle {
344 pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
354 Self {
355 code: BundleCode::Bytecode(bytes),
356 source_map: None,
357 policy: Policy::default(),
358 base_url: None,
359 chunks: Arc::default(),
360 app_id: None,
361 url_schemes: Vec::new(),
362 system_paths: nsh_core::access::TrustedPaths::default(),
363 package: None,
364 updater_config: None,
365 trial: None,
366 main_window: None,
367 }
368 }
369
370 pub fn source(code: String) -> Self {
372 Self {
373 code: BundleCode::Source(code),
374 source_map: None,
375 policy: Policy::default(),
376 base_url: None,
377 chunks: Arc::default(),
378 app_id: None,
379 url_schemes: Vec::new(),
380 system_paths: nsh_core::access::TrustedPaths::default(),
381 package: None,
382 updater_config: None,
383 trial: None,
384 main_window: None,
385 }
386 }
387
388 pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
393 paths.plugin_dir = trusted_directory(paths.plugin_dir);
394 paths.home_dir = trusted_directory(paths.home_dir);
395 self.system_paths = paths;
396 self
397 }
398
399 pub fn with_app_id(mut self, id: Option<&str>) -> Self {
402 self.app_id = id.map(str::to_owned);
403 self
404 }
405
406 pub fn with_main_window(mut self, json: Option<&str>) -> Self {
410 self.main_window = json.and_then(|json| {
411 let parsed = serde_json::from_str(json)
412 .map_err(|e| e.to_string())
413 .and_then(|v| nsh_core::desktop::MainWindowOptions::from_json(&v));
414 parsed.map_err(|e| log::warn!("nsh.json window: {e}")).ok()
415 });
416 self
417 }
418
419 pub fn with_url_schemes(
422 mut self,
423 schemes: impl IntoIterator<Item = impl Into<String>>,
424 ) -> Self {
425 self.url_schemes = schemes.into_iter().map(Into::into).collect();
426 self
427 }
428
429 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
431 self.source_map = Some(map.into());
432 self
433 }
434
435 pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
440 self.base_url = Some(url.into());
441 self
442 }
443
444 pub fn with_policy(mut self, policy: Policy) -> Self {
446 self.policy = policy;
447 self
448 }
449
450 pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
452 Arc::make_mut(&mut self.chunks).extend(chunks);
453 self
454 }
455
456 pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
463 if path.extension().is_some_and(|e| e == "nshc") {
464 return Err(io::Error::other(
465 "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
466 ));
467 }
468 unsafe { Self::read_trusted(path) }
470 }
471
472 pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
479 let bytes = std::fs::read(path)?;
480 let bundle = if path.extension().is_some_and(|e| e == "nshc") {
481 unsafe { Bundle::bytecode(bytes) }
483 } else {
484 Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
485 };
486 let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
487 Ok(map) if !map.is_empty() => bundle.with_source_map(map),
488 _ => bundle,
489 };
490 if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
491 bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
492 }
493 let info = read_app_json(&path.with_file_name("app.json"));
494 bundle.app_id = info
495 .as_ref()
496 .and_then(|info| info.get("id")?.as_str().map(str::to_owned));
497 if let Some(window) = info.as_ref().and_then(|info| info.get("window")) {
498 bundle.main_window = Some(
499 nsh_core::desktop::MainWindowOptions::from_json(window)
500 .map_err(|e| io::Error::other(format!("app.json: {e}")))?,
501 );
502 }
503 if let Some(url_schemes) = info.as_ref().and_then(|info| info.get("schemes")) {
504 let (schemes, ignored) = nsh_core::url_scheme::schemes_from_json_lenient(url_schemes);
506 for what in ignored {
507 log::warn!("app.json: {what}, ignored");
508 }
509 bundle.url_schemes = schemes;
510 }
511 if info
513 .as_ref()
514 .is_some_and(nsh_core::file_type::declares_file_types)
515 {
516 bundle
517 .url_schemes
518 .push(nsh_core::file_type::FILE_SCHEME.to_owned());
519 }
520 bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
521 .parent()
522 .map(std::path::Path::to_path_buf);
523 Ok(bundle)
524 }
525}
526
527#[cfg(feature = "js-core")]
528impl Bundle {
529 pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
535 for ignored in &package.ignored {
536 log::warn!("package {}: ignored {ignored}", package.app.id);
537 }
538 let bundle = match package.bytecode() {
539 Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
542 None => Bundle::source(package.source.clone()),
543 };
544 let mut bundle = match &package.source_map {
545 Some(map) => bundle.with_source_map(map.clone()),
546 None => bundle,
547 };
548 if let Some(json) = &package.capabilities {
549 let (declared, dropped) = Capabilities::from_json_lenient(json)?;
550 for dropped in dropped {
551 log::warn!("package {}: not granted: {dropped}", package.app.id);
552 }
553 bundle.policy.declared = Some(declared);
554 }
555 bundle.app_id = Some(package.app.id.clone());
556 bundle.package = Some(Arc::new(PackageInfo {
557 id: package.app.id.clone(),
558 name: package.app.name.clone(),
559 version: package.app.version.clone(),
560 build: package.app.build,
561 sha256: package.sha256.clone(),
562 }));
563 Ok(bundle)
564 }
565}
566
567fn read_app_json(path: &std::path::Path) -> Option<serde_json::Value> {
570 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
571}
572
573#[cfg(feature = "js-core")]
575#[derive(Debug)]
576pub struct LoadedPackage {
577 pub bundle: Bundle,
579 pub assets: std::path::PathBuf,
581 pub app: nsh_package::App,
583 pub receipt: nsh_package::PackageReceipt,
585}
586
587#[cfg(feature = "js-core")]
592pub fn load_package(
593 trust: &mut nsh_package::TrustStore,
594 bytes: &[u8],
595 assets_root: &std::path::Path,
596) -> Result<LoadedPackage, String> {
597 let package = verify_package(trust, bytes, assets_root)?;
598 accept_package(trust, &package)?;
599 Ok(package)
600}
601
602#[cfg(feature = "js-core")]
610pub fn verify_package(
611 trust: &nsh_package::TrustStore,
612 bytes: &[u8],
613 assets_root: &std::path::Path,
614) -> Result<LoadedPackage, String> {
615 let package = trust
616 .verify(bytes, BYTECODE_VERSION)
617 .map_err(|e| e.to_string())?;
618 let bundle = Bundle::from_package(&package)?;
619 let dir = assets_root.join(&package.app.id).join(&package.sha256);
620 let done = dir.join(".complete");
621 if !done.exists() {
622 let assets = dir.join("assets");
623 for (path, data) in &package.assets {
624 let dest = assets.join(path);
626 if let Some(parent) = dest.parent() {
627 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
628 }
629 std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
630 }
631 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
632 std::fs::write(&done, b"").map_err(|e| e.to_string())?;
633 }
634 Ok(LoadedPackage {
635 bundle,
636 assets: dir.join("assets"),
637 receipt: package.receipt(),
638 app: package.app,
639 })
640}
641
642#[cfg(feature = "js-core")]
647pub fn symbolicate(source_map: &str, text: &str) -> String {
648 symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
649}
650
651#[cfg(feature = "js-core")]
655pub fn accept_package(
656 trust: &mut nsh_package::TrustStore,
657 package: &LoadedPackage,
658) -> Result<(), String> {
659 trust
660 .accept_receipt(&package.receipt)
661 .map_err(|e| e.to_string())
662}
663
664pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
670 let value: serde_json::Value =
671 serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
672 let (capabilities, dropped) = Capabilities::from_json_lenient(&value)?;
673 for dropped in dropped {
674 log::warn!("not granted: {dropped} (unknown to this NSH)");
675 }
676 Ok(capabilities)
677}
678
679impl Bundle {
680 pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
682 self.policy.declared = json.map(parse_capabilities).transpose()?;
683 Ok(self)
684 }
685}
686
687pub trait MountSink: Send + 'static {
690 fn submit(&self, batch: MountBatch);
692
693 fn needs_tree_order(&self) -> bool {
696 false
697 }
698
699 fn needs_projected_states(&self) -> bool {
703 false
704 }
705
706 fn report_error(&self, _message: &str) {}
712
713 fn report(&self, error: &AppError) {
717 self.report_error(&error.to_string());
718 }
719
720 fn request_frame(&self) {}
725
726 fn hot_update_failed(&self) {}
729
730 fn run_on_main_thread(&self, task: MainThreadTask) {
736 task.run();
737 }
738
739 fn resized(&self, _size: Size<Points>) {}
745
746 fn handled(&self, _events: u64) {}
752
753 fn load_chunk(&self, _id: &str) -> bool {
759 false
760 }
761}
762
763pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
767
768pub trait FetchTask: Send {
770 fn send(&mut self, chunk: Vec<u8>);
773 fn finish(&mut self);
775 fn pause(&mut self, paused: bool);
779 fn cancel(self: Box<Self>);
781}
782
783struct UpdaterOverNetwork {
786 network: Arc<dyn Network>,
787 assets: Option<Arc<dyn Assets>>,
788 config: Option<Arc<[u8]>>,
790 running: Option<Arc<PackageInfo>>,
792}
793
794impl UpdaterOverNetwork {
795 #[cfg_attr(
798 not(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32"))),
799 allow(dead_code)
800 )]
801 fn host(
802 network: Option<Arc<dyn Network>>,
803 assets: Option<Arc<dyn Assets>>,
804 bundle: &Bundle,
805 ) -> Option<Arc<dyn nsh_core::runtime::UpdaterHost>> {
806 if assets.is_none() && bundle.updater_config.is_none() {
807 return None;
808 }
809 Some(Arc::new(UpdaterOverNetwork {
810 network: network?,
811 assets,
812 config: bundle.updater_config.clone(),
813 running: bundle.package.clone(),
814 }))
815 }
816}
817
818impl nsh_core::runtime::UpdaterHost for UpdaterOverNetwork {
819 fn config(&self) -> Option<Vec<u8>> {
820 if let Some(config) = &self.config {
821 return Some(config.to_vec());
822 }
823 self.assets.as_ref()?.read("asset:/nsh-updater.json").ok()
825 }
826
827 fn running_package(&self) -> Option<nsh_core::runtime::PackageVersion> {
828 let running = self.running.as_ref()?;
829 let mut version = nsh_core::runtime::PackageVersion::default();
830 version.version = running.version.clone();
831 version.build = running.build;
832 Some(version)
833 }
834
835 fn runs_packages(&self) -> bool {
836 cfg!(all(feature = "js-core", not(target_arch = "wasm32")))
837 }
838
839 #[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
840 fn verify_package(
841 &self,
842 file: &std::path::Path,
843 updates: &std::path::Path,
844 app_id: &str,
845 roots: &[String],
846 newer_than: u64,
847 ) -> Result<nsh_core::runtime::PackageVersion, String> {
848 let app = updates::verify_download(file, updates, app_id, roots, newer_than)?;
849 let mut version = nsh_core::runtime::PackageVersion::default();
850 version.version = app.version;
851 version.build = app.build;
852 Ok(version)
853 }
854
855 fn get(&self, url: &str, sink: nsh_core::runtime::UpdaterSink<'_>) -> Result<(), String> {
856 let (tx, rx) = std::sync::mpsc::channel();
857 let events: FetchEvents = Box::new(move |event| {
858 let _ = tx.send(event);
859 });
860 let task = self.network.fetch(HttpRequest::new("GET", url), events);
861 let mut total = None;
862 let result = loop {
863 match rx.recv() {
864 Ok(FetchEvent::Head(head)) => {
865 if !(200..300).contains(&head.status) {
866 break Err(format!("HTTP {}", head.status));
867 }
868 total = head
869 .headers
870 .iter()
871 .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
872 .and_then(|(_, value)| value.parse().ok());
873 }
874 Ok(FetchEvent::Data(chunk)) => {
875 if let Err(e) = sink(&chunk, total) {
876 break Err(e);
877 }
878 }
879 Ok(FetchEvent::End) => return Ok(()),
880 Ok(FetchEvent::Failed(e)) => break Err(e),
881 Ok(FetchEvent::BodyWanted) => {}
882 Err(_) => break Err("the network stack went away".to_owned()),
883 }
884 };
885 task.cancel();
886 result
887 }
888}
889
890pub trait Network: Send + Sync + 'static {
892 fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
895}
896
897pub trait Assets: Send + Sync + 'static {
902 fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
906
907 fn url(&self, uri: &str) -> Option<String> {
912 let _ = uri;
913 None
914 }
915
916 #[cfg(not(target_arch = "wasm32"))]
923 fn base(&self) -> Option<nsh_core::image::loader::AssetBase> {
924 None
925 }
926}
927
928#[derive(Clone)]
930pub struct EngineConfig {
931 pub app: App,
933 pub viewport: Size<Points>,
935 pub trace: bool,
937 pub content_culling: bool,
941 pub network: Option<Arc<dyn Network>>,
943 pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
945 pub refuse_connections: Option<nsh_core::element::RefuseConnections>,
950 pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
952 pub assets: Option<Arc<dyn Assets>>,
954 pub environment: Environment,
956 pub header_heights: (Points, Points),
959 pub limits: Limits,
961 pub ui_sets: Vec<nsh_core::element::Registry>,
965 pub runtime: Option<tokio::runtime::Handle>,
968 #[doc(hidden)]
979 pub support_dir: Option<std::path::PathBuf>,
980 pub data_dir: Option<std::path::PathBuf>,
985 pub cache: CacheOptions,
989 pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
994 pub clock: Clock,
998 pub context: EngineContext,
1003 pub pinned: EnvironmentPins,
1006 pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
1010 pub host: HostChannel,
1015 pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
1019 pub speech: Option<Arc<dyn nsh_core::speech::SpeechBackend>>,
1024 pub audio: Option<Arc<dyn nsh_core::audio::AudioBackend>>,
1029 pub windows: Option<Arc<dyn nsh_core::desktop::WindowBackend>>,
1035 pub login_item: Option<Arc<dyn nsh_core::desktop::LoginItemBackend>>,
1040}
1041
1042#[derive(Debug, Clone, Copy, Default, PartialEq)]
1045#[non_exhaustive]
1046pub struct EnvironmentPins {
1047 pub locale: Option<nsh_core::platform::Locale>,
1049 pub languages: Option<nsh_core::platform::Languages>,
1051 pub hour_cycle: Option<nsh_core::platform::HourCycle>,
1053 pub first_day_of_week: Option<nsh_core::platform::Weekday>,
1055 pub measurement_system: Option<nsh_core::platform::MeasurementSystem>,
1057 pub temperature_unit: Option<nsh_core::platform::TemperatureUnit>,
1059 pub time_zone: Option<nsh_core::platform::TimeZone>,
1061 pub reduce_motion: Option<bool>,
1064 pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
1066}
1067
1068impl EnvironmentPins {
1069 pub fn apply(&self, environment: &mut Environment) {
1071 if let Some(locale) = self.locale {
1072 environment.locale = locale;
1073 }
1074 let settings = &mut environment.locale_settings;
1075 if let Some(languages) = self.languages {
1076 settings.languages = languages;
1077 }
1078 if let Some(time_zone) = self.time_zone {
1079 settings.time_zone = time_zone;
1080 }
1081 if let Some(hour_cycle) = self.hour_cycle {
1082 settings.hour_cycle = hour_cycle;
1083 }
1084 if let Some(day) = self.first_day_of_week {
1085 settings.first_day_of_week = day;
1086 }
1087 if let Some(system) = self.measurement_system {
1088 settings.measurement_system = system;
1089 }
1090 if let Some(unit) = self.temperature_unit {
1091 settings.temperature_unit = unit;
1092 }
1093 if let Some(reduce_motion) = self.reduce_motion {
1094 environment.reduce_motion = reduce_motion;
1095 }
1096 if let Some(safe_area) = self.safe_area {
1097 environment.safe_area = safe_area;
1098 }
1099 }
1100}
1101
1102fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
1103 let path = path.filter(|path| path.is_absolute())?;
1104 nsh_core::access::canonicalize(&path)
1105 .ok()
1106 .filter(|path| path.is_dir())
1107}
1108
1109fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
1112 system_paths(bundle.system_paths.clone(), !bundle.policy.harden)
1113}
1114
1115fn system_paths(
1118 mut paths: nsh_core::access::TrustedPaths,
1119 development: bool,
1120) -> nsh_core::access::TrustedPaths {
1121 paths.plugin_dir = trusted_directory(paths.plugin_dir);
1122 paths.home_dir = trusted_directory(paths.home_dir);
1123 if paths.home_dir.is_none() {
1124 paths.home_dir = ["HOME", "USERPROFILE"]
1125 .into_iter()
1126 .filter_map(std::env::var_os)
1127 .map(std::path::PathBuf::from)
1128 .find_map(|path| trusted_directory(Some(path)));
1129 }
1130 if paths.plugin_dir.is_none() && development {
1134 paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
1135 .map(std::path::PathBuf::from)
1136 .and_then(|path| trusted_directory(Some(path)));
1137 }
1138 paths
1139}
1140
1141impl EngineConfig {
1142 pub fn new(app: impl Into<App>) -> Self {
1149 Self {
1150 app: app.into(),
1151 viewport: Size::new(Points(390.0), Points(844.0)),
1152 trace: false,
1153 content_culling: false,
1154 network: None,
1155 websocket: None,
1156 refuse_connections: None,
1157 filesystem: None,
1158 assets: None,
1159 environment: Environment::default(),
1160 header_heights: (Points(44.0), Points(96.0)),
1161 limits: Limits::default(),
1162 ui_sets: Vec::new(),
1163 runtime: None,
1164 support_dir: None,
1165 data_dir: None,
1166 cache: CacheOptions::off(),
1167 storage: None,
1168 clock: Clock::system(),
1169 context: EngineContext::default(),
1170 pinned: EnvironmentPins::default(),
1171 clipboard: None,
1172 host: HostChannel::default(),
1173 picker: None,
1174 speech: None,
1175 audio: None,
1176 windows: None,
1177 login_item: None,
1178 }
1179 }
1180
1181 pub fn main_window_placement(
1189 &self,
1190 displays: &[nsh_core::desktop::Display],
1191 ) -> Option<nsh_core::desktop::WindowPlacement> {
1192 let options = self.app.main_window()?;
1193 let storage = app_storage(self)?;
1194 options.kept_placement(&*storage, displays)
1195 }
1196}
1197
1198fn data_dir(config: &EngineConfig) -> Option<std::path::PathBuf> {
1201 config.data_dir.clone().or_else(|| {
1202 config
1203 .support_dir
1204 .as_ref()
1205 .map(|root| root.join(app_dir_name(config.app.app_id())))
1206 })
1207}
1208
1209fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
1212 if let Some(storage) = &config.storage {
1213 return Some(storage.clone());
1214 }
1215 #[cfg(not(target_arch = "wasm32"))]
1216 if let Some(dir) = data_dir(config) {
1217 return Some(FileStorage::open(dir));
1218 }
1219 None
1220}
1221
1222#[cfg(not(target_arch = "wasm32"))]
1223fn shared_runtime() -> tokio::runtime::Handle {
1227 static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
1228 RUNTIME
1229 .get_or_init(|| {
1230 tokio::runtime::Builder::new_multi_thread()
1231 .worker_threads(2)
1232 .thread_name("nsh-tasks")
1233 .enable_all()
1234 .build()
1235 .expect("the tasks' runtime starts")
1236 })
1237 .handle()
1238 .clone()
1239}
1240
1241impl std::fmt::Debug for EngineConfig {
1242 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1243 f.debug_struct("EngineConfig")
1244 .field("app", &self.app)
1245 .field("viewport", &self.viewport)
1246 .field("trace", &self.trace)
1247 .field("content_culling", &self.content_culling)
1248 .field("network", &self.network.is_some())
1249 .field("assets", &self.assets.is_some())
1250 .field("environment", &self.environment)
1251 .field("header_heights", &self.header_heights)
1252 .field("limits", &self.limits)
1253 .field("ui_sets", &self.ui_sets)
1254 .field("clock", &self.clock)
1255 .field("context", &self.context)
1256 .field("pinned", &self.pinned)
1257 .field("clipboard", &self.clipboard.is_some())
1258 .field("host", &self.host)
1259 .field("picker", &self.picker.is_some())
1260 .field("speech", &self.speech.is_some())
1261 .field("audio", &self.audio.is_some())
1262 .field("login_item", &self.login_item.is_some())
1263 .field("windows", &self.windows.is_some())
1264 .finish()
1265 }
1266}
1267
1268const MAX_ADVANCE_ROUNDS: usize = 100_000;
1272
1273const MAX_FLUSH_ROUNDS: usize = 64;
1277
1278enum Message {
1279 Event(NodeId, EventKind, EventPayload),
1280 Scroll(NodeId, Point<Points>, u32),
1281 KeyScrolled(NodeId, nsh_core::scroll::KeyMove),
1282 Kept(Vec<NodeId>),
1283 ContentCulling(bool),
1284 InputScroll(NodeId, Point<Points>, Size<Points>, Size<Points>),
1285 InputComposing(NodeId, Option<String>),
1286 Zoom(NodeId, f32),
1287 ComponentSize(NodeId, Size<Points>),
1288 AnimationsFinished(Vec<nsh_core::animation::Finished>),
1289 Resize(Size<Points>),
1290 Wake,
1292 Environment(Box<Environment>),
1296 ShadersUnavailable,
1299 Displays(Arc<[nsh_core::desktop::Display]>),
1301 RootSize(NodeId, Size<Points>, EdgeInsets),
1302 OverlayArea(Option<nsh_core::Bounds<Points>>),
1305 PressBeyondRoot(nsh_core::Point<Points>),
1307 ScreenHeader(NodeId, Option<Points>),
1308 Frame,
1309 States(NodeId, u16),
1310 Modality(nsh_core::platform::InputModality),
1311 FontsChanged,
1312 Remount,
1313 Fetch(Requester, u64, FetchEvent),
1316 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1319 AssetRead(Requester, u64, HttpRequest, Result<Vec<u8>, String>),
1320 Hot(HotUpdate),
1321 Chunk(Result<Chunk, (String, String)>),
1324 Perf(Option<Arc<perf::PerfMonitor>>),
1325 Tokens(Option<Box<Tokens>>),
1327 HostFont(Vec<u8>),
1330 HostEvent(String, nsh_core::JsonValue),
1333 HostReply(u64, Result<nsh_core::JsonValue, String>),
1335 UrlHandled {
1338 id: u32,
1339 url: String,
1340 handled: bool,
1341 },
1342 Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
1344 Flush(Box<dyn FnOnce(bool) + Send>),
1347 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1349 Shutdown,
1350}
1351
1352#[derive(Debug, Clone)]
1356pub struct HotUpdate {
1357 pub name: String,
1359 pub code: String,
1361 pub source_map: Option<Arc<str>>,
1363}
1364
1365const MAX_LIST_ROUNDS: usize = 8;
1369
1370const PACED_BIND_OPS: usize = 150;
1377const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);
1379
1380#[derive(Clone)]
1382pub struct EngineControl {
1383 tx: Sender<Message>,
1384 modality: Arc<std::sync::atomic::AtomicU8>,
1387 downloads: nsh_core::webview::downloads::DownloadCleanup,
1391}
1392
1393impl EngineControl {
1394 pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
1396 self.downloads.dispatch(id, event, &payload);
1402 let _ = self.tx.send(Message::Event(id, event, payload));
1403 }
1404
1405 pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
1411 let _ = self.tx.send(Message::Scroll(id, offset, applied));
1412 }
1413
1414 pub fn key_scrolled(&self, id: NodeId, key_move: nsh_core::scroll::KeyMove) {
1419 let _ = self.tx.send(Message::KeyScrolled(id, key_move));
1420 }
1421
1422 pub fn keep_rendered(&self, nodes: Vec<NodeId>) {
1426 let _ = self.tx.send(Message::Kept(nodes));
1427 }
1428
1429 pub fn set_content_culling(&self, enabled: bool) {
1434 let _ = self.tx.send(Message::ContentCulling(enabled));
1435 }
1436
1437 pub fn input_scroll(
1442 &self,
1443 id: NodeId,
1444 offset: Point<Points>,
1445 content: Size<Points>,
1446 viewport: Size<Points>,
1447 ) {
1448 let _ = self
1449 .tx
1450 .send(Message::InputScroll(id, offset, content, viewport));
1451 }
1452
1453 pub fn input_composing(&self, id: NodeId, shown: Option<String>) {
1458 let _ = self.tx.send(Message::InputComposing(id, shown));
1459 }
1460
1461 pub fn zoom(&self, id: NodeId, scale: f32) {
1464 let _ = self.tx.send(Message::Zoom(id, scale));
1465 }
1466
1467 pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
1470 let _ = self.tx.send(Message::ComponentSize(id, size));
1471 }
1472
1473 pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
1475 let _ = self.tx.send(Message::AnimationsFinished(finished));
1476 }
1477
1478 pub fn resize(&self, size: Size<Points>) {
1480 let _ = self.tx.send(Message::Resize(size));
1481 }
1482
1483 pub fn set_environment(&self, environment: Environment) {
1486 let _ = self.tx.send(Message::Environment(Box::new(environment)));
1487 }
1488
1489 pub fn shaders_unavailable(&self) {
1494 let _ = self.tx.send(Message::ShadersUnavailable);
1495 }
1496
1497 pub fn set_displays(&self, displays: Vec<nsh_core::desktop::Display>) {
1501 let _ = self.tx.send(Message::Displays(displays.into()));
1502 }
1503
1504 pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
1507 let _ = self.tx.send(Message::RootSize(id, size, insets));
1508 }
1509
1510 pub fn set_overlay_area(&self, area: Option<nsh_core::Bounds<Points>>) {
1515 let _ = self.tx.send(Message::OverlayArea(area));
1516 }
1517
1518 pub fn press_beyond_root(&self, page: nsh_core::Point<Points>) {
1523 let _ = self.tx.send(Message::PressBeyondRoot(page));
1524 }
1525
1526 pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
1529 let _ = self.tx.send(Message::ScreenHeader(id, height));
1530 }
1531
1532 pub fn hot_update(&self, update: HotUpdate) {
1535 let _ = self.tx.send(Message::Hot(update));
1536 }
1537
1538 pub fn chunk_loaded(&self, chunk: Chunk) {
1541 let _ = self.tx.send(Message::Chunk(Ok(chunk)));
1542 }
1543
1544 pub fn chunk_failed(&self, id: String, message: String) {
1547 let _ = self.tx.send(Message::Chunk(Err((id, message))));
1548 }
1549
1550 pub fn frame(&self) {
1553 let _ = self.tx.send(Message::Frame);
1554 }
1555
1556 pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
1563 let _ = self.tx.send(Message::Advance(by, Box::new(done)));
1564 }
1565
1566 pub fn flush(&self, done: impl FnOnce(bool) + Send + 'static) {
1576 let _ = self.tx.send(Message::Flush(Box::new(done)));
1577 }
1578
1579 pub fn set_input_modality(&self, modality: nsh_core::platform::InputModality) {
1586 use std::sync::atomic::Ordering;
1587 let code = match modality {
1588 nsh_core::platform::InputModality::Keyboard => 1,
1589 nsh_core::platform::InputModality::Pointer => 2,
1590 };
1591 if self.modality.swap(code, Ordering::Relaxed) != code {
1592 let _ = self.tx.send(Message::Modality(modality));
1593 }
1594 }
1595
1596 pub fn set_states(&self, id: NodeId, states: u16) {
1601 let _ = self.tx.send(Message::States(id, states));
1602 }
1603
1604 pub fn fonts_changed(&self) {
1608 let _ = self.tx.send(Message::FontsChanged);
1609 }
1610
1611 pub fn remount(&self) {
1615 let _ = self.tx.send(Message::Remount);
1616 }
1617
1618 pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
1621 let _ = self.tx.send(Message::Perf(monitor));
1622 }
1623
1624 pub fn set_tokens(&self, tokens: Option<Tokens>) {
1629 let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1630 }
1631
1632 pub fn register_font(&self, data: Vec<u8>) {
1637 let _ = self.tx.send(Message::HostFont(data));
1638 }
1639}
1640
1641#[cfg(not(target_arch = "wasm32"))]
1642pub struct Engine {
1644 control: EngineControl,
1645 thread: Option<std::thread::JoinHandle<()>>,
1646 host: HostChannel,
1648 stop: Arc<std::sync::atomic::AtomicBool>,
1650 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1653 image_cache: Option<nsh_core::image::DiskCache>,
1655 media_files: Arc<nsh_core::access::MediaFiles>,
1657}
1658
1659#[cfg(not(target_arch = "wasm32"))]
1660impl Engine {
1661 pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
1663 where
1664 M: TextEngine + 'static,
1665 F: FnOnce() -> M + Send + 'static,
1666 S: MountSink,
1667 {
1668 Self::start_with(config, make_text_engine, sink, |_| {})
1669 }
1670
1671 pub fn start_with<M, F, S>(
1675 config: EngineConfig,
1676 make_text_engine: F,
1677 sink: S,
1678 setup: impl FnOnce(&EngineControl),
1679 ) -> io::Result<Engine>
1680 where
1681 M: TextEngine + 'static,
1682 F: FnOnce() -> M + Send + 'static,
1683 S: MountSink,
1684 {
1685 let image_cache = config.cache.open_images(config.app.app_id());
1686 let media_files = Arc::new(media_files(&config, &app_access(&config.app)));
1687 let (tx, rx) = crossbeam_channel::unbounded();
1688 let modality = Arc::default();
1689 let downloads = nsh_core::webview::downloads::DownloadCleanup::new();
1690 setup(&EngineControl {
1691 tx: tx.clone(),
1692 modality: Arc::clone(&modality),
1693 downloads: downloads.clone(),
1694 });
1695 let engine_tx = tx.clone();
1696 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1697 let engine_stop = stop.clone();
1698 let quit_listeners = Arc::new(std::sync::atomic::AtomicBool::new(false));
1699 let engine_quit_listeners = quit_listeners.clone();
1700 let host = config.host.clone();
1701 let engine_downloads = downloads.clone();
1702 let thread = std::thread::Builder::new()
1703 .name("nsh-engine".into())
1704 .stack_size(ENGINE_STACK_SIZE)
1705 .spawn(move || {
1706 run(
1707 config,
1708 make_text_engine(),
1709 sink,
1710 (engine_tx, rx),
1711 engine_stop,
1712 engine_quit_listeners,
1713 engine_downloads,
1714 )
1715 })?;
1716 Ok(Engine {
1717 control: EngineControl {
1718 tx,
1719 modality,
1720 downloads,
1721 },
1722 thread: Some(thread),
1723 host,
1724 stop,
1725 quit_listeners,
1726 image_cache,
1727 media_files,
1728 })
1729 }
1730
1731 pub fn media_files(&self) -> Arc<nsh_core::access::MediaFiles> {
1736 self.media_files.clone()
1737 }
1738
1739 pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
1743 self.image_cache.clone()
1744 }
1745
1746 pub fn control(&self) -> EngineControl {
1748 self.control.clone()
1749 }
1750}
1751
1752#[cfg(not(target_arch = "wasm32"))]
1753impl Drop for Engine {
1754 fn drop(&mut self) {
1755 if self
1759 .quit_listeners
1760 .load(std::sync::atomic::Ordering::Relaxed)
1761 {
1762 self.host.request_shutdown(&self.control.tx);
1763 let deadline = Instant::now() + QUIT_TIMEOUT + QUIT_GRACE;
1764 while self.thread.as_ref().is_some_and(|t| !t.is_finished())
1765 && Instant::now() < deadline
1766 {
1767 std::thread::sleep(Duration::from_millis(1));
1768 }
1769 }
1770 self.host.shutdown(&self.control.tx, &self.stop);
1771 if let Some(thread) = self.thread.take() {
1772 let _ = thread.join();
1773 }
1774 }
1775}
1776
1777#[cfg(not(target_arch = "wasm32"))]
1778fn raise_thread_priority() {
1782 #[cfg(target_vendor = "apple")]
1783 unsafe {
1785 libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
1786 }
1787}
1788
1789#[cfg(not(target_arch = "wasm32"))]
1791use nsh_core::element::desktop::QUIT_TIMEOUT;
1792
1793#[cfg(not(target_arch = "wasm32"))]
1796const QUIT_GRACE: Duration = Duration::from_millis(20);
1797
1798const RESIZE_BURST_GAP: Duration = Duration::from_millis(120);
1801
1802#[cfg(not(target_arch = "wasm32"))]
1803fn run<M: TextEngine + 'static, S: MountSink>(
1804 config: EngineConfig,
1805 text_engine: M,
1806 sink: S,
1807 messages: (Sender<Message>, Receiver<Message>),
1808 stop: Arc<std::sync::atomic::AtomicBool>,
1809 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1810 downloads: nsh_core::webview::downloads::DownloadCleanup,
1811) {
1812 let (tx, rx) = messages;
1813 raise_thread_priority();
1814 let _clock = config.clock.enter();
1816 let _context = config.context.enter();
1817 let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
1818 return;
1819 };
1820 driver.state.core.set_download_cleanup(downloads);
1821 driver.quit_listeners = quit_listeners;
1822 driver.sync_quit_listeners();
1823 drive(&mut driver, &rx);
1824 driver.quit(&rx);
1825 if let Some(trial) = &driver.trial {
1827 trial.healthy();
1828 }
1829}
1830
1831fn start_trial(trial: Arc<dyn Trial>) {
1834 #[cfg(not(target_arch = "wasm32"))]
1835 {
1836 let spawned = std::thread::Builder::new()
1837 .name("nsh-trial".into())
1838 .spawn(move || {
1839 std::thread::sleep(TRIAL_PERIOD);
1840 trial.healthy();
1841 });
1842 if let Err(err) = spawned {
1843 log::error!("cannot time the app's trial: {err}");
1844 }
1845 }
1846 #[cfg(target_arch = "wasm32")]
1848 drop(trial);
1849}
1850
1851#[cfg(not(target_arch = "wasm32"))]
1853fn drive<M: TextEngine + 'static>(driver: &mut Driver<M>, rx: &Receiver<Message>) {
1854 loop {
1855 let message = match driver.deadline() {
1856 Some(deadline) => match rx.recv_deadline(deadline) {
1857 Ok(message) => Some(message),
1858 Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
1859 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
1860 },
1861 None => match rx.recv() {
1862 Ok(message) => Some(message),
1863 Err(_) => return,
1864 },
1865 };
1866 let started = driver.state.perf.is_some().then(Instant::now);
1867 if let Some(message) = message {
1868 if !driver.handle(message, rx) {
1869 return;
1870 }
1871 while let Ok(message) = rx.try_recv() {
1873 if !driver.handle(message, rx) {
1874 return;
1875 }
1876 }
1877 }
1878 driver.turn();
1879 driver.state.record_perf(started);
1880 driver.read_perf_stats();
1881 if rx.is_empty() {
1882 driver.collect_if_idle();
1883 }
1884 }
1885}
1886
1887pub struct LocalEngine<M: TextEngine + 'static> {
1892 driver: ManuallyDrop<Driver<M>>,
1895 rx: Receiver<Message>,
1896 control: EngineControl,
1897 wake: Option<Arc<dyn Fn() + Send + Sync>>,
1899 pumping: Arc<std::sync::atomic::AtomicBool>,
1902 quit_started: bool,
1904}
1905
1906impl<M: TextEngine + 'static> LocalEngine<M> {
1907 pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
1910 Self::start_with(config, text_engine, sink, |_| {})
1911 }
1912
1913 pub fn start_with<S: MountSink>(
1917 config: EngineConfig,
1918 text_engine: M,
1919 sink: S,
1920 setup: impl FnOnce(&EngineControl),
1921 ) -> Option<Self> {
1922 let (tx, rx) = crossbeam_channel::unbounded();
1923 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1924 let downloads = nsh_core::webview::downloads::DownloadCleanup::new();
1925 let control = EngineControl {
1926 tx: tx.clone(),
1927 modality: Arc::default(),
1928 downloads: downloads.clone(),
1929 };
1930 setup(&control);
1931 let _clock = config.clock.enter();
1932 let _context = config.context.enter();
1933 let mut driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
1934 driver.state.core.set_download_cleanup(downloads);
1935 Some(LocalEngine {
1936 driver: ManuallyDrop::new(driver),
1937 rx,
1938 control,
1939 wake: None,
1940 pumping: Arc::default(),
1941 quit_started: false,
1942 })
1943 }
1944
1945 pub fn control(&self) -> EngineControl {
1947 self.control.clone()
1948 }
1949
1950 pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
1959 let tx = self.control.tx.clone();
1960 let pumping = self.pumping.clone();
1961 let host = wake.clone();
1962 let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
1963 let _ = tx.send(Message::Wake);
1964 if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
1967 host();
1968 }
1969 });
1970 self.driver.state.core.set_task_notify(notify.clone());
1971 self.driver.posts.set_notify(notify);
1972 self.wake = Some(wake);
1973 }
1974
1975 pub fn extend_ui_sets(&mut self, ui_sets: &[nsh_core::element::Registry]) {
1979 let sets: Vec<_> = nsh_core::runtime::registries()
1980 .iter()
1981 .chain(ui_sets)
1982 .cloned()
1983 .collect();
1984 self.driver
1985 .state
1986 .core
1987 .extend_components(nsh_core::element::Registry::merged(&sets));
1988 }
1989
1990 #[doc(hidden)]
2006 pub fn key_event(
2007 &mut self,
2008 id: NodeId,
2009 kind: EventKind,
2010 mut payload: EventPayload,
2011 stroke: Option<nsh_core::keymap::Keystroke>,
2012 ) -> bool {
2013 let _clock = self.driver.clock.enter();
2014 let _context = self.driver.context.enter();
2015 let prevented = match &mut payload {
2016 EventPayload::Key(event) => {
2017 event.default_prevented = self.driver.state.core.key_captured(id, stroke.as_ref());
2018 event.default_prevented
2019 }
2020 _ => false,
2021 };
2022 self.driver
2023 .handle(Message::Event(id, kind, payload), &self.rx);
2024 prevented
2025 }
2026
2027 #[doc(hidden)]
2032 pub fn key_interest(&self, id: NodeId) -> bool {
2033 self.driver.state.core.key_interest(id)
2034 }
2035
2036 pub fn pump(&mut self) -> Option<Instant> {
2040 let _clock = self.driver.clock.enter();
2041 let _context = self.driver.context.enter();
2042 self.pumping
2043 .store(true, std::sync::atomic::Ordering::SeqCst);
2044 for _ in 0..4 {
2047 let started = self.driver.state.perf.is_some().then(Instant::now);
2048 while let Ok(message) = self.rx.try_recv() {
2049 self.driver.handle(message, &self.rx);
2050 }
2051 self.driver.turn();
2052 self.driver.state.record_perf(started);
2053 if self.rx.is_empty() {
2054 break;
2055 }
2056 }
2057 self.driver.read_perf_stats();
2058 self.driver.collect_if_idle();
2059 self.pumping
2060 .store(false, std::sync::atomic::Ordering::SeqCst);
2061 if !self.rx.is_empty()
2064 && let Some(wake) = &self.wake
2065 {
2066 wake();
2067 }
2068 self.driver.deadline()
2069 }
2070
2071 #[doc(hidden)]
2079 pub fn start_quit(&mut self) {
2080 if std::mem::replace(&mut self.quit_started, true) {
2081 return;
2082 }
2083 {
2084 let _clock = self.driver.clock.enter();
2085 let _context = self.driver.context.enter();
2086 if !self.driver.state.core.has_quit_listeners() {
2087 return;
2088 }
2089 self.driver.state.core.start_quit();
2090 }
2091 self.pump();
2092 }
2093}
2094
2095impl<M: TextEngine + 'static> Drop for LocalEngine<M> {
2096 fn drop(&mut self) {
2097 let _context = self.driver.context.enter();
2101 unsafe { ManuallyDrop::drop(&mut self.driver) };
2104 }
2105}
2106
2107struct Driver<M: TextEngine + 'static> {
2109 state: State<Rc<M>>,
2110 script: Option<Script>,
2111 sink: Rc<dyn MountSink>,
2112 assets: Option<Arc<dyn Assets>>,
2113 stopped: bool,
2116 last_gc: Instant,
2117 last_active: Instant,
2120 posts: nsh_core::element::Posts,
2123 clock: Clock,
2125 context: EngineContext,
2127 last_frame: Option<Instant>,
2130 _host: host_channel::HostAttachment,
2133 #[cfg(not(target_arch = "wasm32"))]
2137 trial: Option<Arc<dyn Trial>>,
2138 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
2140 quitting: bool,
2143}
2144
2145impl<M: TextEngine + 'static> Driver<M> {
2146 fn start(
2148 mut config: EngineConfig,
2149 text_engine: M,
2150 sink: Rc<dyn MountSink>,
2151 tx: Sender<Message>,
2152 rx: &Receiver<Message>,
2153 stop: Arc<std::sync::atomic::AtomicBool>,
2154 ) -> Option<Self> {
2155 config.pinned.apply(&mut config.environment);
2156 drawn_shaders(&mut config.environment, false);
2157 let trial = match &config.app {
2158 App::Js(bundle) => bundle.trial.clone(),
2159 App::Rust(_) => None,
2160 };
2161 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2162 let system_tx = tx.clone();
2163 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2164 let host_bridge = config.host.bridge(tx.clone());
2165 let host_tx = tx.clone();
2166 let text_engine = Rc::new(text_engine);
2167 let access = Arc::new(app_access(&config.app));
2168 let mut core = Core::new(text_engine.clone(), config.viewport);
2169 core.set_content_culling(config.content_culling);
2170 core.set_tree_order_tracking(sink.needs_tree_order());
2171 core.set_projected_state_mounting(sink.needs_projected_states());
2172 let sets: Vec<_> = nsh_core::runtime::registries()
2175 .iter()
2176 .chain(&config.ui_sets)
2177 .cloned()
2178 .collect();
2179 core.set_components(nsh_core::element::Registry::merged(&sets));
2180 let posts = nsh_core::element::Posts::new();
2184 core.set_posts(posts.clone());
2185 if let App::Js(_) = &config.app {
2186 core.set_max_nodes(config.limits.max_nodes);
2188 }
2189 core.set_access(access.clone());
2190 if let App::Js(bundle) = &config.app {
2191 core.set_base_url(bundle.base_url.clone());
2193 }
2194 let media_files = Arc::new(media_files(&config, &access));
2197 core.set_media_files(media_files.clone());
2198 #[cfg(not(target_arch = "wasm32"))]
2199 core.set_image_context(nsh_core::image::loader::Context {
2200 asset_base: config.assets.as_ref().and_then(|a| a.base()),
2201 read_asset: config.assets.clone().map(|assets| {
2202 Arc::new(move |uri: &str| assets.read(uri)) as nsh_core::image::loader::ReadAsset
2203 }),
2204 access: access.clone(),
2205 media_files,
2206 disk: config.cache.open_images(config.app.app_id()),
2208 transport: None,
2210 });
2211 core.set_storage(app_storage(&config));
2212 core.set_data_dir(data_dir(&config));
2213 core.set_clipboard(config.clipboard.clone());
2214 core.set_picker(config.picker.clone());
2215 core.set_speech(config.speech.clone());
2216 core.set_url_schemes(config.app.url_schemes().iter().cloned());
2217 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2219 let app_url = core.app_url_cell();
2220 core.set_audio(config.audio.clone());
2221 core.set_window_backend(config.windows.clone());
2222 core.set_login_item(config.login_item.clone());
2223 core.set_font_scale(config.environment.font_scale);
2224 core.set_class_environment(class_environment(&config.environment));
2225 core.set_header_heights(config.header_heights.0, config.header_heights.1);
2226 core.set_safe_area(insets(&config.environment));
2227 core.set_environment(ui_environment(&config.environment, config.viewport));
2228 if let Some(window) = config.app.main_window() {
2231 core.set_main_window(window);
2232 }
2233 #[cfg(not(target_arch = "wasm32"))]
2236 let runtime = config.runtime.clone().unwrap_or_else(shared_runtime);
2237 #[cfg(not(target_arch = "wasm32"))]
2238 core.set_task_runtime(runtime.clone());
2239 if let App::Rust(root) = &config.app {
2242 if let Some(tokens) = root.tokens_ref() {
2243 core.set_tokens(tokens.clone());
2244 }
2245 if let Some(appearance) = root.appearance_ref() {
2246 core.set_appearance(appearance);
2247 }
2248 if let Some(translations) = root.translations_ref() {
2249 core.set_translations(translations.clone());
2250 }
2251 for font in root.fonts() {
2252 if let Err(err) = core.register_font(font) {
2253 log::error!("font failed: {err}");
2254 sink.report(&AppError::new(
2255 AppErrorKind::Asset,
2256 &format!("font failed: {err}"),
2257 ));
2258 }
2259 }
2260 }
2261 let fonts = config
2263 .ui_sets
2264 .iter()
2265 .flat_map(nsh_core::element::Registry::asset_files)
2266 .filter(|file| file.kind == nsh_core::element::AssetKind::Font);
2267 for font in fonts {
2268 let result = match config.assets.as_deref() {
2269 Some(assets) => assets.read(font.uri),
2270 None => Err("this host cannot load assets".to_owned()),
2271 }
2272 .and_then(|data| core.register_font(&data));
2273 if let Err(err) = result {
2274 log::error!("font failed: {}: {err}", font.uri);
2275 let message = format!("font failed: {}: {err}", font.uri);
2276 let package = match &config.app {
2277 App::Js(bundle) => bundle.package.clone(),
2278 App::Rust(_) => None,
2279 };
2280 sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
2281 }
2282 }
2283 let wake = tx.clone();
2286 core.set_task_notify(Arc::new(move || {
2287 let _ = wake.send(Message::Wake);
2288 }));
2289 let wake = tx.clone();
2290 posts.set_notify(Arc::new(move || {
2291 let _ = wake.send(Message::Wake);
2292 }));
2293 let mut early = Vec::new();
2300 let mut displays: Arc<[nsh_core::desktop::Display]> = Arc::from(Vec::new());
2301 while let Ok(message) = rx.try_recv() {
2302 match message {
2303 Message::Tokens(tokens) => core.set_host_tokens(tokens.map(|t| *t)),
2304 Message::HostFont(data) => {
2305 if let Err(err) = core.register_font(&data) {
2306 log::error!("font failed: {err}");
2307 }
2308 }
2309 Message::Displays(list) => {
2310 core.set_displays(list.clone());
2311 displays = list;
2312 }
2313 Message::Event(nsh_core::ROOT_ID, EventKind::UrlScheme, payload) => {
2314 core.component_event(nsh_core::ROOT_ID, EventKind::UrlScheme, &payload);
2315 }
2316 message => early.push(message),
2317 }
2318 }
2319 let js_tokens = core.tokens().clone();
2320 let state = State {
2321 core,
2322 js_tokens,
2323 frame_requested: false,
2324 ops: Vec::new(),
2325 binds: Vec::new(),
2326 events: Vec::new(),
2327 trace: config.trace,
2328 perf: None,
2329 perf_stats_at: None,
2330 perf_commit: perf::CommitTiming::default(),
2331 committed_since_gc: false,
2332 hot: Vec::new(),
2333 scroll_events: FxHashMap::default(),
2334 touch_move: None,
2335 mouse_moves: Vec::new(),
2336 mouse_moved: None,
2337 key_path: Vec::new(),
2338 sets_seen: FxHashMap::default(),
2339 resized: None,
2340 resize_burst_ends: None,
2341 window_state: WindowStateReport {
2342 shown: config.environment.window_state,
2343 ..WindowStateReport::default()
2344 },
2345 events_handled: 0,
2346 events_reported: 0,
2347 pinned: config.pinned,
2348 environment: config.environment,
2349 shaders_unavailable: false,
2350 app_locale: None,
2351 host: config.host.clone(),
2352 url_opens: Vec::new(),
2353 net: Net {
2354 network: config.network.clone(),
2355 tx,
2356 queue: NetworkQueue::default(),
2357 inflight: FxHashMap::default(),
2358 tasks: Vec::new(),
2359 abandoned: Vec::new(),
2360 access: access.clone(),
2361 hops: 0,
2362 assets: config.assets.clone(),
2363 #[cfg(not(target_arch = "wasm32"))]
2364 runtime,
2365 },
2366 };
2367
2368 let mut environment = config.environment;
2369 environment.window = config.viewport;
2370 let start = Instant::now();
2371 let mut driver = Driver {
2372 state,
2373 script: None,
2374 sink: sink.clone(),
2375 assets: config.assets.clone(),
2376 stopped: false,
2377 last_gc: Instant::now(),
2378 last_active: Instant::now(),
2379 posts: posts.clone(),
2380 clock: config.clock.clone(),
2381 context: config.context.clone(),
2382 last_frame: None,
2383 _host: config.host.attach(host_tx, rx.clone()),
2384 #[cfg(not(target_arch = "wasm32"))]
2385 trial: trial.clone(),
2386 quit_listeners: Arc::default(),
2387 quitting: false,
2388 };
2389 let eval_us = match &config.app {
2390 App::Js(bundle) => {
2391 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2392 let system = {
2393 script::SystemConfig {
2394 access: (*access).clone(),
2395 websocket: config.websocket.clone(),
2396 refuse_connections: config.refuse_connections.clone(),
2397 filesystem: config.filesystem.clone(),
2398 updater: UpdaterOverNetwork::host(
2399 config.network.clone(),
2400 config.assets.clone(),
2401 bundle,
2402 ),
2403 app_url: app_url.clone(),
2404 data_dir: data_dir(&config),
2405 paths: bundle_system_paths(bundle),
2406 wake: Arc::new(move || {
2407 let _ = system_tx.send(Message::Wake);
2408 }),
2409 host: Rc::new(host_bridge),
2410 lazy_rows: config.content_culling,
2411 }
2412 };
2413 #[cfg(not(any(
2414 feature = "js-core",
2415 all(feature = "browser", target_arch = "wasm32")
2416 )))]
2417 let system = script::SystemConfig;
2418 let (script, eval_us) = Script::start(
2419 bundle,
2420 config.limits,
2421 &config.ui_sets,
2422 posts,
2423 &environment,
2424 &displays,
2425 driver.state.js_tokens.clone(),
2426 driver.state.core.theme_tokens(),
2427 text_engine,
2428 stop,
2429 sink,
2430 system,
2431 )?;
2432 driver.script = Some(script);
2433 eval_us
2434 }
2435 App::Rust(root) => {
2436 driver.state.core.mount_root(root);
2437 0
2438 }
2439 };
2440 let Driver {
2441 state,
2442 script,
2443 sink,
2444 assets,
2445 ..
2446 } = &mut driver;
2447 let script = script.as_ref();
2448 let mut moves = Vec::new();
2451 let pending = early
2452 .into_iter()
2453 .chain(std::iter::from_fn(|| rx.try_recv().ok()));
2454 for message in pending {
2455 if let Message::Advance(..) | Message::Flush(..) = message {
2456 moves.push(message);
2457 } else if !handle(script, state, message) {
2458 return None;
2459 }
2460 }
2461 if let Some(script) = script {
2464 script.run_system();
2465 }
2466 state.load_fonts(script, assets.as_deref(), &**sink);
2467 if let Some(batch) = state.commit(script) {
2468 if state.trace {
2469 log::info!(
2470 target: "nsh::perf",
2471 "first frame: eval {eval_us}µs, total {}µs",
2472 start.elapsed().as_micros()
2473 );
2474 }
2475 sink.submit(batch);
2476 }
2477 state.run_on_main_thread(&**sink);
2478 if let Some(trial) = trial {
2479 start_trial(trial);
2480 }
2481 if let Some(size) = state.resized.take() {
2485 sink.resized(size);
2486 }
2487 state.report_handled(&**sink);
2488 state.net.pump(script, &mut state.core);
2489 state.load_chunks(script, &**sink);
2490 state.request_frame(script, &**sink);
2491 driver.check_stopped();
2492 for message in moves {
2493 if !driver.handle(message, rx) {
2494 return None;
2495 }
2496 }
2497 Some(driver)
2498 }
2499
2500 fn deadline(&self) -> Option<Instant> {
2504 let gc_deadline =
2505 (self.script.is_some() && self.state.committed_since_gc).then(|| self.next_gc());
2506 let due = if self.clock.is_manual() {
2507 None
2508 } else {
2509 self.due()
2510 };
2511 [due, gc_deadline, self.state.perf_stats_at]
2512 .into_iter()
2513 .flatten()
2514 .min()
2515 }
2516
2517 fn read_perf_stats(&mut self) {
2520 let Some(at) = self.state.perf_stats_at else {
2521 return;
2522 };
2523 let now = Instant::now();
2524 if now < at {
2525 return;
2526 }
2527 self.state.perf_stats_at = Some(now + PERF_STATS_INTERVAL);
2528 let Some(stats) = self.state.perf.as_ref().map(|m| m.snapshot().stats()) else {
2529 return;
2530 };
2531 self.state.core.set_perf_stats(Some(stats));
2532 if let Some(script) = &self.script {
2533 script.set_perf_stats(Some(&stats));
2534 }
2535 if let Some(batch) = self.state.commit(self.script.as_ref()) {
2536 self.sink.submit(batch);
2537 }
2538 self.state.run_on_main_thread(&*self.sink);
2539 }
2540
2541 fn due(&self) -> Option<Instant> {
2544 [
2545 self.script.as_ref().and_then(Script::next_timer),
2546 self.state.next_scroll_event(),
2547 self.state.next_mouse_move(),
2548 self.state.core.next_task_timer(),
2549 self.state.core.download_deadline(),
2550 self.state.resize_burst_ends,
2551 self.state.window_state.settles,
2552 ]
2553 .into_iter()
2554 .flatten()
2555 .min()
2556 }
2557
2558 fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
2560 self.last_active = Instant::now();
2561 match message {
2562 Message::Advance(by, done) => {
2563 let running = self.advance(by, rx, self.clock.moves_with_frames());
2564 done();
2565 running
2566 }
2567 Message::Flush(done) => {
2568 let running = self.flush(rx);
2569 done(running && self.idle(rx));
2570 running
2571 }
2572 Message::Frame if self.clock.moves_with_frames() => {
2576 self.state.frame_requested = true;
2579 let by = self.next_frame() - self.clock.now();
2580 self.advance(by, rx, true)
2581 }
2582 message => handle(self.script.as_ref(), &mut self.state, message),
2583 }
2584 }
2585
2586 fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
2594 if !self.clock.is_manual() {
2595 self.turn();
2597 return true;
2598 }
2599 let to = self.clock.now() + by;
2600 for round in 0.. {
2601 let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
2604 let next = [self.due(), self.clock.next_alarm(), frame]
2605 .into_iter()
2606 .flatten()
2607 .min()
2608 .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
2609 if round == MAX_ADVANCE_ROUNDS {
2610 log::warn!(
2611 "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
2612 a timer keeps scheduling another at once"
2613 );
2614 }
2615 let at = next.unwrap_or(to);
2616 self.clock.advance_to(at);
2617 while let Ok(message) = rx.try_recv() {
2618 if !self.handle(message, rx) {
2619 return false;
2620 }
2621 }
2622 if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
2624 && self.state.frame_requested
2625 {
2626 self.frame();
2627 }
2628 self.turn();
2629 if next.is_none() {
2630 break;
2631 }
2632 }
2633 true
2634 }
2635
2636 fn flush(&mut self, rx: &Receiver<Message>) -> bool {
2640 let frames = self.clock.moves_with_frames();
2641 for _ in 0..MAX_FLUSH_ROUNDS {
2642 while let Ok(message) = rx.try_recv() {
2643 if !self.handle(message, rx) {
2644 return false;
2645 }
2646 }
2647 if !self.advance(std::time::Duration::ZERO, rx, frames) {
2649 return false;
2650 }
2651 if rx.is_empty() {
2654 break;
2655 }
2656 }
2657 true
2658 }
2659
2660 fn idle(&self, rx: &Receiver<Message>) -> bool {
2664 let now = self.clock.now();
2665 rx.is_empty()
2666 && self.state.net.idle()
2667 && [self.due(), self.clock.next_alarm()]
2668 .into_iter()
2669 .flatten()
2670 .all(|at| at > now)
2671 }
2672
2673 fn next_frame(&self) -> Instant {
2678 let now = self.clock.now();
2679 self.last_frame
2680 .map_or(now + nsh_core::time::FRAME, |last| {
2681 last + nsh_core::time::FRAME
2682 })
2683 .max(now)
2684 }
2685
2686 fn frame(&mut self) {
2689 self.last_frame = Some(self.clock.now());
2690 handle(self.script.as_ref(), &mut self.state, Message::Frame);
2691 }
2692
2693 fn turn(&mut self) {
2696 let Driver {
2697 state,
2698 script,
2699 sink,
2700 assets,
2701 ..
2702 } = self;
2703 let script = script.as_ref();
2704 if script
2705 .and_then(Script::next_timer)
2706 .is_some_and(|due| due <= nsh_core::time::now())
2707 {
2708 self.last_active = Instant::now();
2709 }
2710 if state
2711 .resize_burst_ends
2712 .is_some_and(|ends| ends <= nsh_core::time::now())
2713 {
2714 state.resize_burst_ends = None;
2715 state.core.set_resizing(false);
2716 }
2717 if state
2718 .window_state
2719 .settles
2720 .is_some_and(|due| due <= nsh_core::time::now())
2721 && let Some(env) = state.window_state.reported
2722 {
2723 state.window_state.settles = None;
2724 state.window_state.shown = env.window_state;
2725 apply_environment(script, state, env);
2726 }
2727 let turn_start = state.trace.then(Instant::now);
2728 state.dispatch_touch_move(script);
2729 if state
2730 .next_mouse_move()
2731 .is_some_and(|due| due <= nsh_core::time::now())
2732 {
2733 state.dispatch_mouse_moves(script);
2734 }
2735 state.dispatch_scroll_events(script);
2736 let hot = std::mem::take(&mut state.hot);
2737 if let Some(script) = script {
2738 for update in hot {
2739 script.hot_update(update, &**sink);
2740 }
2741 script.run_timers(nsh_core::time::now());
2742 script.run_system();
2743 }
2744 state.core.run_component_tasks();
2745 let tasks = turn_start.map(|s| s.elapsed());
2748 state.load_fonts(script, assets.as_deref(), &**sink);
2749 let batch = state.commit(script);
2750 if let Some(batch) = batch.filter(|_| !self.quitting) {
2751 sink.submit(batch);
2752 if let (Some(start), Some(tasks)) = (turn_start, tasks) {
2753 log::info!(
2754 target: "nsh::perf",
2755 "turn: {}µs (timers and tasks {}µs)",
2756 start.elapsed().as_micros(),
2757 tasks.as_micros(),
2758 );
2759 }
2760 }
2761 state.run_on_main_thread(&**sink);
2762 if let Some(size) = state.resized.take() {
2763 sink.resized(size);
2764 }
2765 state.report_handled(&**sink);
2766 state.net.pump(script, &mut state.core);
2767 state.load_chunks(script, &**sink);
2768 state.request_frame(script, &**sink);
2769 self.check_stopped();
2770 self.sync_quit_listeners();
2771 }
2772
2773 fn sync_quit_listeners(&self) {
2775 self.quit_listeners.store(
2776 self.state.core.has_quit_listeners(),
2777 std::sync::atomic::Ordering::Relaxed,
2778 );
2779 }
2780
2781 #[cfg(not(target_arch = "wasm32"))]
2786 fn quit(&mut self, rx: &Receiver<Message>) {
2787 if !self.state.core.has_quit_listeners() {
2788 return;
2789 }
2790 let deadline = Instant::now() + QUIT_TIMEOUT;
2791 self.quitting = true;
2792 self.state.core.start_quit();
2793 let mut kept = Vec::new();
2794 loop {
2795 self.turn();
2796 if !self.state.core.quit_pending() || self.stopped {
2797 break;
2798 }
2799 let wake = self.deadline().map_or(deadline, |at| at.min(deadline));
2800 match rx.recv_deadline(wake) {
2801 Ok(Message::Shutdown) => {}
2802 Ok(message @ Message::HostEvent(..)) => kept.push(message),
2803 Ok(message) => {
2804 self.handle(message, rx);
2805 }
2806 Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
2807 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => break,
2808 }
2809 if Instant::now() >= deadline {
2810 log::warn!(
2811 "the app's quit listeners did not finish in {} ms",
2812 QUIT_TIMEOUT.as_millis()
2813 );
2814 break;
2815 }
2816 }
2817 for message in kept {
2818 let _ = self.state.net.tx.send(message);
2819 }
2820 }
2821
2822 fn next_gc(&self) -> Instant {
2826 let quiet = (self.last_active + IDLE_GC_QUIET).min(self.last_gc + IDLE_GC_LONGEST);
2827 (self.last_gc + IDLE_GC_INTERVAL).max(quiet)
2828 }
2829
2830 fn collect_if_idle(&mut self) {
2833 if let Some(script) = &self.script
2834 && self.state.committed_since_gc
2835 && Instant::now() >= self.next_gc()
2836 {
2837 let start = self.state.trace.then(Instant::now);
2838 script.collect_garbage();
2839 if let Some(start) = start {
2840 log::info!(target: "nsh::perf", "gc: {}µs", start.elapsed().as_micros());
2841 }
2842 if let Some(monitor) = &self.state.perf {
2845 let (js_heap, js_objects) = script.heap_usage();
2846 monitor.set_memory(perf::MemorySample {
2847 js_heap,
2848 js_objects,
2849 nodes: self.state.core.node_count() as u64,
2850 node_ids: self.state.core.node_id_room() as u64,
2851 });
2852 }
2853 self.last_gc = Instant::now();
2854 self.state.committed_since_gc = false;
2855 if let Some(batch) = self.state.commit(Some(script)) {
2856 self.sink.submit(batch);
2857 }
2858 self.state.run_on_main_thread(&*self.sink);
2859 }
2860 }
2861
2862 fn check_stopped(&mut self) {
2863 if let Some(script) = &self.script
2864 && !self.stopped
2865 && let Some(reason) = script.fatal()
2866 {
2867 self.stopped = true;
2868 script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
2869 }
2870 }
2871}
2872
2873struct ScrollEvent {
2874 x: f32,
2875 y: f32,
2876 content: Size<Points>,
2877 viewport: Size<Points>,
2878 zoom: f32,
2880 throttle: Duration,
2881 last: Option<Instant>,
2882 pending: bool,
2884}
2885
2886struct State<M: TextEngine> {
2887 core: Core<M>,
2888 js_tokens: Arc<nsh_core::element::Tokens>,
2891 pinned: EnvironmentPins,
2894 environment: Environment,
2896 shaders_unavailable: bool,
2899 app_locale: Option<nsh_core::platform::Locale>,
2901 frame_requested: bool,
2903 ops: Vec<Op>,
2904 binds: Vec<ListBind>,
2906 events: Vec<JsEvent>,
2908 trace: bool,
2909 perf: Option<Arc<perf::PerfMonitor>>,
2911 perf_stats_at: Option<Instant>,
2914 perf_commit: perf::CommitTiming,
2917 committed_since_gc: bool,
2918 host: HostChannel,
2921 url_opens: Vec<(u32, String)>,
2923 net: Net,
2924 hot: Vec<HotUpdate>,
2926 scroll_events: FxHashMap<NodeId, ScrollEvent>,
2929 touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
2931 mouse_moves: Vec<(NodeId, EventPayload)>,
2935 mouse_moved: Option<Instant>,
2937 key_path: Vec<NodeId>,
2940 sets_seen: FxHashMap<(u8, NodeId, u32), usize>,
2942 resized: Option<Size<Points>>,
2944 resize_burst_ends: Option<Instant>,
2947 window_state: WindowStateReport,
2950 events_handled: u64,
2953 events_reported: u64,
2954}
2955
2956#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2959enum Requester {
2960 Js(RequestId),
2961 Task(u32),
2962}
2963
2964struct Net {
2967 network: Option<Arc<dyn Network>>,
2968 tx: Sender<Message>,
2969 queue: NetworkQueue,
2970 inflight: FxHashMap<Requester, Inflight>,
2971 tasks: Vec<(u32, HttpRequest)>,
2974 abandoned: Vec<u32>,
2975 access: Arc<nsh_core::access::Access>,
2977 hops: u64,
2979 assets: Option<Arc<dyn Assets>>,
2982 #[cfg(not(target_arch = "wasm32"))]
2985 runtime: tokio::runtime::Handle,
2986}
2987
2988struct AssetTask;
2991
2992impl FetchTask for AssetTask {
2993 fn send(&mut self, _: Vec<u8>) {}
2994 fn finish(&mut self) {}
2995 fn pause(&mut self, _: bool) {}
2996 fn cancel(self: Box<Self>) {}
2997}
2998
2999fn is_asset(url: &str) -> bool {
3002 url.get(..6)
3003 .is_some_and(|scheme| scheme.eq_ignore_ascii_case("asset:"))
3004}
3005
3006fn asset_response_url(url: &str) -> String {
3012 let rest = url.get(6..).unwrap_or_default();
3013 format!("asset:{}", rest.split('#').next().unwrap_or_default())
3014}
3015
3016fn asset_file(url: &str) -> &str {
3021 url.split('?').next().unwrap_or_default()
3022}
3023
3024struct Inflight {
3026 task: Box<dyn FetchTask>,
3027 hop: u64,
3029 followed: Option<access::Followed>,
3031 asset: Option<String>,
3035}
3036
3037impl Net {
3038 fn idle(&self) -> bool {
3040 self.inflight.is_empty()
3041 }
3042
3043 fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
3046 let mut abandoned = std::mem::take(&mut self.abandoned);
3047 core.take_fetches(&mut self.tasks, &mut abandoned);
3048 for id in abandoned.drain(..) {
3049 self.cancel(Requester::Task(id));
3050 }
3051 self.abandoned = abandoned;
3052 let mut tasks = std::mem::take(&mut self.tasks);
3053 for (id, request) in tasks.drain(..) {
3054 if let Err(refused) = self.request(Requester::Task(id), request) {
3055 core.fetch_refused(id, refused.message, refused.url);
3056 }
3057 }
3058 self.tasks = tasks;
3059 let Some(script) = script else { return };
3060 script.take_network(&mut self.queue);
3061 for (id, op) in std::mem::take(&mut self.queue.ops) {
3062 let who = Requester::Js(id);
3063 match op {
3064 FetchOp::Start(request) => {
3065 if let Err(refused) = self.request(who, request) {
3066 script.fetch_refused(id, &refused.message, &refused.url);
3067 }
3068 }
3069 FetchOp::Send(chunk) => {
3070 if let Some(i) = self.inflight.get_mut(&who) {
3071 i.task.send(chunk);
3072 }
3073 }
3074 FetchOp::Finish => {
3075 if let Some(i) = self.inflight.get_mut(&who) {
3076 i.task.finish();
3077 }
3078 }
3079 FetchOp::Pause(paused) => {
3080 if let Some(i) = self.inflight.get_mut(&who) {
3081 i.task.pause(paused);
3082 }
3083 }
3084 FetchOp::Cancel => self.cancel(who),
3085 }
3086 }
3087 }
3088
3089 fn cancel(&mut self, who: Requester) {
3091 if let Some(i) = self.inflight.remove(&who) {
3092 i.task.cancel();
3093 }
3094 }
3095
3096 fn request(&mut self, who: Requester, mut request: HttpRequest) -> Result<(), access::Refused> {
3099 if is_asset(&request.url) {
3100 self.asset(who, request);
3101 return Ok(());
3102 }
3103 if self.access.is_unrestricted() {
3104 self.start(who, request, None);
3105 return Ok(());
3106 }
3107 match self.access.http_url(&request.method, &request.url) {
3110 Some(url) => request.url = url.into_owned(),
3111 None => return Err(access::refused(&request.method, &request.url)),
3112 }
3113 if request.follow_redirects {
3114 let hop = access::hop(&request);
3115 let followed = access::Followed { request, hops: 0 };
3116 self.start(who, hop, Some(followed));
3117 } else {
3118 self.start(who, request, None);
3119 }
3120 Ok(())
3121 }
3122
3123 fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
3125 self.hops += 1;
3126 let hop = self.hops;
3127 let Some(network) = &self.network else {
3128 let failed = FetchEvent::Failed("this host has no network stack".to_owned());
3129 let _ = self.tx.send(Message::Fetch(id, hop, failed));
3130 return;
3131 };
3132 let tx = self.tx.clone();
3133 let events: FetchEvents = Box::new(move |event| {
3134 let _ = tx.send(Message::Fetch(id, hop, event));
3135 });
3136 let task = network.fetch(request, events);
3137 self.inflight.insert(
3138 id,
3139 Inflight {
3140 task,
3141 hop,
3142 followed,
3143 asset: None,
3144 },
3145 );
3146 }
3147
3148 fn asset(&mut self, who: Requester, mut request: HttpRequest) {
3153 request.url = asset_response_url(&request.url);
3154 let file = asset_file(&request.url).to_owned();
3155 self.hops += 1;
3156 let hop = self.hops;
3157 self.inflight.insert(
3158 who,
3159 Inflight {
3160 task: Box::new(AssetTask),
3161 hop,
3162 followed: None,
3163 asset: None,
3164 },
3165 );
3166 let refused = if !nsh_core::access::is_inside_assets(&file) {
3169 Some(format!(
3170 "{}: bundled files are named by a path inside the app's files",
3171 request.url
3172 ))
3173 } else if !matches!(request.method.as_str(), "GET" | "HEAD") {
3174 Some(format!(
3175 "{} {}: bundled files are read with GET",
3176 request.method, request.url
3177 ))
3178 } else {
3179 None
3180 };
3181 if let Some(refused) = refused {
3182 let _ = self
3183 .tx
3184 .send(Message::Fetch(who, hop, FetchEvent::Failed(refused)));
3185 return;
3186 }
3187 let Some(assets) = &self.assets else {
3188 let failed = Err("this host cannot load assets".to_owned());
3189 self.asset_read(who, hop, request, failed);
3190 return;
3191 };
3192 #[cfg(not(target_arch = "wasm32"))]
3193 {
3194 let assets = assets.clone();
3195 let tx = self.tx.clone();
3196 drop(self.runtime.spawn_blocking(move || {
3198 let bytes = assets.read(&file);
3199 let _ = tx.send(Message::AssetRead(who, hop, request, bytes));
3200 }));
3201 }
3202 #[cfg(target_arch = "wasm32")]
3203 {
3204 let bytes = assets.read(&file);
3205 self.asset_read(who, hop, request, bytes);
3206 }
3207 }
3208
3209 fn asset_read(
3215 &mut self,
3216 who: Requester,
3217 hop: u64,
3218 request: HttpRequest,
3219 read: Result<Vec<u8>, String>,
3220 ) {
3221 if self.inflight.get(&who).is_none_or(|i| i.hop != hop) {
3222 return;
3223 }
3224 let events = match read {
3225 Ok(bytes) => {
3226 let head = HttpHead {
3227 status: 200,
3228 status_text: "OK".to_owned(),
3229 headers: vec![
3230 ("content-length".to_owned(), bytes.len().to_string()),
3231 (
3232 "content-type".to_owned(),
3233 content_type(asset_file(&request.url)).to_owned(),
3234 ),
3235 ],
3236 url: request.url.clone(),
3237 ..HttpHead::default()
3238 };
3239 let mut events = vec![FetchEvent::Head(head)];
3240 if request.method == "GET" && !bytes.is_empty() {
3241 events.push(FetchEvent::Data(bytes));
3242 }
3243 events.push(FetchEvent::End);
3244 events
3245 }
3246 Err(error) => {
3247 match (self.assets.as_ref()).and_then(|a| a.url(asset_file(&request.url))) {
3248 Some(url) => {
3249 self.inflight.remove(&who);
3250 let uri = request.url.clone();
3251 self.start(who, HttpRequest { url, ..request }, None);
3252 if let Some(download) = self.inflight.get_mut(&who) {
3253 download.asset = Some(uri);
3254 }
3255 return;
3256 }
3257 None => vec![FetchEvent::Failed(error)],
3258 }
3259 }
3260 };
3261 for event in events {
3262 let _ = self.tx.send(Message::Fetch(who, hop, event));
3263 }
3264 }
3265
3266 fn event(
3270 &mut self,
3271 id: Requester,
3272 hop: u64,
3273 event: FetchEvent,
3274 ) -> Option<Result<FetchEvent, access::Refused>> {
3275 if self.network.is_none() {
3276 return Some(Ok(event));
3277 }
3278 let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
3279 match event {
3280 FetchEvent::Head(mut head) => {
3281 let missing = (inflight.asset.as_ref())
3282 .filter(|_| !(200..300).contains(&head.status))
3283 .map(|uri| format!("{uri}: HTTP {}", head.status));
3284 if let Some(missing) = missing {
3285 if let Some(i) = self.inflight.remove(&id) {
3286 i.task.cancel();
3287 }
3288 return Some(Ok(FetchEvent::Failed(missing)));
3289 }
3290 if let Some(uri) = &inflight.asset {
3294 head.url = uri.clone();
3295 head.redirected = false;
3296 if !head
3297 .headers
3298 .iter()
3299 .any(|(name, _)| name.eq_ignore_ascii_case("content-type"))
3300 {
3301 let file_type = content_type(asset_file(uri)).to_owned();
3302 head.headers.push(("content-type".to_owned(), file_type));
3303 }
3304 }
3305 let Some(followed) = &mut inflight.followed else {
3306 return Some(Ok(FetchEvent::Head(head)));
3307 };
3308 match access::next(&self.access, followed, head) {
3309 access::Next::Done(head) => Some(Ok(FetchEvent::Head(head))),
3310 access::Next::Fail(message) => {
3311 if let Some(i) = self.inflight.remove(&id) {
3312 i.task.cancel();
3313 }
3314 Some(Ok(FetchEvent::Failed(message)))
3315 }
3316 access::Next::Refused(refused) => {
3317 if let Some(i) = self.inflight.remove(&id) {
3318 i.task.cancel();
3319 }
3320 Some(Err(refused))
3321 }
3322 access::Next::Hop(request) => {
3323 let i = self.inflight.remove(&id)?;
3324 let followed = i.followed;
3325 i.task.cancel();
3326 self.start(id, request, followed);
3327 None
3328 }
3329 }
3330 }
3331 FetchEvent::End | FetchEvent::Failed(_) => {
3332 self.inflight.remove(&id);
3333 Some(Ok(event))
3334 }
3335 event => Some(Ok(event)),
3336 }
3337 }
3338}
3339
3340impl<M: TextEngine> State<M> {
3341 fn record_perf(&mut self, started: Option<Instant>) {
3344 let (Some(started), Some(monitor)) = (started, &self.perf) else {
3345 return;
3346 };
3347 let busy = started.elapsed();
3348 monitor.record_busy(busy);
3349 let mut commit = std::mem::take(&mut self.perf_commit);
3350 if commit.ops > 0 || commit.items > 0 {
3351 commit.js = busy.saturating_sub(commit.layout);
3352 monitor.record_commit(commit);
3353 }
3354 }
3355
3356 fn dispatch_touch_move(&mut self, script: Option<&Script>) {
3358 if let Some((id, touch)) = self.touch_move.take()
3359 && let Some(script) = script
3360 {
3361 script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
3362 }
3363 }
3364
3365 fn next_mouse_move(&self) -> Option<Instant> {
3367 if self.mouse_moves.is_empty() {
3368 return None;
3369 }
3370 Some(
3371 self.mouse_moved
3372 .map_or_else(nsh_core::time::now, |t| t + MOUSE_MOVE_INTERVAL),
3373 )
3374 }
3375
3376 fn dispatch_mouse_moves(&mut self, script: Option<&Script>) {
3379 if self.mouse_moves.is_empty() {
3380 return;
3381 }
3382 self.mouse_moved = Some(nsh_core::time::now());
3383 for (id, payload) in std::mem::take(&mut self.mouse_moves) {
3384 if self
3385 .core
3386 .component_event(id, EventKind::MouseMove, &payload)
3387 {
3388 continue;
3389 }
3390 if let Some(script) = script {
3391 script.dispatch_event(id, EventKind::MouseMove, &payload);
3392 }
3393 }
3394 }
3395
3396 fn next_scroll_event(&self) -> Option<Instant> {
3398 self.scroll_events
3399 .values()
3400 .filter(|e| e.pending)
3401 .filter_map(|e| e.last.map(|t| t + e.throttle))
3402 .min()
3403 }
3404
3405 fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
3407 if self.scroll_events.is_empty() {
3408 return;
3409 }
3410 let now = nsh_core::time::now();
3411 let core = &self.core;
3413 self.scroll_events
3414 .retain(|&id, _| core.scroll_listener(id).is_some());
3415 for (&id, e) in &mut self.scroll_events {
3416 if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
3417 continue;
3418 }
3419 e.pending = false;
3420 e.last = Some(now);
3421 let n = |v: f32| PayloadValue::Number(v as f64);
3422 let payload = EventPayload::Map(vec![
3423 (
3424 "offset",
3425 PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
3426 ),
3427 ("contentSize", PayloadValue::Size(e.content)),
3428 ("size", PayloadValue::Size(e.viewport)),
3429 ("zoomScale", n(e.zoom)),
3430 ]);
3431 if !self.core.component_event(id, EventKind::Scroll, &payload)
3433 && let Some(script) = script
3434 {
3435 script.dispatch_event(id, EventKind::Scroll, &payload);
3436 }
3437 }
3438 }
3439
3440 fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
3442 let Some(script) = script else { return };
3443 let mut ids = Vec::new();
3444 script.take_chunk_requests(&mut ids);
3445 for id in ids {
3446 if !sink.load_chunk(&id) {
3447 let message = "this host does not load chunks (the app was built split)".to_owned();
3448 let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
3449 }
3450 }
3451 }
3452
3453 fn report_handled(&mut self, sink: &dyn MountSink) {
3456 if self.events_handled != self.events_reported {
3457 self.events_reported = self.events_handled;
3458 sink.handled(self.events_handled);
3459 }
3460 }
3461
3462 fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
3465 if !self.frame_requested
3466 && (script.is_some_and(Script::wants_frame)
3467 || self.core.wants_frame()
3468 || self.core.has_paced_mounts()
3469 || (script.is_some() && self.core.has_paced_list_binds()))
3470 {
3471 self.frame_requested = true;
3472 sink.request_frame();
3473 }
3474 }
3475
3476 fn run_on_main_thread(&mut self, sink: &dyn MountSink) {
3479 for task in self.core.take_main_thread_tasks() {
3480 sink.run_on_main_thread(task);
3481 }
3482 }
3483
3484 fn load_fonts(
3487 &mut self,
3488 script: Option<&Script>,
3489 assets: Option<&dyn Assets>,
3490 sink: &dyn MountSink,
3491 ) {
3492 let Some(script) = script else { return };
3493 let mut fonts = Vec::new();
3494 script.take_fonts(&mut fonts);
3495 for uri in fonts {
3496 let result = match assets {
3497 Some(assets) => assets.read(&uri),
3498 None => Err("this host cannot load assets".to_owned()),
3499 }
3500 .and_then(|data| self.core.register_font(&data));
3501 if let Err(err) = result {
3502 script.report(
3503 sink,
3504 AppErrorKind::Asset,
3505 "font failed",
3506 &format!("{uri}: {err}"),
3507 );
3508 }
3509 }
3510 }
3511
3512 fn open_urls(&mut self) -> bool {
3518 self.core.take_url_opens(&mut self.url_opens);
3519 let mut platform = false;
3520 for (id, url) in self.url_opens.drain(..) {
3521 if self.host.open_url(id, url.clone(), &self.net.tx).is_none() {
3522 self.core.open_url_on_platform(id, url);
3523 platform = true;
3524 }
3525 }
3526 platform
3527 }
3528
3529 fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
3530 let start = Instant::now();
3531 let mut merged: Option<MountBatch> = None;
3532 let mut commits = 0;
3533 let mut op_count = 0;
3534 let mut js = std::time::Duration::ZERO;
3535 let mut paced = PacedBinds::default();
3537 self.core.begin_mount_turn();
3539 for _ in 0..MAX_LIST_ROUNDS {
3540 let js_start = Instant::now();
3542 let binds = self.binds.drain(..);
3545 if let Some(script) = script {
3546 script.take_ops(&mut self.ops);
3552 let unapplied = !self.ops.is_empty();
3553 for bind in binds {
3554 script.bind_list(bind.list, &bind.binds);
3555 }
3556 script.take_ops(&mut self.ops);
3557 let mut binds = Vec::new();
3558 while !unapplied && paced.left() && self.core.has_paced_list_binds() {
3559 let start = Instant::now();
3560 let ops = self.ops.len();
3561 self.core.take_paced_list_binds(1, &mut binds);
3562 for bind in binds.drain(..) {
3563 paced.cells += bind.binds.len();
3564 script.bind_list(bind.list, &bind.binds);
3565 }
3566 script.take_ops(&mut self.ops);
3567 paced.ops += self.ops.len() - ops;
3568 paced.time += start.elapsed();
3569 }
3570 } else {
3571 drop(binds);
3572 }
3573 if let Some(script) = script {
3576 script.run_posted();
3577 }
3578 for event in self.events.drain(..) {
3582 match event {
3583 JsEvent::Event(id, event, payload) => {
3584 if matches!(event, EventKind::KeyDown | EventKind::KeyUp) {
3585 dispatch_key(
3586 script,
3587 &mut self.core,
3588 &mut self.key_path,
3589 id,
3590 event,
3591 &payload,
3592 );
3593 } else if !self.core.component_event(id, event, &payload)
3594 && let Some(script) = script
3595 {
3596 script.dispatch_event(id, event, &payload);
3597 }
3598 }
3599 JsEvent::LayoutListener {
3600 host,
3601 id,
3602 listener,
3603 frame,
3604 } => {
3605 self.core.component_layout(host, id, &listener, frame);
3606 }
3607 other => {
3609 if let Some(script) = script {
3610 script.deliver(other);
3611 }
3612 }
3613 }
3614 }
3615 if let Some(script) = script {
3616 script.take_ops(&mut self.ops);
3617 }
3618 js += js_start.elapsed();
3619 op_count += self.ops.len();
3620 let mut ops = self.ops.drain(..);
3623 while let Some(op) = ops.next() {
3624 match self.core.apply(op) {
3625 Ok(()) => {}
3626 Err(err) if err.is_fatal() => {
3627 self.core.discard_ops(ops.by_ref());
3628 let Some(script) = script else { break };
3629 script.stop(match err {
3630 ApplyError::TooManyNodes(max) => {
3631 format!("the app created more than {max} nodes and was stopped")
3632 }
3633 other => {
3634 format!("the app sent an invalid op ({other:?}) and was stopped")
3635 }
3636 });
3637 break;
3638 }
3639 Err(err) => log::error!("invalid op: {err:?}"),
3640 }
3641 }
3642 drop(ops);
3643 release_spare_ops(&mut self.ops);
3644 if let Some(batch) = self.core.commit() {
3645 commits += 1;
3646 match &mut merged {
3647 Some(m) => extend_frame(&mut m.items, batch.items),
3648 None => merged = Some(batch),
3649 }
3650 }
3651 self.core.take_list_binds(&mut self.binds);
3652 self.core.take_events(&mut self.events);
3653 let urls = self.open_urls();
3655 let posted = script.is_some_and(Script::has_posted);
3657 let retheme = match script {
3660 Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
3661 self.js_tokens = self.core.tokens().clone();
3662 script.set_tokens(self.js_tokens.clone());
3663 true
3664 }
3665 _ => false,
3666 };
3667 let relocale = match self.core.take_locale_request() {
3670 Some(locale) => {
3671 self.app_locale = locale;
3672 apply_environment(script, self, self.environment);
3673 true
3674 }
3675 None => false,
3676 };
3677 let more_paced = script.is_some() && paced.left() && self.core.has_paced_list_binds();
3678 let answers = self.core.has_due_answers();
3682 if self.binds.is_empty()
3683 && self.events.is_empty()
3684 && !posted
3685 && !retheme
3686 && !relocale
3687 && !more_paced
3688 && !urls
3689 && !answers
3690 {
3691 break;
3692 }
3693 }
3694 if commits > 1
3695 && let Some(batch) = &mut merged
3696 {
3697 keep_last_sets(&mut batch.items, &mut self.sets_seen);
3698 }
3699 self.committed_since_gc |= op_count > 0;
3700 if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
3701 let c = &mut self.perf_commit;
3702 c.layout += start.elapsed().saturating_sub(js);
3703 c.ops += op_count as u32;
3704 c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
3705 }
3706 if self.trace && (op_count > 0 || merged.is_some()) {
3707 log::info!(
3708 target: "nsh::perf",
3709 "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
3710 start.elapsed().as_micros(),
3711 js.as_micros(),
3712 merged.as_ref().map_or(0, |b| b.items.len()),
3713 self.core.node_count(),
3714 );
3715 }
3716 merged
3717 }
3718}
3719
3720fn insets(env: &Environment) -> EdgeInsets {
3721 env.safe_area
3722}
3723
3724fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::element::Environment {
3726 nsh_core::element::Environment {
3727 window,
3728 horizontal_size_class: env.horizontal_size_class,
3729 vertical_size_class: env.vertical_size_class,
3730 safe_area: insets(env),
3731 title_bar: env.title_bar,
3732 window_state: env.window_state,
3733 keyboard_height: env.keyboard_height,
3734 keyboard_duration: env.keyboard_duration,
3735 dark: env.color_scheme == ColorScheme::Dark,
3736 font_scale: env.font_scale,
3737 reduce_motion: env.reduce_motion,
3738 screen_reader: env.screen_reader,
3739 reads_active_descendants: env.reads_active_descendants,
3740 rtl: env.rtl,
3741 pixel_ratio: env.pixel_ratio,
3742 os: env.os,
3743 platform: env.platform,
3744 os_version: env.os_version,
3745 idiom: env.idiom,
3746 locale: env.locale,
3747 locale_settings: env.locale_settings,
3748 apple_keyboard: env.apple_keyboard,
3749 ctrl_for_command: env.ctrl_for_command,
3750 host: env.host,
3751 lifecycle: env.lifecycle,
3752 wake_count: env.wake_count,
3753 screen_color: env.screen_color,
3754 canvas_render: env.canvas_render,
3755 share: env.share,
3756 auth_session: env.auth_session,
3757 file_requests: env.file_requests,
3758 speech: env.speech,
3759 notifications: env.notifications,
3760 audio: env.audio,
3761 tab_bar: env.tab_bar,
3762 cell: env.cell,
3763 web_input: env.web_input,
3764 web_evaluate: env.web_evaluate,
3765 web_views: env.web_views,
3766 webview_requests: env.webview_requests,
3767 shaders: env.shaders,
3768 }
3769}
3770
3771fn drawn_shaders(env: &mut Environment, unavailable: bool) {
3775 env.shaders &= env.cell.is_none() && !unavailable && !shader::no_gpu();
3776}
3777
3778fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
3780 nsh_core::tailwind::ClassEnvironment {
3781 dark: env.color_scheme == ColorScheme::Dark,
3782 platform: match env.os {
3783 Os::Web => nsh_core::tailwind::Platform::Web,
3784 Os::Android => nsh_core::tailwind::Platform::Android,
3785 _ => nsh_core::tailwind::Platform::Ios,
3786 },
3787 reduce_motion: env.reduce_motion,
3788 pointer: if env.desktop() {
3789 nsh_core::tailwind::Pointer::Fine
3790 } else {
3791 nsh_core::tailwind::Pointer::Coarse
3792 },
3793 terminal: env.idiom == Idiom::Terminal,
3794 }
3795}
3796
3797const WINDOW_SETTLE: Duration = Duration::from_millis(150);
3800
3801#[derive(Default)]
3806struct WindowStateReport {
3807 shown: Option<nsh_core::desktop::WindowState>,
3809 reported: Option<Environment>,
3811 settles: Option<Instant>,
3813}
3814
3815impl WindowStateReport {
3816 fn report(&mut self, mut env: Environment, now: Instant) -> Environment {
3819 let next = env.window_state;
3820 let moving = match (&self.shown, &next) {
3821 (Some(shown), Some(next)) => shown != next && moved_only(shown, next),
3822 _ => false,
3823 };
3824 if moving {
3825 let moved = self.reported.map(|r| r.window_state) != Some(next);
3828 if moved || self.settles.is_none() {
3829 self.settles = Some(now + WINDOW_SETTLE);
3830 }
3831 self.reported = Some(env);
3832 env.window_state = self.shown;
3833 } else {
3834 self.reported = None;
3835 self.settles = None;
3836 self.shown = next;
3837 }
3838 env
3839 }
3840}
3841
3842fn moved_only(
3846 shown: &nsh_core::desktop::WindowState,
3847 next: &nsh_core::desktop::WindowState,
3848) -> bool {
3849 shown.mode == next.mode
3850 && shown.placement.mode == next.placement.mode
3851 && shown.minimized == next.minimized
3852 && shown.visible == next.visible
3853 && shown.focused == next.focused
3854 && shown.display == next.display
3855 && shown.scale_factor == next.scale_factor
3856}
3857
3858fn apply_environment<M: TextEngine>(
3860 script: Option<&Script>,
3861 state: &mut State<M>,
3862 env: Environment,
3863) {
3864 state.environment = env;
3865 let mut env = env;
3866 if let Some(locale) = state.app_locale {
3869 env.locale = locale;
3870 env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
3871 }
3872 state.core.set_font_scale(env.font_scale);
3873 state.core.set_class_environment(class_environment(&env));
3874 state.core.set_safe_area(insets(&env));
3875 let window = env.window;
3876 state.core.set_environment(ui_environment(&env, window));
3877 if let Some(script) = script {
3878 script.set_environment(&env);
3879 }
3880}
3881
3882fn dispatch_key<M: TextEngine>(
3887 script: Option<&Script>,
3888 core: &mut nsh_core::Core<M>,
3889 path: &mut Vec<NodeId>,
3890 id: NodeId,
3891 event: EventKind,
3892 payload: &EventPayload,
3893) {
3894 core.key_path(id, path);
3895 for node in path.iter().copied() {
3896 core.component_event(node, event, payload);
3897 if core.listens(node, event)
3900 && let Some(script) = script
3901 {
3902 script.dispatch_event(node, event, payload);
3903 }
3904 }
3905 path.clear();
3906}
3907
3908fn press_outside<M: TextEngine>(
3912 script: Option<&Script>,
3913 core: &mut nsh_core::Core<M>,
3914 pressed: Vec<(NodeId, EventPayload)>,
3915) {
3916 for (overlay, payload) in pressed {
3917 if !core.component_event(overlay, EventKind::PressOutside, &payload)
3918 && let Some(script) = script
3919 {
3920 script.dispatch_event(overlay, EventKind::PressOutside, &payload);
3921 }
3922 }
3923}
3924
3925fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
3927 match message {
3928 Message::Event(id, event, mut payload) => {
3929 state.events_handled += 1;
3930 if state.trace {
3931 log::info!(target: "nsh::perf", "event {event:?} on view {id}");
3932 }
3933 if event == EventKind::MouseMove {
3939 match state.mouse_moves.iter_mut().find(|(v, _)| *v == id) {
3940 Some((_, pending)) => *pending = payload,
3941 None => state.mouse_moves.push((id, payload)),
3942 }
3943 return true;
3944 }
3945 if !matches!(&payload, EventPayload::Touch(t) if t.phase == nsh_core::TouchPhase::Move)
3946 {
3947 state.dispatch_mouse_moves(script);
3948 }
3949 if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
3952 state.core.input_changed(id, text, *count);
3953 }
3954 if event == EventKind::CaretMove {
3957 state.core.locate_caret(id, &mut payload);
3958 }
3959 if event == EventKind::SelectionChange {
3960 state.core.locate_selection(id, &mut payload);
3961 }
3962 if event == EventKind::Paste {
3963 payload = payload.into_paste();
3964 }
3965 if let EventPayload::ContextMenu(menu) = &payload {
3970 let pressed = state.core.context_menu_presses_outside(id, menu);
3971 press_outside(script, &mut state.core, pressed);
3972 }
3973 if matches!(event, EventKind::KeyDown | EventKind::KeyUp) {
3977 dispatch_key(
3978 script,
3979 &mut state.core,
3980 &mut state.key_path,
3981 id,
3982 event,
3983 &payload,
3984 );
3985 return true;
3986 }
3987 if state.core.component_event(id, event, &payload) {
3989 return true;
3990 }
3991 if let EventPayload::Touch(touch) = payload {
3992 if touch.phase == nsh_core::TouchPhase::Move {
3993 match &mut state.touch_move {
3994 Some((_, pending)) => pending.merge_move(*touch),
3995 None => state.touch_move = Some((id, touch)),
3996 }
3997 return true;
3998 }
3999 state.dispatch_touch_move(script);
4001 if let Some(script) = script {
4002 script.dispatch_event(id, event, &EventPayload::Touch(touch));
4003 }
4004 return true;
4005 }
4006 let Some(script) = script else { return true };
4007 let start = state.trace.then(Instant::now);
4008 script.dispatch_event(id, event, &payload);
4009 if let Some(start) = start {
4010 log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
4013 }
4014 }
4015 Message::Scroll(id, offset, applied) => {
4016 state.core.set_scroll_offset(id, offset, applied);
4017 let (x, y) = (offset.x.0, offset.y.0);
4018 if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
4019 let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
4020 x,
4021 y,
4022 content,
4023 viewport,
4024 zoom,
4025 throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
4026 last: None,
4027 pending: true,
4028 });
4029 (event.x, event.y, event.content, event.viewport, event.zoom) =
4030 (x, y, content, viewport, zoom);
4031 event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
4032 event.pending = true;
4033 }
4034 }
4035 Message::KeyScrolled(id, key_move) => state.core.key_scrolled(id, key_move),
4036 Message::Kept(nodes) => state.core.set_kept(&nodes),
4037 Message::ContentCulling(enabled) => {
4038 state.core.set_content_culling(enabled);
4039 if let Some(script) = script {
4040 script.set_lazy_rows(enabled);
4041 }
4042 }
4043 Message::InputScroll(id, offset, content, viewport) => {
4044 state.core.set_input_scroll(id, offset, content, viewport);
4045 }
4046 Message::InputComposing(id, shown) => state.core.input_composing(id, shown.as_deref()),
4047 Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
4048 Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
4049 Message::AnimationsFinished(mut finished) => {
4050 state.core.animations_finished(&mut finished);
4052 if let Some(script) = script {
4053 script.animations_finished(&finished);
4054 }
4055 }
4056 Message::Resize(size) => {
4057 if !nsh_core::time::manual() {
4060 let now = nsh_core::time::now();
4061 if state.resize_burst_ends.is_some_and(|ends| now < ends) {
4062 state.core.set_resizing(true);
4063 }
4064 state.resize_burst_ends = Some(now + RESIZE_BURST_GAP);
4065 }
4066 state.core.set_viewport(size);
4067 state.resized = Some(size);
4068 }
4069 Message::Wake => {}
4070 Message::Environment(mut env) => {
4071 state.pinned.apply(&mut env);
4072 drawn_shaders(&mut env, state.shaders_unavailable);
4073 let env = state.window_state.report(*env, nsh_core::time::now());
4074 apply_environment(script, state, env);
4075 }
4076 Message::ShadersUnavailable => {
4077 state.shaders_unavailable = true;
4078 if state.environment.shaders {
4079 let env = Environment {
4080 shaders: false,
4081 ..state.environment
4082 };
4083 apply_environment(script, state, env);
4084 }
4085 }
4086 Message::Displays(displays) => {
4087 state.core.set_displays(displays.clone());
4088 if let Some(script) = script {
4089 script.set_displays(&displays);
4090 }
4091 }
4092 Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
4093 Message::OverlayArea(area) => state.core.set_overlay_area(area),
4094 Message::PressBeyondRoot(page) => {
4095 let pressed = state.core.presses_beyond_root(page);
4096 press_outside(script, &mut state.core, pressed);
4097 }
4098 Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
4099 Message::Frame => {
4100 state.frame_requested = false;
4101 state.core.run_frame(nsh_core::time::now());
4102 if let Some(script) = script {
4103 script.run_frame();
4104 }
4105 }
4106 Message::States(id, states) => state.core.set_states(id, states),
4107 Message::Modality(modality) => state.core.set_input_modality(modality),
4108 Message::FontsChanged => state.core.fonts_changed(),
4109 Message::Remount => state.core.remount(),
4110 Message::Fetch(who, hop, event) => match (who, state.net.event(who, hop, event)) {
4111 (_, None) => {}
4112 (Requester::Js(id), Some(event)) => {
4113 if let Some(script) = script {
4114 match event {
4115 Ok(event) => script.fetch_event(id, event),
4116 Err(refused) => script.fetch_refused(id, &refused.message, &refused.url),
4117 }
4118 }
4119 }
4120 (Requester::Task(id), Some(Ok(event))) => {
4121 if !state.core.fetch_event(id, event) {
4122 state.net.cancel(who);
4123 }
4124 }
4125 (Requester::Task(id), Some(Err(refused))) => {
4128 state.core.fetch_refused(id, refused.message, refused.url)
4129 }
4130 },
4131 Message::AssetRead(who, hop, request, read) => {
4132 state.net.asset_read(who, hop, request, read)
4133 }
4134 Message::Hot(update) => state.hot.push(update),
4135 Message::Chunk(chunk) => {
4136 if let Some(script) = script {
4137 script.chunk(chunk);
4138 }
4139 }
4140 Message::Perf(monitor) => {
4141 state.core.set_perf_monitor(monitor.is_some());
4142 if let Some(script) = script {
4143 script.set_fps_enabled(monitor.is_some());
4144 }
4145 state.perf_stats_at = monitor
4147 .as_ref()
4148 .map(|_| Instant::now() + PERF_STATS_INTERVAL);
4149 if monitor.is_none() {
4150 state.core.set_perf_stats(None);
4151 if let Some(script) = script {
4152 script.set_perf_stats(None);
4153 }
4154 }
4155 state.perf = monitor;
4156 state.perf_commit = perf::CommitTiming::default();
4157 }
4158 Message::Tokens(tokens) => {
4159 state.core.set_host_tokens(tokens.map(|t| *t));
4160 if let Some(script) = script {
4161 script.set_theme_tokens(state.core.theme_tokens());
4162 }
4163 }
4164 Message::HostFont(data) => {
4165 if let Err(err) = state.core.register_font(&data) {
4166 log::error!("font failed: {err}");
4167 }
4168 }
4169 Message::HostEvent(name, data) => {
4171 if let Some(script) = script {
4172 script.host_event(&name, data);
4173 }
4174 }
4175 Message::HostReply(id, result) => {
4176 if let Some(script) = script {
4177 script.host_reply(id, result);
4178 }
4179 }
4180 Message::UrlHandled { id, url, handled } => {
4181 if handled {
4182 state.core.answer_open_url(id, true);
4183 } else {
4184 state.core.open_url_on_platform(id, url);
4185 }
4186 }
4187 Message::Advance(..) | Message::Flush(..) => unreachable!("the driver moves the clock"),
4190 Message::Shutdown => return false,
4191 }
4192 true
4193}
4194
4195#[derive(Default)]
4197struct PacedBinds {
4198 cells: usize,
4199 ops: usize,
4200 time: std::time::Duration,
4201}
4202
4203impl PacedBinds {
4204 fn left(&self) -> bool {
4207 self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
4208 }
4209}
4210
4211fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
4217 use nsh_core::MountItem;
4218 let start = frame.len();
4219 frame.extend(items);
4220 for k in start..frame.len() {
4221 let MountItem::ScrollContent { id, size } = frame[k] else {
4222 continue;
4223 };
4224 let earlier = frame[..k].iter().rposition(|m| {
4225 matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
4226 });
4227 if let Some(j) = earlier
4228 && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
4229 {
4230 *s = size;
4231 }
4232 }
4233}
4234
4235fn keep_last_sets(
4244 frame: &mut Vec<nsh_core::MountItem>,
4245 last: &mut FxHashMap<(u8, NodeId, u32), usize>,
4246) {
4247 last.clear();
4248 let mut repeated = false;
4249 let mut run = 0;
4250 for (k, item) in frame.iter().enumerate() {
4251 run += matches!(item, nsh_core::MountItem::LayoutAnimation(_)) as u32;
4252 if let Some(key) = sets_whole(item, run) {
4253 repeated |= last.insert(key, k).is_some();
4254 }
4255 }
4256 if !repeated {
4257 return;
4258 }
4259 let (mut k, mut run) = (0, 0);
4260 frame.retain(|item| {
4261 k += 1;
4262 run += matches!(item, nsh_core::MountItem::LayoutAnimation(_)) as u32;
4263 sets_whole(item, run).is_none_or(|key| last[&key] == k - 1)
4264 });
4265}
4266
4267fn sets_whole(item: &nsh_core::MountItem, run: u32) -> Option<(u8, nsh_core::NodeId, u32)> {
4271 use nsh_core::MountItem;
4272 Some(match *item {
4273 MountItem::Frame { id, .. } => (0, id, run),
4274 MountItem::Overflow { id, .. } => (1, id, 0),
4275 MountItem::ViewStyle { id, .. } => (2, id, 0),
4276 MountItem::Text { id, .. } => (3, id, 0),
4277 MountItem::Events { id, .. } => (4, id, 0),
4278 MountItem::Image { id, .. } => (5, id, 0),
4279 _ => return None,
4280 })
4281}
4282
4283const RETAINED_OPS: usize = 16 * 1024;
4285
4286fn release_spare_ops(ops: &mut Vec<Op>) {
4291 debug_assert!(ops.is_empty());
4292 if ops.capacity() > RETAINED_OPS {
4293 ops.shrink_to(RETAINED_OPS);
4294 }
4295}
4296
4297fn app_access(app: &App) -> Access {
4301 match app {
4302 App::Js(bundle) => bundle.policy.access(),
4303 App::Rust(root) => Policy {
4304 declared: root.capabilities_ref().cloned(),
4305 ..Policy::default()
4306 }
4307 .access(),
4308 }
4309}
4310
4311fn media_files(config: &EngineConfig, access: &Access) -> nsh_core::access::MediaFiles {
4314 match &config.app {
4315 App::Js(bundle) => nsh_core::access::MediaFiles::new(
4316 access,
4317 data_dir(config).as_deref(),
4318 &bundle_system_paths(bundle),
4319 nsh_core::access::native_files(config.environment.os),
4320 ),
4321 App::Rust(root) if root.capabilities_ref().is_some() => nsh_core::access::MediaFiles::new(
4322 access,
4323 data_dir(config).as_deref(),
4324 &system_paths(nsh_core::access::TrustedPaths::default(), false),
4325 nsh_core::access::native_files(config.environment.os),
4326 ),
4327 App::Rust(_) => nsh_core::access::MediaFiles::default(),
4328 }
4329}
4330
4331#[cfg(test)]
4332mod tests {
4333 #[cfg(feature = "js-core")]
4334 #[test]
4335 fn an_apps_directory_is_its_own_or_the_one_named_by_its_id() {
4336 let app = || super::Bundle::source(String::new()).with_app_id(Some("com.a"));
4337 let mut config = super::EngineConfig::new(app());
4338 assert_eq!(super::data_dir(&config), None);
4339 config.support_dir = Some("/data".into());
4340 assert_eq!(
4341 super::data_dir(&config),
4342 Some(std::path::Path::new("/data").join("com.a"))
4343 );
4344 config.data_dir = Some("/home/a/.myapp".into());
4347 assert_eq!(super::data_dir(&config), Some("/home/a/.myapp".into()));
4348 config.app = app().with_app_id(Some("com.b")).into();
4349 assert_eq!(super::data_dir(&config), Some("/home/a/.myapp".into()));
4350 config.data_dir = None;
4351 assert_eq!(
4352 super::data_dir(&config),
4353 Some(std::path::Path::new("/data").join("com.b"))
4354 );
4355 config.support_dir = None;
4356 assert_eq!(super::data_dir(&config), None);
4357 }
4358
4359 #[test]
4360 fn an_emptied_op_buffer_gives_back_what_a_large_commit_grew() {
4361 let mut ops: Vec<super::Op> = Vec::with_capacity(super::RETAINED_OPS * 8);
4362 super::release_spare_ops(&mut ops);
4363 assert!(ops.capacity() <= super::RETAINED_OPS);
4364 let mut ops: Vec<super::Op> = Vec::with_capacity(1024);
4366 super::release_spare_ops(&mut ops);
4367 assert_eq!(ops.capacity(), 1024);
4368 }
4369
4370 #[test]
4371 fn moves_settle_and_changes_of_mode_do_not() {
4372 use nsh_core::{
4373 desktop::{DisplayId, WindowMode, WindowPlacement, WindowState},
4374 geometry::{Bounds, point, px, size},
4375 };
4376 let rect = |x: f32| Bounds::new(point(px(x), px(0.0)), size(px(800.0), px(600.0)));
4377 let a = WindowState::new(
4378 rect(0.0),
4379 WindowPlacement::new(WindowMode::Normal, rect(0.0)),
4380 );
4381 let mut moved = a;
4382 moved.bounds = rect(10.0);
4383 moved.placement = WindowPlacement::new(WindowMode::Normal, rect(10.0));
4384 assert!(super::moved_only(&a, &moved));
4385 let mut maximized = a;
4386 maximized.mode = WindowMode::Maximized;
4387 maximized.placement = WindowPlacement::new(WindowMode::Maximized, rect(0.0));
4388 assert!(!super::moved_only(&a, &maximized));
4389 let mut minimized = a;
4390 minimized.minimized = true;
4391 assert!(!super::moved_only(&a, &minimized));
4392 let mut hidden = a;
4393 hidden.visible = false;
4394 assert!(!super::moved_only(&a, &hidden));
4395 let mut elsewhere = a;
4396 elsewhere.display = Some(DisplayId(2));
4397 assert!(!super::moved_only(&a, &elsewhere));
4398 }
4399
4400 #[test]
4401 fn pinned_values_hold_whatever_the_platform_reports() {
4402 let pins = super::EnvironmentPins {
4403 locale: nsh_core::platform::Locale::parse("de-DE"),
4404 reduce_motion: Some(true),
4405 ..Default::default()
4406 };
4407 let mut reported = super::Environment {
4408 locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
4409 font_scale: 1.5,
4410 ..Default::default()
4411 };
4412 pins.apply(&mut reported);
4413 assert_eq!(reported.locale.as_str(), "de-DE");
4414 assert!(reported.reduce_motion);
4415 assert_eq!(reported.font_scale, 1.5);
4417 assert_eq!(reported.safe_area, Default::default());
4418 }
4419
4420 #[test]
4421 fn bundle_default_has_no_application_selected_path_anchors() {
4422 let bundle = super::Bundle::default();
4423 assert!(bundle.system_paths.plugin_dir.is_none());
4424 assert!(bundle.system_paths.home_dir.is_none());
4425 assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
4426 }
4427
4428 #[test]
4429 fn bundle_trusted_paths_reject_relative_and_missing_directories() {
4430 let mut paths = nsh_core::access::TrustedPaths::default();
4431 paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
4432 paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
4433 let bundle = super::Bundle::default().with_system_paths(paths);
4434 assert!(bundle.system_paths.plugin_dir.is_none());
4435 assert!(bundle.system_paths.home_dir.is_none());
4436 assert!(
4437 super::trusted_directory(Some(std::path::PathBuf::from(
4438 "/nsh-nonexistent-anchor-never-created"
4439 )))
4440 .is_none()
4441 );
4442 }
4443
4444 #[test]
4445 fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
4446 let root = std::env::var_os("TMPDIR")
4447 .map(std::path::PathBuf::from)
4448 .unwrap_or_else(|| {
4449 std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
4450 .join(".cache/nsh-benchs-test-tmp")
4451 });
4452 assert!(root.is_absolute() && !root.starts_with("/tmp"));
4453 let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
4454 std::fs::create_dir_all(&directory).unwrap();
4455 let path = directory.join("bundle.js");
4456 std::fs::write(&path, "export default null;").unwrap();
4457 let bundle = super::Bundle::read(&path).unwrap();
4458 assert_eq!(
4459 bundle.system_paths.plugin_dir,
4460 Some(nsh_core::access::canonicalize(&directory).unwrap())
4461 );
4462 assert!(bundle.system_paths.home_dir.is_none());
4463 std::fs::remove_dir_all(directory).unwrap();
4464 }
4465
4466 #[test]
4467 fn rust_environment_preserves_native_title_bar_insets() {
4468 use super::{Edges, Points};
4469 let title_bar = Edges {
4470 top: Points(42.0),
4471 left: Points(78.0),
4472 right: Points(138.0),
4473 bottom: Points(0.0),
4474 };
4475 let environment = super::Environment {
4476 title_bar,
4477 ..Default::default()
4478 };
4479 assert_eq!(
4480 super::ui_environment(
4481 &environment,
4482 nsh_core::Size::new(Points(840.0), Points(630.0))
4483 )
4484 .title_bar,
4485 title_bar
4486 );
4487 }
4488
4489 use nsh_core::{MountItem, Points, Size};
4490
4491 #[test]
4492 fn a_frame_sends_a_scroll_views_last_content_size() {
4493 let content = |height| MountItem::ScrollContent {
4494 id: 2,
4495 size: Size::new(Points(390.0), height),
4496 };
4497 let heights = |frame: &[MountItem]| -> Vec<f32> {
4498 frame
4499 .iter()
4500 .filter_map(|m| match m {
4501 MountItem::ScrollContent { size, .. } => Some(size.height.0),
4502 _ => None,
4503 })
4504 .collect()
4505 };
4506 let mut frame = vec![content(Points(313.0))];
4507 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
4508 assert_eq!(heights(&frame), [544.0, 544.0]);
4509 let mut frame = vec![
4511 content(Points(313.0)),
4512 MountItem::ScrollBy {
4513 id: 2,
4514 dx: Points(0.0),
4515 dy: Points(10.0),
4516 },
4517 ];
4518 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
4519 assert_eq!(heights(&frame), [313.0, 544.0]);
4520 }
4521
4522 #[test]
4523 fn a_frame_sends_a_views_last_frame_once() {
4524 use nsh_core::{Bounds, Point};
4525 let at = |id, y| MountItem::Frame {
4526 id,
4527 frame: Bounds::new(
4528 Point::new(Points(0.0), Points(y)),
4529 Size::new(Points(10.0), Points(10.0)),
4530 ),
4531 };
4532 let mut frame = vec![
4533 MountItem::Create {
4534 id: 4,
4535 kind: nsh_core::ViewKind::View,
4536 },
4537 at(4, 0.0),
4538 at(6, 0.0),
4539 ];
4540 super::extend_frame(&mut frame, vec![at(4, 50.0)]);
4541 super::keep_last_sets(&mut frame, &mut Default::default());
4542 assert!(matches!(frame[0], MountItem::Create { id: 4, .. }));
4543 let frames: Vec<_> = frame
4544 .iter()
4545 .filter_map(|m| match m {
4546 MountItem::Frame { id, frame } => Some((*id, frame.origin.y.0)),
4547 _ => None,
4548 })
4549 .collect();
4550 assert_eq!(frames, [(6, 0.0), (4, 50.0)]);
4551
4552 let animation = |update| {
4555 MountItem::LayoutAnimation(nsh_core::LayoutAnimation {
4556 update,
4557 ..Default::default()
4558 })
4559 };
4560 let eased = nsh_core::LayoutAnimation::EASE_IN_EASE_OUT.update;
4561 let mut frame = vec![animation(None), at(4, 50.0), animation(eased), at(4, 0.0)];
4562 super::extend_frame(&mut frame, vec![at(4, 20.0)]);
4563 super::keep_last_sets(&mut frame, &mut Default::default());
4564 let frames: Vec<_> = frame
4565 .iter()
4566 .filter_map(|m| match m {
4567 MountItem::Frame { frame, .. } => Some(frame.origin.y.0),
4568 _ => None,
4569 })
4570 .collect();
4571 assert_eq!(frames, [50.0, 20.0]);
4572 }
4573}
4574
4575#[cfg(test)]
4576mod download_cleanup_tests {
4577 use super::*;
4581
4582 #[test]
4583 fn an_end_queued_into_a_dead_engine_cleans_its_staging_only() {
4584 let dir = std::env::temp_dir().join(format!(
4585 "nsh-engine-download-cleanup-{}",
4586 std::process::id()
4587 ));
4588 let _ = std::fs::remove_dir_all(&dir);
4589 std::fs::create_dir_all(&dir).unwrap();
4590 let leaf = dir.join("out.bin");
4591 std::fs::write(&leaf, b"partial").unwrap();
4592
4593 let cleanup = nsh_core::webview::DownloadCleanup::new();
4594 cleanup.register_staging(7, "d1", dir.clone(), leaf.clone());
4595
4596 let (tx, rx) = crossbeam_channel::unbounded();
4597 let control = EngineControl {
4598 tx,
4599 modality: Arc::default(),
4600 downloads: cleanup.clone(),
4601 };
4602 drop(rx);
4603
4604 control.dispatch_event(
4605 7,
4606 EventKind::DownloadEnd,
4607 nsh_core::webview::download_end(&nsh_core::webview::DownloadEnd {
4608 id: "d1".into(),
4609 outcome: nsh_core::webview::DownloadOutcome::Finished { bytes: 3 },
4610 }),
4611 );
4612 cleanup.close();
4614
4615 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
4616 while dir.exists() {
4617 assert!(
4618 std::time::Instant::now() < deadline,
4619 "the dead engine's staging directory was not cleaned"
4620 );
4621 std::thread::sleep(std::time::Duration::from_millis(2));
4622 }
4623 }
4624}