1mod access;
12mod app_directory;
13mod error;
14mod local_storage;
15#[cfg(feature = "net")]
16pub mod net;
17pub mod perf;
18mod script;
19#[cfg(not(target_arch = "wasm32"))]
20mod storage;
21#[cfg(feature = "js")]
22mod symbolicate;
23
24#[cfg(test)]
27#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
28mod unit_scan;
29
30#[cfg(test)]
31#[test]
32fn public_api_is_typed() {
33 unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
34}
35
36use std::{io, rc::Rc, sync::Arc, time::Duration};
37
38pub use app_directory::app_dir_name;
39use crossbeam_channel::{Receiver, Sender};
40pub use local_storage::local_storage_prefix;
41use nsh_core::{
42 ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
43 PayloadValue, TextEngine, time::Instant, ui::JsEvent,
44};
45pub use nsh_core::{
46 access::{Access, Capabilities},
47 geometry::{self, Bounds, Edges, Point, Points, Size},
48 js::{HostLimits, Limits},
49 platform::{
50 ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HttpBody, HttpHead,
51 HttpRequest, Idiom, Locale, Os,
52 },
53 storage::{StorageBackend, StorageChange},
54 time::Clock,
55 ui::{Root, Tokens},
56};
57#[cfg(feature = "js")]
58pub use nsh_js::BYTECODE_VERSION;
59#[cfg(feature = "js")]
61pub use nsh_package as package;
62use rustc_hash::FxHashMap;
63#[cfg(not(target_arch = "wasm32"))]
64pub use storage::{FileStorage, data_dir};
65
66pub use crate::error::{AppError, AppErrorKind, PackageInfo};
67use crate::script::{NetworkQueue, RequestId, Script};
68
69#[cfg(not(target_arch = "wasm32"))]
70const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
74
75const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
79
80const HOVER_MOVE_INTERVAL: Duration = Duration::from_millis(8);
84
85#[derive(Debug, Clone)]
87#[allow(
88 clippy::large_enum_variant,
89 reason = "one app per surface; keep the public constructor API without allocation"
90)]
91pub enum App {
92 Rust(Root),
94 Js(Bundle),
96}
97
98impl From<Bundle> for App {
99 fn from(bundle: Bundle) -> Self {
100 App::Js(bundle)
101 }
102}
103
104impl App {
105 pub fn app_id(&self) -> Option<&str> {
107 match self {
108 App::Rust(root) => root.app_id_ref(),
109 App::Js(bundle) => bundle.app_id.as_deref(),
110 }
111 }
112}
113
114impl From<Root> for App {
115 fn from(root: Root) -> Self {
116 App::Rust(root)
117 }
118}
119
120#[derive(Debug, Clone)]
122#[non_exhaustive]
123pub struct Bundle {
124 pub code: BundleCode,
126 pub source_map: Option<Arc<str>>,
128 pub policy: Policy,
130 pub base_url: Option<Arc<str>>,
133 pub chunks: Arc<Vec<Chunk>>,
137 pub harden_bytecode: Option<Arc<Vec<u8>>>,
142 pub app_id: Option<String>,
145 pub system_paths: nsh_core::access::TrustedPaths,
149 pub package: Option<Arc<PackageInfo>>,
152}
153
154#[derive(Debug, Clone)]
157pub struct Chunk {
158 pub id: String,
160 pub code: BundleCode,
162 pub source_map: Option<Arc<str>>,
164}
165
166impl Chunk {
167 pub fn source(id: impl Into<String>, code: String) -> Self {
169 Self {
170 id: id.into(),
171 code: BundleCode::Source(code),
172 source_map: None,
173 }
174 }
175
176 pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
182 Self {
183 id: id.into(),
184 code: BundleCode::Bytecode(bytes),
185 source_map: None,
186 }
187 }
188
189 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
191 self.source_map = Some(map.into());
192 self
193 }
194}
195
196#[derive(Debug, Clone)]
198pub struct Policy {
199 pub harden: bool,
203 pub declared: Option<Capabilities>,
206 pub granted: Option<Capabilities>,
209}
210
211impl Default for Policy {
212 fn default() -> Self {
213 Self {
214 harden: true,
215 declared: None,
216 granted: None,
217 }
218 }
219}
220
221impl Policy {
222 pub fn development() -> Self {
226 Self {
227 harden: false,
228 ..Self::default()
229 }
230 }
231
232 pub fn access(&self) -> Access {
234 Access {
235 declared: self.declared.clone().unwrap_or_else(Capabilities::all),
236 granted: self.granted.clone(),
237 }
238 }
239}
240
241#[derive(Debug, Clone)]
243pub enum BundleCode {
244 Bytecode(Vec<u8>),
246 Source(String),
248}
249
250impl Default for Bundle {
251 fn default() -> Self {
252 Self::source(String::new())
253 }
254}
255
256impl Bundle {
257 pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
267 Self {
268 code: BundleCode::Bytecode(bytes),
269 source_map: None,
270 policy: Policy::default(),
271 base_url: None,
272 chunks: Arc::default(),
273 harden_bytecode: None,
274 app_id: None,
275 system_paths: nsh_core::access::TrustedPaths::default(),
276 package: None,
277 }
278 }
279
280 pub fn source(code: String) -> Self {
282 Self {
283 code: BundleCode::Source(code),
284 source_map: None,
285 policy: Policy::default(),
286 base_url: None,
287 chunks: Arc::default(),
288 harden_bytecode: None,
289 app_id: None,
290 system_paths: nsh_core::access::TrustedPaths::default(),
291 package: None,
292 }
293 }
294
295 pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
300 paths.plugin_dir = trusted_directory(paths.plugin_dir);
301 paths.home_dir = trusted_directory(paths.home_dir);
302 self.system_paths = paths;
303 self
304 }
305
306 pub fn with_app_id(mut self, id: Option<&str>) -> Self {
309 self.app_id = id.map(str::to_owned);
310 self
311 }
312
313 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
315 self.source_map = Some(map.into());
316 self
317 }
318
319 pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
321 self.base_url = Some(url.into());
322 self
323 }
324
325 pub unsafe fn with_harden_bytecode(mut self, bytes: Vec<u8>) -> Self {
332 self.harden_bytecode = Some(Arc::new(bytes));
333 self
334 }
335
336 pub fn with_policy(mut self, policy: Policy) -> Self {
338 self.policy = policy;
339 self
340 }
341
342 pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
344 Arc::make_mut(&mut self.chunks).extend(chunks);
345 self
346 }
347
348 pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
354 if path.extension().is_some_and(|e| e == "nshc") {
355 return Err(io::Error::other(
356 "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
357 ));
358 }
359 unsafe { Self::read_trusted(path) }
361 }
362
363 pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
370 let bytes = std::fs::read(path)?;
371 let bundle = if path.extension().is_some_and(|e| e == "nshc") {
372 unsafe { Bundle::bytecode(bytes) }
374 } else {
375 Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
376 };
377 let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
378 Ok(map) if !map.is_empty() => bundle.with_source_map(map),
379 _ => bundle,
380 };
381 if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
382 bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
383 }
384 bundle.app_id = read_app_id(&path.with_file_name("app.json"));
385 bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
386 .parent()
387 .map(std::path::Path::to_path_buf);
388 Ok(bundle)
389 }
390}
391
392#[cfg(feature = "js")]
393impl Bundle {
394 pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
400 for ignored in &package.ignored {
401 log::warn!("package {}: ignored {ignored}", package.app.id);
402 }
403 let bundle = match package.bytecode() {
404 Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
407 None => Bundle::source(package.source.clone()),
408 };
409 let mut bundle = match &package.source_map {
410 Some(map) => bundle.with_source_map(map.clone()),
411 None => bundle,
412 };
413 if let Some(json) = &package.capabilities {
414 let (declared, dropped) = Capabilities::from_json_lenient(json)?;
415 for dropped in dropped {
416 log::warn!("package {}: not granted: {dropped}", package.app.id);
417 }
418 bundle.policy.declared = Some(declared);
419 }
420 bundle.app_id = Some(package.app.id.clone());
421 bundle.package = Some(Arc::new(PackageInfo {
422 id: package.app.id.clone(),
423 name: package.app.name.clone(),
424 version: package.app.version.clone(),
425 build: package.app.build,
426 sha256: package.sha256.clone(),
427 }));
428 Ok(bundle)
429 }
430}
431
432fn read_app_id(path: &std::path::Path) -> Option<String> {
434 let json: serde_json::Value =
435 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()?;
436 json.get("id")?.as_str().map(str::to_owned)
437}
438
439#[cfg(feature = "js")]
441#[derive(Debug)]
442pub struct LoadedPackage {
443 pub bundle: Bundle,
445 pub assets: std::path::PathBuf,
447 pub app: nsh_package::App,
449 pub receipt: nsh_package::PackageReceipt,
451}
452
453#[cfg(feature = "js")]
458pub fn load_package(
459 trust: &mut nsh_package::TrustStore,
460 bytes: &[u8],
461 assets_root: &std::path::Path,
462) -> Result<LoadedPackage, String> {
463 let package = verify_package(trust, bytes, assets_root)?;
464 accept_package(trust, &package)?;
465 Ok(package)
466}
467
468#[cfg(feature = "js")]
476pub fn verify_package(
477 trust: &nsh_package::TrustStore,
478 bytes: &[u8],
479 assets_root: &std::path::Path,
480) -> Result<LoadedPackage, String> {
481 let package = trust
482 .verify(bytes, BYTECODE_VERSION)
483 .map_err(|e| e.to_string())?;
484 let bundle = Bundle::from_package(&package)?;
485 let dir = assets_root.join(&package.app.id).join(&package.sha256);
486 let done = dir.join(".complete");
487 if !done.exists() {
488 let assets = dir.join("assets");
489 for (path, data) in &package.assets {
490 let dest = assets.join(path);
492 if let Some(parent) = dest.parent() {
493 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
494 }
495 std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
496 }
497 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
498 std::fs::write(&done, b"").map_err(|e| e.to_string())?;
499 }
500 Ok(LoadedPackage {
501 bundle,
502 assets: dir.join("assets"),
503 receipt: package.receipt(),
504 app: package.app,
505 })
506}
507
508#[cfg(feature = "js")]
513pub fn symbolicate(source_map: &str, text: &str) -> String {
514 symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
515}
516
517#[cfg(feature = "js")]
521pub fn accept_package(
522 trust: &mut nsh_package::TrustStore,
523 package: &LoadedPackage,
524) -> Result<(), String> {
525 trust
526 .accept_receipt(&package.receipt)
527 .map_err(|e| e.to_string())
528}
529
530pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
533 let value: serde_json::Value =
534 serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
535 Capabilities::from_json(&value)
536}
537
538impl Bundle {
539 pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
541 self.policy.declared = json.map(parse_capabilities).transpose()?;
542 Ok(self)
543 }
544}
545
546pub trait MountSink: Send + 'static {
549 fn submit(&self, batch: MountBatch);
551
552 fn report_error(&self, _message: &str) {}
558
559 fn report(&self, error: &AppError) {
563 self.report_error(&error.to_string());
564 }
565
566 fn request_frame(&self) {}
571
572 fn hot_update_failed(&self) {}
575
576 fn resized(&self, _size: Size<Points>) {}
582
583 fn load_chunk(&self, _id: &str) -> bool {
589 false
590 }
591}
592
593pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
597
598pub trait FetchTask: Send {
600 fn send(&mut self, chunk: Vec<u8>);
603 fn finish(&mut self);
605 fn pause(&mut self, paused: bool);
609 fn cancel(self: Box<Self>);
611}
612
613pub trait Network: Send + Sync + 'static {
615 fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
618}
619
620pub trait Assets: Send + Sync + 'static {
623 fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
625}
626
627#[derive(Clone)]
629pub struct EngineConfig {
630 pub app: App,
632 pub viewport: Size<Points>,
634 pub trace: bool,
636 pub network: Option<Arc<dyn Network>>,
638 pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
640 pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
642 pub assets: Option<Arc<dyn Assets>>,
644 pub environment: Environment,
646 pub header_heights: (Points, Points),
649 pub limits: Limits,
651 pub ui_sets: Vec<nsh_core::ui::Registry>,
655 pub runtime: Option<tokio::runtime::Handle>,
658 pub data_dir: Option<std::path::PathBuf>,
664 pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
668 pub clock: Clock,
672 pub pinned: EnvironmentPins,
675 pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
679}
680
681#[derive(Debug, Clone, Copy, Default, PartialEq)]
684#[non_exhaustive]
685pub struct EnvironmentPins {
686 pub locale: Option<nsh_core::platform::Locale>,
688 pub reduce_motion: Option<bool>,
691 pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
693}
694
695impl EnvironmentPins {
696 pub fn apply(&self, environment: &mut Environment) {
698 if let Some(locale) = self.locale {
699 environment.locale = locale;
700 }
701 if let Some(reduce_motion) = self.reduce_motion {
702 environment.reduce_motion = reduce_motion;
703 }
704 if let Some(safe_area) = self.safe_area {
705 environment.safe_area = safe_area;
706 }
707 }
708}
709
710fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
711 let path = path.filter(|path| path.is_absolute())?;
712 nsh_core::access::canonicalize(&path)
713 .ok()
714 .filter(|path| path.is_dir())
715}
716
717#[cfg(feature = "js")]
719fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
720 let mut paths = bundle.system_paths.clone();
721 paths.plugin_dir = trusted_directory(paths.plugin_dir);
722 paths.home_dir = trusted_directory(paths.home_dir);
723 if paths.home_dir.is_none() {
724 paths.home_dir = ["HOME", "USERPROFILE"]
725 .into_iter()
726 .filter_map(std::env::var_os)
727 .map(std::path::PathBuf::from)
728 .find_map(|path| trusted_directory(Some(path)));
729 }
730 if paths.plugin_dir.is_none() && !bundle.policy.harden {
734 paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
735 .map(std::path::PathBuf::from)
736 .and_then(|path| trusted_directory(Some(path)));
737 }
738 paths
739}
740
741impl EngineConfig {
742 pub fn new(app: impl Into<App>) -> Self {
749 Self {
750 app: app.into(),
751 viewport: Size::new(Points(390.0), Points(844.0)),
752 trace: false,
753 network: None,
754 websocket: None,
755 filesystem: None,
756 assets: None,
757 environment: Environment::default(),
758 header_heights: (Points(44.0), Points(96.0)),
759 limits: Limits::default(),
760 ui_sets: Vec::new(),
761 runtime: None,
762 data_dir: None,
763 storage: None,
764 clock: Clock::system(),
765 pinned: EnvironmentPins::default(),
766 clipboard: None,
767 }
768 }
769}
770
771fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
774 if let Some(storage) = &config.storage {
775 return Some(storage.clone());
776 }
777 #[cfg(not(target_arch = "wasm32"))]
778 if let Some(root) = &config.data_dir {
779 let dir = root.join(app_dir_name(config.app.app_id()));
780 return Some(FileStorage::open(dir));
781 }
782 None
783}
784
785#[cfg(not(target_arch = "wasm32"))]
786fn shared_runtime() -> tokio::runtime::Handle {
790 static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
791 RUNTIME
792 .get_or_init(|| {
793 tokio::runtime::Builder::new_multi_thread()
794 .worker_threads(2)
795 .thread_name("nsh-tasks")
796 .enable_all()
797 .build()
798 .expect("the tasks' runtime starts")
799 })
800 .handle()
801 .clone()
802}
803
804impl std::fmt::Debug for EngineConfig {
805 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
806 f.debug_struct("EngineConfig")
807 .field("app", &self.app)
808 .field("viewport", &self.viewport)
809 .field("trace", &self.trace)
810 .field("network", &self.network.is_some())
811 .field("assets", &self.assets.is_some())
812 .field("environment", &self.environment)
813 .field("header_heights", &self.header_heights)
814 .field("limits", &self.limits)
815 .field("ui_sets", &self.ui_sets)
816 .field("clock", &self.clock)
817 .field("pinned", &self.pinned)
818 .field("clipboard", &self.clipboard.is_some())
819 .finish()
820 }
821}
822
823const MAX_ADVANCE_ROUNDS: usize = 100_000;
827
828enum Message {
829 Event(NodeId, EventKind, EventPayload),
830 Scroll(NodeId, Point<Points>, u32),
831 Zoom(NodeId, f32),
832 ComponentSize(NodeId, Size<Points>),
833 AnimationsFinished(Vec<nsh_core::animation::Finished>),
834 Resize(Size<Points>),
835 Wake,
837 Environment(Environment),
838 RootSize(NodeId, Size<Points>, EdgeInsets),
839 ScreenHeader(NodeId, Option<Points>),
840 Frame,
841 States(NodeId, u8),
842 FontsChanged,
843 Fetch(Requester, u64, FetchEvent),
846 Hot(HotUpdate),
847 Chunk(Result<Chunk, (String, String)>),
850 Perf(Option<Arc<perf::PerfMonitor>>),
851 Tokens(Option<Box<Tokens>>),
853 Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
855 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
857 Shutdown,
858}
859
860#[derive(Debug, Clone)]
864pub struct HotUpdate {
865 pub name: String,
867 pub code: String,
869 pub source_map: Option<Arc<str>>,
871}
872
873const MAX_LIST_ROUNDS: usize = 8;
877
878#[derive(Clone)]
880pub struct EngineControl {
881 tx: Sender<Message>,
882}
883
884impl EngineControl {
885 pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
887 let _ = self.tx.send(Message::Event(id, event, payload));
888 }
889
890 pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
896 let _ = self.tx.send(Message::Scroll(id, offset, applied));
897 }
898
899 pub fn zoom(&self, id: NodeId, scale: f32) {
902 let _ = self.tx.send(Message::Zoom(id, scale));
903 }
904
905 pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
908 let _ = self.tx.send(Message::ComponentSize(id, size));
909 }
910
911 pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
913 let _ = self.tx.send(Message::AnimationsFinished(finished));
914 }
915
916 pub fn resize(&self, size: Size<Points>) {
918 let _ = self.tx.send(Message::Resize(size));
919 }
920
921 pub fn set_environment(&self, environment: Environment) {
924 let _ = self.tx.send(Message::Environment(environment));
925 }
926
927 pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
930 let _ = self.tx.send(Message::RootSize(id, size, insets));
931 }
932
933 pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
936 let _ = self.tx.send(Message::ScreenHeader(id, height));
937 }
938
939 pub fn hot_update(&self, update: HotUpdate) {
942 let _ = self.tx.send(Message::Hot(update));
943 }
944
945 pub fn chunk_loaded(&self, chunk: Chunk) {
948 let _ = self.tx.send(Message::Chunk(Ok(chunk)));
949 }
950
951 pub fn chunk_failed(&self, id: String, message: String) {
954 let _ = self.tx.send(Message::Chunk(Err((id, message))));
955 }
956
957 pub fn frame(&self) {
960 let _ = self.tx.send(Message::Frame);
961 }
962
963 pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
970 let _ = self.tx.send(Message::Advance(by, Box::new(done)));
971 }
972
973 pub fn set_states(&self, id: NodeId, states: u8) {
978 let _ = self.tx.send(Message::States(id, states));
979 }
980
981 pub fn fonts_changed(&self) {
985 let _ = self.tx.send(Message::FontsChanged);
986 }
987
988 pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
991 let _ = self.tx.send(Message::Perf(monitor));
992 }
993
994 pub fn set_tokens(&self, tokens: Option<Tokens>) {
999 let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1000 }
1001}
1002
1003#[cfg(not(target_arch = "wasm32"))]
1004pub struct Engine {
1006 control: EngineControl,
1007 thread: Option<std::thread::JoinHandle<()>>,
1008 stop: Arc<std::sync::atomic::AtomicBool>,
1010}
1011
1012#[cfg(not(target_arch = "wasm32"))]
1013impl Engine {
1014 pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
1016 where
1017 M: TextEngine + 'static,
1018 F: FnOnce() -> M + Send + 'static,
1019 S: MountSink,
1020 {
1021 Self::start_with(config, make_text_engine, sink, |_| {})
1022 }
1023
1024 pub fn start_with<M, F, S>(
1028 config: EngineConfig,
1029 make_text_engine: F,
1030 sink: S,
1031 setup: impl FnOnce(&EngineControl),
1032 ) -> io::Result<Engine>
1033 where
1034 M: TextEngine + 'static,
1035 F: FnOnce() -> M + Send + 'static,
1036 S: MountSink,
1037 {
1038 let (tx, rx) = crossbeam_channel::unbounded();
1039 setup(&EngineControl { tx: tx.clone() });
1040 let engine_tx = tx.clone();
1041 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1042 let engine_stop = stop.clone();
1043 let thread = std::thread::Builder::new()
1044 .name("nsh-engine".into())
1045 .stack_size(ENGINE_STACK_SIZE)
1046 .spawn(move || run(config, make_text_engine(), sink, engine_tx, rx, engine_stop))?;
1047 Ok(Engine {
1048 control: EngineControl { tx },
1049 thread: Some(thread),
1050 stop,
1051 })
1052 }
1053
1054 pub fn control(&self) -> EngineControl {
1056 self.control.clone()
1057 }
1058}
1059
1060#[cfg(not(target_arch = "wasm32"))]
1061impl Drop for Engine {
1062 fn drop(&mut self) {
1063 self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
1066 let _ = self.control.tx.send(Message::Shutdown);
1067 if let Some(thread) = self.thread.take() {
1068 let _ = thread.join();
1069 }
1070 }
1071}
1072
1073#[cfg(not(target_arch = "wasm32"))]
1074fn raise_thread_priority() {
1078 #[cfg(target_vendor = "apple")]
1079 unsafe {
1081 libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
1082 }
1083}
1084
1085#[cfg(not(target_arch = "wasm32"))]
1086fn run<M: TextEngine + 'static, S: MountSink>(
1087 config: EngineConfig,
1088 text_engine: M,
1089 sink: S,
1090 tx: Sender<Message>,
1091 rx: Receiver<Message>,
1092 stop: Arc<std::sync::atomic::AtomicBool>,
1093) {
1094 raise_thread_priority();
1095 let _clock = config.clock.enter();
1097 let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
1098 return;
1099 };
1100 loop {
1101 let message = match driver.deadline() {
1102 Some(deadline) => match rx.recv_deadline(deadline) {
1103 Ok(message) => Some(message),
1104 Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
1105 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
1106 },
1107 None => match rx.recv() {
1108 Ok(message) => Some(message),
1109 Err(_) => return,
1110 },
1111 };
1112 let started = driver.state.perf.is_some().then(Instant::now);
1113 if let Some(message) = message {
1114 if !driver.handle(message, &rx) {
1115 return;
1116 }
1117 while let Ok(message) = rx.try_recv() {
1119 if !driver.handle(message, &rx) {
1120 return;
1121 }
1122 }
1123 }
1124 driver.turn();
1125 driver.state.record_perf(started);
1126 if rx.is_empty() {
1127 driver.collect_if_idle();
1128 }
1129 }
1130}
1131
1132pub struct LocalEngine<M: TextEngine + 'static> {
1137 driver: Driver<M>,
1138 rx: Receiver<Message>,
1139 control: EngineControl,
1140 wake: Option<Arc<dyn Fn() + Send + Sync>>,
1142 pumping: Arc<std::sync::atomic::AtomicBool>,
1145}
1146
1147impl<M: TextEngine + 'static> LocalEngine<M> {
1148 pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
1151 let (tx, rx) = crossbeam_channel::unbounded();
1152 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1153 let control = EngineControl { tx: tx.clone() };
1154 let _clock = config.clock.enter();
1155 let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
1156 Some(LocalEngine {
1157 driver,
1158 rx,
1159 control,
1160 wake: None,
1161 pumping: Arc::default(),
1162 })
1163 }
1164
1165 pub fn control(&self) -> EngineControl {
1167 self.control.clone()
1168 }
1169
1170 pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
1179 let tx = self.control.tx.clone();
1180 let pumping = self.pumping.clone();
1181 let host = wake.clone();
1182 let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
1183 let _ = tx.send(Message::Wake);
1184 if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
1187 host();
1188 }
1189 });
1190 self.driver.state.core.set_task_notify(notify.clone());
1191 self.driver.posts.set_notify(notify);
1192 self.wake = Some(wake);
1193 }
1194
1195 pub fn pump(&mut self) -> Option<Instant> {
1199 let _clock = self.driver.clock.enter();
1200 self.pumping
1201 .store(true, std::sync::atomic::Ordering::SeqCst);
1202 for _ in 0..4 {
1205 let started = self.driver.state.perf.is_some().then(Instant::now);
1206 while let Ok(message) = self.rx.try_recv() {
1207 self.driver.handle(message, &self.rx);
1208 }
1209 self.driver.turn();
1210 self.driver.state.record_perf(started);
1211 if self.rx.is_empty() {
1212 break;
1213 }
1214 }
1215 self.driver.collect_if_idle();
1216 self.pumping
1217 .store(false, std::sync::atomic::Ordering::SeqCst);
1218 if !self.rx.is_empty()
1221 && let Some(wake) = &self.wake
1222 {
1223 wake();
1224 }
1225 self.driver.deadline()
1226 }
1227}
1228
1229struct Driver<M: TextEngine + 'static> {
1231 state: State<Rc<M>>,
1232 script: Option<Script>,
1233 sink: Rc<dyn MountSink>,
1234 assets: Option<Arc<dyn Assets>>,
1235 stopped: bool,
1238 last_gc: Instant,
1239 posts: nsh_core::ui::Posts,
1242 clock: Clock,
1244 last_frame: Option<Instant>,
1247}
1248
1249impl<M: TextEngine + 'static> Driver<M> {
1250 fn start(
1252 mut config: EngineConfig,
1253 text_engine: M,
1254 sink: Rc<dyn MountSink>,
1255 tx: Sender<Message>,
1256 rx: &Receiver<Message>,
1257 stop: Arc<std::sync::atomic::AtomicBool>,
1258 ) -> Option<Self> {
1259 config.pinned.apply(&mut config.environment);
1260 #[cfg(feature = "js")]
1261 let system_tx = tx.clone();
1262 let text_engine = Rc::new(text_engine);
1263 let access = Arc::new(match &config.app {
1264 App::Js(bundle) => bundle.policy.access(),
1265 App::Rust(_) => Policy::default().access(),
1267 });
1268 let mut core = Core::new(text_engine.clone(), config.viewport);
1269 core.set_components(nsh_core::ui::Registry::merged(&config.ui_sets));
1270 let posts = nsh_core::ui::Posts::new();
1274 core.set_posts(posts.clone());
1275 if let App::Js(_) = &config.app {
1276 core.set_max_nodes(config.limits.max_nodes);
1278 }
1279 core.set_access(access.clone());
1280 core.set_storage(app_storage(&config));
1281 core.set_clipboard(config.clipboard.clone());
1282 core.set_font_scale(config.environment.font_scale);
1283 core.set_class_environment(class_environment(&config.environment));
1284 core.set_header_heights(config.header_heights.0, config.header_heights.1);
1285 core.set_safe_area(insets(&config.environment));
1286 core.set_environment(ui_environment(&config.environment, config.viewport));
1287 #[cfg(not(target_arch = "wasm32"))]
1290 core.set_task_runtime(config.runtime.clone().unwrap_or_else(shared_runtime));
1291 if let App::Rust(root) = &config.app {
1294 if let Some(tokens) = root.tokens_ref() {
1295 core.set_tokens(tokens.clone());
1296 }
1297 if let Some(appearance) = root.appearance_ref() {
1298 core.set_appearance(appearance);
1299 }
1300 for font in root.fonts() {
1301 if let Err(err) = core.register_font(font) {
1302 log::error!("font failed: {err}");
1303 sink.report(&AppError::new(
1304 AppErrorKind::Asset,
1305 &format!("font failed: {err}"),
1306 ));
1307 }
1308 }
1309 }
1310 let fonts = config
1312 .ui_sets
1313 .iter()
1314 .flat_map(nsh_core::ui::Registry::asset_files)
1315 .filter(|file| file.kind == nsh_core::ui::AssetKind::Font);
1316 for font in fonts {
1317 let result = match config.assets.as_deref() {
1318 Some(assets) => assets.read(font.uri),
1319 None => Err("this host cannot load assets".to_owned()),
1320 }
1321 .and_then(|data| core.register_font(&data));
1322 if let Err(err) = result {
1323 log::error!("font failed: {}: {err}", font.uri);
1324 let message = format!("font failed: {}: {err}", font.uri);
1325 let package = match &config.app {
1326 App::Js(bundle) => bundle.package.clone(),
1327 App::Rust(_) => None,
1328 };
1329 sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
1330 }
1331 }
1332 let wake = tx.clone();
1335 core.set_task_notify(Arc::new(move || {
1336 let _ = wake.send(Message::Wake);
1337 }));
1338 let wake = tx.clone();
1339 posts.set_notify(Arc::new(move || {
1340 let _ = wake.send(Message::Wake);
1341 }));
1342 let js_tokens = core.tokens().clone();
1343 let state = State {
1344 core,
1345 js_tokens,
1346 frame_requested: false,
1347 ops: Vec::new(),
1348 binds: Vec::new(),
1349 events: Vec::new(),
1350 trace: config.trace,
1351 perf: None,
1352 perf_commit: perf::CommitTiming::default(),
1353 committed_since_gc: false,
1354 hot: Vec::new(),
1355 scroll_events: FxHashMap::default(),
1356 touch_move: None,
1357 hover_moves: Vec::new(),
1358 hover_moved: None,
1359 resized: None,
1360 pinned: config.pinned,
1361 net: Net {
1362 network: config.network.clone(),
1363 tx,
1364 queue: NetworkQueue::default(),
1365 inflight: FxHashMap::default(),
1366 tasks: Vec::new(),
1367 abandoned: Vec::new(),
1368 access: access.clone(),
1369 hops: 0,
1370 },
1371 };
1372
1373 let mut environment = config.environment;
1374 environment.window = config.viewport;
1375 let start = Instant::now();
1376 let mut driver = Driver {
1377 state,
1378 script: None,
1379 sink: sink.clone(),
1380 assets: config.assets.clone(),
1381 stopped: false,
1382 last_gc: Instant::now(),
1383 posts: posts.clone(),
1384 clock: config.clock.clone(),
1385 last_frame: None,
1386 };
1387 let eval_us = match &config.app {
1388 App::Js(bundle) => {
1389 #[cfg(feature = "js")]
1390 let system = {
1391 script::SystemConfig {
1392 access: (*access).clone(),
1393 websocket: config.websocket.clone(),
1394 filesystem: config.filesystem.clone(),
1395 data_dir: config
1396 .data_dir
1397 .as_ref()
1398 .map(|root| root.join(app_dir_name(config.app.app_id()))),
1399 paths: bundle_system_paths(bundle),
1400 wake: Arc::new(move || {
1401 let _ = system_tx.send(Message::Wake);
1402 }),
1403 }
1404 };
1405 #[cfg(not(feature = "js"))]
1406 let system = script::SystemConfig;
1407 let (script, eval_us) = Script::start(
1408 bundle,
1409 config.limits,
1410 &config.ui_sets,
1411 posts,
1412 &environment,
1413 driver.state.js_tokens.clone(),
1414 text_engine,
1415 stop,
1416 sink,
1417 system,
1418 )?;
1419 driver.script = Some(script);
1420 eval_us
1421 }
1422 App::Rust(root) => {
1423 driver.state.core.mount_root(root);
1424 0
1425 }
1426 };
1427 let Driver {
1428 state,
1429 script,
1430 sink,
1431 assets,
1432 ..
1433 } = &mut driver;
1434 let script = script.as_ref();
1435 let mut moves = Vec::new();
1438 while let Ok(message) = rx.try_recv() {
1439 if let Message::Advance(..) = message {
1440 moves.push(message);
1441 } else if !handle(script, state, message) {
1442 return None;
1443 }
1444 }
1445 if let Some(script) = script {
1448 script.run_system();
1449 }
1450 state.load_fonts(script, assets.as_deref(), &**sink);
1451 if let Some(batch) = state.commit(script) {
1452 if state.trace {
1453 log::info!(
1454 target: "nsh::perf",
1455 "first frame: eval {eval_us}µs, total {}µs",
1456 start.elapsed().as_micros()
1457 );
1458 }
1459 sink.submit(batch);
1460 }
1461 state.net.pump(script, &mut state.core);
1462 state.load_chunks(script, &**sink);
1463 state.request_frame(script, &**sink);
1464 driver.check_stopped();
1465 for message in moves {
1466 if !driver.handle(message, rx) {
1467 return None;
1468 }
1469 }
1470 Some(driver)
1471 }
1472
1473 fn deadline(&self) -> Option<Instant> {
1477 let gc_deadline = (self.script.is_some() && self.state.committed_since_gc)
1478 .then(|| self.last_gc + IDLE_GC_INTERVAL);
1479 let due = if self.clock.is_manual() {
1480 None
1481 } else {
1482 self.due()
1483 };
1484 [due, gc_deadline].into_iter().flatten().min()
1485 }
1486
1487 fn due(&self) -> Option<Instant> {
1490 [
1491 self.script.as_ref().and_then(Script::next_timer),
1492 self.state.next_scroll_event(),
1493 self.state.next_hover_move(),
1494 self.state.core.next_task_timer(),
1495 ]
1496 .into_iter()
1497 .flatten()
1498 .min()
1499 }
1500
1501 fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
1503 match message {
1504 Message::Advance(by, done) => {
1505 let running = self.advance(by, rx, self.clock.moves_with_frames());
1506 done();
1507 running
1508 }
1509 Message::Frame if self.clock.moves_with_frames() => {
1513 self.state.frame_requested = true;
1516 let by = self.next_frame() - self.clock.now();
1517 self.advance(by, rx, true)
1518 }
1519 message => handle(self.script.as_ref(), &mut self.state, message),
1520 }
1521 }
1522
1523 fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
1531 if !self.clock.is_manual() {
1532 self.turn();
1534 return true;
1535 }
1536 let to = self.clock.now() + by;
1537 for round in 0.. {
1538 let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
1541 let next = [self.due(), self.clock.next_alarm(), frame]
1542 .into_iter()
1543 .flatten()
1544 .min()
1545 .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
1546 if round == MAX_ADVANCE_ROUNDS {
1547 log::warn!(
1548 "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
1549 a timer keeps scheduling another at once"
1550 );
1551 }
1552 let at = next.unwrap_or(to);
1553 self.clock.advance_to(at);
1554 while let Ok(message) = rx.try_recv() {
1555 if !self.handle(message, rx) {
1556 return false;
1557 }
1558 }
1559 if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
1561 && self.state.frame_requested
1562 {
1563 self.frame();
1564 }
1565 self.turn();
1566 if next.is_none() {
1567 break;
1568 }
1569 }
1570 true
1571 }
1572
1573 fn next_frame(&self) -> Instant {
1578 let now = self.clock.now();
1579 self.last_frame
1580 .map_or(now + nsh_core::time::FRAME, |last| {
1581 last + nsh_core::time::FRAME
1582 })
1583 .max(now)
1584 }
1585
1586 fn frame(&mut self) {
1589 self.last_frame = Some(self.clock.now());
1590 handle(self.script.as_ref(), &mut self.state, Message::Frame);
1591 }
1592
1593 fn turn(&mut self) {
1596 let Driver {
1597 state,
1598 script,
1599 sink,
1600 assets,
1601 ..
1602 } = self;
1603 let script = script.as_ref();
1604 let turn_start = state.trace.then(Instant::now);
1605 state.dispatch_touch_move(script);
1606 if state
1607 .next_hover_move()
1608 .is_some_and(|due| due <= nsh_core::time::now())
1609 {
1610 state.dispatch_hover_moves(script);
1611 }
1612 state.dispatch_scroll_events(script);
1613 let hot = std::mem::take(&mut state.hot);
1614 if let Some(script) = script {
1615 for update in hot {
1616 script.hot_update(update, &**sink);
1617 }
1618 script.run_timers(nsh_core::time::now());
1619 script.run_system();
1620 }
1621 state.core.run_component_tasks();
1622 let tasks = turn_start.map(|s| s.elapsed());
1625 state.load_fonts(script, assets.as_deref(), &**sink);
1626 if let Some(batch) = state.commit(script) {
1627 sink.submit(batch);
1628 if let (Some(start), Some(tasks)) = (turn_start, tasks) {
1629 log::info!(
1630 target: "nsh::perf",
1631 "turn: {}µs (timers and tasks {}µs)",
1632 start.elapsed().as_micros(),
1633 tasks.as_micros(),
1634 );
1635 }
1636 }
1637 if let Some(size) = state.resized.take() {
1638 sink.resized(size);
1639 }
1640 state.net.pump(script, &mut state.core);
1641 state.load_chunks(script, &**sink);
1642 state.request_frame(script, &**sink);
1643 self.check_stopped();
1644 }
1645
1646 fn collect_if_idle(&mut self) {
1649 if let Some(script) = &self.script
1650 && self.state.committed_since_gc
1651 && self.last_gc.elapsed() >= IDLE_GC_INTERVAL
1652 {
1653 script.collect_garbage();
1654 self.last_gc = Instant::now();
1655 self.state.committed_since_gc = false;
1656 if let Some(batch) = self.state.commit(Some(script)) {
1657 self.sink.submit(batch);
1658 }
1659 }
1660 }
1661
1662 fn check_stopped(&mut self) {
1663 if let Some(script) = &self.script
1664 && !self.stopped
1665 && let Some(reason) = script.fatal()
1666 {
1667 self.stopped = true;
1668 script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
1669 }
1670 }
1671}
1672
1673struct ScrollEvent {
1674 x: f32,
1675 y: f32,
1676 content: Size<Points>,
1677 viewport: Size<Points>,
1678 zoom: f32,
1680 throttle: Duration,
1681 last: Option<Instant>,
1682 pending: bool,
1684}
1685
1686struct State<M: TextEngine> {
1687 core: Core<M>,
1688 js_tokens: Arc<nsh_core::ui::Tokens>,
1691 pinned: EnvironmentPins,
1694 frame_requested: bool,
1696 ops: Vec<Op>,
1697 binds: Vec<ListBind>,
1699 events: Vec<JsEvent>,
1701 trace: bool,
1702 perf: Option<Arc<perf::PerfMonitor>>,
1704 perf_commit: perf::CommitTiming,
1707 committed_since_gc: bool,
1708 net: Net,
1709 hot: Vec<HotUpdate>,
1711 scroll_events: FxHashMap<NodeId, ScrollEvent>,
1714 touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
1716 hover_moves: Vec<(NodeId, EventKind, EventPayload)>,
1720 hover_moved: Option<Instant>,
1722 resized: Option<Size<Points>>,
1724}
1725
1726#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1729enum Requester {
1730 Js(RequestId),
1731 Task(u32),
1732}
1733
1734struct Net {
1737 network: Option<Arc<dyn Network>>,
1738 tx: Sender<Message>,
1739 queue: NetworkQueue,
1740 inflight: FxHashMap<Requester, Inflight>,
1741 tasks: Vec<(u32, HttpRequest)>,
1744 abandoned: Vec<u32>,
1745 access: Arc<nsh_core::access::Access>,
1747 hops: u64,
1749}
1750
1751struct Inflight {
1753 task: Box<dyn FetchTask>,
1754 hop: u64,
1756 followed: Option<access::Followed>,
1758}
1759
1760impl Net {
1761 fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
1764 let mut abandoned = std::mem::take(&mut self.abandoned);
1765 core.take_fetches(&mut self.tasks, &mut abandoned);
1766 for id in abandoned.drain(..) {
1767 self.cancel(Requester::Task(id));
1768 }
1769 self.abandoned = abandoned;
1770 let mut tasks = std::mem::take(&mut self.tasks);
1771 for (id, request) in tasks.drain(..) {
1772 if let Err(refused) = self.request(Requester::Task(id), request) {
1773 core.fetch_event(id, FetchEvent::Failed(refused));
1774 }
1775 }
1776 self.tasks = tasks;
1777 let Some(script) = script else { return };
1778 script.take_network(&mut self.queue);
1779 for (id, op) in std::mem::take(&mut self.queue.ops) {
1780 let who = Requester::Js(id);
1781 match op {
1782 FetchOp::Start(request) => {
1783 if let Err(refused) = self.request(who, request) {
1784 script.fetch_event(id, FetchEvent::Failed(refused));
1785 }
1786 }
1787 FetchOp::Send(chunk) => {
1788 if let Some(i) = self.inflight.get_mut(&who) {
1789 i.task.send(chunk);
1790 }
1791 }
1792 FetchOp::Finish => {
1793 if let Some(i) = self.inflight.get_mut(&who) {
1794 i.task.finish();
1795 }
1796 }
1797 FetchOp::Pause(paused) => {
1798 if let Some(i) = self.inflight.get_mut(&who) {
1799 i.task.pause(paused);
1800 }
1801 }
1802 FetchOp::Cancel => self.cancel(who),
1803 }
1804 }
1805 }
1806
1807 fn cancel(&mut self, who: Requester) {
1809 if let Some(i) = self.inflight.remove(&who) {
1810 i.task.cancel();
1811 }
1812 }
1813
1814 fn request(&mut self, who: Requester, request: HttpRequest) -> Result<(), String> {
1816 if self.access.is_unrestricted() {
1817 self.start(who, request, None);
1818 } else if !self.access.allows_http(&request.method, &request.url) {
1819 return Err(access::refused(&request.method, &request.url));
1820 } else if request.follow_redirects {
1821 let hop = access::hop(&request);
1822 let followed = access::Followed { request, hops: 0 };
1823 self.start(who, hop, Some(followed));
1824 } else {
1825 self.start(who, request, None);
1826 }
1827 Ok(())
1828 }
1829
1830 fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
1832 self.hops += 1;
1833 let hop = self.hops;
1834 let Some(network) = &self.network else {
1835 let failed = FetchEvent::Failed("this host has no network stack".to_owned());
1836 let _ = self.tx.send(Message::Fetch(id, hop, failed));
1837 return;
1838 };
1839 let tx = self.tx.clone();
1840 let events: FetchEvents = Box::new(move |event| {
1841 let _ = tx.send(Message::Fetch(id, hop, event));
1842 });
1843 let task = network.fetch(request, events);
1844 self.inflight.insert(
1845 id,
1846 Inflight {
1847 task,
1848 hop,
1849 followed,
1850 },
1851 );
1852 }
1853
1854 fn event(&mut self, id: Requester, hop: u64, event: FetchEvent) -> Option<FetchEvent> {
1858 if self.network.is_none() {
1859 return Some(event);
1860 }
1861 let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
1862 match event {
1863 FetchEvent::Head(head) => {
1864 let Some(followed) = &mut inflight.followed else {
1865 return Some(FetchEvent::Head(head));
1866 };
1867 match access::next(&self.access, followed, head) {
1868 access::Next::Done(head) => Some(FetchEvent::Head(head)),
1869 access::Next::Fail(message) => {
1870 if let Some(i) = self.inflight.remove(&id) {
1871 i.task.cancel();
1872 }
1873 Some(FetchEvent::Failed(message))
1874 }
1875 access::Next::Hop(request) => {
1876 let i = self.inflight.remove(&id)?;
1877 let followed = i.followed;
1878 i.task.cancel();
1879 self.start(id, request, followed);
1880 None
1881 }
1882 }
1883 }
1884 FetchEvent::End | FetchEvent::Failed(_) => {
1885 self.inflight.remove(&id);
1886 Some(event)
1887 }
1888 event => Some(event),
1889 }
1890 }
1891}
1892
1893impl<M: TextEngine> State<M> {
1894 fn record_perf(&mut self, started: Option<Instant>) {
1897 let (Some(started), Some(monitor)) = (started, &self.perf) else {
1898 return;
1899 };
1900 let busy = started.elapsed();
1901 monitor.record_busy(busy);
1902 let mut commit = std::mem::take(&mut self.perf_commit);
1903 if commit.ops > 0 || commit.items > 0 {
1904 commit.js = busy.saturating_sub(commit.layout);
1905 monitor.record_commit(commit);
1906 }
1907 }
1908
1909 fn dispatch_touch_move(&mut self, script: Option<&Script>) {
1911 if let Some((id, touch)) = self.touch_move.take()
1912 && let Some(script) = script
1913 {
1914 script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
1915 }
1916 }
1917
1918 fn next_hover_move(&self) -> Option<Instant> {
1920 if self.hover_moves.is_empty() {
1921 return None;
1922 }
1923 Some(
1924 self.hover_moved
1925 .map_or_else(nsh_core::time::now, |t| t + HOVER_MOVE_INTERVAL),
1926 )
1927 }
1928
1929 fn dispatch_hover_moves(&mut self, script: Option<&Script>) {
1932 if self.hover_moves.is_empty() {
1933 return;
1934 }
1935 self.hover_moved = Some(nsh_core::time::now());
1936 for (id, kind, payload) in std::mem::take(&mut self.hover_moves) {
1937 if self.core.component_event(id, kind, &payload) {
1938 continue;
1939 }
1940 if let Some(script) = script {
1941 script.dispatch_event(id, kind, &payload);
1942 }
1943 }
1944 }
1945
1946 fn next_scroll_event(&self) -> Option<Instant> {
1948 self.scroll_events
1949 .values()
1950 .filter(|e| e.pending)
1951 .filter_map(|e| e.last.map(|t| t + e.throttle))
1952 .min()
1953 }
1954
1955 fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
1957 if self.scroll_events.is_empty() {
1958 return;
1959 }
1960 let now = nsh_core::time::now();
1961 let core = &self.core;
1963 self.scroll_events
1964 .retain(|&id, _| core.scroll_listener(id).is_some());
1965 for (&id, e) in &mut self.scroll_events {
1966 if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
1967 continue;
1968 }
1969 e.pending = false;
1970 e.last = Some(now);
1971 let n = |v: f32| PayloadValue::Number(v as f64);
1972 let payload = EventPayload::Map(vec![
1973 (
1974 "offset",
1975 PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
1976 ),
1977 ("contentSize", PayloadValue::Size(e.content)),
1978 ("size", PayloadValue::Size(e.viewport)),
1979 ("zoomScale", n(e.zoom)),
1980 ]);
1981 if !self.core.component_event(id, EventKind::Scroll, &payload)
1983 && let Some(script) = script
1984 {
1985 script.dispatch_event(id, EventKind::Scroll, &payload);
1986 }
1987 }
1988 }
1989
1990 fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
1992 let Some(script) = script else { return };
1993 let mut ids = Vec::new();
1994 script.take_chunk_requests(&mut ids);
1995 for id in ids {
1996 if !sink.load_chunk(&id) {
1997 let message = "this host does not load chunks (the app was built split)".to_owned();
1998 let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
1999 }
2000 }
2001 }
2002
2003 fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
2006 if !self.frame_requested
2007 && (script.is_some_and(Script::wants_frame) || self.core.wants_frame())
2008 {
2009 self.frame_requested = true;
2010 sink.request_frame();
2011 }
2012 }
2013
2014 fn load_fonts(
2017 &mut self,
2018 script: Option<&Script>,
2019 assets: Option<&dyn Assets>,
2020 sink: &dyn MountSink,
2021 ) {
2022 let Some(script) = script else { return };
2023 let mut fonts = Vec::new();
2024 script.take_fonts(&mut fonts);
2025 for uri in fonts {
2026 let result = match assets {
2027 Some(assets) => assets.read(&uri),
2028 None => Err("this host cannot load assets".to_owned()),
2029 }
2030 .and_then(|data| self.core.register_font(&data));
2031 if let Err(err) = result {
2032 script.report(
2033 sink,
2034 AppErrorKind::Asset,
2035 "font failed",
2036 &format!("{uri}: {err}"),
2037 );
2038 }
2039 }
2040 }
2041
2042 fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
2045 let start = Instant::now();
2046 let mut merged: Option<MountBatch> = None;
2047 let mut op_count = 0;
2048 let mut js = std::time::Duration::ZERO;
2049 for _ in 0..MAX_LIST_ROUNDS {
2050 let js_start = Instant::now();
2052 let binds = self.binds.drain(..);
2055 if let Some(script) = script {
2056 for bind in binds {
2057 script.bind_list(bind.list, &bind.binds);
2058 }
2059 } else {
2060 drop(binds);
2061 }
2062 if let Some(script) = script {
2065 script.run_posted();
2066 }
2067 for event in self.events.drain(..) {
2071 match event {
2072 JsEvent::Event(id, event, payload) => {
2073 if !self.core.component_event(id, event, &payload)
2074 && let Some(script) = script
2075 {
2076 script.dispatch_event(id, event, &payload);
2077 }
2078 }
2079 other => {
2081 if let Some(script) = script {
2082 script.deliver(other);
2083 }
2084 }
2085 }
2086 }
2087 if let Some(script) = script {
2088 script.take_ops(&mut self.ops);
2089 }
2090 js += js_start.elapsed();
2091 op_count += self.ops.len();
2092 let mut ops = self.ops.drain(..);
2095 while let Some(op) = ops.next() {
2096 match self.core.apply(op) {
2097 Ok(()) => {}
2098 Err(err) if err.is_fatal() => {
2099 self.core.discard_ops(ops.by_ref());
2100 let Some(script) = script else { break };
2101 script.stop(match err {
2102 ApplyError::TooManyNodes(max) => {
2103 format!("the app created more than {max} nodes and was stopped")
2104 }
2105 other => {
2106 format!("the app sent an invalid op ({other:?}) and was stopped")
2107 }
2108 });
2109 break;
2110 }
2111 Err(err) => log::error!("invalid op: {err:?}"),
2112 }
2113 }
2114 if let Some(batch) = self.core.commit() {
2115 match &mut merged {
2116 Some(m) => extend_frame(&mut m.items, batch.items),
2117 None => merged = Some(batch),
2118 }
2119 }
2120 self.core.take_list_binds(&mut self.binds);
2121 self.core.take_events(&mut self.events);
2122 let posted = script.is_some_and(Script::has_posted);
2124 let retheme = match script {
2127 Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
2128 self.js_tokens = self.core.tokens().clone();
2129 script.set_tokens(self.js_tokens.clone());
2130 true
2131 }
2132 _ => false,
2133 };
2134 if self.binds.is_empty() && self.events.is_empty() && !posted && !retheme {
2135 break;
2136 }
2137 }
2138 self.committed_since_gc |= op_count > 0;
2139 if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
2140 let c = &mut self.perf_commit;
2141 c.layout += start.elapsed().saturating_sub(js);
2142 c.ops += op_count as u32;
2143 c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
2144 }
2145 if self.trace && (op_count > 0 || merged.is_some()) {
2146 log::info!(
2147 target: "nsh::perf",
2148 "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
2149 start.elapsed().as_micros(),
2150 js.as_micros(),
2151 merged.as_ref().map_or(0, |b| b.items.len()),
2152 self.core.node_count(),
2153 );
2154 }
2155 merged
2156 }
2157}
2158
2159fn insets(env: &Environment) -> EdgeInsets {
2160 env.safe_area
2161}
2162
2163fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::ui::Environment {
2165 nsh_core::ui::Environment {
2166 window,
2167 safe_area: insets(env),
2168 title_bar: env.title_bar,
2169 keyboard_height: env.keyboard_height,
2170 keyboard_duration: env.keyboard_duration,
2171 dark: env.color_scheme == ColorScheme::Dark,
2172 font_scale: env.font_scale,
2173 reduce_motion: env.reduce_motion,
2174 screen_reader: env.screen_reader,
2175 rtl: env.rtl,
2176 pixel_ratio: env.pixel_ratio,
2177 os: env.os,
2178 os_version: env.os_version,
2179 idiom: env.idiom,
2180 locale: env.locale,
2181 apple_keyboard: env.apple_keyboard,
2182 }
2183}
2184
2185fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
2187 nsh_core::tailwind::ClassEnvironment {
2188 dark: env.color_scheme == ColorScheme::Dark,
2189 platform: if env.os == Os::Web {
2190 nsh_core::tailwind::Platform::Web
2191 } else if cfg!(target_os = "android") {
2192 nsh_core::tailwind::Platform::Android
2193 } else {
2194 nsh_core::tailwind::Platform::Ios
2195 },
2196 reduce_motion: env.reduce_motion,
2197 }
2198}
2199
2200fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
2202 match message {
2203 Message::Event(id, event, payload) => {
2204 if state.trace {
2205 log::info!(target: "nsh::perf", "event {event:?} on view {id}");
2206 }
2207 if event == EventKind::MouseMove
2211 || (event == EventKind::HoverMove && matches!(payload, EventPayload::Hover(_)))
2212 {
2213 match state
2214 .hover_moves
2215 .iter_mut()
2216 .find(|(v, kind, _)| *v == id && *kind == event)
2217 {
2218 Some((_, _, pending)) => *pending = payload,
2219 None => state.hover_moves.push((id, event, payload)),
2220 }
2221 return true;
2222 }
2223 state.dispatch_hover_moves(script);
2224 if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
2227 state.core.input_changed(id, text, *count);
2228 }
2229 if state.core.component_event(id, event, &payload) {
2231 return true;
2232 }
2233 if let EventPayload::Touch(touch) = payload {
2234 if touch.phase == nsh_core::TouchPhase::Move {
2235 match &mut state.touch_move {
2236 Some((_, pending)) => pending.merge_move(*touch),
2237 None => state.touch_move = Some((id, touch)),
2238 }
2239 return true;
2240 }
2241 state.dispatch_touch_move(script);
2243 if let Some(script) = script {
2244 script.dispatch_event(id, event, &EventPayload::Touch(touch));
2245 }
2246 return true;
2247 }
2248 let Some(script) = script else { return true };
2249 let start = state.trace.then(Instant::now);
2250 script.dispatch_event(id, event, &payload);
2251 if let Some(start) = start {
2252 log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
2255 }
2256 }
2257 Message::Scroll(id, offset, applied) => {
2258 state.core.set_scroll_offset(id, offset, applied);
2259 let (x, y) = (offset.x.0, offset.y.0);
2260 if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
2261 let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
2262 x,
2263 y,
2264 content,
2265 viewport,
2266 zoom,
2267 throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
2268 last: None,
2269 pending: true,
2270 });
2271 (event.x, event.y, event.content, event.viewport, event.zoom) =
2272 (x, y, content, viewport, zoom);
2273 event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
2274 event.pending = true;
2275 }
2276 }
2277 Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
2278 Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
2279 Message::AnimationsFinished(mut finished) => {
2280 state.core.animations_finished(&mut finished);
2282 if let Some(script) = script {
2283 script.animations_finished(&finished);
2284 }
2285 }
2286 Message::Resize(size) => {
2287 state.core.set_viewport(size);
2288 state.resized = Some(size);
2289 }
2290 Message::Wake => {}
2291 Message::Environment(mut env) => {
2292 state.pinned.apply(&mut env);
2293 state.core.set_font_scale(env.font_scale);
2294 state.core.set_class_environment(class_environment(&env));
2295 state.core.set_safe_area(insets(&env));
2296 let window = env.window;
2297 state.core.set_environment(ui_environment(&env, window));
2298 if let Some(script) = script {
2299 script.set_environment(&env);
2300 }
2301 }
2302 Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
2303 Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
2304 Message::Frame => {
2305 state.frame_requested = false;
2306 state.core.run_frame(nsh_core::time::now());
2307 if let Some(script) = script {
2308 script.run_frame();
2309 }
2310 }
2311 Message::States(id, states) => state.core.set_states(id, states),
2312 Message::FontsChanged => state.core.fonts_changed(),
2313 Message::Fetch(who, hop, event) => {
2314 if let Some(event) = state.net.event(who, hop, event) {
2315 match who {
2316 Requester::Js(id) => {
2317 if let Some(script) = script {
2318 script.fetch_event(id, event);
2319 }
2320 }
2321 Requester::Task(id) => {
2322 if !state.core.fetch_event(id, event) {
2323 state.net.cancel(who);
2324 }
2325 }
2326 }
2327 }
2328 }
2329 Message::Hot(update) => state.hot.push(update),
2330 Message::Chunk(chunk) => {
2331 if let Some(script) = script {
2332 script.chunk(chunk);
2333 }
2334 }
2335 Message::Perf(monitor) => {
2336 state.perf = monitor;
2337 state.perf_commit = perf::CommitTiming::default();
2338 }
2339 Message::Tokens(tokens) => state.core.set_host_tokens(tokens.map(|t| *t)),
2340 Message::Advance(..) => unreachable!("the driver moves the clock"),
2343 Message::Shutdown => return false,
2344 }
2345 true
2346}
2347
2348fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
2354 use nsh_core::MountItem;
2355 let start = frame.len();
2356 frame.extend(items);
2357 for k in start..frame.len() {
2358 let MountItem::ScrollContent { id, size } = frame[k] else {
2359 continue;
2360 };
2361 let earlier = frame[..k].iter().rposition(|m| {
2362 matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
2363 });
2364 if let Some(j) = earlier
2365 && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
2366 {
2367 *s = size;
2368 }
2369 }
2370}
2371
2372#[cfg(test)]
2373mod tests {
2374 #[test]
2375 fn pinned_values_hold_whatever_the_platform_reports() {
2376 let pins = super::EnvironmentPins {
2377 locale: nsh_core::platform::Locale::parse("de-DE"),
2378 reduce_motion: Some(true),
2379 ..Default::default()
2380 };
2381 let mut reported = super::Environment {
2382 locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
2383 font_scale: 1.5,
2384 ..Default::default()
2385 };
2386 pins.apply(&mut reported);
2387 assert_eq!(reported.locale.as_str(), "de-DE");
2388 assert!(reported.reduce_motion);
2389 assert_eq!(reported.font_scale, 1.5);
2391 assert_eq!(reported.safe_area, Default::default());
2392 }
2393
2394 #[test]
2395 fn bundle_default_has_no_application_selected_path_anchors() {
2396 let bundle = super::Bundle::default();
2397 assert!(bundle.system_paths.plugin_dir.is_none());
2398 assert!(bundle.system_paths.home_dir.is_none());
2399 assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
2400 }
2401
2402 #[test]
2403 fn bundle_trusted_paths_reject_relative_and_missing_directories() {
2404 let mut paths = nsh_core::access::TrustedPaths::default();
2405 paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
2406 paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
2407 let bundle = super::Bundle::default().with_system_paths(paths);
2408 assert!(bundle.system_paths.plugin_dir.is_none());
2409 assert!(bundle.system_paths.home_dir.is_none());
2410 assert!(
2411 super::trusted_directory(Some(std::path::PathBuf::from(
2412 "/nsh-nonexistent-anchor-never-created"
2413 )))
2414 .is_none()
2415 );
2416 }
2417
2418 #[test]
2419 fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
2420 let root = std::env::var_os("TMPDIR")
2421 .map(std::path::PathBuf::from)
2422 .unwrap_or_else(|| {
2423 std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
2424 .join(".cache/nsh-benchs-test-tmp")
2425 });
2426 assert!(root.is_absolute() && !root.starts_with("/tmp"));
2427 let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
2428 std::fs::create_dir_all(&directory).unwrap();
2429 let path = directory.join("bundle.js");
2430 std::fs::write(&path, "export default null;").unwrap();
2431 let bundle = super::Bundle::read(&path).unwrap();
2432 assert_eq!(
2433 bundle.system_paths.plugin_dir,
2434 Some(nsh_core::access::canonicalize(&directory).unwrap())
2435 );
2436 assert!(bundle.system_paths.home_dir.is_none());
2437 std::fs::remove_dir_all(directory).unwrap();
2438 }
2439
2440 #[test]
2441 fn rust_environment_preserves_native_title_bar_insets() {
2442 use super::{Edges, Points};
2443 let title_bar = Edges {
2444 top: Points(42.0),
2445 left: Points(78.0),
2446 right: Points(138.0),
2447 bottom: Points(0.0),
2448 };
2449 let environment = super::Environment {
2450 title_bar,
2451 ..Default::default()
2452 };
2453 assert_eq!(
2454 super::ui_environment(
2455 &environment,
2456 nsh_core::Size::new(Points(840.0), Points(630.0))
2457 )
2458 .title_bar,
2459 title_bar
2460 );
2461 }
2462
2463 use nsh_core::{MountItem, Points, Size};
2464
2465 #[test]
2466 fn a_frame_sends_a_scroll_views_last_content_size() {
2467 let content = |height| MountItem::ScrollContent {
2468 id: 2,
2469 size: Size::new(Points(390.0), height),
2470 };
2471 let heights = |frame: &[MountItem]| -> Vec<f32> {
2472 frame
2473 .iter()
2474 .filter_map(|m| match m {
2475 MountItem::ScrollContent { size, .. } => Some(size.height.0),
2476 _ => None,
2477 })
2478 .collect()
2479 };
2480 let mut frame = vec![content(Points(313.0))];
2481 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
2482 assert_eq!(heights(&frame), [544.0, 544.0]);
2483 let mut frame = vec![
2485 content(Points(313.0)),
2486 MountItem::ScrollBy {
2487 id: 2,
2488 dx: Points(0.0),
2489 dy: Points(10.0),
2490 },
2491 ];
2492 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
2493 assert_eq!(heights(&frame), [313.0, 544.0]);
2494 }
2495}