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(feature = "net")]
22pub mod net;
23pub mod perf;
24mod script;
25#[cfg_attr(not(feature = "shader"), path = "shader_off.rs")]
26pub mod shader;
27mod shader_frame;
28#[cfg(all(feature = "shader", target_vendor = "apple"))]
29mod shader_surfaces;
30#[cfg(not(target_arch = "wasm32"))]
31mod storage;
32#[cfg(feature = "js-core")]
33mod symbolicate;
34#[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
35pub mod updates;
36
37#[cfg(test)]
40#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
41mod unit_scan;
42
43#[cfg(test)]
44#[test]
45fn public_api_is_typed() {
46 unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
47}
48
49use std::{io, mem::ManuallyDrop, rc::Rc, sync::Arc, time::Duration};
50
51pub use app_directory::app_dir_name;
52use crossbeam_channel::{Receiver, Sender};
53pub use local_storage::local_storage_prefix;
54use nsh_core::{
55 ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
56 PayloadValue, TextEngine, element::JsEvent, platform::content_type, time::Instant,
57};
58pub use nsh_core::{
59 JsonValue,
60 access::{Access, Capabilities},
61 element::{EngineContext, Root, Tokens},
62 geometry::{self, Bounds, Edges, Point, Points, Size},
63 js::{HostLimits, Limits},
64 main_thread::MainThreadTask,
65 platform::{
66 ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HourCycle, HttpBody,
67 HttpHead, HttpRequest, Idiom, Languages, Lifecycle, Locale, LocaleSettings,
68 MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday,
69 },
70 storage::{StorageBackend, StorageChange},
71 time::Clock,
72};
73#[cfg(feature = "js-core")]
74pub use nsh_js::BYTECODE_VERSION;
75#[cfg(feature = "js-core")]
77pub use nsh_package as package;
78use rustc_hash::FxHashMap;
79#[cfg(not(target_arch = "wasm32"))]
80pub use storage::{FileStorage, data_dir};
81
82use crate::script::{NetworkQueue, RequestId, Script};
83pub use crate::{
84 cache::{ByteSize, CacheLocation, CacheOptions, CachePolicy},
85 error::{AppError, AppErrorKind, PackageInfo},
86 host_channel::{HostCall, HostChannel, HostReply, OpenUrlRequest},
87};
88
89#[cfg(not(target_arch = "wasm32"))]
90const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
94
95const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
99
100const IDLE_GC_QUIET: Duration = Duration::from_millis(300);
107
108const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);
110
111const MOUSE_MOVE_INTERVAL: Duration = Duration::from_millis(8);
115
116#[derive(Debug, Clone)]
118#[allow(
119 clippy::large_enum_variant,
120 reason = "one app per surface; keep the public constructor API without allocation"
121)]
122pub enum App {
123 Rust(Root),
125 Js(Bundle),
127}
128
129impl From<Bundle> for App {
130 fn from(bundle: Bundle) -> Self {
131 App::Js(bundle)
132 }
133}
134
135impl App {
136 pub fn app_id(&self) -> Option<&str> {
138 match self {
139 App::Rust(root) => root.app_id_ref(),
140 App::Js(bundle) => bundle.app_id.as_deref(),
141 }
142 }
143
144 pub fn main_window(&self) -> Option<&nsh_core::desktop::MainWindowOptions> {
149 match self {
150 App::Rust(root) => root.main_window_ref(),
151 App::Js(bundle) => bundle.main_window.as_ref(),
152 }
153 }
154
155 pub fn url_schemes(&self) -> &[String] {
158 match self {
159 App::Rust(root) => root.url_schemes_ref(),
160 App::Js(bundle) => &bundle.url_schemes,
161 }
162 }
163}
164
165impl From<Root> for App {
166 fn from(root: Root) -> Self {
167 App::Rust(root)
168 }
169}
170
171#[derive(Debug, Clone)]
173#[non_exhaustive]
174pub struct Bundle {
175 pub code: BundleCode,
177 pub source_map: Option<Arc<str>>,
179 pub policy: Policy,
181 pub base_url: Option<Arc<str>>,
184 pub chunks: Arc<Vec<Chunk>>,
188 pub app_id: Option<String>,
191 pub url_schemes: Vec<String>,
196 pub system_paths: nsh_core::access::TrustedPaths,
200 pub package: Option<Arc<PackageInfo>>,
203 pub updater_config: Option<Arc<[u8]>>,
209 pub trial: Option<Arc<dyn Trial>>,
213 pub main_window: Option<nsh_core::desktop::MainWindowOptions>,
218}
219
220pub const TRIAL_PERIOD: Duration = Duration::from_secs(10);
223
224pub trait Trial: Send + Sync + std::fmt::Debug + 'static {
228 fn healthy(&self);
231 fn failed(&self, error: &AppError);
233}
234
235#[derive(Debug, Clone)]
238pub struct Chunk {
239 pub id: String,
241 pub code: BundleCode,
243 pub source_map: Option<Arc<str>>,
245}
246
247impl Chunk {
248 pub fn source(id: impl Into<String>, code: String) -> Self {
250 Self {
251 id: id.into(),
252 code: BundleCode::Source(code),
253 source_map: None,
254 }
255 }
256
257 pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
263 Self {
264 id: id.into(),
265 code: BundleCode::Bytecode(bytes),
266 source_map: None,
267 }
268 }
269
270 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
272 self.source_map = Some(map.into());
273 self
274 }
275}
276
277#[derive(Debug, Clone)]
279pub struct Policy {
280 pub harden: bool,
284 pub declared: Option<Capabilities>,
287 pub granted: Option<Capabilities>,
290}
291
292impl Default for Policy {
293 fn default() -> Self {
294 Self {
295 harden: true,
296 declared: None,
297 granted: None,
298 }
299 }
300}
301
302impl Policy {
303 pub fn development() -> Self {
307 Self {
308 harden: false,
309 ..Self::default()
310 }
311 }
312
313 pub fn access(&self) -> Access {
315 Access {
316 declared: self.declared.clone().unwrap_or_else(Capabilities::all),
317 granted: self.granted.clone(),
318 }
319 }
320}
321
322#[derive(Debug, Clone)]
324pub enum BundleCode {
325 Bytecode(Vec<u8>),
327 Source(String),
329}
330
331impl Default for Bundle {
332 fn default() -> Self {
333 Self::source(String::new())
334 }
335}
336
337impl Bundle {
338 pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
348 Self {
349 code: BundleCode::Bytecode(bytes),
350 source_map: None,
351 policy: Policy::default(),
352 base_url: None,
353 chunks: Arc::default(),
354 app_id: None,
355 url_schemes: Vec::new(),
356 system_paths: nsh_core::access::TrustedPaths::default(),
357 package: None,
358 updater_config: None,
359 trial: None,
360 main_window: None,
361 }
362 }
363
364 pub fn source(code: String) -> Self {
366 Self {
367 code: BundleCode::Source(code),
368 source_map: None,
369 policy: Policy::default(),
370 base_url: None,
371 chunks: Arc::default(),
372 app_id: None,
373 url_schemes: Vec::new(),
374 system_paths: nsh_core::access::TrustedPaths::default(),
375 package: None,
376 updater_config: None,
377 trial: None,
378 main_window: None,
379 }
380 }
381
382 pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
387 paths.plugin_dir = trusted_directory(paths.plugin_dir);
388 paths.home_dir = trusted_directory(paths.home_dir);
389 self.system_paths = paths;
390 self
391 }
392
393 pub fn with_app_id(mut self, id: Option<&str>) -> Self {
396 self.app_id = id.map(str::to_owned);
397 self
398 }
399
400 pub fn with_main_window(mut self, json: Option<&str>) -> Self {
404 self.main_window = json.and_then(|json| {
405 let parsed = serde_json::from_str(json)
406 .map_err(|e| e.to_string())
407 .and_then(|v| nsh_core::desktop::MainWindowOptions::from_json(&v));
408 parsed.map_err(|e| log::warn!("nsh.json window: {e}")).ok()
409 });
410 self
411 }
412
413 pub fn with_url_schemes(
416 mut self,
417 schemes: impl IntoIterator<Item = impl Into<String>>,
418 ) -> Self {
419 self.url_schemes = schemes.into_iter().map(Into::into).collect();
420 self
421 }
422
423 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
425 self.source_map = Some(map.into());
426 self
427 }
428
429 pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
434 self.base_url = Some(url.into());
435 self
436 }
437
438 pub fn with_policy(mut self, policy: Policy) -> Self {
440 self.policy = policy;
441 self
442 }
443
444 pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
446 Arc::make_mut(&mut self.chunks).extend(chunks);
447 self
448 }
449
450 pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
457 if path.extension().is_some_and(|e| e == "nshc") {
458 return Err(io::Error::other(
459 "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
460 ));
461 }
462 unsafe { Self::read_trusted(path) }
464 }
465
466 pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
473 let bytes = std::fs::read(path)?;
474 let bundle = if path.extension().is_some_and(|e| e == "nshc") {
475 unsafe { Bundle::bytecode(bytes) }
477 } else {
478 Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
479 };
480 let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
481 Ok(map) if !map.is_empty() => bundle.with_source_map(map),
482 _ => bundle,
483 };
484 if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
485 bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
486 }
487 let info = read_app_json(&path.with_file_name("app.json"));
488 bundle.app_id = info
489 .as_ref()
490 .and_then(|info| info.get("id")?.as_str().map(str::to_owned));
491 if let Some(window) = info.as_ref().and_then(|info| info.get("window")) {
492 bundle.main_window = Some(
493 nsh_core::desktop::MainWindowOptions::from_json(window)
494 .map_err(|e| io::Error::other(format!("app.json: {e}")))?,
495 );
496 }
497 if let Some(url_schemes) = info.as_ref().and_then(|info| info.get("schemes")) {
498 let (schemes, ignored) = nsh_core::url_scheme::schemes_from_json_lenient(url_schemes);
500 for what in ignored {
501 log::warn!("app.json: {what}, ignored");
502 }
503 bundle.url_schemes = schemes;
504 }
505 if info
507 .as_ref()
508 .is_some_and(nsh_core::file_type::declares_file_types)
509 {
510 bundle
511 .url_schemes
512 .push(nsh_core::file_type::FILE_SCHEME.to_owned());
513 }
514 bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
515 .parent()
516 .map(std::path::Path::to_path_buf);
517 Ok(bundle)
518 }
519}
520
521#[cfg(feature = "js-core")]
522impl Bundle {
523 pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
529 for ignored in &package.ignored {
530 log::warn!("package {}: ignored {ignored}", package.app.id);
531 }
532 let bundle = match package.bytecode() {
533 Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
536 None => Bundle::source(package.source.clone()),
537 };
538 let mut bundle = match &package.source_map {
539 Some(map) => bundle.with_source_map(map.clone()),
540 None => bundle,
541 };
542 if let Some(json) = &package.capabilities {
543 let (declared, dropped) = Capabilities::from_json_lenient(json)?;
544 for dropped in dropped {
545 log::warn!("package {}: not granted: {dropped}", package.app.id);
546 }
547 bundle.policy.declared = Some(declared);
548 }
549 bundle.app_id = Some(package.app.id.clone());
550 bundle.package = Some(Arc::new(PackageInfo {
551 id: package.app.id.clone(),
552 name: package.app.name.clone(),
553 version: package.app.version.clone(),
554 build: package.app.build,
555 sha256: package.sha256.clone(),
556 }));
557 Ok(bundle)
558 }
559}
560
561fn read_app_json(path: &std::path::Path) -> Option<serde_json::Value> {
564 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
565}
566
567#[cfg(feature = "js-core")]
569#[derive(Debug)]
570pub struct LoadedPackage {
571 pub bundle: Bundle,
573 pub assets: std::path::PathBuf,
575 pub app: nsh_package::App,
577 pub receipt: nsh_package::PackageReceipt,
579}
580
581#[cfg(feature = "js-core")]
586pub fn load_package(
587 trust: &mut nsh_package::TrustStore,
588 bytes: &[u8],
589 assets_root: &std::path::Path,
590) -> Result<LoadedPackage, String> {
591 let package = verify_package(trust, bytes, assets_root)?;
592 accept_package(trust, &package)?;
593 Ok(package)
594}
595
596#[cfg(feature = "js-core")]
604pub fn verify_package(
605 trust: &nsh_package::TrustStore,
606 bytes: &[u8],
607 assets_root: &std::path::Path,
608) -> Result<LoadedPackage, String> {
609 let package = trust
610 .verify(bytes, BYTECODE_VERSION)
611 .map_err(|e| e.to_string())?;
612 let bundle = Bundle::from_package(&package)?;
613 let dir = assets_root.join(&package.app.id).join(&package.sha256);
614 let done = dir.join(".complete");
615 if !done.exists() {
616 let assets = dir.join("assets");
617 for (path, data) in &package.assets {
618 let dest = assets.join(path);
620 if let Some(parent) = dest.parent() {
621 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
622 }
623 std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
624 }
625 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
626 std::fs::write(&done, b"").map_err(|e| e.to_string())?;
627 }
628 Ok(LoadedPackage {
629 bundle,
630 assets: dir.join("assets"),
631 receipt: package.receipt(),
632 app: package.app,
633 })
634}
635
636#[cfg(feature = "js-core")]
641pub fn symbolicate(source_map: &str, text: &str) -> String {
642 symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
643}
644
645#[cfg(feature = "js-core")]
649pub fn accept_package(
650 trust: &mut nsh_package::TrustStore,
651 package: &LoadedPackage,
652) -> Result<(), String> {
653 trust
654 .accept_receipt(&package.receipt)
655 .map_err(|e| e.to_string())
656}
657
658pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
664 let value: serde_json::Value =
665 serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
666 let (capabilities, dropped) = Capabilities::from_json_lenient(&value)?;
667 for dropped in dropped {
668 log::warn!("not granted: {dropped} (unknown to this NSH)");
669 }
670 Ok(capabilities)
671}
672
673impl Bundle {
674 pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
676 self.policy.declared = json.map(parse_capabilities).transpose()?;
677 Ok(self)
678 }
679}
680
681pub trait MountSink: Send + 'static {
684 fn submit(&self, batch: MountBatch);
686
687 fn needs_tree_order(&self) -> bool {
690 false
691 }
692
693 fn needs_projected_states(&self) -> bool {
697 false
698 }
699
700 fn report_error(&self, _message: &str) {}
706
707 fn report(&self, error: &AppError) {
711 self.report_error(&error.to_string());
712 }
713
714 fn request_frame(&self) {}
719
720 fn hot_update_failed(&self) {}
723
724 fn run_on_main_thread(&self, task: MainThreadTask) {
730 task.run();
731 }
732
733 fn resized(&self, _size: Size<Points>) {}
739
740 fn handled(&self, _events: u64) {}
746
747 fn load_chunk(&self, _id: &str) -> bool {
753 false
754 }
755}
756
757pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
761
762pub trait FetchTask: Send {
764 fn send(&mut self, chunk: Vec<u8>);
767 fn finish(&mut self);
769 fn pause(&mut self, paused: bool);
773 fn cancel(self: Box<Self>);
775}
776
777struct UpdaterOverNetwork {
780 network: Arc<dyn Network>,
781 assets: Option<Arc<dyn Assets>>,
782 config: Option<Arc<[u8]>>,
784 running: Option<Arc<PackageInfo>>,
786}
787
788impl UpdaterOverNetwork {
789 #[cfg_attr(
792 not(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32"))),
793 allow(dead_code)
794 )]
795 fn host(
796 network: Option<Arc<dyn Network>>,
797 assets: Option<Arc<dyn Assets>>,
798 bundle: &Bundle,
799 ) -> Option<Arc<dyn nsh_core::runtime::UpdaterHost>> {
800 if assets.is_none() && bundle.updater_config.is_none() {
801 return None;
802 }
803 Some(Arc::new(UpdaterOverNetwork {
804 network: network?,
805 assets,
806 config: bundle.updater_config.clone(),
807 running: bundle.package.clone(),
808 }))
809 }
810}
811
812impl nsh_core::runtime::UpdaterHost for UpdaterOverNetwork {
813 fn config(&self) -> Option<Vec<u8>> {
814 if let Some(config) = &self.config {
815 return Some(config.to_vec());
816 }
817 self.assets.as_ref()?.read("asset:/nsh-updater.json").ok()
819 }
820
821 fn running_package(&self) -> Option<nsh_core::runtime::PackageVersion> {
822 let running = self.running.as_ref()?;
823 let mut version = nsh_core::runtime::PackageVersion::default();
824 version.version = running.version.clone();
825 version.build = running.build;
826 Some(version)
827 }
828
829 fn runs_packages(&self) -> bool {
830 cfg!(all(feature = "js-core", not(target_arch = "wasm32")))
831 }
832
833 #[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
834 fn verify_package(
835 &self,
836 file: &std::path::Path,
837 updates: &std::path::Path,
838 app_id: &str,
839 roots: &[String],
840 newer_than: u64,
841 ) -> Result<nsh_core::runtime::PackageVersion, String> {
842 let app = updates::verify_download(file, updates, app_id, roots, newer_than)?;
843 let mut version = nsh_core::runtime::PackageVersion::default();
844 version.version = app.version;
845 version.build = app.build;
846 Ok(version)
847 }
848
849 fn get(&self, url: &str, sink: nsh_core::runtime::UpdaterSink<'_>) -> Result<(), String> {
850 let (tx, rx) = std::sync::mpsc::channel();
851 let events: FetchEvents = Box::new(move |event| {
852 let _ = tx.send(event);
853 });
854 let task = self.network.fetch(HttpRequest::new("GET", url), events);
855 let mut total = None;
856 let result = loop {
857 match rx.recv() {
858 Ok(FetchEvent::Head(head)) => {
859 if !(200..300).contains(&head.status) {
860 break Err(format!("HTTP {}", head.status));
861 }
862 total = head
863 .headers
864 .iter()
865 .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
866 .and_then(|(_, value)| value.parse().ok());
867 }
868 Ok(FetchEvent::Data(chunk)) => {
869 if let Err(e) = sink(&chunk, total) {
870 break Err(e);
871 }
872 }
873 Ok(FetchEvent::End) => return Ok(()),
874 Ok(FetchEvent::Failed(e)) => break Err(e),
875 Ok(FetchEvent::BodyWanted) => {}
876 Err(_) => break Err("the network stack went away".to_owned()),
877 }
878 };
879 task.cancel();
880 result
881 }
882}
883
884pub trait Network: Send + Sync + 'static {
886 fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
889}
890
891pub trait Assets: Send + Sync + 'static {
896 fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
900
901 fn url(&self, uri: &str) -> Option<String> {
906 let _ = uri;
907 None
908 }
909
910 #[cfg(not(target_arch = "wasm32"))]
917 fn base(&self) -> Option<nsh_core::image::loader::AssetBase> {
918 None
919 }
920}
921
922#[derive(Clone)]
924pub struct EngineConfig {
925 pub app: App,
927 pub viewport: Size<Points>,
929 pub trace: bool,
931 pub content_culling: bool,
935 pub network: Option<Arc<dyn Network>>,
937 pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
939 pub refuse_connections: Option<nsh_core::element::RefuseConnections>,
944 pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
946 pub assets: Option<Arc<dyn Assets>>,
948 pub environment: Environment,
950 pub header_heights: (Points, Points),
953 pub limits: Limits,
955 pub ui_sets: Vec<nsh_core::element::Registry>,
959 pub runtime: Option<tokio::runtime::Handle>,
962 pub data_dir: Option<std::path::PathBuf>,
968 pub cache: CacheOptions,
972 pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
976 pub clock: Clock,
980 pub context: EngineContext,
985 pub pinned: EnvironmentPins,
988 pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
992 pub host: HostChannel,
997 pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
1001 pub speech: Option<Arc<dyn nsh_core::speech::SpeechBackend>>,
1006 pub audio: Option<Arc<dyn nsh_core::audio::AudioBackend>>,
1011 pub windows: Option<Arc<dyn nsh_core::desktop::WindowBackend>>,
1017}
1018
1019#[derive(Debug, Clone, Copy, Default, PartialEq)]
1022#[non_exhaustive]
1023pub struct EnvironmentPins {
1024 pub locale: Option<nsh_core::platform::Locale>,
1026 pub languages: Option<nsh_core::platform::Languages>,
1028 pub hour_cycle: Option<nsh_core::platform::HourCycle>,
1030 pub first_day_of_week: Option<nsh_core::platform::Weekday>,
1032 pub measurement_system: Option<nsh_core::platform::MeasurementSystem>,
1034 pub temperature_unit: Option<nsh_core::platform::TemperatureUnit>,
1036 pub time_zone: Option<nsh_core::platform::TimeZone>,
1038 pub reduce_motion: Option<bool>,
1041 pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
1043}
1044
1045impl EnvironmentPins {
1046 pub fn apply(&self, environment: &mut Environment) {
1048 if let Some(locale) = self.locale {
1049 environment.locale = locale;
1050 }
1051 let settings = &mut environment.locale_settings;
1052 if let Some(languages) = self.languages {
1053 settings.languages = languages;
1054 }
1055 if let Some(time_zone) = self.time_zone {
1056 settings.time_zone = time_zone;
1057 }
1058 if let Some(hour_cycle) = self.hour_cycle {
1059 settings.hour_cycle = hour_cycle;
1060 }
1061 if let Some(day) = self.first_day_of_week {
1062 settings.first_day_of_week = day;
1063 }
1064 if let Some(system) = self.measurement_system {
1065 settings.measurement_system = system;
1066 }
1067 if let Some(unit) = self.temperature_unit {
1068 settings.temperature_unit = unit;
1069 }
1070 if let Some(reduce_motion) = self.reduce_motion {
1071 environment.reduce_motion = reduce_motion;
1072 }
1073 if let Some(safe_area) = self.safe_area {
1074 environment.safe_area = safe_area;
1075 }
1076 }
1077}
1078
1079fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
1080 let path = path.filter(|path| path.is_absolute())?;
1081 nsh_core::access::canonicalize(&path)
1082 .ok()
1083 .filter(|path| path.is_dir())
1084}
1085
1086fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
1089 let mut paths = bundle.system_paths.clone();
1090 paths.plugin_dir = trusted_directory(paths.plugin_dir);
1091 paths.home_dir = trusted_directory(paths.home_dir);
1092 if paths.home_dir.is_none() {
1093 paths.home_dir = ["HOME", "USERPROFILE"]
1094 .into_iter()
1095 .filter_map(std::env::var_os)
1096 .map(std::path::PathBuf::from)
1097 .find_map(|path| trusted_directory(Some(path)));
1098 }
1099 if paths.plugin_dir.is_none() && !bundle.policy.harden {
1103 paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
1104 .map(std::path::PathBuf::from)
1105 .and_then(|path| trusted_directory(Some(path)));
1106 }
1107 paths
1108}
1109
1110impl EngineConfig {
1111 pub fn new(app: impl Into<App>) -> Self {
1118 Self {
1119 app: app.into(),
1120 viewport: Size::new(Points(390.0), Points(844.0)),
1121 trace: false,
1122 content_culling: false,
1123 network: None,
1124 websocket: None,
1125 refuse_connections: None,
1126 filesystem: None,
1127 assets: None,
1128 environment: Environment::default(),
1129 header_heights: (Points(44.0), Points(96.0)),
1130 limits: Limits::default(),
1131 ui_sets: Vec::new(),
1132 runtime: None,
1133 data_dir: None,
1134 cache: CacheOptions::off(),
1135 storage: None,
1136 clock: Clock::system(),
1137 context: EngineContext::default(),
1138 pinned: EnvironmentPins::default(),
1139 clipboard: None,
1140 host: HostChannel::default(),
1141 picker: None,
1142 speech: None,
1143 audio: None,
1144 windows: None,
1145 }
1146 }
1147
1148 pub fn main_window_placement(
1156 &self,
1157 displays: &[nsh_core::desktop::Display],
1158 ) -> Option<nsh_core::desktop::WindowPlacement> {
1159 let options = self.app.main_window()?;
1160 let storage = app_storage(self)?;
1161 options.kept_placement(&*storage, displays)
1162 }
1163}
1164
1165fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
1168 if let Some(storage) = &config.storage {
1169 return Some(storage.clone());
1170 }
1171 #[cfg(not(target_arch = "wasm32"))]
1172 if let Some(root) = &config.data_dir {
1173 let dir = root.join(app_dir_name(config.app.app_id()));
1174 return Some(FileStorage::open(dir));
1175 }
1176 None
1177}
1178
1179#[cfg(not(target_arch = "wasm32"))]
1180fn shared_runtime() -> tokio::runtime::Handle {
1184 static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
1185 RUNTIME
1186 .get_or_init(|| {
1187 tokio::runtime::Builder::new_multi_thread()
1188 .worker_threads(2)
1189 .thread_name("nsh-tasks")
1190 .enable_all()
1191 .build()
1192 .expect("the tasks' runtime starts")
1193 })
1194 .handle()
1195 .clone()
1196}
1197
1198impl std::fmt::Debug for EngineConfig {
1199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1200 f.debug_struct("EngineConfig")
1201 .field("app", &self.app)
1202 .field("viewport", &self.viewport)
1203 .field("trace", &self.trace)
1204 .field("content_culling", &self.content_culling)
1205 .field("network", &self.network.is_some())
1206 .field("assets", &self.assets.is_some())
1207 .field("environment", &self.environment)
1208 .field("header_heights", &self.header_heights)
1209 .field("limits", &self.limits)
1210 .field("ui_sets", &self.ui_sets)
1211 .field("clock", &self.clock)
1212 .field("context", &self.context)
1213 .field("pinned", &self.pinned)
1214 .field("clipboard", &self.clipboard.is_some())
1215 .field("host", &self.host)
1216 .field("picker", &self.picker.is_some())
1217 .field("speech", &self.speech.is_some())
1218 .field("audio", &self.audio.is_some())
1219 .field("windows", &self.windows.is_some())
1220 .finish()
1221 }
1222}
1223
1224const MAX_ADVANCE_ROUNDS: usize = 100_000;
1228
1229const MAX_FLUSH_ROUNDS: usize = 64;
1233
1234enum Message {
1235 Event(NodeId, EventKind, EventPayload),
1236 Scroll(NodeId, Point<Points>, u32),
1237 Kept(Vec<NodeId>),
1238 ContentCulling(bool),
1239 InputScroll(NodeId, Point<Points>, Size<Points>, Size<Points>),
1240 Zoom(NodeId, f32),
1241 ComponentSize(NodeId, Size<Points>),
1242 AnimationsFinished(Vec<nsh_core::animation::Finished>),
1243 Resize(Size<Points>),
1244 Wake,
1246 Environment(Box<Environment>),
1250 ShadersUnavailable,
1253 Displays(Arc<[nsh_core::desktop::Display]>),
1255 RootSize(NodeId, Size<Points>, EdgeInsets),
1256 ScreenHeader(NodeId, Option<Points>),
1257 Frame,
1258 States(NodeId, u16),
1259 Modality(nsh_core::platform::InputModality),
1260 FontsChanged,
1261 Remount,
1262 Fetch(Requester, u64, FetchEvent),
1265 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1268 AssetRead(Requester, u64, HttpRequest, Result<Vec<u8>, String>),
1269 Hot(HotUpdate),
1270 Chunk(Result<Chunk, (String, String)>),
1273 Perf(Option<Arc<perf::PerfMonitor>>),
1274 Tokens(Option<Box<Tokens>>),
1276 HostFont(Vec<u8>),
1279 HostEvent(String, nsh_core::JsonValue),
1282 HostReply(u64, Result<nsh_core::JsonValue, String>),
1284 UrlHandled {
1287 id: u32,
1288 url: String,
1289 handled: bool,
1290 },
1291 Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
1293 Flush(Box<dyn FnOnce(bool) + Send>),
1296 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
1298 Shutdown,
1299}
1300
1301#[derive(Debug, Clone)]
1305pub struct HotUpdate {
1306 pub name: String,
1308 pub code: String,
1310 pub source_map: Option<Arc<str>>,
1312}
1313
1314const MAX_LIST_ROUNDS: usize = 8;
1318
1319const PACED_BIND_OPS: usize = 150;
1326const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);
1328
1329#[derive(Clone)]
1331pub struct EngineControl {
1332 tx: Sender<Message>,
1333 modality: Arc<std::sync::atomic::AtomicU8>,
1336}
1337
1338impl EngineControl {
1339 pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
1341 let _ = self.tx.send(Message::Event(id, event, payload));
1342 }
1343
1344 pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
1350 let _ = self.tx.send(Message::Scroll(id, offset, applied));
1351 }
1352
1353 pub fn keep_rendered(&self, nodes: Vec<NodeId>) {
1357 let _ = self.tx.send(Message::Kept(nodes));
1358 }
1359
1360 pub fn set_content_culling(&self, enabled: bool) {
1365 let _ = self.tx.send(Message::ContentCulling(enabled));
1366 }
1367
1368 pub fn input_scroll(
1373 &self,
1374 id: NodeId,
1375 offset: Point<Points>,
1376 content: Size<Points>,
1377 viewport: Size<Points>,
1378 ) {
1379 let _ = self
1380 .tx
1381 .send(Message::InputScroll(id, offset, content, viewport));
1382 }
1383
1384 pub fn zoom(&self, id: NodeId, scale: f32) {
1387 let _ = self.tx.send(Message::Zoom(id, scale));
1388 }
1389
1390 pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
1393 let _ = self.tx.send(Message::ComponentSize(id, size));
1394 }
1395
1396 pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
1398 let _ = self.tx.send(Message::AnimationsFinished(finished));
1399 }
1400
1401 pub fn resize(&self, size: Size<Points>) {
1403 let _ = self.tx.send(Message::Resize(size));
1404 }
1405
1406 pub fn set_environment(&self, environment: Environment) {
1409 let _ = self.tx.send(Message::Environment(Box::new(environment)));
1410 }
1411
1412 pub fn shaders_unavailable(&self) {
1417 let _ = self.tx.send(Message::ShadersUnavailable);
1418 }
1419
1420 pub fn set_displays(&self, displays: Vec<nsh_core::desktop::Display>) {
1424 let _ = self.tx.send(Message::Displays(displays.into()));
1425 }
1426
1427 pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
1430 let _ = self.tx.send(Message::RootSize(id, size, insets));
1431 }
1432
1433 pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
1436 let _ = self.tx.send(Message::ScreenHeader(id, height));
1437 }
1438
1439 pub fn hot_update(&self, update: HotUpdate) {
1442 let _ = self.tx.send(Message::Hot(update));
1443 }
1444
1445 pub fn chunk_loaded(&self, chunk: Chunk) {
1448 let _ = self.tx.send(Message::Chunk(Ok(chunk)));
1449 }
1450
1451 pub fn chunk_failed(&self, id: String, message: String) {
1454 let _ = self.tx.send(Message::Chunk(Err((id, message))));
1455 }
1456
1457 pub fn frame(&self) {
1460 let _ = self.tx.send(Message::Frame);
1461 }
1462
1463 pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
1470 let _ = self.tx.send(Message::Advance(by, Box::new(done)));
1471 }
1472
1473 pub fn flush(&self, done: impl FnOnce(bool) + Send + 'static) {
1483 let _ = self.tx.send(Message::Flush(Box::new(done)));
1484 }
1485
1486 pub fn set_input_modality(&self, modality: nsh_core::platform::InputModality) {
1493 use std::sync::atomic::Ordering;
1494 let code = match modality {
1495 nsh_core::platform::InputModality::Keyboard => 1,
1496 nsh_core::platform::InputModality::Pointer => 2,
1497 };
1498 if self.modality.swap(code, Ordering::Relaxed) != code {
1499 let _ = self.tx.send(Message::Modality(modality));
1500 }
1501 }
1502
1503 pub fn set_states(&self, id: NodeId, states: u16) {
1508 let _ = self.tx.send(Message::States(id, states));
1509 }
1510
1511 pub fn fonts_changed(&self) {
1515 let _ = self.tx.send(Message::FontsChanged);
1516 }
1517
1518 pub fn remount(&self) {
1522 let _ = self.tx.send(Message::Remount);
1523 }
1524
1525 pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
1528 let _ = self.tx.send(Message::Perf(monitor));
1529 }
1530
1531 pub fn set_tokens(&self, tokens: Option<Tokens>) {
1536 let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1537 }
1538
1539 pub fn register_font(&self, data: Vec<u8>) {
1544 let _ = self.tx.send(Message::HostFont(data));
1545 }
1546}
1547
1548#[cfg(not(target_arch = "wasm32"))]
1549pub struct Engine {
1551 control: EngineControl,
1552 thread: Option<std::thread::JoinHandle<()>>,
1553 host: HostChannel,
1555 stop: Arc<std::sync::atomic::AtomicBool>,
1557 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1560 image_cache: Option<nsh_core::image::DiskCache>,
1562 media_files: Arc<nsh_core::access::MediaFiles>,
1564}
1565
1566#[cfg(not(target_arch = "wasm32"))]
1567impl Engine {
1568 pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
1570 where
1571 M: TextEngine + 'static,
1572 F: FnOnce() -> M + Send + 'static,
1573 S: MountSink,
1574 {
1575 Self::start_with(config, make_text_engine, sink, |_| {})
1576 }
1577
1578 pub fn start_with<M, F, S>(
1582 config: EngineConfig,
1583 make_text_engine: F,
1584 sink: S,
1585 setup: impl FnOnce(&EngineControl),
1586 ) -> io::Result<Engine>
1587 where
1588 M: TextEngine + 'static,
1589 F: FnOnce() -> M + Send + 'static,
1590 S: MountSink,
1591 {
1592 let image_cache = config.cache.open_images(config.app.app_id());
1593 let media_files = Arc::new(media_files(&config, &app_access(&config.app)));
1594 let (tx, rx) = crossbeam_channel::unbounded();
1595 let modality = Arc::default();
1596 setup(&EngineControl {
1597 tx: tx.clone(),
1598 modality: Arc::clone(&modality),
1599 });
1600 let engine_tx = tx.clone();
1601 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1602 let engine_stop = stop.clone();
1603 let quit_listeners = Arc::new(std::sync::atomic::AtomicBool::new(false));
1604 let engine_quit_listeners = quit_listeners.clone();
1605 let host = config.host.clone();
1606 let thread = std::thread::Builder::new()
1607 .name("nsh-engine".into())
1608 .stack_size(ENGINE_STACK_SIZE)
1609 .spawn(move || {
1610 run(
1611 config,
1612 make_text_engine(),
1613 sink,
1614 engine_tx,
1615 rx,
1616 engine_stop,
1617 engine_quit_listeners,
1618 )
1619 })?;
1620 Ok(Engine {
1621 control: EngineControl { tx, modality },
1622 thread: Some(thread),
1623 host,
1624 stop,
1625 quit_listeners,
1626 image_cache,
1627 media_files,
1628 })
1629 }
1630
1631 pub fn media_files(&self) -> Arc<nsh_core::access::MediaFiles> {
1636 self.media_files.clone()
1637 }
1638
1639 pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
1643 self.image_cache.clone()
1644 }
1645
1646 pub fn control(&self) -> EngineControl {
1648 self.control.clone()
1649 }
1650}
1651
1652#[cfg(not(target_arch = "wasm32"))]
1653impl Drop for Engine {
1654 fn drop(&mut self) {
1655 if self
1659 .quit_listeners
1660 .load(std::sync::atomic::Ordering::Relaxed)
1661 {
1662 self.host.request_shutdown(&self.control.tx);
1663 let deadline = Instant::now() + QUIT_TIMEOUT + QUIT_GRACE;
1664 while self.thread.as_ref().is_some_and(|t| !t.is_finished())
1665 && Instant::now() < deadline
1666 {
1667 std::thread::sleep(Duration::from_millis(1));
1668 }
1669 }
1670 self.host.shutdown(&self.control.tx, &self.stop);
1671 if let Some(thread) = self.thread.take() {
1672 let _ = thread.join();
1673 }
1674 }
1675}
1676
1677#[cfg(not(target_arch = "wasm32"))]
1678fn raise_thread_priority() {
1682 #[cfg(target_vendor = "apple")]
1683 unsafe {
1685 libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
1686 }
1687}
1688
1689#[cfg(not(target_arch = "wasm32"))]
1691use nsh_core::element::desktop::QUIT_TIMEOUT;
1692
1693#[cfg(not(target_arch = "wasm32"))]
1696const QUIT_GRACE: Duration = Duration::from_millis(20);
1697
1698const RESIZE_BURST_GAP: Duration = Duration::from_millis(120);
1701
1702#[cfg(not(target_arch = "wasm32"))]
1703fn run<M: TextEngine + 'static, S: MountSink>(
1704 config: EngineConfig,
1705 text_engine: M,
1706 sink: S,
1707 tx: Sender<Message>,
1708 rx: Receiver<Message>,
1709 stop: Arc<std::sync::atomic::AtomicBool>,
1710 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1711) {
1712 raise_thread_priority();
1713 let _clock = config.clock.enter();
1715 let _context = config.context.enter();
1716 let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
1717 return;
1718 };
1719 driver.quit_listeners = quit_listeners;
1720 driver.sync_quit_listeners();
1721 drive(&mut driver, &rx);
1722 driver.quit(&rx);
1723 if let Some(trial) = &driver.trial {
1725 trial.healthy();
1726 }
1727}
1728
1729fn start_trial(trial: Arc<dyn Trial>) {
1732 #[cfg(not(target_arch = "wasm32"))]
1733 {
1734 let spawned = std::thread::Builder::new()
1735 .name("nsh-trial".into())
1736 .spawn(move || {
1737 std::thread::sleep(TRIAL_PERIOD);
1738 trial.healthy();
1739 });
1740 if let Err(err) = spawned {
1741 log::error!("cannot time the app's trial: {err}");
1742 }
1743 }
1744 #[cfg(target_arch = "wasm32")]
1746 drop(trial);
1747}
1748
1749#[cfg(not(target_arch = "wasm32"))]
1751fn drive<M: TextEngine + 'static>(driver: &mut Driver<M>, rx: &Receiver<Message>) {
1752 loop {
1753 let message = match driver.deadline() {
1754 Some(deadline) => match rx.recv_deadline(deadline) {
1755 Ok(message) => Some(message),
1756 Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
1757 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
1758 },
1759 None => match rx.recv() {
1760 Ok(message) => Some(message),
1761 Err(_) => return,
1762 },
1763 };
1764 let started = driver.state.perf.is_some().then(Instant::now);
1765 if let Some(message) = message {
1766 if !driver.handle(message, rx) {
1767 return;
1768 }
1769 while let Ok(message) = rx.try_recv() {
1771 if !driver.handle(message, rx) {
1772 return;
1773 }
1774 }
1775 }
1776 driver.turn();
1777 driver.state.record_perf(started);
1778 if rx.is_empty() {
1779 driver.collect_if_idle();
1780 }
1781 }
1782}
1783
1784pub struct LocalEngine<M: TextEngine + 'static> {
1789 driver: ManuallyDrop<Driver<M>>,
1792 rx: Receiver<Message>,
1793 control: EngineControl,
1794 wake: Option<Arc<dyn Fn() + Send + Sync>>,
1796 pumping: Arc<std::sync::atomic::AtomicBool>,
1799}
1800
1801impl<M: TextEngine + 'static> LocalEngine<M> {
1802 pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
1805 Self::start_with(config, text_engine, sink, |_| {})
1806 }
1807
1808 pub fn start_with<S: MountSink>(
1812 config: EngineConfig,
1813 text_engine: M,
1814 sink: S,
1815 setup: impl FnOnce(&EngineControl),
1816 ) -> Option<Self> {
1817 let (tx, rx) = crossbeam_channel::unbounded();
1818 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1819 let control = EngineControl {
1820 tx: tx.clone(),
1821 modality: Arc::default(),
1822 };
1823 setup(&control);
1824 let _clock = config.clock.enter();
1825 let _context = config.context.enter();
1826 let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
1827 Some(LocalEngine {
1828 driver: ManuallyDrop::new(driver),
1829 rx,
1830 control,
1831 wake: None,
1832 pumping: Arc::default(),
1833 })
1834 }
1835
1836 pub fn control(&self) -> EngineControl {
1838 self.control.clone()
1839 }
1840
1841 pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
1850 let tx = self.control.tx.clone();
1851 let pumping = self.pumping.clone();
1852 let host = wake.clone();
1853 let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
1854 let _ = tx.send(Message::Wake);
1855 if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
1858 host();
1859 }
1860 });
1861 self.driver.state.core.set_task_notify(notify.clone());
1862 self.driver.posts.set_notify(notify);
1863 self.wake = Some(wake);
1864 }
1865
1866 pub fn extend_ui_sets(&mut self, ui_sets: &[nsh_core::element::Registry]) {
1870 let sets: Vec<_> = nsh_core::runtime::registries()
1871 .iter()
1872 .chain(ui_sets)
1873 .cloned()
1874 .collect();
1875 self.driver
1876 .state
1877 .core
1878 .extend_components(nsh_core::element::Registry::merged(&sets));
1879 }
1880
1881 pub fn pump(&mut self) -> Option<Instant> {
1885 let _clock = self.driver.clock.enter();
1886 let _context = self.driver.context.enter();
1887 self.pumping
1888 .store(true, std::sync::atomic::Ordering::SeqCst);
1889 for _ in 0..4 {
1892 let started = self.driver.state.perf.is_some().then(Instant::now);
1893 while let Ok(message) = self.rx.try_recv() {
1894 self.driver.handle(message, &self.rx);
1895 }
1896 self.driver.turn();
1897 self.driver.state.record_perf(started);
1898 if self.rx.is_empty() {
1899 break;
1900 }
1901 }
1902 self.driver.collect_if_idle();
1903 self.pumping
1904 .store(false, std::sync::atomic::Ordering::SeqCst);
1905 if !self.rx.is_empty()
1908 && let Some(wake) = &self.wake
1909 {
1910 wake();
1911 }
1912 self.driver.deadline()
1913 }
1914}
1915
1916impl<M: TextEngine + 'static> Drop for LocalEngine<M> {
1917 fn drop(&mut self) {
1918 let _context = self.driver.context.enter();
1922 unsafe { ManuallyDrop::drop(&mut self.driver) };
1925 }
1926}
1927
1928struct Driver<M: TextEngine + 'static> {
1930 state: State<Rc<M>>,
1931 script: Option<Script>,
1932 sink: Rc<dyn MountSink>,
1933 assets: Option<Arc<dyn Assets>>,
1934 stopped: bool,
1937 last_gc: Instant,
1938 last_active: Instant,
1941 posts: nsh_core::element::Posts,
1944 clock: Clock,
1946 context: EngineContext,
1948 last_frame: Option<Instant>,
1951 _host: host_channel::HostAttachment,
1954 #[cfg(not(target_arch = "wasm32"))]
1958 trial: Option<Arc<dyn Trial>>,
1959 quit_listeners: Arc<std::sync::atomic::AtomicBool>,
1961 quitting: bool,
1964}
1965
1966impl<M: TextEngine + 'static> Driver<M> {
1967 fn start(
1969 mut config: EngineConfig,
1970 text_engine: M,
1971 sink: Rc<dyn MountSink>,
1972 tx: Sender<Message>,
1973 rx: &Receiver<Message>,
1974 stop: Arc<std::sync::atomic::AtomicBool>,
1975 ) -> Option<Self> {
1976 config.pinned.apply(&mut config.environment);
1977 drawn_shaders(&mut config.environment, false);
1978 let trial = match &config.app {
1979 App::Js(bundle) => bundle.trial.clone(),
1980 App::Rust(_) => None,
1981 };
1982 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
1983 let system_tx = tx.clone();
1984 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
1985 let host_bridge = config.host.bridge(tx.clone());
1986 let host_tx = tx.clone();
1987 let text_engine = Rc::new(text_engine);
1988 let access = Arc::new(app_access(&config.app));
1989 let mut core = Core::new(text_engine.clone(), config.viewport);
1990 core.set_content_culling(config.content_culling);
1991 core.set_tree_order_tracking(sink.needs_tree_order());
1992 core.set_projected_state_mounting(sink.needs_projected_states());
1993 let sets: Vec<_> = nsh_core::runtime::registries()
1996 .iter()
1997 .chain(&config.ui_sets)
1998 .cloned()
1999 .collect();
2000 core.set_components(nsh_core::element::Registry::merged(&sets));
2001 let posts = nsh_core::element::Posts::new();
2005 core.set_posts(posts.clone());
2006 if let App::Js(_) = &config.app {
2007 core.set_max_nodes(config.limits.max_nodes);
2009 }
2010 core.set_access(access.clone());
2011 if let App::Js(bundle) = &config.app {
2012 core.set_base_url(bundle.base_url.clone());
2014 }
2015 let media_files = Arc::new(media_files(&config, &access));
2018 core.set_media_files(media_files.clone());
2019 #[cfg(not(target_arch = "wasm32"))]
2020 core.set_image_context(nsh_core::image::loader::Context {
2021 asset_base: config.assets.as_ref().and_then(|a| a.base()),
2022 read_asset: config.assets.clone().map(|assets| {
2023 Arc::new(move |uri: &str| assets.read(uri)) as nsh_core::image::loader::ReadAsset
2024 }),
2025 access: access.clone(),
2026 media_files,
2027 disk: config.cache.open_images(config.app.app_id()),
2029 transport: None,
2031 });
2032 core.set_storage(app_storage(&config));
2033 core.set_data_dir(
2034 config
2035 .data_dir
2036 .as_ref()
2037 .map(|root| root.join(app_dir_name(config.app.app_id()))),
2038 );
2039 core.set_clipboard(config.clipboard.clone());
2040 core.set_picker(config.picker.clone());
2041 core.set_speech(config.speech.clone());
2042 core.set_url_schemes(config.app.url_schemes().iter().cloned());
2043 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2045 let app_url = core.app_url_cell();
2046 core.set_audio(config.audio.clone());
2047 core.set_window_backend(config.windows.clone());
2048 if let Some(window) = config.app.main_window() {
2049 core.set_main_window(window);
2050 }
2051 core.set_font_scale(config.environment.font_scale);
2052 core.set_class_environment(class_environment(&config.environment));
2053 core.set_header_heights(config.header_heights.0, config.header_heights.1);
2054 core.set_safe_area(insets(&config.environment));
2055 core.set_environment(ui_environment(&config.environment, config.viewport));
2056 #[cfg(not(target_arch = "wasm32"))]
2059 let runtime = config.runtime.clone().unwrap_or_else(shared_runtime);
2060 #[cfg(not(target_arch = "wasm32"))]
2061 core.set_task_runtime(runtime.clone());
2062 if let App::Rust(root) = &config.app {
2065 if let Some(tokens) = root.tokens_ref() {
2066 core.set_tokens(tokens.clone());
2067 }
2068 if let Some(appearance) = root.appearance_ref() {
2069 core.set_appearance(appearance);
2070 }
2071 if let Some(translations) = root.translations_ref() {
2072 core.set_translations(translations.clone());
2073 }
2074 for font in root.fonts() {
2075 if let Err(err) = core.register_font(font) {
2076 log::error!("font failed: {err}");
2077 sink.report(&AppError::new(
2078 AppErrorKind::Asset,
2079 &format!("font failed: {err}"),
2080 ));
2081 }
2082 }
2083 }
2084 let fonts = config
2086 .ui_sets
2087 .iter()
2088 .flat_map(nsh_core::element::Registry::asset_files)
2089 .filter(|file| file.kind == nsh_core::element::AssetKind::Font);
2090 for font in fonts {
2091 let result = match config.assets.as_deref() {
2092 Some(assets) => assets.read(font.uri),
2093 None => Err("this host cannot load assets".to_owned()),
2094 }
2095 .and_then(|data| core.register_font(&data));
2096 if let Err(err) = result {
2097 log::error!("font failed: {}: {err}", font.uri);
2098 let message = format!("font failed: {}: {err}", font.uri);
2099 let package = match &config.app {
2100 App::Js(bundle) => bundle.package.clone(),
2101 App::Rust(_) => None,
2102 };
2103 sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
2104 }
2105 }
2106 let wake = tx.clone();
2109 core.set_task_notify(Arc::new(move || {
2110 let _ = wake.send(Message::Wake);
2111 }));
2112 let wake = tx.clone();
2113 posts.set_notify(Arc::new(move || {
2114 let _ = wake.send(Message::Wake);
2115 }));
2116 let mut early = Vec::new();
2123 let mut displays: Arc<[nsh_core::desktop::Display]> = Arc::from(Vec::new());
2124 while let Ok(message) = rx.try_recv() {
2125 match message {
2126 Message::Tokens(tokens) => core.set_host_tokens(tokens.map(|t| *t)),
2127 Message::HostFont(data) => {
2128 if let Err(err) = core.register_font(&data) {
2129 log::error!("font failed: {err}");
2130 }
2131 }
2132 Message::Displays(list) => {
2133 core.set_displays(list.clone());
2134 displays = list;
2135 }
2136 Message::Event(nsh_core::ROOT_ID, EventKind::UrlScheme, payload) => {
2137 core.component_event(nsh_core::ROOT_ID, EventKind::UrlScheme, &payload);
2138 }
2139 message => early.push(message),
2140 }
2141 }
2142 let js_tokens = core.tokens().clone();
2143 let state = State {
2144 core,
2145 js_tokens,
2146 frame_requested: false,
2147 ops: Vec::new(),
2148 binds: Vec::new(),
2149 events: Vec::new(),
2150 trace: config.trace,
2151 perf: None,
2152 perf_commit: perf::CommitTiming::default(),
2153 committed_since_gc: false,
2154 hot: Vec::new(),
2155 scroll_events: FxHashMap::default(),
2156 touch_move: None,
2157 mouse_moves: Vec::new(),
2158 mouse_moved: None,
2159 sets_seen: FxHashMap::default(),
2160 resized: None,
2161 resize_burst_ends: None,
2162 window_state: WindowStateReport {
2163 shown: config.environment.window_state,
2164 ..WindowStateReport::default()
2165 },
2166 events_handled: 0,
2167 events_reported: 0,
2168 pinned: config.pinned,
2169 environment: config.environment,
2170 shaders_unavailable: false,
2171 app_locale: None,
2172 host: config.host.clone(),
2173 url_opens: Vec::new(),
2174 net: Net {
2175 network: config.network.clone(),
2176 tx,
2177 queue: NetworkQueue::default(),
2178 inflight: FxHashMap::default(),
2179 tasks: Vec::new(),
2180 abandoned: Vec::new(),
2181 access: access.clone(),
2182 hops: 0,
2183 assets: config.assets.clone(),
2184 #[cfg(not(target_arch = "wasm32"))]
2185 runtime,
2186 },
2187 };
2188
2189 let mut environment = config.environment;
2190 environment.window = config.viewport;
2191 let start = Instant::now();
2192 let mut driver = Driver {
2193 state,
2194 script: None,
2195 sink: sink.clone(),
2196 assets: config.assets.clone(),
2197 stopped: false,
2198 last_gc: Instant::now(),
2199 last_active: Instant::now(),
2200 posts: posts.clone(),
2201 clock: config.clock.clone(),
2202 context: config.context.clone(),
2203 last_frame: None,
2204 _host: config.host.attach(host_tx, rx.clone()),
2205 #[cfg(not(target_arch = "wasm32"))]
2206 trial: trial.clone(),
2207 quit_listeners: Arc::default(),
2208 quitting: false,
2209 };
2210 let eval_us = match &config.app {
2211 App::Js(bundle) => {
2212 #[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
2213 let system = {
2214 script::SystemConfig {
2215 access: (*access).clone(),
2216 websocket: config.websocket.clone(),
2217 refuse_connections: config.refuse_connections.clone(),
2218 filesystem: config.filesystem.clone(),
2219 updater: UpdaterOverNetwork::host(
2220 config.network.clone(),
2221 config.assets.clone(),
2222 bundle,
2223 ),
2224 app_url: app_url.clone(),
2225 data_dir: config
2226 .data_dir
2227 .as_ref()
2228 .map(|root| root.join(app_dir_name(config.app.app_id()))),
2229 paths: bundle_system_paths(bundle),
2230 wake: Arc::new(move || {
2231 let _ = system_tx.send(Message::Wake);
2232 }),
2233 host: Rc::new(host_bridge),
2234 lazy_rows: config.content_culling,
2235 }
2236 };
2237 #[cfg(not(any(
2238 feature = "js-core",
2239 all(feature = "browser", target_arch = "wasm32")
2240 )))]
2241 let system = script::SystemConfig;
2242 let (script, eval_us) = Script::start(
2243 bundle,
2244 config.limits,
2245 &config.ui_sets,
2246 posts,
2247 &environment,
2248 &displays,
2249 driver.state.js_tokens.clone(),
2250 driver.state.core.theme_tokens(),
2251 text_engine,
2252 stop,
2253 sink,
2254 system,
2255 )?;
2256 driver.script = Some(script);
2257 eval_us
2258 }
2259 App::Rust(root) => {
2260 driver.state.core.mount_root(root);
2261 0
2262 }
2263 };
2264 let Driver {
2265 state,
2266 script,
2267 sink,
2268 assets,
2269 ..
2270 } = &mut driver;
2271 let script = script.as_ref();
2272 let mut moves = Vec::new();
2275 let pending = early
2276 .into_iter()
2277 .chain(std::iter::from_fn(|| rx.try_recv().ok()));
2278 for message in pending {
2279 if let Message::Advance(..) | Message::Flush(..) = message {
2280 moves.push(message);
2281 } else if !handle(script, state, message) {
2282 return None;
2283 }
2284 }
2285 if let Some(script) = script {
2288 script.run_system();
2289 }
2290 state.load_fonts(script, assets.as_deref(), &**sink);
2291 if let Some(batch) = state.commit(script) {
2292 if state.trace {
2293 log::info!(
2294 target: "nsh::perf",
2295 "first frame: eval {eval_us}µs, total {}µs",
2296 start.elapsed().as_micros()
2297 );
2298 }
2299 sink.submit(batch);
2300 }
2301 state.run_on_main_thread(&**sink);
2302 if let Some(trial) = trial {
2303 start_trial(trial);
2304 }
2305 if let Some(size) = state.resized.take() {
2309 sink.resized(size);
2310 }
2311 state.report_handled(&**sink);
2312 state.net.pump(script, &mut state.core);
2313 state.load_chunks(script, &**sink);
2314 state.request_frame(script, &**sink);
2315 driver.check_stopped();
2316 for message in moves {
2317 if !driver.handle(message, rx) {
2318 return None;
2319 }
2320 }
2321 Some(driver)
2322 }
2323
2324 fn deadline(&self) -> Option<Instant> {
2328 let gc_deadline =
2329 (self.script.is_some() && self.state.committed_since_gc).then(|| self.next_gc());
2330 let due = if self.clock.is_manual() {
2331 None
2332 } else {
2333 self.due()
2334 };
2335 [due, gc_deadline].into_iter().flatten().min()
2336 }
2337
2338 fn due(&self) -> Option<Instant> {
2341 [
2342 self.script.as_ref().and_then(Script::next_timer),
2343 self.state.next_scroll_event(),
2344 self.state.next_mouse_move(),
2345 self.state.core.next_task_timer(),
2346 self.state.resize_burst_ends,
2347 self.state.window_state.settles,
2348 ]
2349 .into_iter()
2350 .flatten()
2351 .min()
2352 }
2353
2354 fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
2356 self.last_active = Instant::now();
2357 match message {
2358 Message::Advance(by, done) => {
2359 let running = self.advance(by, rx, self.clock.moves_with_frames());
2360 done();
2361 running
2362 }
2363 Message::Flush(done) => {
2364 let running = self.flush(rx);
2365 done(running && self.idle(rx));
2366 running
2367 }
2368 Message::Frame if self.clock.moves_with_frames() => {
2372 self.state.frame_requested = true;
2375 let by = self.next_frame() - self.clock.now();
2376 self.advance(by, rx, true)
2377 }
2378 message => handle(self.script.as_ref(), &mut self.state, message),
2379 }
2380 }
2381
2382 fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
2390 if !self.clock.is_manual() {
2391 self.turn();
2393 return true;
2394 }
2395 let to = self.clock.now() + by;
2396 for round in 0.. {
2397 let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
2400 let next = [self.due(), self.clock.next_alarm(), frame]
2401 .into_iter()
2402 .flatten()
2403 .min()
2404 .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
2405 if round == MAX_ADVANCE_ROUNDS {
2406 log::warn!(
2407 "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
2408 a timer keeps scheduling another at once"
2409 );
2410 }
2411 let at = next.unwrap_or(to);
2412 self.clock.advance_to(at);
2413 while let Ok(message) = rx.try_recv() {
2414 if !self.handle(message, rx) {
2415 return false;
2416 }
2417 }
2418 if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
2420 && self.state.frame_requested
2421 {
2422 self.frame();
2423 }
2424 self.turn();
2425 if next.is_none() {
2426 break;
2427 }
2428 }
2429 true
2430 }
2431
2432 fn flush(&mut self, rx: &Receiver<Message>) -> bool {
2436 let frames = self.clock.moves_with_frames();
2437 for _ in 0..MAX_FLUSH_ROUNDS {
2438 while let Ok(message) = rx.try_recv() {
2439 if !self.handle(message, rx) {
2440 return false;
2441 }
2442 }
2443 if !self.advance(std::time::Duration::ZERO, rx, frames) {
2445 return false;
2446 }
2447 if rx.is_empty() {
2450 break;
2451 }
2452 }
2453 true
2454 }
2455
2456 fn idle(&self, rx: &Receiver<Message>) -> bool {
2460 let now = self.clock.now();
2461 rx.is_empty()
2462 && self.state.net.idle()
2463 && [self.due(), self.clock.next_alarm()]
2464 .into_iter()
2465 .flatten()
2466 .all(|at| at > now)
2467 }
2468
2469 fn next_frame(&self) -> Instant {
2474 let now = self.clock.now();
2475 self.last_frame
2476 .map_or(now + nsh_core::time::FRAME, |last| {
2477 last + nsh_core::time::FRAME
2478 })
2479 .max(now)
2480 }
2481
2482 fn frame(&mut self) {
2485 self.last_frame = Some(self.clock.now());
2486 handle(self.script.as_ref(), &mut self.state, Message::Frame);
2487 }
2488
2489 fn turn(&mut self) {
2492 let Driver {
2493 state,
2494 script,
2495 sink,
2496 assets,
2497 ..
2498 } = self;
2499 let script = script.as_ref();
2500 if script
2501 .and_then(Script::next_timer)
2502 .is_some_and(|due| due <= nsh_core::time::now())
2503 {
2504 self.last_active = Instant::now();
2505 }
2506 if state
2507 .resize_burst_ends
2508 .is_some_and(|ends| ends <= nsh_core::time::now())
2509 {
2510 state.resize_burst_ends = None;
2511 state.core.set_resizing(false);
2512 }
2513 if state
2514 .window_state
2515 .settles
2516 .is_some_and(|due| due <= nsh_core::time::now())
2517 && let Some(env) = state.window_state.reported
2518 {
2519 state.window_state.settles = None;
2520 state.window_state.shown = env.window_state;
2521 apply_environment(script, state, env);
2522 }
2523 let turn_start = state.trace.then(Instant::now);
2524 state.dispatch_touch_move(script);
2525 if state
2526 .next_mouse_move()
2527 .is_some_and(|due| due <= nsh_core::time::now())
2528 {
2529 state.dispatch_mouse_moves(script);
2530 }
2531 state.dispatch_scroll_events(script);
2532 let hot = std::mem::take(&mut state.hot);
2533 if let Some(script) = script {
2534 for update in hot {
2535 script.hot_update(update, &**sink);
2536 }
2537 script.run_timers(nsh_core::time::now());
2538 script.run_system();
2539 }
2540 state.core.run_component_tasks();
2541 let tasks = turn_start.map(|s| s.elapsed());
2544 state.load_fonts(script, assets.as_deref(), &**sink);
2545 let batch = state.commit(script);
2546 if let Some(batch) = batch.filter(|_| !self.quitting) {
2547 sink.submit(batch);
2548 if let (Some(start), Some(tasks)) = (turn_start, tasks) {
2549 log::info!(
2550 target: "nsh::perf",
2551 "turn: {}µs (timers and tasks {}µs)",
2552 start.elapsed().as_micros(),
2553 tasks.as_micros(),
2554 );
2555 }
2556 }
2557 state.run_on_main_thread(&**sink);
2558 if let Some(size) = state.resized.take() {
2559 sink.resized(size);
2560 }
2561 state.report_handled(&**sink);
2562 state.net.pump(script, &mut state.core);
2563 state.load_chunks(script, &**sink);
2564 state.request_frame(script, &**sink);
2565 self.check_stopped();
2566 self.sync_quit_listeners();
2567 }
2568
2569 fn sync_quit_listeners(&self) {
2571 self.quit_listeners.store(
2572 self.state.core.has_quit_listeners(),
2573 std::sync::atomic::Ordering::Relaxed,
2574 );
2575 }
2576
2577 #[cfg(not(target_arch = "wasm32"))]
2582 fn quit(&mut self, rx: &Receiver<Message>) {
2583 if !self.state.core.has_quit_listeners() {
2584 return;
2585 }
2586 let deadline = Instant::now() + QUIT_TIMEOUT;
2587 self.quitting = true;
2588 self.state.core.start_quit();
2589 let mut kept = Vec::new();
2590 loop {
2591 self.turn();
2592 if !self.state.core.quit_pending() || self.stopped {
2593 break;
2594 }
2595 let wake = self.deadline().map_or(deadline, |at| at.min(deadline));
2596 match rx.recv_deadline(wake) {
2597 Ok(Message::Shutdown) => {}
2598 Ok(message @ Message::HostEvent(..)) => kept.push(message),
2599 Ok(message) => {
2600 self.handle(message, rx);
2601 }
2602 Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
2603 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => break,
2604 }
2605 if Instant::now() >= deadline {
2606 log::warn!(
2607 "the app's quit listeners did not finish in {} ms",
2608 QUIT_TIMEOUT.as_millis()
2609 );
2610 break;
2611 }
2612 }
2613 for message in kept {
2614 let _ = self.state.net.tx.send(message);
2615 }
2616 }
2617
2618 fn next_gc(&self) -> Instant {
2622 let quiet = (self.last_active + IDLE_GC_QUIET).min(self.last_gc + IDLE_GC_LONGEST);
2623 (self.last_gc + IDLE_GC_INTERVAL).max(quiet)
2624 }
2625
2626 fn collect_if_idle(&mut self) {
2629 if let Some(script) = &self.script
2630 && self.state.committed_since_gc
2631 && Instant::now() >= self.next_gc()
2632 {
2633 let start = self.state.trace.then(Instant::now);
2634 script.collect_garbage();
2635 if let Some(start) = start {
2636 log::info!(target: "nsh::perf", "gc: {}µs", start.elapsed().as_micros());
2637 }
2638 if let Some(monitor) = &self.state.perf {
2641 let (js_heap, js_objects) = script.heap_usage();
2642 monitor.set_memory(perf::MemorySample {
2643 js_heap,
2644 js_objects,
2645 nodes: self.state.core.node_count() as u64,
2646 node_ids: self.state.core.node_id_room() as u64,
2647 });
2648 }
2649 self.last_gc = Instant::now();
2650 self.state.committed_since_gc = false;
2651 if let Some(batch) = self.state.commit(Some(script)) {
2652 self.sink.submit(batch);
2653 }
2654 self.state.run_on_main_thread(&*self.sink);
2655 }
2656 }
2657
2658 fn check_stopped(&mut self) {
2659 if let Some(script) = &self.script
2660 && !self.stopped
2661 && let Some(reason) = script.fatal()
2662 {
2663 self.stopped = true;
2664 script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
2665 }
2666 }
2667}
2668
2669struct ScrollEvent {
2670 x: f32,
2671 y: f32,
2672 content: Size<Points>,
2673 viewport: Size<Points>,
2674 zoom: f32,
2676 throttle: Duration,
2677 last: Option<Instant>,
2678 pending: bool,
2680}
2681
2682struct State<M: TextEngine> {
2683 core: Core<M>,
2684 js_tokens: Arc<nsh_core::element::Tokens>,
2687 pinned: EnvironmentPins,
2690 environment: Environment,
2692 shaders_unavailable: bool,
2695 app_locale: Option<nsh_core::platform::Locale>,
2697 frame_requested: bool,
2699 ops: Vec<Op>,
2700 binds: Vec<ListBind>,
2702 events: Vec<JsEvent>,
2704 trace: bool,
2705 perf: Option<Arc<perf::PerfMonitor>>,
2707 perf_commit: perf::CommitTiming,
2710 committed_since_gc: bool,
2711 host: HostChannel,
2714 url_opens: Vec<(u32, String)>,
2716 net: Net,
2717 hot: Vec<HotUpdate>,
2719 scroll_events: FxHashMap<NodeId, ScrollEvent>,
2722 touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
2724 mouse_moves: Vec<(NodeId, EventPayload)>,
2728 mouse_moved: Option<Instant>,
2730 sets_seen: FxHashMap<(u8, NodeId), usize>,
2732 resized: Option<Size<Points>>,
2734 resize_burst_ends: Option<Instant>,
2737 window_state: WindowStateReport,
2740 events_handled: u64,
2743 events_reported: u64,
2744}
2745
2746#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2749enum Requester {
2750 Js(RequestId),
2751 Task(u32),
2752}
2753
2754struct Net {
2757 network: Option<Arc<dyn Network>>,
2758 tx: Sender<Message>,
2759 queue: NetworkQueue,
2760 inflight: FxHashMap<Requester, Inflight>,
2761 tasks: Vec<(u32, HttpRequest)>,
2764 abandoned: Vec<u32>,
2765 access: Arc<nsh_core::access::Access>,
2767 hops: u64,
2769 assets: Option<Arc<dyn Assets>>,
2772 #[cfg(not(target_arch = "wasm32"))]
2775 runtime: tokio::runtime::Handle,
2776}
2777
2778struct AssetTask;
2781
2782impl FetchTask for AssetTask {
2783 fn send(&mut self, _: Vec<u8>) {}
2784 fn finish(&mut self) {}
2785 fn pause(&mut self, _: bool) {}
2786 fn cancel(self: Box<Self>) {}
2787}
2788
2789fn is_asset(url: &str) -> bool {
2792 url.get(..6)
2793 .is_some_and(|scheme| scheme.eq_ignore_ascii_case("asset:"))
2794}
2795
2796fn asset_response_url(url: &str) -> String {
2802 let rest = url.get(6..).unwrap_or_default();
2803 format!("asset:{}", rest.split('#').next().unwrap_or_default())
2804}
2805
2806fn asset_file(url: &str) -> &str {
2811 url.split('?').next().unwrap_or_default()
2812}
2813
2814struct Inflight {
2816 task: Box<dyn FetchTask>,
2817 hop: u64,
2819 followed: Option<access::Followed>,
2821 asset: Option<String>,
2825}
2826
2827impl Net {
2828 fn idle(&self) -> bool {
2830 self.inflight.is_empty()
2831 }
2832
2833 fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
2836 let mut abandoned = std::mem::take(&mut self.abandoned);
2837 core.take_fetches(&mut self.tasks, &mut abandoned);
2838 for id in abandoned.drain(..) {
2839 self.cancel(Requester::Task(id));
2840 }
2841 self.abandoned = abandoned;
2842 let mut tasks = std::mem::take(&mut self.tasks);
2843 for (id, request) in tasks.drain(..) {
2844 if let Err(refused) = self.request(Requester::Task(id), request) {
2845 core.fetch_refused(id, refused.message, refused.url);
2846 }
2847 }
2848 self.tasks = tasks;
2849 let Some(script) = script else { return };
2850 script.take_network(&mut self.queue);
2851 for (id, op) in std::mem::take(&mut self.queue.ops) {
2852 let who = Requester::Js(id);
2853 match op {
2854 FetchOp::Start(request) => {
2855 if let Err(refused) = self.request(who, request) {
2856 script.fetch_refused(id, &refused.message, &refused.url);
2857 }
2858 }
2859 FetchOp::Send(chunk) => {
2860 if let Some(i) = self.inflight.get_mut(&who) {
2861 i.task.send(chunk);
2862 }
2863 }
2864 FetchOp::Finish => {
2865 if let Some(i) = self.inflight.get_mut(&who) {
2866 i.task.finish();
2867 }
2868 }
2869 FetchOp::Pause(paused) => {
2870 if let Some(i) = self.inflight.get_mut(&who) {
2871 i.task.pause(paused);
2872 }
2873 }
2874 FetchOp::Cancel => self.cancel(who),
2875 }
2876 }
2877 }
2878
2879 fn cancel(&mut self, who: Requester) {
2881 if let Some(i) = self.inflight.remove(&who) {
2882 i.task.cancel();
2883 }
2884 }
2885
2886 fn request(&mut self, who: Requester, mut request: HttpRequest) -> Result<(), access::Refused> {
2889 if is_asset(&request.url) {
2890 self.asset(who, request);
2891 return Ok(());
2892 }
2893 if self.access.is_unrestricted() {
2894 self.start(who, request, None);
2895 return Ok(());
2896 }
2897 match self.access.http_url(&request.method, &request.url) {
2900 Some(url) => request.url = url.into_owned(),
2901 None => return Err(access::refused(&request.method, &request.url)),
2902 }
2903 if request.follow_redirects {
2904 let hop = access::hop(&request);
2905 let followed = access::Followed { request, hops: 0 };
2906 self.start(who, hop, Some(followed));
2907 } else {
2908 self.start(who, request, None);
2909 }
2910 Ok(())
2911 }
2912
2913 fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
2915 self.hops += 1;
2916 let hop = self.hops;
2917 let Some(network) = &self.network else {
2918 let failed = FetchEvent::Failed("this host has no network stack".to_owned());
2919 let _ = self.tx.send(Message::Fetch(id, hop, failed));
2920 return;
2921 };
2922 let tx = self.tx.clone();
2923 let events: FetchEvents = Box::new(move |event| {
2924 let _ = tx.send(Message::Fetch(id, hop, event));
2925 });
2926 let task = network.fetch(request, events);
2927 self.inflight.insert(
2928 id,
2929 Inflight {
2930 task,
2931 hop,
2932 followed,
2933 asset: None,
2934 },
2935 );
2936 }
2937
2938 fn asset(&mut self, who: Requester, mut request: HttpRequest) {
2943 request.url = asset_response_url(&request.url);
2944 let file = asset_file(&request.url).to_owned();
2945 self.hops += 1;
2946 let hop = self.hops;
2947 self.inflight.insert(
2948 who,
2949 Inflight {
2950 task: Box::new(AssetTask),
2951 hop,
2952 followed: None,
2953 asset: None,
2954 },
2955 );
2956 let refused = if !nsh_core::access::is_inside_assets(&file) {
2959 Some(format!(
2960 "{}: bundled files are named by a path inside the app's files",
2961 request.url
2962 ))
2963 } else if !matches!(request.method.as_str(), "GET" | "HEAD") {
2964 Some(format!(
2965 "{} {}: bundled files are read with GET",
2966 request.method, request.url
2967 ))
2968 } else {
2969 None
2970 };
2971 if let Some(refused) = refused {
2972 let _ = self
2973 .tx
2974 .send(Message::Fetch(who, hop, FetchEvent::Failed(refused)));
2975 return;
2976 }
2977 let Some(assets) = &self.assets else {
2978 let failed = Err("this host cannot load assets".to_owned());
2979 self.asset_read(who, hop, request, failed);
2980 return;
2981 };
2982 #[cfg(not(target_arch = "wasm32"))]
2983 {
2984 let assets = assets.clone();
2985 let tx = self.tx.clone();
2986 drop(self.runtime.spawn_blocking(move || {
2988 let bytes = assets.read(&file);
2989 let _ = tx.send(Message::AssetRead(who, hop, request, bytes));
2990 }));
2991 }
2992 #[cfg(target_arch = "wasm32")]
2993 {
2994 let bytes = assets.read(&file);
2995 self.asset_read(who, hop, request, bytes);
2996 }
2997 }
2998
2999 fn asset_read(
3005 &mut self,
3006 who: Requester,
3007 hop: u64,
3008 request: HttpRequest,
3009 read: Result<Vec<u8>, String>,
3010 ) {
3011 if self.inflight.get(&who).is_none_or(|i| i.hop != hop) {
3012 return;
3013 }
3014 let events = match read {
3015 Ok(bytes) => {
3016 let head = HttpHead {
3017 status: 200,
3018 status_text: "OK".to_owned(),
3019 headers: vec![
3020 ("content-length".to_owned(), bytes.len().to_string()),
3021 (
3022 "content-type".to_owned(),
3023 content_type(asset_file(&request.url)).to_owned(),
3024 ),
3025 ],
3026 url: request.url.clone(),
3027 ..HttpHead::default()
3028 };
3029 let mut events = vec![FetchEvent::Head(head)];
3030 if request.method == "GET" && !bytes.is_empty() {
3031 events.push(FetchEvent::Data(bytes));
3032 }
3033 events.push(FetchEvent::End);
3034 events
3035 }
3036 Err(error) => {
3037 match (self.assets.as_ref()).and_then(|a| a.url(asset_file(&request.url))) {
3038 Some(url) => {
3039 self.inflight.remove(&who);
3040 let uri = request.url.clone();
3041 self.start(who, HttpRequest { url, ..request }, None);
3042 if let Some(download) = self.inflight.get_mut(&who) {
3043 download.asset = Some(uri);
3044 }
3045 return;
3046 }
3047 None => vec![FetchEvent::Failed(error)],
3048 }
3049 }
3050 };
3051 for event in events {
3052 let _ = self.tx.send(Message::Fetch(who, hop, event));
3053 }
3054 }
3055
3056 fn event(
3060 &mut self,
3061 id: Requester,
3062 hop: u64,
3063 event: FetchEvent,
3064 ) -> Option<Result<FetchEvent, access::Refused>> {
3065 if self.network.is_none() {
3066 return Some(Ok(event));
3067 }
3068 let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
3069 match event {
3070 FetchEvent::Head(mut head) => {
3071 let missing = (inflight.asset.as_ref())
3072 .filter(|_| !(200..300).contains(&head.status))
3073 .map(|uri| format!("{uri}: HTTP {}", head.status));
3074 if let Some(missing) = missing {
3075 if let Some(i) = self.inflight.remove(&id) {
3076 i.task.cancel();
3077 }
3078 return Some(Ok(FetchEvent::Failed(missing)));
3079 }
3080 if let Some(uri) = &inflight.asset {
3084 head.url = uri.clone();
3085 head.redirected = false;
3086 if !head
3087 .headers
3088 .iter()
3089 .any(|(name, _)| name.eq_ignore_ascii_case("content-type"))
3090 {
3091 let file_type = content_type(asset_file(uri)).to_owned();
3092 head.headers.push(("content-type".to_owned(), file_type));
3093 }
3094 }
3095 let Some(followed) = &mut inflight.followed else {
3096 return Some(Ok(FetchEvent::Head(head)));
3097 };
3098 match access::next(&self.access, followed, head) {
3099 access::Next::Done(head) => Some(Ok(FetchEvent::Head(head))),
3100 access::Next::Fail(message) => {
3101 if let Some(i) = self.inflight.remove(&id) {
3102 i.task.cancel();
3103 }
3104 Some(Ok(FetchEvent::Failed(message)))
3105 }
3106 access::Next::Refused(refused) => {
3107 if let Some(i) = self.inflight.remove(&id) {
3108 i.task.cancel();
3109 }
3110 Some(Err(refused))
3111 }
3112 access::Next::Hop(request) => {
3113 let i = self.inflight.remove(&id)?;
3114 let followed = i.followed;
3115 i.task.cancel();
3116 self.start(id, request, followed);
3117 None
3118 }
3119 }
3120 }
3121 FetchEvent::End | FetchEvent::Failed(_) => {
3122 self.inflight.remove(&id);
3123 Some(Ok(event))
3124 }
3125 event => Some(Ok(event)),
3126 }
3127 }
3128}
3129
3130impl<M: TextEngine> State<M> {
3131 fn record_perf(&mut self, started: Option<Instant>) {
3134 let (Some(started), Some(monitor)) = (started, &self.perf) else {
3135 return;
3136 };
3137 let busy = started.elapsed();
3138 monitor.record_busy(busy);
3139 let mut commit = std::mem::take(&mut self.perf_commit);
3140 if commit.ops > 0 || commit.items > 0 {
3141 commit.js = busy.saturating_sub(commit.layout);
3142 monitor.record_commit(commit);
3143 }
3144 }
3145
3146 fn dispatch_touch_move(&mut self, script: Option<&Script>) {
3148 if let Some((id, touch)) = self.touch_move.take()
3149 && let Some(script) = script
3150 {
3151 script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
3152 }
3153 }
3154
3155 fn next_mouse_move(&self) -> Option<Instant> {
3157 if self.mouse_moves.is_empty() {
3158 return None;
3159 }
3160 Some(
3161 self.mouse_moved
3162 .map_or_else(nsh_core::time::now, |t| t + MOUSE_MOVE_INTERVAL),
3163 )
3164 }
3165
3166 fn dispatch_mouse_moves(&mut self, script: Option<&Script>) {
3169 if self.mouse_moves.is_empty() {
3170 return;
3171 }
3172 self.mouse_moved = Some(nsh_core::time::now());
3173 for (id, payload) in std::mem::take(&mut self.mouse_moves) {
3174 if self
3175 .core
3176 .component_event(id, EventKind::MouseMove, &payload)
3177 {
3178 continue;
3179 }
3180 if let Some(script) = script {
3181 script.dispatch_event(id, EventKind::MouseMove, &payload);
3182 }
3183 }
3184 }
3185
3186 fn next_scroll_event(&self) -> Option<Instant> {
3188 self.scroll_events
3189 .values()
3190 .filter(|e| e.pending)
3191 .filter_map(|e| e.last.map(|t| t + e.throttle))
3192 .min()
3193 }
3194
3195 fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
3197 if self.scroll_events.is_empty() {
3198 return;
3199 }
3200 let now = nsh_core::time::now();
3201 let core = &self.core;
3203 self.scroll_events
3204 .retain(|&id, _| core.scroll_listener(id).is_some());
3205 for (&id, e) in &mut self.scroll_events {
3206 if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
3207 continue;
3208 }
3209 e.pending = false;
3210 e.last = Some(now);
3211 let n = |v: f32| PayloadValue::Number(v as f64);
3212 let payload = EventPayload::Map(vec![
3213 (
3214 "offset",
3215 PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
3216 ),
3217 ("contentSize", PayloadValue::Size(e.content)),
3218 ("size", PayloadValue::Size(e.viewport)),
3219 ("zoomScale", n(e.zoom)),
3220 ]);
3221 if !self.core.component_event(id, EventKind::Scroll, &payload)
3223 && let Some(script) = script
3224 {
3225 script.dispatch_event(id, EventKind::Scroll, &payload);
3226 }
3227 }
3228 }
3229
3230 fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
3232 let Some(script) = script else { return };
3233 let mut ids = Vec::new();
3234 script.take_chunk_requests(&mut ids);
3235 for id in ids {
3236 if !sink.load_chunk(&id) {
3237 let message = "this host does not load chunks (the app was built split)".to_owned();
3238 let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
3239 }
3240 }
3241 }
3242
3243 fn report_handled(&mut self, sink: &dyn MountSink) {
3246 if self.events_handled != self.events_reported {
3247 self.events_reported = self.events_handled;
3248 sink.handled(self.events_handled);
3249 }
3250 }
3251
3252 fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
3255 if !self.frame_requested
3256 && (script.is_some_and(Script::wants_frame)
3257 || self.core.wants_frame()
3258 || self.core.has_paced_mounts()
3259 || (script.is_some() && self.core.has_paced_list_binds()))
3260 {
3261 self.frame_requested = true;
3262 sink.request_frame();
3263 }
3264 }
3265
3266 fn run_on_main_thread(&mut self, sink: &dyn MountSink) {
3269 for task in self.core.take_main_thread_tasks() {
3270 sink.run_on_main_thread(task);
3271 }
3272 }
3273
3274 fn load_fonts(
3277 &mut self,
3278 script: Option<&Script>,
3279 assets: Option<&dyn Assets>,
3280 sink: &dyn MountSink,
3281 ) {
3282 let Some(script) = script else { return };
3283 let mut fonts = Vec::new();
3284 script.take_fonts(&mut fonts);
3285 for uri in fonts {
3286 let result = match assets {
3287 Some(assets) => assets.read(&uri),
3288 None => Err("this host cannot load assets".to_owned()),
3289 }
3290 .and_then(|data| self.core.register_font(&data));
3291 if let Err(err) = result {
3292 script.report(
3293 sink,
3294 AppErrorKind::Asset,
3295 "font failed",
3296 &format!("{uri}: {err}"),
3297 );
3298 }
3299 }
3300 }
3301
3302 fn open_urls(&mut self) -> bool {
3308 self.core.take_url_opens(&mut self.url_opens);
3309 let mut platform = false;
3310 for (id, url) in self.url_opens.drain(..) {
3311 if self.host.open_url(id, url.clone(), &self.net.tx).is_none() {
3312 self.core.open_url_on_platform(id, url);
3313 platform = true;
3314 }
3315 }
3316 platform
3317 }
3318
3319 fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
3320 let start = Instant::now();
3321 let mut merged: Option<MountBatch> = None;
3322 let mut commits = 0;
3323 let mut op_count = 0;
3324 let mut js = std::time::Duration::ZERO;
3325 let mut paced = PacedBinds::default();
3327 self.core.begin_mount_turn();
3329 for _ in 0..MAX_LIST_ROUNDS {
3330 let js_start = Instant::now();
3332 let binds = self.binds.drain(..);
3335 if let Some(script) = script {
3336 for bind in binds {
3337 script.bind_list(bind.list, &bind.binds);
3338 }
3339 script.take_ops(&mut self.ops);
3340 let mut binds = Vec::new();
3341 while paced.left() && self.core.has_paced_list_binds() {
3342 let start = Instant::now();
3343 let ops = self.ops.len();
3344 self.core.take_paced_list_binds(1, &mut binds);
3345 for bind in binds.drain(..) {
3346 paced.cells += bind.binds.len();
3347 script.bind_list(bind.list, &bind.binds);
3348 }
3349 script.take_ops(&mut self.ops);
3350 paced.ops += self.ops.len() - ops;
3351 paced.time += start.elapsed();
3352 }
3353 } else {
3354 drop(binds);
3355 }
3356 if let Some(script) = script {
3359 script.run_posted();
3360 }
3361 for event in self.events.drain(..) {
3365 match event {
3366 JsEvent::Event(id, event, payload) => {
3367 if !self.core.component_event(id, event, &payload)
3368 && let Some(script) = script
3369 {
3370 script.dispatch_event(id, event, &payload);
3371 }
3372 }
3373 JsEvent::LayoutListener {
3374 host,
3375 id,
3376 listener,
3377 frame,
3378 } => {
3379 self.core.component_layout(host, id, &listener, frame);
3380 }
3381 other => {
3383 if let Some(script) = script {
3384 script.deliver(other);
3385 }
3386 }
3387 }
3388 }
3389 if let Some(script) = script {
3390 script.take_ops(&mut self.ops);
3391 }
3392 js += js_start.elapsed();
3393 op_count += self.ops.len();
3394 let mut ops = self.ops.drain(..);
3397 while let Some(op) = ops.next() {
3398 match self.core.apply(op) {
3399 Ok(()) => {}
3400 Err(err) if err.is_fatal() => {
3401 self.core.discard_ops(ops.by_ref());
3402 let Some(script) = script else { break };
3403 script.stop(match err {
3404 ApplyError::TooManyNodes(max) => {
3405 format!("the app created more than {max} nodes and was stopped")
3406 }
3407 other => {
3408 format!("the app sent an invalid op ({other:?}) and was stopped")
3409 }
3410 });
3411 break;
3412 }
3413 Err(err) => log::error!("invalid op: {err:?}"),
3414 }
3415 }
3416 drop(ops);
3417 release_spare_ops(&mut self.ops);
3418 if let Some(batch) = self.core.commit() {
3419 commits += 1;
3420 match &mut merged {
3421 Some(m) => extend_frame(&mut m.items, batch.items),
3422 None => merged = Some(batch),
3423 }
3424 }
3425 self.core.take_list_binds(&mut self.binds);
3426 self.core.take_events(&mut self.events);
3427 let urls = self.open_urls();
3429 let posted = script.is_some_and(Script::has_posted);
3431 let retheme = match script {
3434 Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
3435 self.js_tokens = self.core.tokens().clone();
3436 script.set_tokens(self.js_tokens.clone());
3437 true
3438 }
3439 _ => false,
3440 };
3441 let relocale = match self.core.take_locale_request() {
3444 Some(locale) => {
3445 self.app_locale = locale;
3446 apply_environment(script, self, self.environment);
3447 true
3448 }
3449 None => false,
3450 };
3451 let more_paced = script.is_some() && paced.left() && self.core.has_paced_list_binds();
3452 let answers = self.core.has_due_answers();
3456 if self.binds.is_empty()
3457 && self.events.is_empty()
3458 && !posted
3459 && !retheme
3460 && !relocale
3461 && !more_paced
3462 && !urls
3463 && !answers
3464 {
3465 break;
3466 }
3467 }
3468 if commits > 1
3469 && let Some(batch) = &mut merged
3470 {
3471 keep_last_sets(&mut batch.items, &mut self.sets_seen);
3472 }
3473 self.committed_since_gc |= op_count > 0;
3474 if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
3475 let c = &mut self.perf_commit;
3476 c.layout += start.elapsed().saturating_sub(js);
3477 c.ops += op_count as u32;
3478 c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
3479 }
3480 if self.trace && (op_count > 0 || merged.is_some()) {
3481 log::info!(
3482 target: "nsh::perf",
3483 "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
3484 start.elapsed().as_micros(),
3485 js.as_micros(),
3486 merged.as_ref().map_or(0, |b| b.items.len()),
3487 self.core.node_count(),
3488 );
3489 }
3490 merged
3491 }
3492}
3493
3494fn insets(env: &Environment) -> EdgeInsets {
3495 env.safe_area
3496}
3497
3498fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::element::Environment {
3500 nsh_core::element::Environment {
3501 window,
3502 safe_area: insets(env),
3503 title_bar: env.title_bar,
3504 window_state: env.window_state,
3505 keyboard_height: env.keyboard_height,
3506 keyboard_duration: env.keyboard_duration,
3507 dark: env.color_scheme == ColorScheme::Dark,
3508 font_scale: env.font_scale,
3509 reduce_motion: env.reduce_motion,
3510 screen_reader: env.screen_reader,
3511 rtl: env.rtl,
3512 pixel_ratio: env.pixel_ratio,
3513 os: env.os,
3514 platform: env.platform,
3515 os_version: env.os_version,
3516 idiom: env.idiom,
3517 locale: env.locale,
3518 locale_settings: env.locale_settings,
3519 apple_keyboard: env.apple_keyboard,
3520 ctrl_for_command: env.ctrl_for_command,
3521 host: env.host,
3522 lifecycle: env.lifecycle,
3523 screen_color: env.screen_color,
3524 file_requests: env.file_requests,
3525 speech: env.speech,
3526 notifications: env.notifications,
3527 audio: env.audio,
3528 cell: env.cell,
3529 web_input: env.web_input,
3530 web_evaluate: env.web_evaluate,
3531 web_views: env.web_views,
3532 shaders: env.shaders,
3533 }
3534}
3535
3536fn drawn_shaders(env: &mut Environment, unavailable: bool) {
3540 env.shaders &= env.cell.is_none() && !unavailable && !shader::no_gpu();
3541}
3542
3543fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
3545 nsh_core::tailwind::ClassEnvironment {
3546 dark: env.color_scheme == ColorScheme::Dark,
3547 platform: if env.os == Os::Web {
3548 nsh_core::tailwind::Platform::Web
3549 } else if cfg!(target_os = "android") {
3550 nsh_core::tailwind::Platform::Android
3551 } else {
3552 nsh_core::tailwind::Platform::Ios
3553 },
3554 reduce_motion: env.reduce_motion,
3555 pointer: if env.desktop() {
3556 nsh_core::tailwind::Pointer::Fine
3557 } else {
3558 nsh_core::tailwind::Pointer::Coarse
3559 },
3560 terminal: env.idiom == Idiom::Terminal,
3561 }
3562}
3563
3564const WINDOW_SETTLE: Duration = Duration::from_millis(150);
3567
3568#[derive(Default)]
3573struct WindowStateReport {
3574 shown: Option<nsh_core::desktop::WindowState>,
3576 reported: Option<Environment>,
3578 settles: Option<Instant>,
3580}
3581
3582impl WindowStateReport {
3583 fn report(&mut self, mut env: Environment, now: Instant) -> Environment {
3586 let next = env.window_state;
3587 let moving = match (&self.shown, &next) {
3588 (Some(shown), Some(next)) => shown != next && moved_only(shown, next),
3589 _ => false,
3590 };
3591 if moving {
3592 let moved = self.reported.map(|r| r.window_state) != Some(next);
3595 if moved || self.settles.is_none() {
3596 self.settles = Some(now + WINDOW_SETTLE);
3597 }
3598 self.reported = Some(env);
3599 env.window_state = self.shown;
3600 } else {
3601 self.reported = None;
3602 self.settles = None;
3603 self.shown = next;
3604 }
3605 env
3606 }
3607}
3608
3609fn moved_only(
3613 shown: &nsh_core::desktop::WindowState,
3614 next: &nsh_core::desktop::WindowState,
3615) -> bool {
3616 shown.mode == next.mode
3617 && shown.placement.mode == next.placement.mode
3618 && shown.minimized == next.minimized
3619 && shown.visible == next.visible
3620 && shown.focused == next.focused
3621 && shown.display == next.display
3622 && shown.scale_factor == next.scale_factor
3623}
3624
3625fn apply_environment<M: TextEngine>(
3627 script: Option<&Script>,
3628 state: &mut State<M>,
3629 env: Environment,
3630) {
3631 state.environment = env;
3632 let mut env = env;
3633 if let Some(locale) = state.app_locale {
3636 env.locale = locale;
3637 env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
3638 }
3639 state.core.set_font_scale(env.font_scale);
3640 state.core.set_class_environment(class_environment(&env));
3641 state.core.set_safe_area(insets(&env));
3642 let window = env.window;
3643 state.core.set_environment(ui_environment(&env, window));
3644 if let Some(script) = script {
3645 script.set_environment(&env);
3646 }
3647}
3648
3649fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
3651 match message {
3652 Message::Event(id, event, mut payload) => {
3653 state.events_handled += 1;
3654 if state.trace {
3655 log::info!(target: "nsh::perf", "event {event:?} on view {id}");
3656 }
3657 if event == EventKind::MouseMove {
3663 match state.mouse_moves.iter_mut().find(|(v, _)| *v == id) {
3664 Some((_, pending)) => *pending = payload,
3665 None => state.mouse_moves.push((id, payload)),
3666 }
3667 return true;
3668 }
3669 if !matches!(&payload, EventPayload::Touch(t) if t.phase == nsh_core::TouchPhase::Move)
3670 {
3671 state.dispatch_mouse_moves(script);
3672 }
3673 if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
3676 state.core.input_changed(id, text, *count);
3677 }
3678 if event == EventKind::CaretMove {
3681 state.core.locate_caret(id, &mut payload);
3682 }
3683 if event == EventKind::SelectionChange {
3684 state.core.locate_selection(id, &mut payload);
3685 }
3686 if event == EventKind::Paste {
3687 payload = payload.into_paste();
3688 }
3689 if let EventPayload::ContextMenu(menu) = &payload {
3694 for (overlay, pressed) in state.core.context_menu_presses_outside(id, menu) {
3695 if !state
3696 .core
3697 .component_event(overlay, EventKind::PressOutside, &pressed)
3698 && let Some(script) = script
3699 {
3700 script.dispatch_event(overlay, EventKind::PressOutside, &pressed);
3701 }
3702 }
3703 }
3704 if state.core.component_event(id, event, &payload) {
3706 return true;
3707 }
3708 if let EventPayload::Touch(touch) = payload {
3709 if touch.phase == nsh_core::TouchPhase::Move {
3710 match &mut state.touch_move {
3711 Some((_, pending)) => pending.merge_move(*touch),
3712 None => state.touch_move = Some((id, touch)),
3713 }
3714 return true;
3715 }
3716 state.dispatch_touch_move(script);
3718 if let Some(script) = script {
3719 script.dispatch_event(id, event, &EventPayload::Touch(touch));
3720 }
3721 return true;
3722 }
3723 let Some(script) = script else { return true };
3724 let start = state.trace.then(Instant::now);
3725 script.dispatch_event(id, event, &payload);
3726 if let Some(start) = start {
3727 log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
3730 }
3731 }
3732 Message::Scroll(id, offset, applied) => {
3733 state.core.set_scroll_offset(id, offset, applied);
3734 let (x, y) = (offset.x.0, offset.y.0);
3735 if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
3736 let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
3737 x,
3738 y,
3739 content,
3740 viewport,
3741 zoom,
3742 throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
3743 last: None,
3744 pending: true,
3745 });
3746 (event.x, event.y, event.content, event.viewport, event.zoom) =
3747 (x, y, content, viewport, zoom);
3748 event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
3749 event.pending = true;
3750 }
3751 }
3752 Message::Kept(nodes) => state.core.set_kept(&nodes),
3753 Message::ContentCulling(enabled) => {
3754 state.core.set_content_culling(enabled);
3755 if let Some(script) = script {
3756 script.set_lazy_rows(enabled);
3757 }
3758 }
3759 Message::InputScroll(id, offset, content, viewport) => {
3760 state.core.set_input_scroll(id, offset, content, viewport);
3761 }
3762 Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
3763 Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
3764 Message::AnimationsFinished(mut finished) => {
3765 state.core.animations_finished(&mut finished);
3767 if let Some(script) = script {
3768 script.animations_finished(&finished);
3769 }
3770 }
3771 Message::Resize(size) => {
3772 if !nsh_core::time::manual() {
3775 let now = nsh_core::time::now();
3776 if state.resize_burst_ends.is_some_and(|ends| now < ends) {
3777 state.core.set_resizing(true);
3778 }
3779 state.resize_burst_ends = Some(now + RESIZE_BURST_GAP);
3780 }
3781 state.core.set_viewport(size);
3782 state.resized = Some(size);
3783 }
3784 Message::Wake => {}
3785 Message::Environment(mut env) => {
3786 state.pinned.apply(&mut env);
3787 drawn_shaders(&mut env, state.shaders_unavailable);
3788 let env = state.window_state.report(*env, nsh_core::time::now());
3789 apply_environment(script, state, env);
3790 }
3791 Message::ShadersUnavailable => {
3792 state.shaders_unavailable = true;
3793 if state.environment.shaders {
3794 let env = Environment {
3795 shaders: false,
3796 ..state.environment
3797 };
3798 apply_environment(script, state, env);
3799 }
3800 }
3801 Message::Displays(displays) => {
3802 state.core.set_displays(displays.clone());
3803 if let Some(script) = script {
3804 script.set_displays(&displays);
3805 }
3806 }
3807 Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
3808 Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
3809 Message::Frame => {
3810 state.frame_requested = false;
3811 state.core.run_frame(nsh_core::time::now());
3812 if let Some(script) = script {
3813 script.run_frame();
3814 }
3815 }
3816 Message::States(id, states) => state.core.set_states(id, states),
3817 Message::Modality(modality) => state.core.set_input_modality(modality),
3818 Message::FontsChanged => state.core.fonts_changed(),
3819 Message::Remount => state.core.remount(),
3820 Message::Fetch(who, hop, event) => match (who, state.net.event(who, hop, event)) {
3821 (_, None) => {}
3822 (Requester::Js(id), Some(event)) => {
3823 if let Some(script) = script {
3824 match event {
3825 Ok(event) => script.fetch_event(id, event),
3826 Err(refused) => script.fetch_refused(id, &refused.message, &refused.url),
3827 }
3828 }
3829 }
3830 (Requester::Task(id), Some(Ok(event))) => {
3831 if !state.core.fetch_event(id, event) {
3832 state.net.cancel(who);
3833 }
3834 }
3835 (Requester::Task(id), Some(Err(refused))) => {
3838 state.core.fetch_refused(id, refused.message, refused.url)
3839 }
3840 },
3841 Message::AssetRead(who, hop, request, read) => {
3842 state.net.asset_read(who, hop, request, read)
3843 }
3844 Message::Hot(update) => state.hot.push(update),
3845 Message::Chunk(chunk) => {
3846 if let Some(script) = script {
3847 script.chunk(chunk);
3848 }
3849 }
3850 Message::Perf(monitor) => {
3851 state.core.set_perf_monitor(monitor.is_some());
3852 if let Some(script) = script {
3853 script.set_fps_enabled(monitor.is_some());
3854 }
3855 state.perf = monitor;
3856 state.perf_commit = perf::CommitTiming::default();
3857 }
3858 Message::Tokens(tokens) => {
3859 state.core.set_host_tokens(tokens.map(|t| *t));
3860 if let Some(script) = script {
3861 script.set_theme_tokens(state.core.theme_tokens());
3862 }
3863 }
3864 Message::HostFont(data) => {
3865 if let Err(err) = state.core.register_font(&data) {
3866 log::error!("font failed: {err}");
3867 }
3868 }
3869 Message::HostEvent(name, data) => {
3871 if let Some(script) = script {
3872 script.host_event(&name, data);
3873 }
3874 }
3875 Message::HostReply(id, result) => {
3876 if let Some(script) = script {
3877 script.host_reply(id, result);
3878 }
3879 }
3880 Message::UrlHandled { id, url, handled } => {
3881 if handled {
3882 state.core.answer_open_url(id, true);
3883 } else {
3884 state.core.open_url_on_platform(id, url);
3885 }
3886 }
3887 Message::Advance(..) | Message::Flush(..) => unreachable!("the driver moves the clock"),
3890 Message::Shutdown => return false,
3891 }
3892 true
3893}
3894
3895#[derive(Default)]
3897struct PacedBinds {
3898 cells: usize,
3899 ops: usize,
3900 time: std::time::Duration,
3901}
3902
3903impl PacedBinds {
3904 fn left(&self) -> bool {
3907 self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
3908 }
3909}
3910
3911fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
3917 use nsh_core::MountItem;
3918 let start = frame.len();
3919 frame.extend(items);
3920 for k in start..frame.len() {
3921 let MountItem::ScrollContent { id, size } = frame[k] else {
3922 continue;
3923 };
3924 let earlier = frame[..k].iter().rposition(|m| {
3925 matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
3926 });
3927 if let Some(j) = earlier
3928 && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
3929 {
3930 *s = size;
3931 }
3932 }
3933}
3934
3935fn keep_last_sets(frame: &mut Vec<nsh_core::MountItem>, last: &mut FxHashMap<(u8, NodeId), usize>) {
3941 last.clear();
3942 let mut repeated = false;
3943 for (k, item) in frame.iter().enumerate() {
3944 if let Some(key) = sets_whole(item) {
3945 repeated |= last.insert(key, k).is_some();
3946 }
3947 }
3948 if !repeated {
3949 return;
3950 }
3951 let mut k = 0;
3952 frame.retain(|item| {
3953 k += 1;
3954 sets_whole(item).is_none_or(|key| last[&key] == k - 1)
3955 });
3956}
3957
3958fn sets_whole(item: &nsh_core::MountItem) -> Option<(u8, nsh_core::NodeId)> {
3961 use nsh_core::MountItem;
3962 Some(match *item {
3963 MountItem::Frame { id, .. } => (0, id),
3964 MountItem::Overflow { id, .. } => (1, id),
3965 MountItem::ViewStyle { id, .. } => (2, id),
3966 MountItem::Text { id, .. } => (3, id),
3967 MountItem::Events { id, .. } => (4, id),
3968 MountItem::Image { id, .. } => (5, id),
3969 _ => return None,
3970 })
3971}
3972
3973const RETAINED_OPS: usize = 16 * 1024;
3975
3976fn release_spare_ops(ops: &mut Vec<Op>) {
3981 debug_assert!(ops.is_empty());
3982 if ops.capacity() > RETAINED_OPS {
3983 ops.shrink_to(RETAINED_OPS);
3984 }
3985}
3986
3987fn app_access(app: &App) -> Access {
3990 match app {
3991 App::Js(bundle) => bundle.policy.access(),
3992 App::Rust(_) => Policy::default().access(),
3993 }
3994}
3995
3996fn media_files(config: &EngineConfig, access: &Access) -> nsh_core::access::MediaFiles {
3999 match &config.app {
4000 App::Js(bundle) => nsh_core::access::MediaFiles::new(
4001 access,
4002 config
4003 .data_dir
4004 .as_ref()
4005 .map(|root| root.join(app_dir_name(config.app.app_id())))
4006 .as_deref(),
4007 &bundle_system_paths(bundle),
4008 nsh_core::access::native_files(config.environment.os),
4009 ),
4010 _ => nsh_core::access::MediaFiles::default(),
4011 }
4012}
4013
4014#[cfg(test)]
4015mod tests {
4016 #[test]
4017 fn an_emptied_op_buffer_gives_back_what_a_large_commit_grew() {
4018 let mut ops: Vec<super::Op> = Vec::with_capacity(super::RETAINED_OPS * 8);
4019 super::release_spare_ops(&mut ops);
4020 assert!(ops.capacity() <= super::RETAINED_OPS);
4021 let mut ops: Vec<super::Op> = Vec::with_capacity(1024);
4023 super::release_spare_ops(&mut ops);
4024 assert_eq!(ops.capacity(), 1024);
4025 }
4026
4027 #[test]
4028 fn moves_settle_and_changes_of_mode_do_not() {
4029 use nsh_core::{
4030 desktop::{DisplayId, WindowMode, WindowPlacement, WindowState},
4031 geometry::{Bounds, point, px, size},
4032 };
4033 let rect = |x: f32| Bounds::new(point(px(x), px(0.0)), size(px(800.0), px(600.0)));
4034 let a = WindowState::new(
4035 rect(0.0),
4036 WindowPlacement::new(WindowMode::Normal, rect(0.0)),
4037 );
4038 let mut moved = a;
4039 moved.bounds = rect(10.0);
4040 moved.placement = WindowPlacement::new(WindowMode::Normal, rect(10.0));
4041 assert!(super::moved_only(&a, &moved));
4042 let mut maximized = a;
4043 maximized.mode = WindowMode::Maximized;
4044 maximized.placement = WindowPlacement::new(WindowMode::Maximized, rect(0.0));
4045 assert!(!super::moved_only(&a, &maximized));
4046 let mut minimized = a;
4047 minimized.minimized = true;
4048 assert!(!super::moved_only(&a, &minimized));
4049 let mut hidden = a;
4050 hidden.visible = false;
4051 assert!(!super::moved_only(&a, &hidden));
4052 let mut elsewhere = a;
4053 elsewhere.display = Some(DisplayId(2));
4054 assert!(!super::moved_only(&a, &elsewhere));
4055 }
4056
4057 #[test]
4058 fn pinned_values_hold_whatever_the_platform_reports() {
4059 let pins = super::EnvironmentPins {
4060 locale: nsh_core::platform::Locale::parse("de-DE"),
4061 reduce_motion: Some(true),
4062 ..Default::default()
4063 };
4064 let mut reported = super::Environment {
4065 locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
4066 font_scale: 1.5,
4067 ..Default::default()
4068 };
4069 pins.apply(&mut reported);
4070 assert_eq!(reported.locale.as_str(), "de-DE");
4071 assert!(reported.reduce_motion);
4072 assert_eq!(reported.font_scale, 1.5);
4074 assert_eq!(reported.safe_area, Default::default());
4075 }
4076
4077 #[test]
4078 fn bundle_default_has_no_application_selected_path_anchors() {
4079 let bundle = super::Bundle::default();
4080 assert!(bundle.system_paths.plugin_dir.is_none());
4081 assert!(bundle.system_paths.home_dir.is_none());
4082 assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
4083 }
4084
4085 #[test]
4086 fn bundle_trusted_paths_reject_relative_and_missing_directories() {
4087 let mut paths = nsh_core::access::TrustedPaths::default();
4088 paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
4089 paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
4090 let bundle = super::Bundle::default().with_system_paths(paths);
4091 assert!(bundle.system_paths.plugin_dir.is_none());
4092 assert!(bundle.system_paths.home_dir.is_none());
4093 assert!(
4094 super::trusted_directory(Some(std::path::PathBuf::from(
4095 "/nsh-nonexistent-anchor-never-created"
4096 )))
4097 .is_none()
4098 );
4099 }
4100
4101 #[test]
4102 fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
4103 let root = std::env::var_os("TMPDIR")
4104 .map(std::path::PathBuf::from)
4105 .unwrap_or_else(|| {
4106 std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
4107 .join(".cache/nsh-benchs-test-tmp")
4108 });
4109 assert!(root.is_absolute() && !root.starts_with("/tmp"));
4110 let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
4111 std::fs::create_dir_all(&directory).unwrap();
4112 let path = directory.join("bundle.js");
4113 std::fs::write(&path, "export default null;").unwrap();
4114 let bundle = super::Bundle::read(&path).unwrap();
4115 assert_eq!(
4116 bundle.system_paths.plugin_dir,
4117 Some(nsh_core::access::canonicalize(&directory).unwrap())
4118 );
4119 assert!(bundle.system_paths.home_dir.is_none());
4120 std::fs::remove_dir_all(directory).unwrap();
4121 }
4122
4123 #[test]
4124 fn rust_environment_preserves_native_title_bar_insets() {
4125 use super::{Edges, Points};
4126 let title_bar = Edges {
4127 top: Points(42.0),
4128 left: Points(78.0),
4129 right: Points(138.0),
4130 bottom: Points(0.0),
4131 };
4132 let environment = super::Environment {
4133 title_bar,
4134 ..Default::default()
4135 };
4136 assert_eq!(
4137 super::ui_environment(
4138 &environment,
4139 nsh_core::Size::new(Points(840.0), Points(630.0))
4140 )
4141 .title_bar,
4142 title_bar
4143 );
4144 }
4145
4146 use nsh_core::{MountItem, Points, Size};
4147
4148 #[test]
4149 fn a_frame_sends_a_scroll_views_last_content_size() {
4150 let content = |height| MountItem::ScrollContent {
4151 id: 2,
4152 size: Size::new(Points(390.0), height),
4153 };
4154 let heights = |frame: &[MountItem]| -> Vec<f32> {
4155 frame
4156 .iter()
4157 .filter_map(|m| match m {
4158 MountItem::ScrollContent { size, .. } => Some(size.height.0),
4159 _ => None,
4160 })
4161 .collect()
4162 };
4163 let mut frame = vec![content(Points(313.0))];
4164 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
4165 assert_eq!(heights(&frame), [544.0, 544.0]);
4166 let mut frame = vec![
4168 content(Points(313.0)),
4169 MountItem::ScrollBy {
4170 id: 2,
4171 dx: Points(0.0),
4172 dy: Points(10.0),
4173 },
4174 ];
4175 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
4176 assert_eq!(heights(&frame), [313.0, 544.0]);
4177 }
4178
4179 #[test]
4180 fn a_frame_sends_a_views_last_frame_once() {
4181 use nsh_core::{Bounds, Point};
4182 let at = |id, y| MountItem::Frame {
4183 id,
4184 frame: Bounds::new(
4185 Point::new(Points(0.0), Points(y)),
4186 Size::new(Points(10.0), Points(10.0)),
4187 ),
4188 };
4189 let mut frame = vec![
4190 MountItem::Create {
4191 id: 4,
4192 kind: nsh_core::ViewKind::View,
4193 },
4194 at(4, 0.0),
4195 at(6, 0.0),
4196 ];
4197 super::extend_frame(&mut frame, vec![at(4, 50.0)]);
4198 super::keep_last_sets(&mut frame, &mut Default::default());
4199 assert!(matches!(frame[0], MountItem::Create { id: 4, .. }));
4200 let frames: Vec<_> = frame
4201 .iter()
4202 .filter_map(|m| match m {
4203 MountItem::Frame { id, frame } => Some((*id, frame.origin.y.0)),
4204 _ => None,
4205 })
4206 .collect();
4207 assert_eq!(frames, [(6, 0.0), (4, 50.0)]);
4208 }
4209}