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}
84
85#[derive(Debug, Clone)]
87pub struct Policy {
88 pub harden: bool,
92 pub declared: Option<Capabilities>,
95 pub granted: Option<Capabilities>,
98}
99
100impl Default for Policy {
101 fn default() -> Self {
102 Self {
103 harden: true,
104 declared: None,
105 granted: None,
106 }
107 }
108}
109
110impl Policy {
111 pub fn development() -> Self {
115 Self {
116 harden: false,
117 ..Self::default()
118 }
119 }
120
121 pub fn access(&self) -> Access {
123 Access {
124 declared: self.declared.clone().unwrap_or_else(Capabilities::all),
125 granted: self.granted.clone(),
126 }
127 }
128}
129
130#[derive(Debug, Clone)]
132pub enum BundleCode {
133 Bytecode(Vec<u8>),
135 Source(String),
137}
138
139impl Bundle {
140 pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
150 Self {
151 code: BundleCode::Bytecode(bytes),
152 source_map: None,
153 policy: Policy::default(),
154 }
155 }
156
157 pub fn source(code: String) -> Self {
159 Self {
160 code: BundleCode::Source(code),
161 source_map: None,
162 policy: Policy::default(),
163 }
164 }
165
166 pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
168 self.source_map = Some(map.into());
169 self
170 }
171
172 pub fn with_policy(mut self, policy: Policy) -> Self {
174 self.policy = policy;
175 self
176 }
177
178 pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
184 if path.extension().is_some_and(|e| e == "nshc") {
185 return Err(io::Error::other(
186 "bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
187 ));
188 }
189 unsafe { Self::read_trusted(path) }
191 }
192
193 pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
200 let bytes = std::fs::read(path)?;
201 let bundle = if path.extension().is_some_and(|e| e == "nshc") {
202 unsafe { Bundle::bytecode(bytes) }
204 } else {
205 Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
206 };
207 let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
208 Ok(map) if !map.is_empty() => bundle.with_source_map(map),
209 _ => bundle,
210 };
211 if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
212 bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
213 }
214 Ok(bundle)
215 }
216}
217
218#[cfg(feature = "js")]
219impl Bundle {
220 pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
224 let bundle = match package.bytecode() {
225 Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
228 None => Bundle::source(package.source.clone()),
229 };
230 let mut bundle = match &package.source_map {
231 Some(map) => bundle.with_source_map(map.clone()),
232 None => bundle,
233 };
234 bundle.policy.declared = package
235 .capabilities
236 .as_ref()
237 .map(Capabilities::from_json)
238 .transpose()?;
239 Ok(bundle)
240 }
241}
242
243#[cfg(feature = "js")]
245#[derive(Debug)]
246pub struct LoadedPackage {
247 pub bundle: Bundle,
249 pub assets: std::path::PathBuf,
251 pub app: nsh_package::App,
253}
254
255#[cfg(feature = "js")]
259pub fn load_package(
260 trust: &mut nsh_package::TrustStore,
261 bytes: &[u8],
262 assets_root: &std::path::Path,
263) -> Result<LoadedPackage, String> {
264 let package = trust
265 .verify(bytes, BYTECODE_VERSION)
266 .map_err(|e| e.to_string())?;
267 let bundle = Bundle::from_package(&package)?;
268 let dir = assets_root.join(&package.app.id).join(&package.sha256);
269 let done = dir.join(".complete");
270 if !done.exists() {
271 let assets = dir.join("assets");
272 for (path, data) in &package.assets {
273 let dest = assets.join(path);
275 if let Some(parent) = dest.parent() {
276 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
277 }
278 std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
279 }
280 std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
281 std::fs::write(&done, b"").map_err(|e| e.to_string())?;
282 }
283 trust.accept(&package).map_err(|e| e.to_string())?;
284 Ok(LoadedPackage {
285 bundle,
286 assets: dir.join("assets"),
287 app: package.app,
288 })
289}
290
291pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
294 let value: serde_json::Value =
295 serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
296 Capabilities::from_json(&value)
297}
298
299impl Bundle {
300 pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
302 self.policy.declared = json.map(parse_capabilities).transpose()?;
303 Ok(self)
304 }
305}
306
307pub trait MountSink: Send + 'static {
310 fn submit(&self, batch: MountBatch);
312
313 fn report_error(&self, _message: &str) {}
317
318 fn request_frame(&self) {}
323
324 fn hot_update_failed(&self) {}
327
328 fn resized(&self, _size: Size) {}
334}
335
336pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
340
341pub trait FetchTask: Send {
343 fn send(&mut self, chunk: Vec<u8>);
346 fn finish(&mut self);
348 fn pause(&mut self, paused: bool);
352 fn cancel(self: Box<Self>);
354}
355
356pub trait Network: Send + Sync + 'static {
358 fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
361}
362
363pub trait Assets: Send + Sync + 'static {
366 fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
368}
369
370#[derive(Clone)]
372pub struct EngineConfig {
373 pub app: App,
375 pub viewport: Size,
377 pub trace: bool,
379 pub network: Option<Arc<dyn Network>>,
381 pub assets: Option<Arc<dyn Assets>>,
383 pub environment: Environment,
385 pub header_heights: (f32, f32),
388 pub limits: Limits,
390 pub ui_sets: Vec<nsh_core::ui::Registry>,
394 pub runtime: Option<tokio::runtime::Handle>,
397}
398
399#[cfg(not(target_arch = "wasm32"))]
400fn shared_runtime() -> tokio::runtime::Handle {
404 static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
405 RUNTIME
406 .get_or_init(|| {
407 tokio::runtime::Builder::new_multi_thread()
408 .worker_threads(2)
409 .thread_name("nsh-tasks")
410 .enable_all()
411 .build()
412 .expect("the tasks' runtime starts")
413 })
414 .handle()
415 .clone()
416}
417
418impl std::fmt::Debug for EngineConfig {
419 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420 f.debug_struct("EngineConfig")
421 .field("app", &self.app)
422 .field("viewport", &self.viewport)
423 .field("trace", &self.trace)
424 .field("network", &self.network.is_some())
425 .field("assets", &self.assets.is_some())
426 .field("environment", &self.environment)
427 .field("header_heights", &self.header_heights)
428 .field("limits", &self.limits)
429 .field("ui_sets", &self.ui_sets)
430 .finish()
431 }
432}
433
434enum Message {
435 Event(NodeId, EventKind, EventPayload),
436 Scroll(NodeId, f32, f32, u32),
437 Zoom(NodeId, f32),
438 ComponentSize(NodeId, Size),
439 AnimationsFinished(Vec<nsh_animation::Finished>),
440 Resize(Size),
441 Wake,
443 Environment(Environment),
444 RootSize(NodeId, Size, EdgeInsets),
445 ScreenHeader(NodeId, Option<f32>),
446 Frame,
447 States(NodeId, u8),
448 Fetch(RequestId, u64, FetchEvent),
451 Hot(HotUpdate),
452 Perf(Option<Arc<perf::PerfMonitor>>),
453 Theme(Option<Box<Theme>>),
455 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
457 Shutdown,
458}
459
460#[derive(Debug, Clone)]
464pub struct HotUpdate {
465 pub name: String,
467 pub code: String,
469 pub source_map: Option<Arc<str>>,
471}
472
473const MAX_LIST_ROUNDS: usize = 8;
477
478#[derive(Clone)]
480pub struct EngineControl {
481 tx: Sender<Message>,
482}
483
484impl EngineControl {
485 pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
487 let _ = self.tx.send(Message::Event(id, event, payload));
488 }
489
490 pub fn scroll(&self, id: NodeId, x: f32, y: f32, applied: u32) {
496 let _ = self.tx.send(Message::Scroll(id, x, y, applied));
497 }
498
499 pub fn zoom(&self, id: NodeId, scale: f32) {
502 let _ = self.tx.send(Message::Zoom(id, scale));
503 }
504
505 pub fn set_component_size(&self, id: NodeId, size: Size) {
508 let _ = self.tx.send(Message::ComponentSize(id, size));
509 }
510
511 pub fn animations_finished(&self, finished: Vec<nsh_animation::Finished>) {
513 let _ = self.tx.send(Message::AnimationsFinished(finished));
514 }
515
516 pub fn resize(&self, size: Size) {
518 let _ = self.tx.send(Message::Resize(size));
519 }
520
521 pub fn set_environment(&self, environment: Environment) {
524 let _ = self.tx.send(Message::Environment(environment));
525 }
526
527 pub fn set_root_size(&self, id: NodeId, size: Size, insets: EdgeInsets) {
530 let _ = self.tx.send(Message::RootSize(id, size, insets));
531 }
532
533 pub fn set_screen_header(&self, id: NodeId, height: Option<f32>) {
536 let _ = self.tx.send(Message::ScreenHeader(id, height));
537 }
538
539 pub fn hot_update(&self, update: HotUpdate) {
542 let _ = self.tx.send(Message::Hot(update));
543 }
544
545 pub fn frame(&self) {
548 let _ = self.tx.send(Message::Frame);
549 }
550
551 pub fn set_states(&self, id: NodeId, states: u8) {
556 let _ = self.tx.send(Message::States(id, states));
557 }
558
559 pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
562 let _ = self.tx.send(Message::Perf(monitor));
563 }
564
565 pub fn set_theme(&self, theme: Option<Theme>) {
570 let _ = self.tx.send(Message::Theme(theme.map(Box::new)));
571 }
572}
573
574#[cfg(not(target_arch = "wasm32"))]
575pub struct Engine {
577 control: EngineControl,
578 thread: Option<std::thread::JoinHandle<()>>,
579 stop: Arc<std::sync::atomic::AtomicBool>,
581}
582
583#[cfg(not(target_arch = "wasm32"))]
584impl Engine {
585 pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
587 where
588 M: TextEngine + 'static,
589 F: FnOnce() -> M + Send + 'static,
590 S: MountSink,
591 {
592 Self::start_with(config, make_text_engine, sink, |_| {})
593 }
594
595 pub fn start_with<M, F, S>(
599 config: EngineConfig,
600 make_text_engine: F,
601 sink: S,
602 setup: impl FnOnce(&EngineControl),
603 ) -> io::Result<Engine>
604 where
605 M: TextEngine + 'static,
606 F: FnOnce() -> M + Send + 'static,
607 S: MountSink,
608 {
609 let (tx, rx) = crossbeam_channel::unbounded();
610 setup(&EngineControl { tx: tx.clone() });
611 let engine_tx = tx.clone();
612 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
613 let engine_stop = stop.clone();
614 let thread = std::thread::Builder::new()
615 .name("nsh-engine".into())
616 .stack_size(ENGINE_STACK_SIZE)
617 .spawn(move || run(config, make_text_engine(), sink, engine_tx, rx, engine_stop))?;
618 Ok(Engine {
619 control: EngineControl { tx },
620 thread: Some(thread),
621 stop,
622 })
623 }
624
625 pub fn control(&self) -> EngineControl {
627 self.control.clone()
628 }
629}
630
631#[cfg(not(target_arch = "wasm32"))]
632impl Drop for Engine {
633 fn drop(&mut self) {
634 self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
637 let _ = self.control.tx.send(Message::Shutdown);
638 if let Some(thread) = self.thread.take() {
639 let _ = thread.join();
640 }
641 }
642}
643
644#[cfg(not(target_arch = "wasm32"))]
645fn raise_thread_priority() {
649 #[cfg(target_vendor = "apple")]
650 unsafe {
652 libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
653 }
654}
655
656#[cfg(not(target_arch = "wasm32"))]
657fn run<M: TextEngine + 'static, S: MountSink>(
658 config: EngineConfig,
659 text_engine: M,
660 sink: S,
661 tx: Sender<Message>,
662 rx: Receiver<Message>,
663 stop: Arc<std::sync::atomic::AtomicBool>,
664) {
665 raise_thread_priority();
666 let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
667 return;
668 };
669 loop {
670 let message = match driver.deadline() {
671 Some(deadline) => match rx.recv_deadline(deadline) {
672 Ok(message) => Some(message),
673 Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
674 Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
675 },
676 None => match rx.recv() {
677 Ok(message) => Some(message),
678 Err(_) => return,
679 },
680 };
681 let started = driver.state.perf.is_some().then(Instant::now);
682 if let Some(message) = message {
683 if !driver.handle(message) {
684 return;
685 }
686 while let Ok(message) = rx.try_recv() {
688 if !driver.handle(message) {
689 return;
690 }
691 }
692 }
693 driver.turn();
694 driver.state.record_perf(started);
695 if rx.is_empty() {
696 driver.collect_if_idle();
697 }
698 }
699}
700
701pub struct LocalEngine<M: TextEngine + 'static> {
706 driver: Driver<M>,
707 rx: Receiver<Message>,
708 control: EngineControl,
709}
710
711impl<M: TextEngine + 'static> LocalEngine<M> {
712 pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
715 let (tx, rx) = crossbeam_channel::unbounded();
716 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
717 let control = EngineControl { tx: tx.clone() };
718 let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
719 Some(LocalEngine {
720 driver,
721 rx,
722 control,
723 })
724 }
725
726 pub fn control(&self) -> EngineControl {
728 self.control.clone()
729 }
730
731 pub fn pump(&mut self) -> Option<Instant> {
735 for _ in 0..4 {
738 let started = self.driver.state.perf.is_some().then(Instant::now);
739 while let Ok(message) = self.rx.try_recv() {
740 self.driver.handle(message);
741 }
742 self.driver.turn();
743 self.driver.state.record_perf(started);
744 if self.rx.is_empty() {
745 break;
746 }
747 }
748 self.driver.collect_if_idle();
749 self.driver.deadline()
750 }
751}
752
753struct Driver<M: TextEngine + 'static> {
755 state: State<Rc<M>>,
756 script: Option<Script>,
757 sink: Rc<dyn MountSink>,
758 assets: Option<Arc<dyn Assets>>,
759 stopped: bool,
762 last_gc: Instant,
763}
764
765impl<M: TextEngine + 'static> Driver<M> {
766 fn start(
768 config: EngineConfig,
769 text_engine: M,
770 sink: Rc<dyn MountSink>,
771 tx: Sender<Message>,
772 rx: &Receiver<Message>,
773 stop: Arc<std::sync::atomic::AtomicBool>,
774 ) -> Option<Self> {
775 let text_engine = Rc::new(text_engine);
776 let access = Arc::new(match &config.app {
777 App::Js(bundle) => bundle.policy.access(),
778 App::Rust(_) => Policy::default().access(),
780 });
781 let mut core = Core::new(text_engine.clone(), config.viewport);
782 core.set_components(nsh_core::ui::Registry::merged(&config.ui_sets));
783 if let App::Js(_) = &config.app {
784 core.set_max_nodes(config.limits.max_nodes);
786 }
787 core.set_access(access.clone());
788 core.set_font_scale(config.environment.font_scale);
789 core.set_class_environment(class_environment(&config.environment));
790 core.set_header_heights(config.header_heights.0, config.header_heights.1);
791 core.set_safe_area(insets(&config.environment));
792 core.set_environment(ui_environment(&config.environment, config.viewport));
793 #[cfg(not(target_arch = "wasm32"))]
796 core.set_task_runtime(config.runtime.clone().unwrap_or_else(shared_runtime));
797 if let App::Rust(root) = &config.app {
800 if let Some(theme) = root.theme_ref() {
801 core.set_theme(theme.clone());
802 }
803 for font in root.fonts() {
804 if let Err(err) = core.register_font(font) {
805 log::error!("font failed: {err}");
806 sink.report_error(&format!("font failed: {err}"));
807 }
808 }
809 }
810 let fonts = config
812 .ui_sets
813 .iter()
814 .flat_map(nsh_core::ui::Registry::asset_files)
815 .filter(|file| file.kind == nsh_core::ui::AssetKind::Font);
816 for font in fonts {
817 let result = match config.assets.as_deref() {
818 Some(assets) => assets.read(font.uri),
819 None => Err("this host cannot load assets".to_owned()),
820 }
821 .and_then(|data| core.register_font(&data));
822 if let Err(err) = result {
823 log::error!("font failed: {}: {err}", font.uri);
824 sink.report_error(&format!("font failed: {}: {err}", font.uri));
825 }
826 }
827 let wake = tx.clone();
829 core.set_task_notify(Arc::new(move || {
830 let _ = wake.send(Message::Wake);
831 }));
832 let state = State {
833 core,
834 frame_requested: false,
835 ops: Vec::new(),
836 binds: Vec::new(),
837 events: Vec::new(),
838 trace: config.trace,
839 perf: None,
840 perf_commit: perf::CommitTiming::default(),
841 committed_since_gc: false,
842 hot: Vec::new(),
843 scroll_events: FxHashMap::default(),
844 touch_move: None,
845 resized: None,
846 net: Net {
847 network: config.network.clone(),
848 tx,
849 queue: NetworkQueue::default(),
850 inflight: FxHashMap::default(),
851 access: access.clone(),
852 hops: 0,
853 },
854 };
855
856 let mut environment = config.environment;
857 environment.window = (config.viewport.width, config.viewport.height);
858 let start = Instant::now();
859 let mut driver = Driver {
860 state,
861 script: None,
862 sink: sink.clone(),
863 assets: config.assets.clone(),
864 stopped: false,
865 last_gc: Instant::now(),
866 };
867 let eval_us = match &config.app {
868 App::Js(bundle) => {
869 let (script, eval_us) = Script::start(
870 bundle,
871 config.limits,
872 &config.ui_sets,
873 &environment,
874 text_engine,
875 stop,
876 sink,
877 )?;
878 driver.script = Some(script);
879 eval_us
880 }
881 App::Rust(root) => {
882 driver.state.core.mount_root(root);
883 0
884 }
885 };
886 let Driver {
887 state,
888 script,
889 sink,
890 assets,
891 ..
892 } = &mut driver;
893 let script = script.as_ref();
894 while let Ok(message) = rx.try_recv() {
897 if !handle(script, state, message) {
898 return None;
899 }
900 }
901 state.load_fonts(script, assets.as_deref(), &**sink);
902 if let Some(batch) = state.commit(script) {
903 if state.trace {
904 log::info!(
905 target: "nsh::perf",
906 "first frame: eval {eval_us}µs, total {}µs",
907 start.elapsed().as_micros()
908 );
909 }
910 sink.submit(batch);
911 }
912 state.net.pump(script);
913 state.request_frame(script, &**sink);
914 driver.check_stopped();
915 Some(driver)
916 }
917
918 fn deadline(&self) -> Option<Instant> {
921 let script = self.script.as_ref();
922 let gc_deadline = (script.is_some() && self.state.committed_since_gc)
923 .then(|| self.last_gc + IDLE_GC_INTERVAL);
924 #[cfg(target_arch = "wasm32")]
925 let task_timer = nsh_core::time::next_timer();
926 #[cfg(not(target_arch = "wasm32"))]
927 let task_timer = None;
928 [
929 script.and_then(Script::next_timer),
930 gc_deadline,
931 self.state.next_scroll_event(),
932 task_timer,
933 ]
934 .into_iter()
935 .flatten()
936 .min()
937 }
938
939 fn handle(&mut self, message: Message) -> bool {
941 handle(self.script.as_ref(), &mut self.state, message)
942 }
943
944 fn turn(&mut self) {
947 let Driver {
948 state,
949 script,
950 sink,
951 assets,
952 ..
953 } = self;
954 let script = script.as_ref();
955 let turn_start = state.trace.then(Instant::now);
956 state.dispatch_touch_move(script);
957 state.dispatch_scroll_events(script);
958 let hot = std::mem::take(&mut state.hot);
959 if let Some(script) = script {
960 for update in hot {
961 script.hot_update(update, &**sink);
962 }
963 script.run_timers(Instant::now());
964 }
965 #[cfg(target_arch = "wasm32")]
966 nsh_core::time::fire_timers(Instant::now());
967 state.core.run_component_tasks();
968 let tasks = turn_start.map(|s| s.elapsed());
971 state.load_fonts(script, assets.as_deref(), &**sink);
972 if let Some(batch) = state.commit(script) {
973 sink.submit(batch);
974 if let (Some(start), Some(tasks)) = (turn_start, tasks) {
975 log::info!(
976 target: "nsh::perf",
977 "turn: {}µs (timers and tasks {}µs)",
978 start.elapsed().as_micros(),
979 tasks.as_micros(),
980 );
981 }
982 }
983 if let Some(size) = state.resized.take() {
984 sink.resized(size);
985 }
986 state.net.pump(script);
987 state.request_frame(script, &**sink);
988 self.check_stopped();
989 }
990
991 fn collect_if_idle(&mut self) {
994 if let Some(script) = &self.script
995 && self.state.committed_since_gc
996 && self.last_gc.elapsed() >= IDLE_GC_INTERVAL
997 {
998 script.collect_garbage();
999 self.last_gc = Instant::now();
1000 self.state.committed_since_gc = false;
1001 if let Some(batch) = self.state.commit(Some(script)) {
1002 self.sink.submit(batch);
1003 }
1004 }
1005 }
1006
1007 fn check_stopped(&mut self) {
1008 if let Some(script) = &self.script
1009 && !self.stopped
1010 && let Some(reason) = script.fatal()
1011 {
1012 self.stopped = true;
1013 script.report(&*self.sink, "stopped", &reason);
1014 }
1015 }
1016}
1017
1018struct ScrollEvent {
1019 x: f32,
1020 y: f32,
1021 content: Size,
1022 viewport: Size,
1023 zoom: f32,
1025 throttle: Duration,
1026 last: Option<Instant>,
1027 pending: bool,
1029}
1030
1031struct State<M: TextEngine> {
1032 core: Core<M>,
1033 frame_requested: bool,
1035 ops: Vec<Op>,
1036 binds: Vec<ListBind>,
1038 events: Vec<(NodeId, EventKind, EventPayload)>,
1040 trace: bool,
1041 perf: Option<Arc<perf::PerfMonitor>>,
1043 perf_commit: perf::CommitTiming,
1046 committed_since_gc: bool,
1047 net: Net,
1048 hot: Vec<HotUpdate>,
1050 scroll_events: FxHashMap<NodeId, ScrollEvent>,
1053 touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
1055 resized: Option<Size>,
1057}
1058
1059struct Net {
1061 network: Option<Arc<dyn Network>>,
1062 tx: Sender<Message>,
1063 queue: NetworkQueue,
1064 inflight: FxHashMap<RequestId, Inflight>,
1065 access: Arc<nsh_core::access::Access>,
1067 hops: u64,
1069}
1070
1071struct Inflight {
1073 task: Box<dyn FetchTask>,
1074 hop: u64,
1076 followed: Option<access::Followed>,
1078}
1079
1080impl Net {
1081 fn pump(&mut self, script: Option<&Script>) {
1083 let Some(script) = script else { return };
1084 script.take_network(&mut self.queue);
1085 for (id, op) in std::mem::take(&mut self.queue.ops) {
1086 match op {
1087 FetchOp::Start(request) => self.request(script, id, request),
1088 FetchOp::Send(chunk) => {
1089 if let Some(i) = self.inflight.get_mut(&id) {
1090 i.task.send(chunk);
1091 }
1092 }
1093 FetchOp::Finish => {
1094 if let Some(i) = self.inflight.get_mut(&id) {
1095 i.task.finish();
1096 }
1097 }
1098 FetchOp::Pause(paused) => {
1099 if let Some(i) = self.inflight.get_mut(&id) {
1100 i.task.pause(paused);
1101 }
1102 }
1103 FetchOp::Cancel => {
1104 if let Some(i) = self.inflight.remove(&id) {
1105 i.task.cancel();
1106 }
1107 }
1108 }
1109 }
1110 }
1111
1112 fn request(&mut self, script: &Script, id: RequestId, request: HttpRequest) {
1114 if self.access.is_unrestricted() {
1115 self.start(id, request, None);
1116 } else if !self.access.allows_http(&request.method, &request.url) {
1117 let refused = access::refused(&request.method, &request.url);
1118 script.fetch_event(id, FetchEvent::Failed(refused));
1119 } else if request.follow_redirects {
1120 let hop = access::hop(&request);
1121 let followed = access::Followed { request, hops: 0 };
1122 self.start(id, hop, Some(followed));
1123 } else {
1124 self.start(id, request, None);
1125 }
1126 }
1127
1128 fn start(&mut self, id: RequestId, request: HttpRequest, followed: Option<access::Followed>) {
1130 self.hops += 1;
1131 let hop = self.hops;
1132 let Some(network) = &self.network else {
1133 let failed = FetchEvent::Failed("this host has no network stack".to_owned());
1134 let _ = self.tx.send(Message::Fetch(id, hop, failed));
1135 return;
1136 };
1137 let tx = self.tx.clone();
1138 let events: FetchEvents = Box::new(move |event| {
1139 let _ = tx.send(Message::Fetch(id, hop, event));
1140 });
1141 let task = network.fetch(request, events);
1142 self.inflight.insert(
1143 id,
1144 Inflight {
1145 task,
1146 hop,
1147 followed,
1148 },
1149 );
1150 }
1151
1152 fn event(&mut self, id: RequestId, hop: u64, event: FetchEvent) -> Option<FetchEvent> {
1156 if self.network.is_none() {
1157 return Some(event);
1158 }
1159 let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
1160 match event {
1161 FetchEvent::Head(head) => {
1162 let Some(followed) = &mut inflight.followed else {
1163 return Some(FetchEvent::Head(head));
1164 };
1165 match access::next(&self.access, followed, head) {
1166 access::Next::Done(head) => Some(FetchEvent::Head(head)),
1167 access::Next::Fail(message) => {
1168 if let Some(i) = self.inflight.remove(&id) {
1169 i.task.cancel();
1170 }
1171 Some(FetchEvent::Failed(message))
1172 }
1173 access::Next::Hop(request) => {
1174 let i = self.inflight.remove(&id)?;
1175 let followed = i.followed;
1176 i.task.cancel();
1177 self.start(id, request, followed);
1178 None
1179 }
1180 }
1181 }
1182 FetchEvent::End | FetchEvent::Failed(_) => {
1183 self.inflight.remove(&id);
1184 Some(event)
1185 }
1186 event => Some(event),
1187 }
1188 }
1189}
1190
1191impl<M: TextEngine> State<M> {
1192 fn record_perf(&mut self, started: Option<Instant>) {
1195 let (Some(started), Some(monitor)) = (started, &self.perf) else {
1196 return;
1197 };
1198 let busy = started.elapsed();
1199 monitor.record_busy(busy);
1200 let mut commit = std::mem::take(&mut self.perf_commit);
1201 if commit.ops > 0 || commit.items > 0 {
1202 commit.js = busy.saturating_sub(commit.layout);
1203 monitor.record_commit(commit);
1204 }
1205 }
1206
1207 fn dispatch_touch_move(&mut self, script: Option<&Script>) {
1209 if let Some((id, touch)) = self.touch_move.take()
1210 && let Some(script) = script
1211 {
1212 script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
1213 }
1214 }
1215
1216 fn next_scroll_event(&self) -> Option<Instant> {
1218 self.scroll_events
1219 .values()
1220 .filter(|e| e.pending)
1221 .filter_map(|e| e.last.map(|t| t + e.throttle))
1222 .min()
1223 }
1224
1225 fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
1227 if self.scroll_events.is_empty() {
1228 return;
1229 }
1230 let now = Instant::now();
1231 let core = &self.core;
1233 self.scroll_events
1234 .retain(|&id, _| core.scroll_listener(id).is_some());
1235 for (&id, e) in &mut self.scroll_events {
1236 if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
1237 continue;
1238 }
1239 e.pending = false;
1240 e.last = Some(now);
1241 let n = |v: f32| PayloadValue::Number(v as f64);
1242 let payload = EventPayload::Map(vec![
1243 ("x", n(e.x)),
1244 ("y", n(e.y)),
1245 ("contentWidth", n(e.content.width)),
1246 ("contentHeight", n(e.content.height)),
1247 ("width", n(e.viewport.width)),
1248 ("height", n(e.viewport.height)),
1249 ("zoomScale", n(e.zoom)),
1250 ]);
1251 if !self.core.component_event(id, EventKind::Scroll, &payload)
1253 && let Some(script) = script
1254 {
1255 script.dispatch_event(id, EventKind::Scroll, &payload);
1256 }
1257 }
1258 }
1259
1260 fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
1263 if !self.frame_requested
1264 && (script.is_some_and(Script::wants_frame) || self.core.wants_frame())
1265 {
1266 self.frame_requested = true;
1267 sink.request_frame();
1268 }
1269 }
1270
1271 fn load_fonts(
1274 &mut self,
1275 script: Option<&Script>,
1276 assets: Option<&dyn Assets>,
1277 sink: &dyn MountSink,
1278 ) {
1279 let Some(script) = script else { return };
1280 let mut fonts = Vec::new();
1281 script.take_fonts(&mut fonts);
1282 for uri in fonts {
1283 let result = match assets {
1284 Some(assets) => assets.read(&uri),
1285 None => Err("this host cannot load assets".to_owned()),
1286 }
1287 .and_then(|data| self.core.register_font(&data));
1288 if let Err(err) = result {
1289 script.report(sink, "font failed", &format!("{uri}: {err}"));
1290 }
1291 }
1292 }
1293
1294 fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
1297 let start = Instant::now();
1298 let mut merged: Option<MountBatch> = None;
1299 let mut op_count = 0;
1300 let mut js = std::time::Duration::ZERO;
1301 for _ in 0..MAX_LIST_ROUNDS {
1302 let js_start = Instant::now();
1304 let binds = self.binds.drain(..);
1307 if let Some(script) = script {
1308 for bind in binds {
1309 script.bind_list(bind.list, &bind.binds);
1310 }
1311 } else {
1312 drop(binds);
1313 }
1314 for (id, event, payload) in self.events.drain(..) {
1317 if !self.core.component_event(id, event, &payload)
1318 && let Some(script) = script
1319 {
1320 script.dispatch_event(id, event, &payload);
1321 }
1322 }
1323 if let Some(script) = script {
1324 script.take_ops(&mut self.ops);
1325 }
1326 js += js_start.elapsed();
1327 op_count += self.ops.len();
1328 for op in self.ops.drain(..) {
1330 match self.core.apply(op) {
1331 Ok(()) => {}
1332 Err(err) if err.is_fatal() => {
1333 let Some(script) = script else { break };
1334 script.stop(match err {
1335 ApplyError::TooManyNodes(max) => {
1336 format!("the app created more than {max} nodes and was stopped")
1337 }
1338 other => {
1339 format!("the app sent an invalid op ({other:?}) and was stopped")
1340 }
1341 });
1342 break;
1343 }
1344 Err(err) => log::error!("invalid op: {err:?}"),
1345 }
1346 }
1347 if let Some(batch) = self.core.commit() {
1348 match &mut merged {
1349 Some(m) => extend_frame(&mut m.items, batch.items),
1350 None => merged = Some(batch),
1351 }
1352 }
1353 self.core.take_list_binds(&mut self.binds);
1354 self.core.take_events(&mut self.events);
1355 if self.binds.is_empty() && self.events.is_empty() {
1356 break;
1357 }
1358 }
1359 self.committed_since_gc |= op_count > 0;
1360 if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
1361 let c = &mut self.perf_commit;
1362 c.layout += start.elapsed().saturating_sub(js);
1363 c.ops += op_count as u32;
1364 c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
1365 }
1366 if self.trace && (op_count > 0 || merged.is_some()) {
1367 log::info!(
1368 target: "nsh::perf",
1369 "commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
1370 start.elapsed().as_micros(),
1371 js.as_micros(),
1372 merged.as_ref().map_or(0, |b| b.items.len()),
1373 self.core.node_count(),
1374 );
1375 }
1376 merged
1377 }
1378}
1379
1380fn insets(env: &Environment) -> EdgeInsets {
1381 let a = env.safe_area;
1382 EdgeInsets {
1383 top: a.top,
1384 right: a.right,
1385 bottom: a.bottom,
1386 left: a.left,
1387 }
1388}
1389
1390fn ui_environment(env: &Environment, window: Size) -> nsh_core::ui::Environment {
1392 nsh_core::ui::Environment {
1393 window,
1394 safe_area: insets(env),
1395 keyboard_height: env.keyboard_height,
1396 keyboard_duration: env.keyboard_duration,
1397 dark: env.color_scheme == ColorScheme::Dark,
1398 font_scale: env.font_scale,
1399 reduce_motion: env.reduce_motion,
1400 screen_reader: env.screen_reader,
1401 rtl: env.rtl,
1402 pixel_ratio: env.pixel_ratio,
1403 os: env.os,
1404 os_version: env.os_version,
1405 idiom: env.idiom,
1406 locale: env.locale,
1407 }
1408}
1409
1410fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
1412 nsh_core::tailwind::ClassEnvironment {
1413 dark: env.color_scheme == ColorScheme::Dark,
1414 platform: if cfg!(target_os = "android") {
1415 nsh_core::tailwind::Platform::Android
1416 } else {
1417 nsh_core::tailwind::Platform::Ios
1418 },
1419 reduce_motion: env.reduce_motion,
1420 }
1421}
1422
1423fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
1425 match message {
1426 Message::Event(id, event, payload) => {
1427 if state.trace {
1428 log::info!(target: "nsh::perf", "event {event:?} on view {id}");
1429 }
1430 if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
1433 state.core.input_changed(id, text, *count);
1434 }
1435 if state.core.component_event(id, event, &payload) {
1437 return true;
1438 }
1439 if let EventPayload::Touch(touch) = payload {
1440 if touch.phase == nsh_core::TouchPhase::Move {
1441 match &mut state.touch_move {
1442 Some((_, pending)) => pending.merge_move(*touch),
1443 None => state.touch_move = Some((id, touch)),
1444 }
1445 return true;
1446 }
1447 state.dispatch_touch_move(script);
1449 if let Some(script) = script {
1450 script.dispatch_event(id, event, &EventPayload::Touch(touch));
1451 }
1452 return true;
1453 }
1454 let Some(script) = script else { return true };
1455 let start = state.trace.then(Instant::now);
1456 script.dispatch_event(id, event, &payload);
1457 if let Some(start) = start {
1458 log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
1461 }
1462 }
1463 Message::Scroll(id, x, y, applied) => {
1464 state.core.set_scroll_offset(id, x, y, applied);
1465 if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
1466 let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
1467 x,
1468 y,
1469 content,
1470 viewport,
1471 zoom,
1472 throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
1473 last: None,
1474 pending: true,
1475 });
1476 (event.x, event.y, event.content, event.viewport, event.zoom) =
1477 (x, y, content, viewport, zoom);
1478 event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
1479 event.pending = true;
1480 }
1481 }
1482 Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
1483 Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
1484 Message::AnimationsFinished(mut finished) => {
1485 state.core.animations_finished(&mut finished);
1487 if let Some(script) = script {
1488 script.animations_finished(&finished);
1489 }
1490 }
1491 Message::Resize(size) => {
1492 state.core.set_viewport(size);
1493 state.resized = Some(size);
1494 }
1495 Message::Wake => {}
1496 Message::Environment(env) => {
1497 state.core.set_font_scale(env.font_scale);
1498 state.core.set_class_environment(class_environment(&env));
1499 state.core.set_safe_area(insets(&env));
1500 let window = Size::new(env.window.0, env.window.1);
1501 state.core.set_environment(ui_environment(&env, window));
1502 if let Some(script) = script {
1503 script.set_environment(&env);
1504 }
1505 }
1506 Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
1507 Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
1508 Message::Frame => {
1509 state.frame_requested = false;
1510 state.core.run_frame(Instant::now());
1511 if let Some(script) = script {
1512 script.run_frame();
1513 }
1514 }
1515 Message::States(id, states) => state.core.set_states(id, states),
1516 Message::Fetch(id, hop, event) => {
1517 if let Some(event) = state.net.event(id, hop, event)
1518 && let Some(script) = script
1519 {
1520 script.fetch_event(id, event);
1521 }
1522 }
1523 Message::Hot(update) => state.hot.push(update),
1524 Message::Perf(monitor) => {
1525 state.perf = monitor;
1526 state.perf_commit = perf::CommitTiming::default();
1527 }
1528 Message::Theme(theme) => state.core.set_host_theme(theme.map(|t| *t)),
1529 Message::Shutdown => return false,
1530 }
1531 true
1532}
1533
1534fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
1540 use nsh_core::MountItem;
1541 let start = frame.len();
1542 frame.extend(items);
1543 for k in start..frame.len() {
1544 let MountItem::ScrollContent { id, size } = frame[k] else {
1545 continue;
1546 };
1547 let earlier = frame[..k].iter().rposition(|m| {
1548 matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
1549 });
1550 if let Some(j) = earlier
1551 && let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
1552 {
1553 *s = size;
1554 }
1555 }
1556}
1557
1558#[cfg(test)]
1559mod tests {
1560 use nsh_core::{MountItem, Size};
1561
1562 #[test]
1563 fn a_frame_sends_a_scroll_views_last_content_size() {
1564 let content = |height| MountItem::ScrollContent {
1565 id: 2,
1566 size: Size::new(390.0, height),
1567 };
1568 let heights = |frame: &[MountItem]| -> Vec<f32> {
1569 frame
1570 .iter()
1571 .filter_map(|m| match m {
1572 MountItem::ScrollContent { size, .. } => Some(size.height),
1573 _ => None,
1574 })
1575 .collect()
1576 };
1577 let mut frame = vec![content(313.0)];
1578 super::extend_frame(&mut frame, vec![content(544.0)]);
1579 assert_eq!(heights(&frame), [544.0, 544.0]);
1580 let mut frame = vec![
1582 content(313.0),
1583 MountItem::ScrollBy {
1584 id: 2,
1585 dx: 0.0,
1586 dy: 10.0,
1587 },
1588 ];
1589 super::extend_frame(&mut frame, vec![content(544.0)]);
1590 assert_eq!(heights(&frame), [313.0, 544.0]);
1591 }
1592}