1mod access;
12pub mod perf;
13mod script;
14#[cfg(feature = "js")]
15mod symbolicate;
16
17use std::{io, rc::Rc, sync::Arc, time::Duration};
18
19use crossbeam_channel::{Receiver, Sender};
20use nsh_core::{
21 ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
22 PayloadValue, Size, TextEngine, time::Instant,
23};
24pub use nsh_core::{
25 access::{Access, Capabilities},
26 js::Limits,
27 platform::{
28 ColorScheme, Environment, FetchEvent, FetchOp, HttpBody, HttpHead, HttpRequest, Idiom,
29 Insets, Locale, Os,
30 },
31 ui::{Root, Theme},
32};
33#[cfg(feature = "js")]
34pub use nsh_js::BYTECODE_VERSION;
35#[cfg(feature = "js")]
37pub use nsh_package as package;
38use rustc_hash::FxHashMap;
39
40use crate::script::{NetworkQueue, RequestId, Script};
41
42#[cfg(not(target_arch = "wasm32"))]
43const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
47
48const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
52
53#[derive(Debug, Clone)]
55pub enum App {
56 Rust(Root),
58 Js(Bundle),
60}
61
62impl From<Bundle> for App {
63 fn from(bundle: Bundle) -> Self {
64 App::Js(bundle)
65 }
66}
67
68impl From<Root> for App {
69 fn from(root: Root) -> Self {
70 App::Rust(root)
71 }
72}
73
74#[derive(Debug, Clone)]
76pub struct Bundle {
77 pub code: BundleCode,
79 pub source_map: Option<Arc<str>>,
81 pub policy: Policy,
83 pub base_url: Option<Arc<str>>,
86 pub chunks: Arc<Vec<Chunk>>,
90 pub harden_bytecode: Option<Arc<Vec<u8>>>,
95}
96
97#[derive(Debug, Clone)]
100pub struct Chunk {
101 pub id: String,
103 pub code: BundleCode,
105 pub source_map: Option<Arc<str>>,
107}
108
109impl Chunk {
110 pub fn source(id: impl Into<String>, code: String) -> Self {
112 Self {
113 id: id.into(),
114 code: BundleCode::Source(code),
115 source_map: None,
116 }
117 }
118
119 pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
125 Self {
126 id: id.into(),
127 code: BundleCode::Bytecode(bytes),
128 source_map: None,
129 }
130 }
131
132 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
134 self.source_map = Some(map.into());
135 self
136 }
137}
138
139#[derive(Debug, Clone)]
141pub struct Policy {
142 pub harden: bool,
146 pub declared: Option<Capabilities>,
149 pub granted: Option<Capabilities>,
152}
153
154impl Default for Policy {
155 fn default() -> Self {
156 Self {
157 harden: true,
158 declared: None,
159 granted: None,
160 }
161 }
162}
163
164impl Policy {
165 pub fn development() -> Self {
169 Self {
170 harden: false,
171 ..Self::default()
172 }
173 }
174
175 pub fn access(&self) -> Access {
177 Access {
178 declared: self.declared.clone().unwrap_or_else(Capabilities::all),
179 granted: self.granted.clone(),
180 }
181 }
182}
183
184#[derive(Debug, Clone)]
186pub enum BundleCode {
187 Bytecode(Vec<u8>),
189 Source(String),
191}
192
193impl Bundle {
194 pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
204 Self {
205 code: BundleCode::Bytecode(bytes),
206 source_map: None,
207 policy: Policy::default(),
208 base_url: None,
209 chunks: Arc::default(),
210 harden_bytecode: None,
211 }
212 }
213
214 pub fn source(code: String) -> Self {
216 Self {
217 code: BundleCode::Source(code),
218 source_map: None,
219 policy: Policy::default(),
220 base_url: None,
221 chunks: Arc::default(),
222 harden_bytecode: None,
223 }
224 }
225
226 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
228 self.source_map = Some(map.into());
229 self
230 }
231
232 pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
234 self.base_url = Some(url.into());
235 self
236 }
237
238 pub unsafe fn with_harden_bytecode(mut self, bytes: Vec<u8>) -> Self {
245 self.harden_bytecode = Some(Arc::new(bytes));
246 self
247 }
248
249 pub fn with_policy(mut self, policy: Policy) -> Self {
251 self.policy = policy;
252 self
253 }
254
255 pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
257 Arc::make_mut(&mut self.chunks).extend(chunks);
258 self
259 }
260
261 pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
267 if path.extension().is_some_and(|e| e == "nshc") {
268 return Err(io::Error::other(
269 "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
270 ));
271 }
272 unsafe { Self::read_trusted(path) }
274 }
275
276 pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
283 let bytes = std::fs::read(path)?;
284 let bundle = if path.extension().is_some_and(|e| e == "nshc") {
285 unsafe { Bundle::bytecode(bytes) }
287 } else {
288 Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
289 };
290 let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
291 Ok(map) if !map.is_empty() => bundle.with_source_map(map),
292 _ => bundle,
293 };
294 if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
295 bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
296 }
297 Ok(bundle)
298 }
299}
300
301#[cfg(feature = "js")]
302impl Bundle {
303 pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
307 let bundle = match package.bytecode() {
308 Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
311 None => Bundle::source(package.source.clone()),
312 };
313 let mut bundle = match &package.source_map {
314 Some(map) => bundle.with_source_map(map.clone()),
315 None => bundle,
316 };
317 bundle.policy.declared = package
318 .capabilities
319 .as_ref()
320 .map(Capabilities::from_json)
321 .transpose()?;
322 Ok(bundle)
323 }
324}
325
326#[cfg(feature = "js")]
328#[derive(Debug)]
329pub struct LoadedPackage {
330 pub bundle: Bundle,
332 pub assets: std::path::PathBuf,
334 pub app: nsh_package::App,
336}
337
338#[cfg(feature = "js")]
342pub fn load_package(
343 trust: &mut nsh_package::TrustStore,
344 bytes: &[u8],
345 assets_root: &std::path::Path,
346) -> Result<LoadedPackage, String> {
347 let package = trust
348 .verify(bytes, BYTECODE_VERSION)
349 .map_err(|e| e.to_string())?;
350 let bundle = Bundle::from_package(&package)?;
351 let dir = assets_root.join(&package.app.id).join(&package.sha256);
352 let done = dir.join(".complete");
353 if !done.exists() {
354 let assets = dir.join("assets");
355 for (path, data) in &package.assets {
356 let dest = assets.join(path);
358 if let Some(parent) = dest.parent() {
359 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
360 }
361 std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
362 }
363 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
364 std::fs::write(&done, b"").map_err(|e| e.to_string())?;
365 }
366 trust.accept(&package).map_err(|e| e.to_string())?;
367 Ok(LoadedPackage {
368 bundle,
369 assets: dir.join("assets"),
370 app: package.app,
371 })
372}
373
374pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
377 let value: serde_json::Value =
378 serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
379 Capabilities::from_json(&value)
380}
381
382impl Bundle {
383 pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
385 self.policy.declared = json.map(parse_capabilities).transpose()?;
386 Ok(self)
387 }
388}
389
390pub trait MountSink: Send + 'static {
393 fn submit(&self, batch: MountBatch);
395
396 fn report_error(&self, _message: &str) {}
400
401 fn request_frame(&self) {}
406
407 fn hot_update_failed(&self) {}
410
411 fn resized(&self, _size: Size) {}
417
418 fn load_chunk(&self, _id: &str) -> bool {
424 false
425 }
426}
427
428pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
432
433pub trait FetchTask: Send {
435 fn send(&mut self, chunk: Vec<u8>);
438 fn finish(&mut self);
440 fn pause(&mut self, paused: bool);
444 fn cancel(self: Box<Self>);
446}
447
448pub trait Network: Send + Sync + 'static {
450 fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
453}
454
455pub trait Assets: Send + Sync + 'static {
458 fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
460}
461
462#[derive(Clone)]
464pub struct EngineConfig {
465 pub app: App,
467 pub viewport: Size,
469 pub trace: bool,
471 pub network: Option<Arc<dyn Network>>,
473 pub assets: Option<Arc<dyn Assets>>,
475 pub environment: Environment,
477 pub header_heights: (f32, f32),
480 pub limits: Limits,
482 pub ui_sets: Vec<nsh_core::ui::Registry>,
486 pub runtime: Option<tokio::runtime::Handle>,
489}
490
491#[cfg(not(target_arch = "wasm32"))]
492fn shared_runtime() -> tokio::runtime::Handle {
496 static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
497 RUNTIME
498 .get_or_init(|| {
499 tokio::runtime::Builder::new_multi_thread()
500 .worker_threads(2)
501 .thread_name("nsh-tasks")
502 .enable_all()
503 .build()
504 .expect("the tasks' runtime starts")
505 })
506 .handle()
507 .clone()
508}
509
510impl std::fmt::Debug for EngineConfig {
511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512 f.debug_struct("EngineConfig")
513 .field("app", &self.app)
514 .field("viewport", &self.viewport)
515 .field("trace", &self.trace)
516 .field("network", &self.network.is_some())
517 .field("assets", &self.assets.is_some())
518 .field("environment", &self.environment)
519 .field("header_heights", &self.header_heights)
520 .field("limits", &self.limits)
521 .field("ui_sets", &self.ui_sets)
522 .finish()
523 }
524}
525
526enum Message {
527 Event(NodeId, EventKind, EventPayload),
528 Scroll(NodeId, f32, f32, u32),
529 Zoom(NodeId, f32),
530 ComponentSize(NodeId, Size),
531 AnimationsFinished(Vec<nsh_animation::Finished>),
532 Resize(Size),
533 Wake,
535 Environment(Environment),
536 RootSize(NodeId, Size, EdgeInsets),
537 ScreenHeader(NodeId, Option<f32>),
538 Frame,
539 States(NodeId, u8),
540 FontsChanged,
541 Fetch(RequestId, u64, FetchEvent),
544 Hot(HotUpdate),
545 Chunk(Result<Chunk, (String, String)>),
548 Perf(Option<Arc<perf::PerfMonitor>>),
549 Theme(Option<Box<Theme>>),
551 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
553 Shutdown,
554}
555
556#[derive(Debug, Clone)]
560pub struct HotUpdate {
561 pub name: String,
563 pub code: String,
565 pub source_map: Option<Arc<str>>,
567}
568
569const MAX_LIST_ROUNDS: usize = 8;
573
574#[derive(Clone)]
576pub struct EngineControl {
577 tx: Sender<Message>,
578}
579
580impl EngineControl {
581 pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
583 let _ = self.tx.send(Message::Event(id, event, payload));
584 }
585
586 pub fn scroll(&self, id: NodeId, x: f32, y: f32, applied: u32) {
592 let _ = self.tx.send(Message::Scroll(id, x, y, applied));
593 }
594
595 pub fn zoom(&self, id: NodeId, scale: f32) {
598 let _ = self.tx.send(Message::Zoom(id, scale));
599 }
600
601 pub fn set_component_size(&self, id: NodeId, size: Size) {
604 let _ = self.tx.send(Message::ComponentSize(id, size));
605 }
606
607 pub fn animations_finished(&self, finished: Vec<nsh_animation::Finished>) {
609 let _ = self.tx.send(Message::AnimationsFinished(finished));
610 }
611
612 pub fn resize(&self, size: Size) {
614 let _ = self.tx.send(Message::Resize(size));
615 }
616
617 pub fn set_environment(&self, environment: Environment) {
620 let _ = self.tx.send(Message::Environment(environment));
621 }
622
623 pub fn set_root_size(&self, id: NodeId, size: Size, insets: EdgeInsets) {
626 let _ = self.tx.send(Message::RootSize(id, size, insets));
627 }
628
629 pub fn set_screen_header(&self, id: NodeId, height: Option<f32>) {
632 let _ = self.tx.send(Message::ScreenHeader(id, height));
633 }
634
635 pub fn hot_update(&self, update: HotUpdate) {
638 let _ = self.tx.send(Message::Hot(update));
639 }
640
641 pub fn chunk_loaded(&self, chunk: Chunk) {
644 let _ = self.tx.send(Message::Chunk(Ok(chunk)));
645 }
646
647 pub fn chunk_failed(&self, id: String, message: String) {
650 let _ = self.tx.send(Message::Chunk(Err((id, message))));
651 }
652
653 pub fn frame(&self) {
656 let _ = self.tx.send(Message::Frame);
657 }
658
659 pub fn set_states(&self, id: NodeId, states: u8) {
664 let _ = self.tx.send(Message::States(id, states));
665 }
666
667 pub fn fonts_changed(&self) {
671 let _ = self.tx.send(Message::FontsChanged);
672 }
673
674 pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
677 let _ = self.tx.send(Message::Perf(monitor));
678 }
679
680 pub fn set_theme(&self, theme: Option<Theme>) {
685 let _ = self.tx.send(Message::Theme(theme.map(Box::new)));
686 }
687}
688
689#[cfg(not(target_arch = "wasm32"))]
690pub struct Engine {
692 control: EngineControl,
693 thread: Option<std::thread::JoinHandle<()>>,
694 stop: Arc<std::sync::atomic::AtomicBool>,
696}
697
698#[cfg(not(target_arch = "wasm32"))]
699impl Engine {
700 pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
702 where
703 M: TextEngine + 'static,
704 F: FnOnce() -> M + Send + 'static,
705 S: MountSink,
706 {
707 Self::start_with(config, make_text_engine, sink, |_| {})
708 }
709
710 pub fn start_with<M, F, S>(
714 config: EngineConfig,
715 make_text_engine: F,
716 sink: S,
717 setup: impl FnOnce(&EngineControl),
718 ) -> io::Result<Engine>
719 where
720 M: TextEngine + 'static,
721 F: FnOnce() -> M + Send + 'static,
722 S: MountSink,
723 {
724 let (tx, rx) = crossbeam_channel::unbounded();
725 setup(&EngineControl { tx: tx.clone() });
726 let engine_tx = tx.clone();
727 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
728 let engine_stop = stop.clone();
729 let thread = std::thread::Builder::new()
730 .name("nsh-engine".into())
731 .stack_size(ENGINE_STACK_SIZE)
732 .spawn(move || run(config, make_text_engine(), sink, engine_tx, rx, engine_stop))?;
733 Ok(Engine {
734 control: EngineControl { tx },
735 thread: Some(thread),
736 stop,
737 })
738 }
739
740 pub fn control(&self) -> EngineControl {
742 self.control.clone()
743 }
744}
745
746#[cfg(not(target_arch = "wasm32"))]
747impl Drop for Engine {
748 fn drop(&mut self) {
749 self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
752 let _ = self.control.tx.send(Message::Shutdown);
753 if let Some(thread) = self.thread.take() {
754 let _ = thread.join();
755 }
756 }
757}
758
759#[cfg(not(target_arch = "wasm32"))]
760fn raise_thread_priority() {
764 #[cfg(target_vendor = "apple")]
765 unsafe {
767 libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
768 }
769}
770
771#[cfg(not(target_arch = "wasm32"))]
772fn run<M: TextEngine + 'static, S: MountSink>(
773 config: EngineConfig,
774 text_engine: M,
775 sink: S,
776 tx: Sender<Message>,
777 rx: Receiver<Message>,
778 stop: Arc<std::sync::atomic::AtomicBool>,
779) {
780 raise_thread_priority();
781 let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
782 return;
783 };
784 loop {
785 let message = match driver.deadline() {
786 Some(deadline) => match rx.recv_deadline(deadline) {
787 Ok(message) => Some(message),
788 Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
789 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
790 },
791 None => match rx.recv() {
792 Ok(message) => Some(message),
793 Err(_) => return,
794 },
795 };
796 let started = driver.state.perf.is_some().then(Instant::now);
797 if let Some(message) = message {
798 if !driver.handle(message) {
799 return;
800 }
801 while let Ok(message) = rx.try_recv() {
803 if !driver.handle(message) {
804 return;
805 }
806 }
807 }
808 driver.turn();
809 driver.state.record_perf(started);
810 if rx.is_empty() {
811 driver.collect_if_idle();
812 }
813 }
814}
815
816pub struct LocalEngine<M: TextEngine + 'static> {
821 driver: Driver<M>,
822 rx: Receiver<Message>,
823 control: EngineControl,
824}
825
826impl<M: TextEngine + 'static> LocalEngine<M> {
827 pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
830 let (tx, rx) = crossbeam_channel::unbounded();
831 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
832 let control = EngineControl { tx: tx.clone() };
833 let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
834 Some(LocalEngine {
835 driver,
836 rx,
837 control,
838 })
839 }
840
841 pub fn control(&self) -> EngineControl {
843 self.control.clone()
844 }
845
846 pub fn pump(&mut self) -> Option<Instant> {
850 for _ in 0..4 {
853 let started = self.driver.state.perf.is_some().then(Instant::now);
854 while let Ok(message) = self.rx.try_recv() {
855 self.driver.handle(message);
856 }
857 self.driver.turn();
858 self.driver.state.record_perf(started);
859 if self.rx.is_empty() {
860 break;
861 }
862 }
863 self.driver.collect_if_idle();
864 self.driver.deadline()
865 }
866}
867
868struct Driver<M: TextEngine + 'static> {
870 state: State<Rc<M>>,
871 script: Option<Script>,
872 sink: Rc<dyn MountSink>,
873 assets: Option<Arc<dyn Assets>>,
874 stopped: bool,
877 last_gc: Instant,
878}
879
880impl<M: TextEngine + 'static> Driver<M> {
881 fn start(
883 config: EngineConfig,
884 text_engine: M,
885 sink: Rc<dyn MountSink>,
886 tx: Sender<Message>,
887 rx: &Receiver<Message>,
888 stop: Arc<std::sync::atomic::AtomicBool>,
889 ) -> Option<Self> {
890 let text_engine = Rc::new(text_engine);
891 let access = Arc::new(match &config.app {
892 App::Js(bundle) => bundle.policy.access(),
893 App::Rust(_) => Policy::default().access(),
895 });
896 let mut core = Core::new(text_engine.clone(), config.viewport);
897 core.set_components(nsh_core::ui::Registry::merged(&config.ui_sets));
898 if let App::Js(_) = &config.app {
899 core.set_max_nodes(config.limits.max_nodes);
901 }
902 core.set_access(access.clone());
903 core.set_font_scale(config.environment.font_scale);
904 core.set_class_environment(class_environment(&config.environment));
905 core.set_header_heights(config.header_heights.0, config.header_heights.1);
906 core.set_safe_area(insets(&config.environment));
907 core.set_environment(ui_environment(&config.environment, config.viewport));
908 #[cfg(not(target_arch = "wasm32"))]
911 core.set_task_runtime(config.runtime.clone().unwrap_or_else(shared_runtime));
912 if let App::Rust(root) = &config.app {
915 if let Some(theme) = root.theme_ref() {
916 core.set_theme(theme.clone());
917 }
918 for font in root.fonts() {
919 if let Err(err) = core.register_font(font) {
920 log::error!("font failed: {err}");
921 sink.report_error(&format!("font failed: {err}"));
922 }
923 }
924 }
925 let fonts = config
927 .ui_sets
928 .iter()
929 .flat_map(nsh_core::ui::Registry::asset_files)
930 .filter(|file| file.kind == nsh_core::ui::AssetKind::Font);
931 for font in fonts {
932 let result = match config.assets.as_deref() {
933 Some(assets) => assets.read(font.uri),
934 None => Err("this host cannot load assets".to_owned()),
935 }
936 .and_then(|data| core.register_font(&data));
937 if let Err(err) = result {
938 log::error!("font failed: {}: {err}", font.uri);
939 sink.report_error(&format!("font failed: {}: {err}", font.uri));
940 }
941 }
942 let wake = tx.clone();
944 core.set_task_notify(Arc::new(move || {
945 let _ = wake.send(Message::Wake);
946 }));
947 let state = State {
948 core,
949 frame_requested: false,
950 ops: Vec::new(),
951 binds: Vec::new(),
952 events: Vec::new(),
953 trace: config.trace,
954 perf: None,
955 perf_commit: perf::CommitTiming::default(),
956 committed_since_gc: false,
957 hot: Vec::new(),
958 scroll_events: FxHashMap::default(),
959 touch_move: None,
960 resized: None,
961 net: Net {
962 network: config.network.clone(),
963 tx,
964 queue: NetworkQueue::default(),
965 inflight: FxHashMap::default(),
966 access: access.clone(),
967 hops: 0,
968 },
969 };
970
971 let mut environment = config.environment;
972 environment.window = (config.viewport.width, config.viewport.height);
973 let start = Instant::now();
974 let mut driver = Driver {
975 state,
976 script: None,
977 sink: sink.clone(),
978 assets: config.assets.clone(),
979 stopped: false,
980 last_gc: Instant::now(),
981 };
982 let eval_us = match &config.app {
983 App::Js(bundle) => {
984 let (script, eval_us) = Script::start(
985 bundle,
986 config.limits,
987 &config.ui_sets,
988 &environment,
989 text_engine,
990 stop,
991 sink,
992 )?;
993 driver.script = Some(script);
994 eval_us
995 }
996 App::Rust(root) => {
997 driver.state.core.mount_root(root);
998 0
999 }
1000 };
1001 let Driver {
1002 state,
1003 script,
1004 sink,
1005 assets,
1006 ..
1007 } = &mut driver;
1008 let script = script.as_ref();
1009 while let Ok(message) = rx.try_recv() {
1012 if !handle(script, state, message) {
1013 return None;
1014 }
1015 }
1016 state.load_fonts(script, assets.as_deref(), &**sink);
1017 if let Some(batch) = state.commit(script) {
1018 if state.trace {
1019 log::info!(
1020 target: "nsh::perf",
1021 "first frame: eval {eval_us}µs, total {}µs",
1022 start.elapsed().as_micros()
1023 );
1024 }
1025 sink.submit(batch);
1026 }
1027 state.net.pump(script);
1028 state.load_chunks(script, &**sink);
1029 state.request_frame(script, &**sink);
1030 driver.check_stopped();
1031 Some(driver)
1032 }
1033
1034 fn deadline(&self) -> Option<Instant> {
1037 let script = self.script.as_ref();
1038 let gc_deadline = (script.is_some() && self.state.committed_since_gc)
1039 .then(|| self.last_gc + IDLE_GC_INTERVAL);
1040 let task_timer = self.state.core.next_task_timer();
1041 [
1042 script.and_then(Script::next_timer),
1043 gc_deadline,
1044 self.state.next_scroll_event(),
1045 task_timer,
1046 ]
1047 .into_iter()
1048 .flatten()
1049 .min()
1050 }
1051
1052 fn handle(&mut self, message: Message) -> bool {
1054 handle(self.script.as_ref(), &mut self.state, message)
1055 }
1056
1057 fn turn(&mut self) {
1060 let Driver {
1061 state,
1062 script,
1063 sink,
1064 assets,
1065 ..
1066 } = self;
1067 let script = script.as_ref();
1068 let turn_start = state.trace.then(Instant::now);
1069 state.dispatch_touch_move(script);
1070 state.dispatch_scroll_events(script);
1071 let hot = std::mem::take(&mut state.hot);
1072 if let Some(script) = script {
1073 for update in hot {
1074 script.hot_update(update, &**sink);
1075 }
1076 script.run_timers(Instant::now());
1077 }
1078 state.core.run_component_tasks();
1079 let tasks = turn_start.map(|s| s.elapsed());
1082 state.load_fonts(script, assets.as_deref(), &**sink);
1083 if let Some(batch) = state.commit(script) {
1084 sink.submit(batch);
1085 if let (Some(start), Some(tasks)) = (turn_start, tasks) {
1086 log::info!(
1087 target: "nsh::perf",
1088 "turn: {}µs (timers and tasks {}µs)",
1089 start.elapsed().as_micros(),
1090 tasks.as_micros(),
1091 );
1092 }
1093 }
1094 if let Some(size) = state.resized.take() {
1095 sink.resized(size);
1096 }
1097 state.net.pump(script);
1098 state.load_chunks(script, &**sink);
1099 state.request_frame(script, &**sink);
1100 self.check_stopped();
1101 }
1102
1103 fn collect_if_idle(&mut self) {
1106 if let Some(script) = &self.script
1107 && self.state.committed_since_gc
1108 && self.last_gc.elapsed() >= IDLE_GC_INTERVAL
1109 {
1110 script.collect_garbage();
1111 self.last_gc = Instant::now();
1112 self.state.committed_since_gc = false;
1113 if let Some(batch) = self.state.commit(Some(script)) {
1114 self.sink.submit(batch);
1115 }
1116 }
1117 }
1118
1119 fn check_stopped(&mut self) {
1120 if let Some(script) = &self.script
1121 && !self.stopped
1122 && let Some(reason) = script.fatal()
1123 {
1124 self.stopped = true;
1125 script.report(&*self.sink, "stopped", &reason);
1126 }
1127 }
1128}
1129
1130struct ScrollEvent {
1131 x: f32,
1132 y: f32,
1133 content: Size,
1134 viewport: Size,
1135 zoom: f32,
1137 throttle: Duration,
1138 last: Option<Instant>,
1139 pending: bool,
1141}
1142
1143struct State<M: TextEngine> {
1144 core: Core<M>,
1145 frame_requested: bool,
1147 ops: Vec<Op>,
1148 binds: Vec<ListBind>,
1150 events: Vec<(NodeId, EventKind, EventPayload)>,
1152 trace: bool,
1153 perf: Option<Arc<perf::PerfMonitor>>,
1155 perf_commit: perf::CommitTiming,
1158 committed_since_gc: bool,
1159 net: Net,
1160 hot: Vec<HotUpdate>,
1162 scroll_events: FxHashMap<NodeId, ScrollEvent>,
1165 touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
1167 resized: Option<Size>,
1169}
1170
1171struct Net {
1173 network: Option<Arc<dyn Network>>,
1174 tx: Sender<Message>,
1175 queue: NetworkQueue,
1176 inflight: FxHashMap<RequestId, Inflight>,
1177 access: Arc<nsh_core::access::Access>,
1179 hops: u64,
1181}
1182
1183struct Inflight {
1185 task: Box<dyn FetchTask>,
1186 hop: u64,
1188 followed: Option<access::Followed>,
1190}
1191
1192impl Net {
1193 fn pump(&mut self, script: Option<&Script>) {
1195 let Some(script) = script else { return };
1196 script.take_network(&mut self.queue);
1197 for (id, op) in std::mem::take(&mut self.queue.ops) {
1198 match op {
1199 FetchOp::Start(request) => self.request(script, id, request),
1200 FetchOp::Send(chunk) => {
1201 if let Some(i) = self.inflight.get_mut(&id) {
1202 i.task.send(chunk);
1203 }
1204 }
1205 FetchOp::Finish => {
1206 if let Some(i) = self.inflight.get_mut(&id) {
1207 i.task.finish();
1208 }
1209 }
1210 FetchOp::Pause(paused) => {
1211 if let Some(i) = self.inflight.get_mut(&id) {
1212 i.task.pause(paused);
1213 }
1214 }
1215 FetchOp::Cancel => {
1216 if let Some(i) = self.inflight.remove(&id) {
1217 i.task.cancel();
1218 }
1219 }
1220 }
1221 }
1222 }
1223
1224 fn request(&mut self, script: &Script, id: RequestId, request: HttpRequest) {
1226 if self.access.is_unrestricted() {
1227 self.start(id, request, None);
1228 } else if !self.access.allows_http(&request.method, &request.url) {
1229 let refused = access::refused(&request.method, &request.url);
1230 script.fetch_event(id, FetchEvent::Failed(refused));
1231 } else if request.follow_redirects {
1232 let hop = access::hop(&request);
1233 let followed = access::Followed { request, hops: 0 };
1234 self.start(id, hop, Some(followed));
1235 } else {
1236 self.start(id, request, None);
1237 }
1238 }
1239
1240 fn start(&mut self, id: RequestId, request: HttpRequest, followed: Option<access::Followed>) {
1242 self.hops += 1;
1243 let hop = self.hops;
1244 let Some(network) = &self.network else {
1245 let failed = FetchEvent::Failed("this host has no network stack".to_owned());
1246 let _ = self.tx.send(Message::Fetch(id, hop, failed));
1247 return;
1248 };
1249 let tx = self.tx.clone();
1250 let events: FetchEvents = Box::new(move |event| {
1251 let _ = tx.send(Message::Fetch(id, hop, event));
1252 });
1253 let task = network.fetch(request, events);
1254 self.inflight.insert(
1255 id,
1256 Inflight {
1257 task,
1258 hop,
1259 followed,
1260 },
1261 );
1262 }
1263
1264 fn event(&mut self, id: RequestId, hop: u64, event: FetchEvent) -> Option<FetchEvent> {
1268 if self.network.is_none() {
1269 return Some(event);
1270 }
1271 let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
1272 match event {
1273 FetchEvent::Head(head) => {
1274 let Some(followed) = &mut inflight.followed else {
1275 return Some(FetchEvent::Head(head));
1276 };
1277 match access::next(&self.access, followed, head) {
1278 access::Next::Done(head) => Some(FetchEvent::Head(head)),
1279 access::Next::Fail(message) => {
1280 if let Some(i) = self.inflight.remove(&id) {
1281 i.task.cancel();
1282 }
1283 Some(FetchEvent::Failed(message))
1284 }
1285 access::Next::Hop(request) => {
1286 let i = self.inflight.remove(&id)?;
1287 let followed = i.followed;
1288 i.task.cancel();
1289 self.start(id, request, followed);
1290 None
1291 }
1292 }
1293 }
1294 FetchEvent::End | FetchEvent::Failed(_) => {
1295 self.inflight.remove(&id);
1296 Some(event)
1297 }
1298 event => Some(event),
1299 }
1300 }
1301}
1302
1303impl<M: TextEngine> State<M> {
1304 fn record_perf(&mut self, started: Option<Instant>) {
1307 let (Some(started), Some(monitor)) = (started, &self.perf) else {
1308 return;
1309 };
1310 let busy = started.elapsed();
1311 monitor.record_busy(busy);
1312 let mut commit = std::mem::take(&mut self.perf_commit);
1313 if commit.ops > 0 || commit.items > 0 {
1314 commit.js = busy.saturating_sub(commit.layout);
1315 monitor.record_commit(commit);
1316 }
1317 }
1318
1319 fn dispatch_touch_move(&mut self, script: Option<&Script>) {
1321 if let Some((id, touch)) = self.touch_move.take()
1322 && let Some(script) = script
1323 {
1324 script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
1325 }
1326 }
1327
1328 fn next_scroll_event(&self) -> Option<Instant> {
1330 self.scroll_events
1331 .values()
1332 .filter(|e| e.pending)
1333 .filter_map(|e| e.last.map(|t| t + e.throttle))
1334 .min()
1335 }
1336
1337 fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
1339 if self.scroll_events.is_empty() {
1340 return;
1341 }
1342 let now = Instant::now();
1343 let core = &self.core;
1345 self.scroll_events
1346 .retain(|&id, _| core.scroll_listener(id).is_some());
1347 for (&id, e) in &mut self.scroll_events {
1348 if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
1349 continue;
1350 }
1351 e.pending = false;
1352 e.last = Some(now);
1353 let n = |v: f32| PayloadValue::Number(v as f64);
1354 let payload = EventPayload::Map(vec![
1355 ("x", n(e.x)),
1356 ("y", n(e.y)),
1357 ("contentWidth", n(e.content.width)),
1358 ("contentHeight", n(e.content.height)),
1359 ("width", n(e.viewport.width)),
1360 ("height", n(e.viewport.height)),
1361 ("zoomScale", n(e.zoom)),
1362 ]);
1363 if !self.core.component_event(id, EventKind::Scroll, &payload)
1365 && let Some(script) = script
1366 {
1367 script.dispatch_event(id, EventKind::Scroll, &payload);
1368 }
1369 }
1370 }
1371
1372 fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
1374 let Some(script) = script else { return };
1375 let mut ids = Vec::new();
1376 script.take_chunk_requests(&mut ids);
1377 for id in ids {
1378 if !sink.load_chunk(&id) {
1379 let message = "this host does not load chunks (the app was built split)".to_owned();
1380 let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
1381 }
1382 }
1383 }
1384
1385 fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
1388 if !self.frame_requested
1389 && (script.is_some_and(Script::wants_frame) || self.core.wants_frame())
1390 {
1391 self.frame_requested = true;
1392 sink.request_frame();
1393 }
1394 }
1395
1396 fn load_fonts(
1399 &mut self,
1400 script: Option<&Script>,
1401 assets: Option<&dyn Assets>,
1402 sink: &dyn MountSink,
1403 ) {
1404 let Some(script) = script else { return };
1405 let mut fonts = Vec::new();
1406 script.take_fonts(&mut fonts);
1407 for uri in fonts {
1408 let result = match assets {
1409 Some(assets) => assets.read(&uri),
1410 None => Err("this host cannot load assets".to_owned()),
1411 }
1412 .and_then(|data| self.core.register_font(&data));
1413 if let Err(err) = result {
1414 script.report(sink, "font failed", &format!("{uri}: {err}"));
1415 }
1416 }
1417 }
1418
1419 fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
1422 let start = Instant::now();
1423 let mut merged: Option<MountBatch> = None;
1424 let mut op_count = 0;
1425 let mut js = std::time::Duration::ZERO;
1426 for _ in 0..MAX_LIST_ROUNDS {
1427 let js_start = Instant::now();
1429 let binds = self.binds.drain(..);
1432 if let Some(script) = script {
1433 for bind in binds {
1434 script.bind_list(bind.list, &bind.binds);
1435 }
1436 } else {
1437 drop(binds);
1438 }
1439 for (id, event, payload) in self.events.drain(..) {
1442 if !self.core.component_event(id, event, &payload)
1443 && let Some(script) = script
1444 {
1445 script.dispatch_event(id, event, &payload);
1446 }
1447 }
1448 if let Some(script) = script {
1449 script.take_ops(&mut self.ops);
1450 }
1451 js += js_start.elapsed();
1452 op_count += self.ops.len();
1453 for op in self.ops.drain(..) {
1455 match self.core.apply(op) {
1456 Ok(()) => {}
1457 Err(err) if err.is_fatal() => {
1458 let Some(script) = script else { break };
1459 script.stop(match err {
1460 ApplyError::TooManyNodes(max) => {
1461 format!("the app created more than {max} nodes and was stopped")
1462 }
1463 other => {
1464 format!("the app sent an invalid op ({other:?}) and was stopped")
1465 }
1466 });
1467 break;
1468 }
1469 Err(err) => log::error!("invalid op: {err:?}"),
1470 }
1471 }
1472 if let Some(batch) = self.core.commit() {
1473 match &mut merged {
1474 Some(m) => extend_frame(&mut m.items, batch.items),
1475 None => merged = Some(batch),
1476 }
1477 }
1478 self.core.take_list_binds(&mut self.binds);
1479 self.core.take_events(&mut self.events);
1480 if self.binds.is_empty() && self.events.is_empty() {
1481 break;
1482 }
1483 }
1484 self.committed_since_gc |= op_count > 0;
1485 if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
1486 let c = &mut self.perf_commit;
1487 c.layout += start.elapsed().saturating_sub(js);
1488 c.ops += op_count as u32;
1489 c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
1490 }
1491 if self.trace && (op_count > 0 || merged.is_some()) {
1492 log::info!(
1493 target: "nsh::perf",
1494 "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
1495 start.elapsed().as_micros(),
1496 js.as_micros(),
1497 merged.as_ref().map_or(0, |b| b.items.len()),
1498 self.core.node_count(),
1499 );
1500 }
1501 merged
1502 }
1503}
1504
1505fn insets(env: &Environment) -> EdgeInsets {
1506 let a = env.safe_area;
1507 EdgeInsets {
1508 top: a.top,
1509 right: a.right,
1510 bottom: a.bottom,
1511 left: a.left,
1512 }
1513}
1514
1515fn ui_environment(env: &Environment, window: Size) -> nsh_core::ui::Environment {
1517 nsh_core::ui::Environment {
1518 window,
1519 safe_area: insets(env),
1520 keyboard_height: env.keyboard_height,
1521 keyboard_duration: env.keyboard_duration,
1522 dark: env.color_scheme == ColorScheme::Dark,
1523 font_scale: env.font_scale,
1524 reduce_motion: env.reduce_motion,
1525 screen_reader: env.screen_reader,
1526 rtl: env.rtl,
1527 pixel_ratio: env.pixel_ratio,
1528 os: env.os,
1529 os_version: env.os_version,
1530 idiom: env.idiom,
1531 locale: env.locale,
1532 apple_keyboard: env.apple_keyboard,
1533 }
1534}
1535
1536fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
1538 nsh_core::tailwind::ClassEnvironment {
1539 dark: env.color_scheme == ColorScheme::Dark,
1540 platform: if env.os == Os::Web {
1541 nsh_core::tailwind::Platform::Web
1542 } else if cfg!(target_os = "android") {
1543 nsh_core::tailwind::Platform::Android
1544 } else {
1545 nsh_core::tailwind::Platform::Ios
1546 },
1547 reduce_motion: env.reduce_motion,
1548 }
1549}
1550
1551fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
1553 match message {
1554 Message::Event(id, event, payload) => {
1555 if state.trace {
1556 log::info!(target: "nsh::perf", "event {event:?} on view {id}");
1557 }
1558 if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
1561 state.core.input_changed(id, text, *count);
1562 }
1563 if state.core.component_event(id, event, &payload) {
1565 return true;
1566 }
1567 if let EventPayload::Touch(touch) = payload {
1568 if touch.phase == nsh_core::TouchPhase::Move {
1569 match &mut state.touch_move {
1570 Some((_, pending)) => pending.merge_move(*touch),
1571 None => state.touch_move = Some((id, touch)),
1572 }
1573 return true;
1574 }
1575 state.dispatch_touch_move(script);
1577 if let Some(script) = script {
1578 script.dispatch_event(id, event, &EventPayload::Touch(touch));
1579 }
1580 return true;
1581 }
1582 let Some(script) = script else { return true };
1583 let start = state.trace.then(Instant::now);
1584 script.dispatch_event(id, event, &payload);
1585 if let Some(start) = start {
1586 log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
1589 }
1590 }
1591 Message::Scroll(id, x, y, applied) => {
1592 state.core.set_scroll_offset(id, x, y, applied);
1593 if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
1594 let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
1595 x,
1596 y,
1597 content,
1598 viewport,
1599 zoom,
1600 throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
1601 last: None,
1602 pending: true,
1603 });
1604 (event.x, event.y, event.content, event.viewport, event.zoom) =
1605 (x, y, content, viewport, zoom);
1606 event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
1607 event.pending = true;
1608 }
1609 }
1610 Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
1611 Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
1612 Message::AnimationsFinished(mut finished) => {
1613 state.core.animations_finished(&mut finished);
1615 if let Some(script) = script {
1616 script.animations_finished(&finished);
1617 }
1618 }
1619 Message::Resize(size) => {
1620 state.core.set_viewport(size);
1621 state.resized = Some(size);
1622 }
1623 Message::Wake => {}
1624 Message::Environment(env) => {
1625 state.core.set_font_scale(env.font_scale);
1626 state.core.set_class_environment(class_environment(&env));
1627 state.core.set_safe_area(insets(&env));
1628 let window = Size::new(env.window.0, env.window.1);
1629 state.core.set_environment(ui_environment(&env, window));
1630 if let Some(script) = script {
1631 script.set_environment(&env);
1632 }
1633 }
1634 Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
1635 Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
1636 Message::Frame => {
1637 state.frame_requested = false;
1638 state.core.run_frame(Instant::now());
1639 if let Some(script) = script {
1640 script.run_frame();
1641 }
1642 }
1643 Message::States(id, states) => state.core.set_states(id, states),
1644 Message::FontsChanged => state.core.fonts_changed(),
1645 Message::Fetch(id, hop, event) => {
1646 if let Some(event) = state.net.event(id, hop, event)
1647 && let Some(script) = script
1648 {
1649 script.fetch_event(id, event);
1650 }
1651 }
1652 Message::Hot(update) => state.hot.push(update),
1653 Message::Chunk(chunk) => {
1654 if let Some(script) = script {
1655 script.chunk(chunk);
1656 }
1657 }
1658 Message::Perf(monitor) => {
1659 state.perf = monitor;
1660 state.perf_commit = perf::CommitTiming::default();
1661 }
1662 Message::Theme(theme) => state.core.set_host_theme(theme.map(|t| *t)),
1663 Message::Shutdown => return false,
1664 }
1665 true
1666}
1667
1668fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
1674 use nsh_core::MountItem;
1675 let start = frame.len();
1676 frame.extend(items);
1677 for k in start..frame.len() {
1678 let MountItem::ScrollContent { id, size } = frame[k] else {
1679 continue;
1680 };
1681 let earlier = frame[..k].iter().rposition(|m| {
1682 matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
1683 });
1684 if let Some(j) = earlier
1685 && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
1686 {
1687 *s = size;
1688 }
1689 }
1690}
1691
1692#[cfg(test)]
1693mod tests {
1694 use nsh_core::{MountItem, Size};
1695
1696 #[test]
1697 fn a_frame_sends_a_scroll_views_last_content_size() {
1698 let content = |height| MountItem::ScrollContent {
1699 id: 2,
1700 size: Size::new(390.0, height),
1701 };
1702 let heights = |frame: &[MountItem]| -> Vec<f32> {
1703 frame
1704 .iter()
1705 .filter_map(|m| match m {
1706 MountItem::ScrollContent { size, .. } => Some(size.height),
1707 _ => None,
1708 })
1709 .collect()
1710 };
1711 let mut frame = vec![content(313.0)];
1712 super::extend_frame(&mut frame, vec![content(544.0)]);
1713 assert_eq!(heights(&frame), [544.0, 544.0]);
1714 let mut frame = vec![
1716 content(313.0),
1717 MountItem::ScrollBy {
1718 id: 2,
1719 dx: 0.0,
1720 dy: 10.0,
1721 },
1722 ];
1723 super::extend_frame(&mut frame, vec![content(544.0)]);
1724 assert_eq!(heights(&frame), [313.0, 544.0]);
1725 }
1726}