1mod access;
12mod app_directory;
13mod cache;
14mod error;
15mod host_channel;
16mod local_storage;
17#[cfg(feature = "net")]
18pub mod net;
19pub mod perf;
20mod script;
21#[cfg(not(target_arch = "wasm32"))]
22mod storage;
23#[cfg(feature = "js")]
24mod symbolicate;
25
26#[cfg(test)]
29#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
30mod unit_scan;
31
32#[cfg(test)]
33#[test]
34fn public_api_is_typed() {
35 unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
36}
37
38use std::{io, mem::ManuallyDrop, rc::Rc, sync::Arc, time::Duration};
39
40pub use app_directory::app_dir_name;
41use crossbeam_channel::{Receiver, Sender};
42pub use local_storage::local_storage_prefix;
43use nsh_core::{
44 ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
45 PayloadValue, TextEngine, element::JsEvent, time::Instant,
46};
47pub use nsh_core::{
48 JsonValue,
49 access::{Access, Capabilities},
50 element::{EngineContext, Root, Tokens},
51 geometry::{self, Bounds, Edges, Point, Points, Size},
52 js::{HostLimits, Limits},
53 platform::{
54 ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HttpBody, HttpHead,
55 HttpRequest, Idiom, Locale, Os,
56 },
57 storage::{StorageBackend, StorageChange},
58 time::Clock,
59};
60#[cfg(feature = "js")]
61pub use nsh_js::BYTECODE_VERSION;
62#[cfg(feature = "js")]
64pub use nsh_package as package;
65use rustc_hash::FxHashMap;
66#[cfg(not(target_arch = "wasm32"))]
67pub use storage::{FileStorage, data_dir};
68
69use crate::script::{NetworkQueue, RequestId, Script};
70pub use crate::{
71 cache::{ByteSize, CacheLocation, CacheOptions, CachePolicy},
72 error::{AppError, AppErrorKind, PackageInfo},
73 host_channel::{HostCall, HostChannel, HostReply, OpenUrlRequest},
74};
75
76#[cfg(not(target_arch = "wasm32"))]
77const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
81
82const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
86
87const IDLE_GC_QUIET: Duration = Duration::from_millis(300);
94
95const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);
97
98const HOVER_MOVE_INTERVAL: Duration = Duration::from_millis(8);
102
103#[derive(Debug, Clone)]
105#[allow(
106 clippy::large_enum_variant,
107 reason = "one app per surface; keep the public constructor API without allocation"
108)]
109pub enum App {
110 Rust(Root),
112 Js(Bundle),
114}
115
116impl From<Bundle> for App {
117 fn from(bundle: Bundle) -> Self {
118 App::Js(bundle)
119 }
120}
121
122impl App {
123 pub fn app_id(&self) -> Option<&str> {
125 match self {
126 App::Rust(root) => root.app_id_ref(),
127 App::Js(bundle) => bundle.app_id.as_deref(),
128 }
129 }
130}
131
132impl From<Root> for App {
133 fn from(root: Root) -> Self {
134 App::Rust(root)
135 }
136}
137
138#[derive(Debug, Clone)]
140#[non_exhaustive]
141pub struct Bundle {
142 pub code: BundleCode,
144 pub source_map: Option<Arc<str>>,
146 pub policy: Policy,
148 pub base_url: Option<Arc<str>>,
151 pub chunks: Arc<Vec<Chunk>>,
155 pub harden_bytecode: Option<Arc<Vec<u8>>>,
160 pub app_id: Option<String>,
163 pub system_paths: nsh_core::access::TrustedPaths,
167 pub package: Option<Arc<PackageInfo>>,
170}
171
172#[derive(Debug, Clone)]
175pub struct Chunk {
176 pub id: String,
178 pub code: BundleCode,
180 pub source_map: Option<Arc<str>>,
182}
183
184impl Chunk {
185 pub fn source(id: impl Into<String>, code: String) -> Self {
187 Self {
188 id: id.into(),
189 code: BundleCode::Source(code),
190 source_map: None,
191 }
192 }
193
194 pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
200 Self {
201 id: id.into(),
202 code: BundleCode::Bytecode(bytes),
203 source_map: None,
204 }
205 }
206
207 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
209 self.source_map = Some(map.into());
210 self
211 }
212}
213
214#[derive(Debug, Clone)]
216pub struct Policy {
217 pub harden: bool,
221 pub declared: Option<Capabilities>,
224 pub granted: Option<Capabilities>,
227}
228
229impl Default for Policy {
230 fn default() -> Self {
231 Self {
232 harden: true,
233 declared: None,
234 granted: None,
235 }
236 }
237}
238
239impl Policy {
240 pub fn development() -> Self {
244 Self {
245 harden: false,
246 ..Self::default()
247 }
248 }
249
250 pub fn access(&self) -> Access {
252 Access {
253 declared: self.declared.clone().unwrap_or_else(Capabilities::all),
254 granted: self.granted.clone(),
255 }
256 }
257}
258
259#[derive(Debug, Clone)]
261pub enum BundleCode {
262 Bytecode(Vec<u8>),
264 Source(String),
266}
267
268impl Default for Bundle {
269 fn default() -> Self {
270 Self::source(String::new())
271 }
272}
273
274impl Bundle {
275 pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
285 Self {
286 code: BundleCode::Bytecode(bytes),
287 source_map: None,
288 policy: Policy::default(),
289 base_url: None,
290 chunks: Arc::default(),
291 harden_bytecode: None,
292 app_id: None,
293 system_paths: nsh_core::access::TrustedPaths::default(),
294 package: None,
295 }
296 }
297
298 pub fn source(code: String) -> Self {
300 Self {
301 code: BundleCode::Source(code),
302 source_map: None,
303 policy: Policy::default(),
304 base_url: None,
305 chunks: Arc::default(),
306 harden_bytecode: None,
307 app_id: None,
308 system_paths: nsh_core::access::TrustedPaths::default(),
309 package: None,
310 }
311 }
312
313 pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
318 paths.plugin_dir = trusted_directory(paths.plugin_dir);
319 paths.home_dir = trusted_directory(paths.home_dir);
320 self.system_paths = paths;
321 self
322 }
323
324 pub fn with_app_id(mut self, id: Option<&str>) -> Self {
327 self.app_id = id.map(str::to_owned);
328 self
329 }
330
331 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
333 self.source_map = Some(map.into());
334 self
335 }
336
337 pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
339 self.base_url = Some(url.into());
340 self
341 }
342
343 pub unsafe fn with_harden_bytecode(mut self, bytes: Vec<u8>) -> Self {
350 self.harden_bytecode = Some(Arc::new(bytes));
351 self
352 }
353
354 pub fn with_policy(mut self, policy: Policy) -> Self {
356 self.policy = policy;
357 self
358 }
359
360 pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
362 Arc::make_mut(&mut self.chunks).extend(chunks);
363 self
364 }
365
366 pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
372 if path.extension().is_some_and(|e| e == "nshc") {
373 return Err(io::Error::other(
374 "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
375 ));
376 }
377 unsafe { Self::read_trusted(path) }
379 }
380
381 pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
388 let bytes = std::fs::read(path)?;
389 let bundle = if path.extension().is_some_and(|e| e == "nshc") {
390 unsafe { Bundle::bytecode(bytes) }
392 } else {
393 Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
394 };
395 let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
396 Ok(map) if !map.is_empty() => bundle.with_source_map(map),
397 _ => bundle,
398 };
399 if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
400 bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
401 }
402 bundle.app_id = read_app_id(&path.with_file_name("app.json"));
403 bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
404 .parent()
405 .map(std::path::Path::to_path_buf);
406 Ok(bundle)
407 }
408}
409
410#[cfg(feature = "js")]
411impl Bundle {
412 pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
418 for ignored in &package.ignored {
419 log::warn!("package {}: ignored {ignored}", package.app.id);
420 }
421 let bundle = match package.bytecode() {
422 Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
425 None => Bundle::source(package.source.clone()),
426 };
427 let mut bundle = match &package.source_map {
428 Some(map) => bundle.with_source_map(map.clone()),
429 None => bundle,
430 };
431 if let Some(json) = &package.capabilities {
432 let (declared, dropped) = Capabilities::from_json_lenient(json)?;
433 for dropped in dropped {
434 log::warn!("package {}: not granted: {dropped}", package.app.id);
435 }
436 bundle.policy.declared = Some(declared);
437 }
438 bundle.app_id = Some(package.app.id.clone());
439 bundle.package = Some(Arc::new(PackageInfo {
440 id: package.app.id.clone(),
441 name: package.app.name.clone(),
442 version: package.app.version.clone(),
443 build: package.app.build,
444 sha256: package.sha256.clone(),
445 }));
446 Ok(bundle)
447 }
448}
449
450fn read_app_id(path: &std::path::Path) -> Option<String> {
452 let json: serde_json::Value =
453 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()?;
454 json.get("id")?.as_str().map(str::to_owned)
455}
456
457#[cfg(feature = "js")]
459#[derive(Debug)]
460pub struct LoadedPackage {
461 pub bundle: Bundle,
463 pub assets: std::path::PathBuf,
465 pub app: nsh_package::App,
467 pub receipt: nsh_package::PackageReceipt,
469}
470
471#[cfg(feature = "js")]
476pub fn load_package(
477 trust: &mut nsh_package::TrustStore,
478 bytes: &[u8],
479 assets_root: &std::path::Path,
480) -> Result<LoadedPackage, String> {
481 let package = verify_package(trust, bytes, assets_root)?;
482 accept_package(trust, &package)?;
483 Ok(package)
484}
485
486#[cfg(feature = "js")]
494pub fn verify_package(
495 trust: &nsh_package::TrustStore,
496 bytes: &[u8],
497 assets_root: &std::path::Path,
498) -> Result<LoadedPackage, String> {
499 let package = trust
500 .verify(bytes, BYTECODE_VERSION)
501 .map_err(|e| e.to_string())?;
502 let bundle = Bundle::from_package(&package)?;
503 let dir = assets_root.join(&package.app.id).join(&package.sha256);
504 let done = dir.join(".complete");
505 if !done.exists() {
506 let assets = dir.join("assets");
507 for (path, data) in &package.assets {
508 let dest = assets.join(path);
510 if let Some(parent) = dest.parent() {
511 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
512 }
513 std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
514 }
515 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
516 std::fs::write(&done, b"").map_err(|e| e.to_string())?;
517 }
518 Ok(LoadedPackage {
519 bundle,
520 assets: dir.join("assets"),
521 receipt: package.receipt(),
522 app: package.app,
523 })
524}
525
526#[cfg(feature = "js")]
531pub fn symbolicate(source_map: &str, text: &str) -> String {
532 symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
533}
534
535#[cfg(feature = "js")]
539pub fn accept_package(
540 trust: &mut nsh_package::TrustStore,
541 package: &LoadedPackage,
542) -> Result<(), String> {
543 trust
544 .accept_receipt(&package.receipt)
545 .map_err(|e| e.to_string())
546}
547
548pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
551 let value: serde_json::Value =
552 serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
553 Capabilities::from_json(&value)
554}
555
556impl Bundle {
557 pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
559 self.policy.declared = json.map(parse_capabilities).transpose()?;
560 Ok(self)
561 }
562}
563
564pub trait MountSink: Send + 'static {
567 fn submit(&self, batch: MountBatch);
569
570 fn report_error(&self, _message: &str) {}
576
577 fn report(&self, error: &AppError) {
581 self.report_error(&error.to_string());
582 }
583
584 fn request_frame(&self) {}
589
590 fn hot_update_failed(&self) {}
593
594 fn resized(&self, _size: Size<Points>) {}
600
601 fn load_chunk(&self, _id: &str) -> bool {
607 false
608 }
609}
610
611pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
615
616pub trait FetchTask: Send {
618 fn send(&mut self, chunk: Vec<u8>);
621 fn finish(&mut self);
623 fn pause(&mut self, paused: bool);
627 fn cancel(self: Box<Self>);
629}
630
631pub trait Network: Send + Sync + 'static {
633 fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
636}
637
638pub trait Assets: Send + Sync + 'static {
641 fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
643}
644
645#[derive(Clone)]
647pub struct EngineConfig {
648 pub app: App,
650 pub viewport: Size<Points>,
652 pub trace: bool,
654 pub network: Option<Arc<dyn Network>>,
656 pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
658 pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
660 pub assets: Option<Arc<dyn Assets>>,
662 pub environment: Environment,
664 pub header_heights: (Points, Points),
667 pub limits: Limits,
669 pub ui_sets: Vec<nsh_core::element::Registry>,
673 pub runtime: Option<tokio::runtime::Handle>,
676 pub data_dir: Option<std::path::PathBuf>,
682 pub cache: CacheOptions,
686 pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
690 pub clock: Clock,
694 pub context: EngineContext,
699 pub pinned: EnvironmentPins,
702 pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
706 pub host: HostChannel,
711 pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
715}
716
717#[derive(Debug, Clone, Copy, Default, PartialEq)]
720#[non_exhaustive]
721pub struct EnvironmentPins {
722 pub locale: Option<nsh_core::platform::Locale>,
724 pub reduce_motion: Option<bool>,
727 pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
729}
730
731impl EnvironmentPins {
732 pub fn apply(&self, environment: &mut Environment) {
734 if let Some(locale) = self.locale {
735 environment.locale = locale;
736 }
737 if let Some(reduce_motion) = self.reduce_motion {
738 environment.reduce_motion = reduce_motion;
739 }
740 if let Some(safe_area) = self.safe_area {
741 environment.safe_area = safe_area;
742 }
743 }
744}
745
746fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
747 let path = path.filter(|path| path.is_absolute())?;
748 nsh_core::access::canonicalize(&path)
749 .ok()
750 .filter(|path| path.is_dir())
751}
752
753#[cfg(feature = "js")]
755fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
756 let mut paths = bundle.system_paths.clone();
757 paths.plugin_dir = trusted_directory(paths.plugin_dir);
758 paths.home_dir = trusted_directory(paths.home_dir);
759 if paths.home_dir.is_none() {
760 paths.home_dir = ["HOME", "USERPROFILE"]
761 .into_iter()
762 .filter_map(std::env::var_os)
763 .map(std::path::PathBuf::from)
764 .find_map(|path| trusted_directory(Some(path)));
765 }
766 if paths.plugin_dir.is_none() && !bundle.policy.harden {
770 paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
771 .map(std::path::PathBuf::from)
772 .and_then(|path| trusted_directory(Some(path)));
773 }
774 paths
775}
776
777impl EngineConfig {
778 pub fn new(app: impl Into<App>) -> Self {
785 Self {
786 app: app.into(),
787 viewport: Size::new(Points(390.0), Points(844.0)),
788 trace: false,
789 network: None,
790 websocket: None,
791 filesystem: None,
792 assets: None,
793 environment: Environment::default(),
794 header_heights: (Points(44.0), Points(96.0)),
795 limits: Limits::default(),
796 ui_sets: Vec::new(),
797 runtime: None,
798 data_dir: None,
799 cache: CacheOptions::off(),
800 storage: None,
801 clock: Clock::system(),
802 context: EngineContext::default(),
803 pinned: EnvironmentPins::default(),
804 clipboard: None,
805 host: HostChannel::default(),
806 picker: None,
807 }
808 }
809}
810
811fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
814 if let Some(storage) = &config.storage {
815 return Some(storage.clone());
816 }
817 #[cfg(not(target_arch = "wasm32"))]
818 if let Some(root) = &config.data_dir {
819 let dir = root.join(app_dir_name(config.app.app_id()));
820 return Some(FileStorage::open(dir));
821 }
822 None
823}
824
825#[cfg(not(target_arch = "wasm32"))]
826fn shared_runtime() -> tokio::runtime::Handle {
830 static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
831 RUNTIME
832 .get_or_init(|| {
833 tokio::runtime::Builder::new_multi_thread()
834 .worker_threads(2)
835 .thread_name("nsh-tasks")
836 .enable_all()
837 .build()
838 .expect("the tasks' runtime starts")
839 })
840 .handle()
841 .clone()
842}
843
844impl std::fmt::Debug for EngineConfig {
845 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
846 f.debug_struct("EngineConfig")
847 .field("app", &self.app)
848 .field("viewport", &self.viewport)
849 .field("trace", &self.trace)
850 .field("network", &self.network.is_some())
851 .field("assets", &self.assets.is_some())
852 .field("environment", &self.environment)
853 .field("header_heights", &self.header_heights)
854 .field("limits", &self.limits)
855 .field("ui_sets", &self.ui_sets)
856 .field("clock", &self.clock)
857 .field("context", &self.context)
858 .field("pinned", &self.pinned)
859 .field("clipboard", &self.clipboard.is_some())
860 .field("host", &self.host)
861 .field("picker", &self.picker.is_some())
862 .finish()
863 }
864}
865
866const MAX_ADVANCE_ROUNDS: usize = 100_000;
870
871enum Message {
872 Event(NodeId, EventKind, EventPayload),
873 Scroll(NodeId, Point<Points>, u32),
874 Zoom(NodeId, f32),
875 ComponentSize(NodeId, Size<Points>),
876 AnimationsFinished(Vec<nsh_core::animation::Finished>),
877 Resize(Size<Points>),
878 Wake,
880 Environment(Environment),
881 RootSize(NodeId, Size<Points>, EdgeInsets),
882 ScreenHeader(NodeId, Option<Points>),
883 Frame,
884 States(NodeId, u8),
885 FontsChanged,
886 Fetch(Requester, u64, FetchEvent),
889 Hot(HotUpdate),
890 Chunk(Result<Chunk, (String, String)>),
893 Perf(Option<Arc<perf::PerfMonitor>>),
894 Tokens(Option<Box<Tokens>>),
896 HostEvent(String, nsh_core::JsonValue),
899 HostReply(u64, Result<nsh_core::JsonValue, String>),
901 UrlHandled {
904 id: u32,
905 url: String,
906 handled: bool,
907 },
908 Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
910 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
912 Shutdown,
913}
914
915#[derive(Debug, Clone)]
919pub struct HotUpdate {
920 pub name: String,
922 pub code: String,
924 pub source_map: Option<Arc<str>>,
926}
927
928const MAX_LIST_ROUNDS: usize = 8;
932
933const PACED_BIND_OPS: usize = 150;
940const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);
942
943#[derive(Clone)]
945pub struct EngineControl {
946 tx: Sender<Message>,
947}
948
949impl EngineControl {
950 pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
952 let _ = self.tx.send(Message::Event(id, event, payload));
953 }
954
955 pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
961 let _ = self.tx.send(Message::Scroll(id, offset, applied));
962 }
963
964 pub fn zoom(&self, id: NodeId, scale: f32) {
967 let _ = self.tx.send(Message::Zoom(id, scale));
968 }
969
970 pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
973 let _ = self.tx.send(Message::ComponentSize(id, size));
974 }
975
976 pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
978 let _ = self.tx.send(Message::AnimationsFinished(finished));
979 }
980
981 pub fn resize(&self, size: Size<Points>) {
983 let _ = self.tx.send(Message::Resize(size));
984 }
985
986 pub fn set_environment(&self, environment: Environment) {
989 let _ = self.tx.send(Message::Environment(environment));
990 }
991
992 pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
995 let _ = self.tx.send(Message::RootSize(id, size, insets));
996 }
997
998 pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
1001 let _ = self.tx.send(Message::ScreenHeader(id, height));
1002 }
1003
1004 pub fn hot_update(&self, update: HotUpdate) {
1007 let _ = self.tx.send(Message::Hot(update));
1008 }
1009
1010 pub fn chunk_loaded(&self, chunk: Chunk) {
1013 let _ = self.tx.send(Message::Chunk(Ok(chunk)));
1014 }
1015
1016 pub fn chunk_failed(&self, id: String, message: String) {
1019 let _ = self.tx.send(Message::Chunk(Err((id, message))));
1020 }
1021
1022 pub fn frame(&self) {
1025 let _ = self.tx.send(Message::Frame);
1026 }
1027
1028 pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
1035 let _ = self.tx.send(Message::Advance(by, Box::new(done)));
1036 }
1037
1038 pub fn set_states(&self, id: NodeId, states: u8) {
1043 let _ = self.tx.send(Message::States(id, states));
1044 }
1045
1046 pub fn fonts_changed(&self) {
1050 let _ = self.tx.send(Message::FontsChanged);
1051 }
1052
1053 pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
1056 let _ = self.tx.send(Message::Perf(monitor));
1057 }
1058
1059 pub fn set_tokens(&self, tokens: Option<Tokens>) {
1064 let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
1065 }
1066}
1067
1068#[cfg(not(target_arch = "wasm32"))]
1069pub struct Engine {
1071 control: EngineControl,
1072 thread: Option<std::thread::JoinHandle<()>>,
1073 host: HostChannel,
1075 stop: Arc<std::sync::atomic::AtomicBool>,
1077 image_cache: Option<nsh_core::image::DiskCache>,
1079}
1080
1081#[cfg(not(target_arch = "wasm32"))]
1082impl Engine {
1083 pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
1085 where
1086 M: TextEngine + 'static,
1087 F: FnOnce() -> M + Send + 'static,
1088 S: MountSink,
1089 {
1090 Self::start_with(config, make_text_engine, sink, |_| {})
1091 }
1092
1093 pub fn start_with<M, F, S>(
1097 config: EngineConfig,
1098 make_text_engine: F,
1099 sink: S,
1100 setup: impl FnOnce(&EngineControl),
1101 ) -> io::Result<Engine>
1102 where
1103 M: TextEngine + 'static,
1104 F: FnOnce() -> M + Send + 'static,
1105 S: MountSink,
1106 {
1107 let image_cache = config.cache.open_images(config.app.app_id());
1108 let (tx, rx) = crossbeam_channel::unbounded();
1109 setup(&EngineControl { tx: tx.clone() });
1110 let engine_tx = tx.clone();
1111 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1112 let engine_stop = stop.clone();
1113 let host = config.host.clone();
1114 let thread = std::thread::Builder::new()
1115 .name("nsh-engine".into())
1116 .stack_size(ENGINE_STACK_SIZE)
1117 .spawn(move || run(config, make_text_engine(), sink, engine_tx, rx, engine_stop))?;
1118 Ok(Engine {
1119 control: EngineControl { tx },
1120 thread: Some(thread),
1121 host,
1122 stop,
1123 image_cache,
1124 })
1125 }
1126
1127 pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
1131 self.image_cache.clone()
1132 }
1133
1134 pub fn control(&self) -> EngineControl {
1136 self.control.clone()
1137 }
1138}
1139
1140#[cfg(not(target_arch = "wasm32"))]
1141impl Drop for Engine {
1142 fn drop(&mut self) {
1143 self.host.shutdown(&self.control.tx, &self.stop);
1146 if let Some(thread) = self.thread.take() {
1147 let _ = thread.join();
1148 }
1149 }
1150}
1151
1152#[cfg(not(target_arch = "wasm32"))]
1153fn raise_thread_priority() {
1157 #[cfg(target_vendor = "apple")]
1158 unsafe {
1160 libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
1161 }
1162}
1163
1164#[cfg(not(target_arch = "wasm32"))]
1165fn run<M: TextEngine + 'static, S: MountSink>(
1166 config: EngineConfig,
1167 text_engine: M,
1168 sink: S,
1169 tx: Sender<Message>,
1170 rx: Receiver<Message>,
1171 stop: Arc<std::sync::atomic::AtomicBool>,
1172) {
1173 raise_thread_priority();
1174 let _clock = config.clock.enter();
1176 let _context = config.context.enter();
1177 let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
1178 return;
1179 };
1180 loop {
1181 let message = match driver.deadline() {
1182 Some(deadline) => match rx.recv_deadline(deadline) {
1183 Ok(message) => Some(message),
1184 Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
1185 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
1186 },
1187 None => match rx.recv() {
1188 Ok(message) => Some(message),
1189 Err(_) => return,
1190 },
1191 };
1192 let started = driver.state.perf.is_some().then(Instant::now);
1193 if let Some(message) = message {
1194 if !driver.handle(message, &rx) {
1195 return;
1196 }
1197 while let Ok(message) = rx.try_recv() {
1199 if !driver.handle(message, &rx) {
1200 return;
1201 }
1202 }
1203 }
1204 driver.turn();
1205 driver.state.record_perf(started);
1206 if rx.is_empty() {
1207 driver.collect_if_idle();
1208 }
1209 }
1210}
1211
1212pub struct LocalEngine<M: TextEngine + 'static> {
1217 driver: ManuallyDrop<Driver<M>>,
1220 rx: Receiver<Message>,
1221 control: EngineControl,
1222 wake: Option<Arc<dyn Fn() + Send + Sync>>,
1224 pumping: Arc<std::sync::atomic::AtomicBool>,
1227}
1228
1229impl<M: TextEngine + 'static> LocalEngine<M> {
1230 pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
1233 let (tx, rx) = crossbeam_channel::unbounded();
1234 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1235 let control = EngineControl { tx: tx.clone() };
1236 let _clock = config.clock.enter();
1237 let _context = config.context.enter();
1238 let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
1239 Some(LocalEngine {
1240 driver: ManuallyDrop::new(driver),
1241 rx,
1242 control,
1243 wake: None,
1244 pumping: Arc::default(),
1245 })
1246 }
1247
1248 pub fn control(&self) -> EngineControl {
1250 self.control.clone()
1251 }
1252
1253 pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
1262 let tx = self.control.tx.clone();
1263 let pumping = self.pumping.clone();
1264 let host = wake.clone();
1265 let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
1266 let _ = tx.send(Message::Wake);
1267 if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
1270 host();
1271 }
1272 });
1273 self.driver.state.core.set_task_notify(notify.clone());
1274 self.driver.posts.set_notify(notify);
1275 self.wake = Some(wake);
1276 }
1277
1278 pub fn pump(&mut self) -> Option<Instant> {
1282 let _clock = self.driver.clock.enter();
1283 let _context = self.driver.context.enter();
1284 self.pumping
1285 .store(true, std::sync::atomic::Ordering::SeqCst);
1286 for _ in 0..4 {
1289 let started = self.driver.state.perf.is_some().then(Instant::now);
1290 while let Ok(message) = self.rx.try_recv() {
1291 self.driver.handle(message, &self.rx);
1292 }
1293 self.driver.turn();
1294 self.driver.state.record_perf(started);
1295 if self.rx.is_empty() {
1296 break;
1297 }
1298 }
1299 self.driver.collect_if_idle();
1300 self.pumping
1301 .store(false, std::sync::atomic::Ordering::SeqCst);
1302 if !self.rx.is_empty()
1305 && let Some(wake) = &self.wake
1306 {
1307 wake();
1308 }
1309 self.driver.deadline()
1310 }
1311}
1312
1313impl<M: TextEngine + 'static> Drop for LocalEngine<M> {
1314 fn drop(&mut self) {
1315 let _context = self.driver.context.enter();
1319 unsafe { ManuallyDrop::drop(&mut self.driver) };
1322 }
1323}
1324
1325struct Driver<M: TextEngine + 'static> {
1327 state: State<Rc<M>>,
1328 script: Option<Script>,
1329 sink: Rc<dyn MountSink>,
1330 assets: Option<Arc<dyn Assets>>,
1331 stopped: bool,
1334 last_gc: Instant,
1335 last_active: Instant,
1338 posts: nsh_core::element::Posts,
1341 clock: Clock,
1343 context: EngineContext,
1345 last_frame: Option<Instant>,
1348 _host: host_channel::HostAttachment,
1351}
1352
1353impl<M: TextEngine + 'static> Driver<M> {
1354 fn start(
1356 mut config: EngineConfig,
1357 text_engine: M,
1358 sink: Rc<dyn MountSink>,
1359 tx: Sender<Message>,
1360 rx: &Receiver<Message>,
1361 stop: Arc<std::sync::atomic::AtomicBool>,
1362 ) -> Option<Self> {
1363 config.pinned.apply(&mut config.environment);
1364 #[cfg(feature = "js")]
1365 let system_tx = tx.clone();
1366 #[cfg(feature = "js")]
1367 let host_bridge = config.host.bridge(tx.clone());
1368 let host_tx = tx.clone();
1369 let text_engine = Rc::new(text_engine);
1370 let access = Arc::new(match &config.app {
1371 App::Js(bundle) => bundle.policy.access(),
1372 App::Rust(_) => Policy::default().access(),
1374 });
1375 let mut core = Core::new(text_engine.clone(), config.viewport);
1376 let sets: Vec<_> = nsh_core::runtime::registries()
1379 .iter()
1380 .chain(&config.ui_sets)
1381 .cloned()
1382 .collect();
1383 core.set_components(nsh_core::element::Registry::merged(&sets));
1384 let posts = nsh_core::element::Posts::new();
1388 core.set_posts(posts.clone());
1389 if let App::Js(_) = &config.app {
1390 core.set_max_nodes(config.limits.max_nodes);
1392 }
1393 core.set_access(access.clone());
1394 core.set_storage(app_storage(&config));
1395 core.set_clipboard(config.clipboard.clone());
1396 core.set_picker(config.picker.clone());
1397 core.set_font_scale(config.environment.font_scale);
1398 core.set_class_environment(class_environment(&config.environment));
1399 core.set_header_heights(config.header_heights.0, config.header_heights.1);
1400 core.set_safe_area(insets(&config.environment));
1401 core.set_environment(ui_environment(&config.environment, config.viewport));
1402 #[cfg(not(target_arch = "wasm32"))]
1405 core.set_task_runtime(config.runtime.clone().unwrap_or_else(shared_runtime));
1406 if let App::Rust(root) = &config.app {
1409 if let Some(tokens) = root.tokens_ref() {
1410 core.set_tokens(tokens.clone());
1411 }
1412 if let Some(appearance) = root.appearance_ref() {
1413 core.set_appearance(appearance);
1414 }
1415 for font in root.fonts() {
1416 if let Err(err) = core.register_font(font) {
1417 log::error!("font failed: {err}");
1418 sink.report(&AppError::new(
1419 AppErrorKind::Asset,
1420 &format!("font failed: {err}"),
1421 ));
1422 }
1423 }
1424 }
1425 let fonts = config
1427 .ui_sets
1428 .iter()
1429 .flat_map(nsh_core::element::Registry::asset_files)
1430 .filter(|file| file.kind == nsh_core::element::AssetKind::Font);
1431 for font in fonts {
1432 let result = match config.assets.as_deref() {
1433 Some(assets) => assets.read(font.uri),
1434 None => Err("this host cannot load assets".to_owned()),
1435 }
1436 .and_then(|data| core.register_font(&data));
1437 if let Err(err) = result {
1438 log::error!("font failed: {}: {err}", font.uri);
1439 let message = format!("font failed: {}: {err}", font.uri);
1440 let package = match &config.app {
1441 App::Js(bundle) => bundle.package.clone(),
1442 App::Rust(_) => None,
1443 };
1444 sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
1445 }
1446 }
1447 let wake = tx.clone();
1450 core.set_task_notify(Arc::new(move || {
1451 let _ = wake.send(Message::Wake);
1452 }));
1453 let wake = tx.clone();
1454 posts.set_notify(Arc::new(move || {
1455 let _ = wake.send(Message::Wake);
1456 }));
1457 let mut early = Vec::new();
1461 while let Ok(message) = rx.try_recv() {
1462 match message {
1463 Message::Tokens(tokens) => core.set_host_tokens(tokens.map(|t| *t)),
1464 message => early.push(message),
1465 }
1466 }
1467 let js_tokens = core.tokens().clone();
1468 let state = State {
1469 core,
1470 js_tokens,
1471 frame_requested: false,
1472 ops: Vec::new(),
1473 binds: Vec::new(),
1474 events: Vec::new(),
1475 trace: config.trace,
1476 perf: None,
1477 perf_commit: perf::CommitTiming::default(),
1478 committed_since_gc: false,
1479 hot: Vec::new(),
1480 scroll_events: FxHashMap::default(),
1481 touch_move: None,
1482 hover_moves: Vec::new(),
1483 hover_moved: None,
1484 sets_seen: FxHashMap::default(),
1485 resized: None,
1486 pinned: config.pinned,
1487 host: config.host.clone(),
1488 url_opens: Vec::new(),
1489 net: Net {
1490 network: config.network.clone(),
1491 tx,
1492 queue: NetworkQueue::default(),
1493 inflight: FxHashMap::default(),
1494 tasks: Vec::new(),
1495 abandoned: Vec::new(),
1496 access: access.clone(),
1497 hops: 0,
1498 },
1499 };
1500
1501 let mut environment = config.environment;
1502 environment.window = config.viewport;
1503 let start = Instant::now();
1504 let mut driver = Driver {
1505 state,
1506 script: None,
1507 sink: sink.clone(),
1508 assets: config.assets.clone(),
1509 stopped: false,
1510 last_gc: Instant::now(),
1511 last_active: Instant::now(),
1512 posts: posts.clone(),
1513 clock: config.clock.clone(),
1514 context: config.context.clone(),
1515 last_frame: None,
1516 _host: config.host.attach(host_tx, rx.clone()),
1517 };
1518 let eval_us = match &config.app {
1519 App::Js(bundle) => {
1520 #[cfg(feature = "js")]
1521 let system = {
1522 script::SystemConfig {
1523 access: (*access).clone(),
1524 websocket: config.websocket.clone(),
1525 filesystem: config.filesystem.clone(),
1526 data_dir: config
1527 .data_dir
1528 .as_ref()
1529 .map(|root| root.join(app_dir_name(config.app.app_id()))),
1530 paths: bundle_system_paths(bundle),
1531 wake: Arc::new(move || {
1532 let _ = system_tx.send(Message::Wake);
1533 }),
1534 host: Rc::new(host_bridge),
1535 }
1536 };
1537 #[cfg(not(feature = "js"))]
1538 let system = script::SystemConfig;
1539 let (script, eval_us) = Script::start(
1540 bundle,
1541 config.limits,
1542 &config.ui_sets,
1543 posts,
1544 &environment,
1545 driver.state.js_tokens.clone(),
1546 driver.state.core.theme_tokens(),
1547 text_engine,
1548 stop,
1549 sink,
1550 system,
1551 )?;
1552 driver.script = Some(script);
1553 eval_us
1554 }
1555 App::Rust(root) => {
1556 driver.state.core.mount_root(root);
1557 0
1558 }
1559 };
1560 let Driver {
1561 state,
1562 script,
1563 sink,
1564 assets,
1565 ..
1566 } = &mut driver;
1567 let script = script.as_ref();
1568 let mut moves = Vec::new();
1571 let pending = early
1572 .into_iter()
1573 .chain(std::iter::from_fn(|| rx.try_recv().ok()));
1574 for message in pending {
1575 if let Message::Advance(..) = message {
1576 moves.push(message);
1577 } else if !handle(script, state, message) {
1578 return None;
1579 }
1580 }
1581 if let Some(script) = script {
1584 script.run_system();
1585 }
1586 state.load_fonts(script, assets.as_deref(), &**sink);
1587 if let Some(batch) = state.commit(script) {
1588 if state.trace {
1589 log::info!(
1590 target: "nsh::perf",
1591 "first frame: eval {eval_us}µs, total {}µs",
1592 start.elapsed().as_micros()
1593 );
1594 }
1595 sink.submit(batch);
1596 }
1597 state.net.pump(script, &mut state.core);
1598 state.load_chunks(script, &**sink);
1599 state.request_frame(script, &**sink);
1600 driver.check_stopped();
1601 for message in moves {
1602 if !driver.handle(message, rx) {
1603 return None;
1604 }
1605 }
1606 Some(driver)
1607 }
1608
1609 fn deadline(&self) -> Option<Instant> {
1613 let gc_deadline =
1614 (self.script.is_some() && self.state.committed_since_gc).then(|| self.next_gc());
1615 let due = if self.clock.is_manual() {
1616 None
1617 } else {
1618 self.due()
1619 };
1620 [due, gc_deadline].into_iter().flatten().min()
1621 }
1622
1623 fn due(&self) -> Option<Instant> {
1626 [
1627 self.script.as_ref().and_then(Script::next_timer),
1628 self.state.next_scroll_event(),
1629 self.state.next_hover_move(),
1630 self.state.core.next_task_timer(),
1631 ]
1632 .into_iter()
1633 .flatten()
1634 .min()
1635 }
1636
1637 fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
1639 self.last_active = Instant::now();
1640 match message {
1641 Message::Advance(by, done) => {
1642 let running = self.advance(by, rx, self.clock.moves_with_frames());
1643 done();
1644 running
1645 }
1646 Message::Frame if self.clock.moves_with_frames() => {
1650 self.state.frame_requested = true;
1653 let by = self.next_frame() - self.clock.now();
1654 self.advance(by, rx, true)
1655 }
1656 message => handle(self.script.as_ref(), &mut self.state, message),
1657 }
1658 }
1659
1660 fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
1668 if !self.clock.is_manual() {
1669 self.turn();
1671 return true;
1672 }
1673 let to = self.clock.now() + by;
1674 for round in 0.. {
1675 let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
1678 let next = [self.due(), self.clock.next_alarm(), frame]
1679 .into_iter()
1680 .flatten()
1681 .min()
1682 .filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
1683 if round == MAX_ADVANCE_ROUNDS {
1684 log::warn!(
1685 "the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
1686 a timer keeps scheduling another at once"
1687 );
1688 }
1689 let at = next.unwrap_or(to);
1690 self.clock.advance_to(at);
1691 while let Ok(message) = rx.try_recv() {
1692 if !self.handle(message, rx) {
1693 return false;
1694 }
1695 }
1696 if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
1698 && self.state.frame_requested
1699 {
1700 self.frame();
1701 }
1702 self.turn();
1703 if next.is_none() {
1704 break;
1705 }
1706 }
1707 true
1708 }
1709
1710 fn next_frame(&self) -> Instant {
1715 let now = self.clock.now();
1716 self.last_frame
1717 .map_or(now + nsh_core::time::FRAME, |last| {
1718 last + nsh_core::time::FRAME
1719 })
1720 .max(now)
1721 }
1722
1723 fn frame(&mut self) {
1726 self.last_frame = Some(self.clock.now());
1727 handle(self.script.as_ref(), &mut self.state, Message::Frame);
1728 }
1729
1730 fn turn(&mut self) {
1733 let Driver {
1734 state,
1735 script,
1736 sink,
1737 assets,
1738 ..
1739 } = self;
1740 let script = script.as_ref();
1741 if script
1742 .and_then(Script::next_timer)
1743 .is_some_and(|due| due <= nsh_core::time::now())
1744 {
1745 self.last_active = Instant::now();
1746 }
1747 let turn_start = state.trace.then(Instant::now);
1748 state.dispatch_touch_move(script);
1749 if state
1750 .next_hover_move()
1751 .is_some_and(|due| due <= nsh_core::time::now())
1752 {
1753 state.dispatch_hover_moves(script);
1754 }
1755 state.dispatch_scroll_events(script);
1756 let hot = std::mem::take(&mut state.hot);
1757 if let Some(script) = script {
1758 for update in hot {
1759 script.hot_update(update, &**sink);
1760 }
1761 script.run_timers(nsh_core::time::now());
1762 script.run_system();
1763 }
1764 state.core.run_component_tasks();
1765 let tasks = turn_start.map(|s| s.elapsed());
1768 state.load_fonts(script, assets.as_deref(), &**sink);
1769 if let Some(batch) = state.commit(script) {
1770 sink.submit(batch);
1771 if let (Some(start), Some(tasks)) = (turn_start, tasks) {
1772 log::info!(
1773 target: "nsh::perf",
1774 "turn: {}µs (timers and tasks {}µs)",
1775 start.elapsed().as_micros(),
1776 tasks.as_micros(),
1777 );
1778 }
1779 }
1780 if let Some(size) = state.resized.take() {
1781 sink.resized(size);
1782 }
1783 state.net.pump(script, &mut state.core);
1784 state.load_chunks(script, &**sink);
1785 state.request_frame(script, &**sink);
1786 self.check_stopped();
1787 }
1788
1789 fn next_gc(&self) -> Instant {
1793 let quiet = (self.last_active + IDLE_GC_QUIET).min(self.last_gc + IDLE_GC_LONGEST);
1794 (self.last_gc + IDLE_GC_INTERVAL).max(quiet)
1795 }
1796
1797 fn collect_if_idle(&mut self) {
1800 if let Some(script) = &self.script
1801 && self.state.committed_since_gc
1802 && Instant::now() >= self.next_gc()
1803 {
1804 let start = self.state.trace.then(Instant::now);
1805 script.collect_garbage();
1806 if let Some(start) = start {
1807 log::info!(target: "nsh::perf", "gc: {}µs", start.elapsed().as_micros());
1808 }
1809 self.last_gc = Instant::now();
1810 self.state.committed_since_gc = false;
1811 if let Some(batch) = self.state.commit(Some(script)) {
1812 self.sink.submit(batch);
1813 }
1814 }
1815 }
1816
1817 fn check_stopped(&mut self) {
1818 if let Some(script) = &self.script
1819 && !self.stopped
1820 && let Some(reason) = script.fatal()
1821 {
1822 self.stopped = true;
1823 script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
1824 }
1825 }
1826}
1827
1828struct ScrollEvent {
1829 x: f32,
1830 y: f32,
1831 content: Size<Points>,
1832 viewport: Size<Points>,
1833 zoom: f32,
1835 throttle: Duration,
1836 last: Option<Instant>,
1837 pending: bool,
1839}
1840
1841struct State<M: TextEngine> {
1842 core: Core<M>,
1843 js_tokens: Arc<nsh_core::element::Tokens>,
1846 pinned: EnvironmentPins,
1849 frame_requested: bool,
1851 ops: Vec<Op>,
1852 binds: Vec<ListBind>,
1854 events: Vec<JsEvent>,
1856 trace: bool,
1857 perf: Option<Arc<perf::PerfMonitor>>,
1859 perf_commit: perf::CommitTiming,
1862 committed_since_gc: bool,
1863 host: HostChannel,
1866 url_opens: Vec<(u32, String)>,
1868 net: Net,
1869 hot: Vec<HotUpdate>,
1871 scroll_events: FxHashMap<NodeId, ScrollEvent>,
1874 touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
1876 hover_moves: Vec<(NodeId, EventKind, EventPayload)>,
1880 hover_moved: Option<Instant>,
1882 sets_seen: FxHashMap<(u8, NodeId), usize>,
1884 resized: Option<Size<Points>>,
1886}
1887
1888#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1891enum Requester {
1892 Js(RequestId),
1893 Task(u32),
1894}
1895
1896struct Net {
1899 network: Option<Arc<dyn Network>>,
1900 tx: Sender<Message>,
1901 queue: NetworkQueue,
1902 inflight: FxHashMap<Requester, Inflight>,
1903 tasks: Vec<(u32, HttpRequest)>,
1906 abandoned: Vec<u32>,
1907 access: Arc<nsh_core::access::Access>,
1909 hops: u64,
1911}
1912
1913struct Inflight {
1915 task: Box<dyn FetchTask>,
1916 hop: u64,
1918 followed: Option<access::Followed>,
1920}
1921
1922impl Net {
1923 fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
1926 let mut abandoned = std::mem::take(&mut self.abandoned);
1927 core.take_fetches(&mut self.tasks, &mut abandoned);
1928 for id in abandoned.drain(..) {
1929 self.cancel(Requester::Task(id));
1930 }
1931 self.abandoned = abandoned;
1932 let mut tasks = std::mem::take(&mut self.tasks);
1933 for (id, request) in tasks.drain(..) {
1934 if let Err(refused) = self.request(Requester::Task(id), request) {
1935 core.fetch_event(id, FetchEvent::Failed(refused));
1936 }
1937 }
1938 self.tasks = tasks;
1939 let Some(script) = script else { return };
1940 script.take_network(&mut self.queue);
1941 for (id, op) in std::mem::take(&mut self.queue.ops) {
1942 let who = Requester::Js(id);
1943 match op {
1944 FetchOp::Start(request) => {
1945 if let Err(refused) = self.request(who, request) {
1946 script.fetch_event(id, FetchEvent::Failed(refused));
1947 }
1948 }
1949 FetchOp::Send(chunk) => {
1950 if let Some(i) = self.inflight.get_mut(&who) {
1951 i.task.send(chunk);
1952 }
1953 }
1954 FetchOp::Finish => {
1955 if let Some(i) = self.inflight.get_mut(&who) {
1956 i.task.finish();
1957 }
1958 }
1959 FetchOp::Pause(paused) => {
1960 if let Some(i) = self.inflight.get_mut(&who) {
1961 i.task.pause(paused);
1962 }
1963 }
1964 FetchOp::Cancel => self.cancel(who),
1965 }
1966 }
1967 }
1968
1969 fn cancel(&mut self, who: Requester) {
1971 if let Some(i) = self.inflight.remove(&who) {
1972 i.task.cancel();
1973 }
1974 }
1975
1976 fn request(&mut self, who: Requester, request: HttpRequest) -> Result<(), String> {
1978 if self.access.is_unrestricted() {
1979 self.start(who, request, None);
1980 } else if !self.access.allows_http(&request.method, &request.url) {
1981 return Err(access::refused(&request.method, &request.url));
1982 } else if request.follow_redirects {
1983 let hop = access::hop(&request);
1984 let followed = access::Followed { request, hops: 0 };
1985 self.start(who, hop, Some(followed));
1986 } else {
1987 self.start(who, request, None);
1988 }
1989 Ok(())
1990 }
1991
1992 fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
1994 self.hops += 1;
1995 let hop = self.hops;
1996 let Some(network) = &self.network else {
1997 let failed = FetchEvent::Failed("this host has no network stack".to_owned());
1998 let _ = self.tx.send(Message::Fetch(id, hop, failed));
1999 return;
2000 };
2001 let tx = self.tx.clone();
2002 let events: FetchEvents = Box::new(move |event| {
2003 let _ = tx.send(Message::Fetch(id, hop, event));
2004 });
2005 let task = network.fetch(request, events);
2006 self.inflight.insert(
2007 id,
2008 Inflight {
2009 task,
2010 hop,
2011 followed,
2012 },
2013 );
2014 }
2015
2016 fn event(&mut self, id: Requester, hop: u64, event: FetchEvent) -> Option<FetchEvent> {
2020 if self.network.is_none() {
2021 return Some(event);
2022 }
2023 let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
2024 match event {
2025 FetchEvent::Head(head) => {
2026 let Some(followed) = &mut inflight.followed else {
2027 return Some(FetchEvent::Head(head));
2028 };
2029 match access::next(&self.access, followed, head) {
2030 access::Next::Done(head) => Some(FetchEvent::Head(head)),
2031 access::Next::Fail(message) => {
2032 if let Some(i) = self.inflight.remove(&id) {
2033 i.task.cancel();
2034 }
2035 Some(FetchEvent::Failed(message))
2036 }
2037 access::Next::Hop(request) => {
2038 let i = self.inflight.remove(&id)?;
2039 let followed = i.followed;
2040 i.task.cancel();
2041 self.start(id, request, followed);
2042 None
2043 }
2044 }
2045 }
2046 FetchEvent::End | FetchEvent::Failed(_) => {
2047 self.inflight.remove(&id);
2048 Some(event)
2049 }
2050 event => Some(event),
2051 }
2052 }
2053}
2054
2055impl<M: TextEngine> State<M> {
2056 fn record_perf(&mut self, started: Option<Instant>) {
2059 let (Some(started), Some(monitor)) = (started, &self.perf) else {
2060 return;
2061 };
2062 let busy = started.elapsed();
2063 monitor.record_busy(busy);
2064 let mut commit = std::mem::take(&mut self.perf_commit);
2065 if commit.ops > 0 || commit.items > 0 {
2066 commit.js = busy.saturating_sub(commit.layout);
2067 monitor.record_commit(commit);
2068 }
2069 }
2070
2071 fn dispatch_touch_move(&mut self, script: Option<&Script>) {
2073 if let Some((id, touch)) = self.touch_move.take()
2074 && let Some(script) = script
2075 {
2076 script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
2077 }
2078 }
2079
2080 fn next_hover_move(&self) -> Option<Instant> {
2082 if self.hover_moves.is_empty() {
2083 return None;
2084 }
2085 Some(
2086 self.hover_moved
2087 .map_or_else(nsh_core::time::now, |t| t + HOVER_MOVE_INTERVAL),
2088 )
2089 }
2090
2091 fn dispatch_hover_moves(&mut self, script: Option<&Script>) {
2094 if self.hover_moves.is_empty() {
2095 return;
2096 }
2097 self.hover_moved = Some(nsh_core::time::now());
2098 for (id, kind, payload) in std::mem::take(&mut self.hover_moves) {
2099 if self.core.component_event(id, kind, &payload) {
2100 continue;
2101 }
2102 if let Some(script) = script {
2103 script.dispatch_event(id, kind, &payload);
2104 }
2105 }
2106 }
2107
2108 fn next_scroll_event(&self) -> Option<Instant> {
2110 self.scroll_events
2111 .values()
2112 .filter(|e| e.pending)
2113 .filter_map(|e| e.last.map(|t| t + e.throttle))
2114 .min()
2115 }
2116
2117 fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
2119 if self.scroll_events.is_empty() {
2120 return;
2121 }
2122 let now = nsh_core::time::now();
2123 let core = &self.core;
2125 self.scroll_events
2126 .retain(|&id, _| core.scroll_listener(id).is_some());
2127 for (&id, e) in &mut self.scroll_events {
2128 if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
2129 continue;
2130 }
2131 e.pending = false;
2132 e.last = Some(now);
2133 let n = |v: f32| PayloadValue::Number(v as f64);
2134 let payload = EventPayload::Map(vec![
2135 (
2136 "offset",
2137 PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
2138 ),
2139 ("contentSize", PayloadValue::Size(e.content)),
2140 ("size", PayloadValue::Size(e.viewport)),
2141 ("zoomScale", n(e.zoom)),
2142 ]);
2143 if !self.core.component_event(id, EventKind::Scroll, &payload)
2145 && let Some(script) = script
2146 {
2147 script.dispatch_event(id, EventKind::Scroll, &payload);
2148 }
2149 }
2150 }
2151
2152 fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
2154 let Some(script) = script else { return };
2155 let mut ids = Vec::new();
2156 script.take_chunk_requests(&mut ids);
2157 for id in ids {
2158 if !sink.load_chunk(&id) {
2159 let message = "this host does not load chunks (the app was built split)".to_owned();
2160 let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
2161 }
2162 }
2163 }
2164
2165 fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
2168 if !self.frame_requested
2169 && (script.is_some_and(Script::wants_frame)
2170 || self.core.wants_frame()
2171 || (script.is_some() && self.core.has_paced_list_binds()))
2172 {
2173 self.frame_requested = true;
2174 sink.request_frame();
2175 }
2176 }
2177
2178 fn load_fonts(
2181 &mut self,
2182 script: Option<&Script>,
2183 assets: Option<&dyn Assets>,
2184 sink: &dyn MountSink,
2185 ) {
2186 let Some(script) = script else { return };
2187 let mut fonts = Vec::new();
2188 script.take_fonts(&mut fonts);
2189 for uri in fonts {
2190 let result = match assets {
2191 Some(assets) => assets.read(&uri),
2192 None => Err("this host cannot load assets".to_owned()),
2193 }
2194 .and_then(|data| self.core.register_font(&data));
2195 if let Err(err) = result {
2196 script.report(
2197 sink,
2198 AppErrorKind::Asset,
2199 "font failed",
2200 &format!("{uri}: {err}"),
2201 );
2202 }
2203 }
2204 }
2205
2206 fn open_urls(&mut self) -> bool {
2212 self.core.take_url_opens(&mut self.url_opens);
2213 let mut platform = false;
2214 for (id, url) in self.url_opens.drain(..) {
2215 if self.host.open_url(id, url.clone(), &self.net.tx).is_none() {
2216 self.core.open_url_on_platform(id, url);
2217 platform = true;
2218 }
2219 }
2220 platform
2221 }
2222
2223 fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
2224 let start = Instant::now();
2225 let mut merged: Option<MountBatch> = None;
2226 let mut commits = 0;
2227 let mut op_count = 0;
2228 let mut js = std::time::Duration::ZERO;
2229 let mut paced = PacedBinds::default();
2231 for _ in 0..MAX_LIST_ROUNDS {
2232 let js_start = Instant::now();
2234 let binds = self.binds.drain(..);
2237 if let Some(script) = script {
2238 for bind in binds {
2239 script.bind_list(bind.list, &bind.binds);
2240 }
2241 script.take_ops(&mut self.ops);
2242 let mut binds = Vec::new();
2243 while paced.left() && self.core.has_paced_list_binds() {
2244 let start = Instant::now();
2245 let ops = self.ops.len();
2246 self.core.take_paced_list_binds(1, &mut binds);
2247 for bind in binds.drain(..) {
2248 paced.cells += bind.binds.len();
2249 script.bind_list(bind.list, &bind.binds);
2250 }
2251 script.take_ops(&mut self.ops);
2252 paced.ops += self.ops.len() - ops;
2253 paced.time += start.elapsed();
2254 }
2255 } else {
2256 drop(binds);
2257 }
2258 if let Some(script) = script {
2261 script.run_posted();
2262 }
2263 for event in self.events.drain(..) {
2267 match event {
2268 JsEvent::Event(id, event, payload) => {
2269 if !self.core.component_event(id, event, &payload)
2270 && let Some(script) = script
2271 {
2272 script.dispatch_event(id, event, &payload);
2273 }
2274 }
2275 other => {
2277 if let Some(script) = script {
2278 script.deliver(other);
2279 }
2280 }
2281 }
2282 }
2283 if let Some(script) = script {
2284 script.take_ops(&mut self.ops);
2285 }
2286 js += js_start.elapsed();
2287 op_count += self.ops.len();
2288 let mut ops = self.ops.drain(..);
2291 while let Some(op) = ops.next() {
2292 match self.core.apply(op) {
2293 Ok(()) => {}
2294 Err(err) if err.is_fatal() => {
2295 self.core.discard_ops(ops.by_ref());
2296 let Some(script) = script else { break };
2297 script.stop(match err {
2298 ApplyError::TooManyNodes(max) => {
2299 format!("the app created more than {max} nodes and was stopped")
2300 }
2301 other => {
2302 format!("the app sent an invalid op ({other:?}) and was stopped")
2303 }
2304 });
2305 break;
2306 }
2307 Err(err) => log::error!("invalid op: {err:?}"),
2308 }
2309 }
2310 drop(ops);
2311 if let Some(batch) = self.core.commit() {
2312 commits += 1;
2313 match &mut merged {
2314 Some(m) => extend_frame(&mut m.items, batch.items),
2315 None => merged = Some(batch),
2316 }
2317 }
2318 self.core.take_list_binds(&mut self.binds);
2319 self.core.take_events(&mut self.events);
2320 let urls = self.open_urls();
2322 let posted = script.is_some_and(Script::has_posted);
2324 let retheme = match script {
2327 Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
2328 self.js_tokens = self.core.tokens().clone();
2329 script.set_tokens(self.js_tokens.clone());
2330 true
2331 }
2332 _ => false,
2333 };
2334 let more_paced = script.is_some() && paced.left() && self.core.has_paced_list_binds();
2335 if self.binds.is_empty()
2336 && self.events.is_empty()
2337 && !posted
2338 && !retheme
2339 && !more_paced
2340 && !urls
2341 {
2342 break;
2343 }
2344 }
2345 if commits > 1
2346 && let Some(batch) = &mut merged
2347 {
2348 keep_last_sets(&mut batch.items, &mut self.sets_seen);
2349 }
2350 self.committed_since_gc |= op_count > 0;
2351 if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
2352 let c = &mut self.perf_commit;
2353 c.layout += start.elapsed().saturating_sub(js);
2354 c.ops += op_count as u32;
2355 c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
2356 }
2357 if self.trace && (op_count > 0 || merged.is_some()) {
2358 log::info!(
2359 target: "nsh::perf",
2360 "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
2361 start.elapsed().as_micros(),
2362 js.as_micros(),
2363 merged.as_ref().map_or(0, |b| b.items.len()),
2364 self.core.node_count(),
2365 );
2366 }
2367 merged
2368 }
2369}
2370
2371fn insets(env: &Environment) -> EdgeInsets {
2372 env.safe_area
2373}
2374
2375fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::element::Environment {
2377 nsh_core::element::Environment {
2378 window,
2379 safe_area: insets(env),
2380 title_bar: env.title_bar,
2381 keyboard_height: env.keyboard_height,
2382 keyboard_duration: env.keyboard_duration,
2383 dark: env.color_scheme == ColorScheme::Dark,
2384 font_scale: env.font_scale,
2385 reduce_motion: env.reduce_motion,
2386 screen_reader: env.screen_reader,
2387 rtl: env.rtl,
2388 pixel_ratio: env.pixel_ratio,
2389 os: env.os,
2390 os_version: env.os_version,
2391 idiom: env.idiom,
2392 locale: env.locale,
2393 apple_keyboard: env.apple_keyboard,
2394 host: env.host,
2395 }
2396}
2397
2398fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
2400 nsh_core::tailwind::ClassEnvironment {
2401 dark: env.color_scheme == ColorScheme::Dark,
2402 platform: if env.os == Os::Web {
2403 nsh_core::tailwind::Platform::Web
2404 } else if cfg!(target_os = "android") {
2405 nsh_core::tailwind::Platform::Android
2406 } else {
2407 nsh_core::tailwind::Platform::Ios
2408 },
2409 reduce_motion: env.reduce_motion,
2410 }
2411}
2412
2413fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
2415 match message {
2416 Message::Event(id, event, mut payload) => {
2417 if state.trace {
2418 log::info!(target: "nsh::perf", "event {event:?} on view {id}");
2419 }
2420 if event == EventKind::MouseMove
2424 || (event == EventKind::HoverMove && matches!(payload, EventPayload::Hover(_)))
2425 {
2426 match state
2427 .hover_moves
2428 .iter_mut()
2429 .find(|(v, kind, _)| *v == id && *kind == event)
2430 {
2431 Some((_, _, pending)) => *pending = payload,
2432 None => state.hover_moves.push((id, event, payload)),
2433 }
2434 return true;
2435 }
2436 state.dispatch_hover_moves(script);
2437 if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
2440 state.core.input_changed(id, text, *count);
2441 }
2442 if event == EventKind::CaretMove {
2445 state.core.locate_caret(id, &mut payload);
2446 }
2447 if event == EventKind::Paste {
2448 payload = payload.into_paste();
2449 }
2450 if state.core.component_event(id, event, &payload) {
2452 return true;
2453 }
2454 if let EventPayload::Touch(touch) = payload {
2455 if touch.phase == nsh_core::TouchPhase::Move {
2456 match &mut state.touch_move {
2457 Some((_, pending)) => pending.merge_move(*touch),
2458 None => state.touch_move = Some((id, touch)),
2459 }
2460 return true;
2461 }
2462 state.dispatch_touch_move(script);
2464 if let Some(script) = script {
2465 script.dispatch_event(id, event, &EventPayload::Touch(touch));
2466 }
2467 return true;
2468 }
2469 let Some(script) = script else { return true };
2470 let start = state.trace.then(Instant::now);
2471 script.dispatch_event(id, event, &payload);
2472 if let Some(start) = start {
2473 log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
2476 }
2477 }
2478 Message::Scroll(id, offset, applied) => {
2479 state.core.set_scroll_offset(id, offset, applied);
2480 let (x, y) = (offset.x.0, offset.y.0);
2481 if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
2482 let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
2483 x,
2484 y,
2485 content,
2486 viewport,
2487 zoom,
2488 throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
2489 last: None,
2490 pending: true,
2491 });
2492 (event.x, event.y, event.content, event.viewport, event.zoom) =
2493 (x, y, content, viewport, zoom);
2494 event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
2495 event.pending = true;
2496 }
2497 }
2498 Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
2499 Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
2500 Message::AnimationsFinished(mut finished) => {
2501 state.core.animations_finished(&mut finished);
2503 if let Some(script) = script {
2504 script.animations_finished(&finished);
2505 }
2506 }
2507 Message::Resize(size) => {
2508 state.core.set_viewport(size);
2509 state.resized = Some(size);
2510 }
2511 Message::Wake => {}
2512 Message::Environment(mut env) => {
2513 state.pinned.apply(&mut env);
2514 state.core.set_font_scale(env.font_scale);
2515 state.core.set_class_environment(class_environment(&env));
2516 state.core.set_safe_area(insets(&env));
2517 let window = env.window;
2518 state.core.set_environment(ui_environment(&env, window));
2519 if let Some(script) = script {
2520 script.set_environment(&env);
2521 }
2522 }
2523 Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
2524 Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
2525 Message::Frame => {
2526 state.frame_requested = false;
2527 state.core.run_frame(nsh_core::time::now());
2528 if let Some(script) = script {
2529 script.run_frame();
2530 }
2531 }
2532 Message::States(id, states) => state.core.set_states(id, states),
2533 Message::FontsChanged => state.core.fonts_changed(),
2534 Message::Fetch(who, hop, event) => {
2535 if let Some(event) = state.net.event(who, hop, event) {
2536 match who {
2537 Requester::Js(id) => {
2538 if let Some(script) = script {
2539 script.fetch_event(id, event);
2540 }
2541 }
2542 Requester::Task(id) => {
2543 if !state.core.fetch_event(id, event) {
2544 state.net.cancel(who);
2545 }
2546 }
2547 }
2548 }
2549 }
2550 Message::Hot(update) => state.hot.push(update),
2551 Message::Chunk(chunk) => {
2552 if let Some(script) = script {
2553 script.chunk(chunk);
2554 }
2555 }
2556 Message::Perf(monitor) => {
2557 state.perf = monitor;
2558 state.perf_commit = perf::CommitTiming::default();
2559 }
2560 Message::Tokens(tokens) => {
2561 state.core.set_host_tokens(tokens.map(|t| *t));
2562 if let Some(script) = script {
2563 script.set_theme_tokens(state.core.theme_tokens());
2564 }
2565 }
2566 Message::HostEvent(name, data) => {
2568 if let Some(script) = script {
2569 script.host_event(&name, data);
2570 }
2571 }
2572 Message::HostReply(id, result) => {
2573 if let Some(script) = script {
2574 script.host_reply(id, result);
2575 }
2576 }
2577 Message::UrlHandled { id, url, handled } => {
2578 if handled {
2579 state.core.answer_open_url(id, true);
2580 } else {
2581 state.core.open_url_on_platform(id, url);
2582 }
2583 }
2584 Message::Advance(..) => unreachable!("the driver moves the clock"),
2587 Message::Shutdown => return false,
2588 }
2589 true
2590}
2591
2592#[derive(Default)]
2594struct PacedBinds {
2595 cells: usize,
2596 ops: usize,
2597 time: std::time::Duration,
2598}
2599
2600impl PacedBinds {
2601 fn left(&self) -> bool {
2604 self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
2605 }
2606}
2607
2608fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
2614 use nsh_core::MountItem;
2615 let start = frame.len();
2616 frame.extend(items);
2617 for k in start..frame.len() {
2618 let MountItem::ScrollContent { id, size } = frame[k] else {
2619 continue;
2620 };
2621 let earlier = frame[..k].iter().rposition(|m| {
2622 matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
2623 });
2624 if let Some(j) = earlier
2625 && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
2626 {
2627 *s = size;
2628 }
2629 }
2630}
2631
2632fn keep_last_sets(frame: &mut Vec<nsh_core::MountItem>, last: &mut FxHashMap<(u8, NodeId), usize>) {
2638 last.clear();
2639 let mut repeated = false;
2640 for (k, item) in frame.iter().enumerate() {
2641 if let Some(key) = sets_whole(item) {
2642 repeated |= last.insert(key, k).is_some();
2643 }
2644 }
2645 if !repeated {
2646 return;
2647 }
2648 let mut k = 0;
2649 frame.retain(|item| {
2650 k += 1;
2651 sets_whole(item).is_none_or(|key| last[&key] == k - 1)
2652 });
2653}
2654
2655fn sets_whole(item: &nsh_core::MountItem) -> Option<(u8, nsh_core::NodeId)> {
2658 use nsh_core::MountItem;
2659 Some(match *item {
2660 MountItem::Frame { id, .. } => (0, id),
2661 MountItem::Overflow { id, .. } => (1, id),
2662 MountItem::ViewStyle { id, .. } => (2, id),
2663 MountItem::Text { id, .. } => (3, id),
2664 MountItem::Events { id, .. } => (4, id),
2665 MountItem::Image { id, .. } => (5, id),
2666 _ => return None,
2667 })
2668}
2669
2670#[cfg(test)]
2671mod tests {
2672 #[test]
2673 fn pinned_values_hold_whatever_the_platform_reports() {
2674 let pins = super::EnvironmentPins {
2675 locale: nsh_core::platform::Locale::parse("de-DE"),
2676 reduce_motion: Some(true),
2677 ..Default::default()
2678 };
2679 let mut reported = super::Environment {
2680 locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
2681 font_scale: 1.5,
2682 ..Default::default()
2683 };
2684 pins.apply(&mut reported);
2685 assert_eq!(reported.locale.as_str(), "de-DE");
2686 assert!(reported.reduce_motion);
2687 assert_eq!(reported.font_scale, 1.5);
2689 assert_eq!(reported.safe_area, Default::default());
2690 }
2691
2692 #[test]
2693 fn bundle_default_has_no_application_selected_path_anchors() {
2694 let bundle = super::Bundle::default();
2695 assert!(bundle.system_paths.plugin_dir.is_none());
2696 assert!(bundle.system_paths.home_dir.is_none());
2697 assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
2698 }
2699
2700 #[test]
2701 fn bundle_trusted_paths_reject_relative_and_missing_directories() {
2702 let mut paths = nsh_core::access::TrustedPaths::default();
2703 paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
2704 paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
2705 let bundle = super::Bundle::default().with_system_paths(paths);
2706 assert!(bundle.system_paths.plugin_dir.is_none());
2707 assert!(bundle.system_paths.home_dir.is_none());
2708 assert!(
2709 super::trusted_directory(Some(std::path::PathBuf::from(
2710 "/nsh-nonexistent-anchor-never-created"
2711 )))
2712 .is_none()
2713 );
2714 }
2715
2716 #[test]
2717 fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
2718 let root = std::env::var_os("TMPDIR")
2719 .map(std::path::PathBuf::from)
2720 .unwrap_or_else(|| {
2721 std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
2722 .join(".cache/nsh-benchs-test-tmp")
2723 });
2724 assert!(root.is_absolute() && !root.starts_with("/tmp"));
2725 let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
2726 std::fs::create_dir_all(&directory).unwrap();
2727 let path = directory.join("bundle.js");
2728 std::fs::write(&path, "export default null;").unwrap();
2729 let bundle = super::Bundle::read(&path).unwrap();
2730 assert_eq!(
2731 bundle.system_paths.plugin_dir,
2732 Some(nsh_core::access::canonicalize(&directory).unwrap())
2733 );
2734 assert!(bundle.system_paths.home_dir.is_none());
2735 std::fs::remove_dir_all(directory).unwrap();
2736 }
2737
2738 #[test]
2739 fn rust_environment_preserves_native_title_bar_insets() {
2740 use super::{Edges, Points};
2741 let title_bar = Edges {
2742 top: Points(42.0),
2743 left: Points(78.0),
2744 right: Points(138.0),
2745 bottom: Points(0.0),
2746 };
2747 let environment = super::Environment {
2748 title_bar,
2749 ..Default::default()
2750 };
2751 assert_eq!(
2752 super::ui_environment(
2753 &environment,
2754 nsh_core::Size::new(Points(840.0), Points(630.0))
2755 )
2756 .title_bar,
2757 title_bar
2758 );
2759 }
2760
2761 use nsh_core::{MountItem, Points, Size};
2762
2763 #[test]
2764 fn a_frame_sends_a_scroll_views_last_content_size() {
2765 let content = |height| MountItem::ScrollContent {
2766 id: 2,
2767 size: Size::new(Points(390.0), height),
2768 };
2769 let heights = |frame: &[MountItem]| -> Vec<f32> {
2770 frame
2771 .iter()
2772 .filter_map(|m| match m {
2773 MountItem::ScrollContent { size, .. } => Some(size.height.0),
2774 _ => None,
2775 })
2776 .collect()
2777 };
2778 let mut frame = vec![content(Points(313.0))];
2779 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
2780 assert_eq!(heights(&frame), [544.0, 544.0]);
2781 let mut frame = vec![
2783 content(Points(313.0)),
2784 MountItem::ScrollBy {
2785 id: 2,
2786 dx: Points(0.0),
2787 dy: Points(10.0),
2788 },
2789 ];
2790 super::extend_frame(&mut frame, vec![content(Points(544.0))]);
2791 assert_eq!(heights(&frame), [313.0, 544.0]);
2792 }
2793
2794 #[test]
2795 fn a_frame_sends_a_views_last_frame_once() {
2796 use nsh_core::{Bounds, Point};
2797 let at = |id, y| MountItem::Frame {
2798 id,
2799 frame: Bounds::new(
2800 Point::new(Points(0.0), Points(y)),
2801 Size::new(Points(10.0), Points(10.0)),
2802 ),
2803 };
2804 let mut frame = vec![
2805 MountItem::Create {
2806 id: 4,
2807 kind: nsh_core::ViewKind::View,
2808 },
2809 at(4, 0.0),
2810 at(6, 0.0),
2811 ];
2812 super::extend_frame(&mut frame, vec![at(4, 50.0)]);
2813 super::keep_last_sets(&mut frame, &mut Default::default());
2814 assert!(matches!(frame[0], MountItem::Create { id: 4, .. }));
2815 let frames: Vec<_> = frame
2816 .iter()
2817 .filter_map(|m| match m {
2818 MountItem::Frame { id, frame } => Some((*id, frame.origin.y.0)),
2819 _ => None,
2820 })
2821 .collect();
2822 assert_eq!(frames, [(6, 0.0), (4, 50.0)]);
2823 }
2824}