#[cfg(all(feature = "browser", target_arch = "wasm32", not(feature = "js-core")))]
pub mod browser;
mod access;
mod app_directory;
mod cache;
mod error;
mod host_channel;
mod local_storage;
#[cfg(feature = "net")]
pub mod net;
pub mod perf;
mod script;
#[cfg_attr(not(feature = "shader"), path = "shader_off.rs")]
pub mod shader;
mod shader_frame;
#[cfg(all(feature = "shader", target_vendor = "apple"))]
mod shader_surfaces;
#[cfg(not(target_arch = "wasm32"))]
mod storage;
#[cfg(feature = "js-core")]
mod symbolicate;
#[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
pub mod updates;
#[cfg(test)]
#[path = "../../nsh-core/src/geometry/unit_scan.rs"]
mod unit_scan;
#[cfg(test)]
#[test]
fn public_api_is_typed() {
unit_scan::check(std::path::Path::new(env!("CARGO_MANIFEST_DIR")), &[]);
}
use std::{io, mem::ManuallyDrop, rc::Rc, sync::Arc, time::Duration};
pub use app_directory::app_dir_name;
use crossbeam_channel::{Receiver, Sender};
pub use local_storage::local_storage_prefix;
use nsh_core::{
ApplyError, Core, EdgeInsets, EventKind, EventPayload, ListBind, MountBatch, NodeId, Op,
PayloadValue, TextEngine, element::JsEvent, platform::content_type, time::Instant,
};
pub use nsh_core::{
JsonValue,
access::{Access, Capabilities},
element::{EngineContext, Root, Tokens},
geometry::{self, Bounds, Edges, Point, Points, Size},
js::{HostLimits, Limits},
main_thread::MainThreadTask,
platform::{
ColorScheme, Environment, FetchEvent, FetchOp, HostEnvironment, HourCycle, HttpBody,
HttpHead, HttpRequest, Idiom, Languages, Lifecycle, Locale, LocaleSettings,
MeasurementSystem, Os, TemperatureUnit, TimeZone, Weekday,
},
storage::{StorageBackend, StorageChange},
time::Clock,
};
#[cfg(feature = "js-core")]
pub use nsh_js::BYTECODE_VERSION;
#[cfg(feature = "js-core")]
pub use nsh_package as package;
use rustc_hash::FxHashMap;
#[cfg(not(target_arch = "wasm32"))]
pub use storage::{FileStorage, data_dir};
use crate::script::{NetworkQueue, RequestId, Script};
pub use crate::{
cache::{ByteSize, CacheLocation, CacheOptions, CachePolicy},
error::{AppError, AppErrorKind, PackageInfo},
host_channel::{HostCall, HostChannel, HostReply, OpenUrlRequest},
};
#[cfg(not(target_arch = "wasm32"))]
const ENGINE_STACK_SIZE: usize = 8 * 1024 * 1024;
const IDLE_GC_INTERVAL: Duration = Duration::from_secs(1);
const IDLE_GC_QUIET: Duration = Duration::from_millis(300);
const IDLE_GC_LONGEST: Duration = Duration::from_secs(5);
const MOUSE_MOVE_INTERVAL: Duration = Duration::from_millis(8);
#[derive(Debug, Clone)]
#[allow(
clippy::large_enum_variant,
reason = "one app per surface; keep the public constructor API without allocation"
)]
pub enum App {
Rust(Root),
Js(Bundle),
}
impl From<Bundle> for App {
fn from(bundle: Bundle) -> Self {
App::Js(bundle)
}
}
impl App {
pub fn app_id(&self) -> Option<&str> {
match self {
App::Rust(root) => root.app_id_ref(),
App::Js(bundle) => bundle.app_id.as_deref(),
}
}
pub fn main_window(&self) -> Option<&nsh_core::desktop::MainWindowOptions> {
match self {
App::Rust(root) => root.main_window_ref(),
App::Js(bundle) => bundle.main_window.as_ref(),
}
}
pub fn url_schemes(&self) -> &[String] {
match self {
App::Rust(root) => root.url_schemes_ref(),
App::Js(bundle) => &bundle.url_schemes,
}
}
}
impl From<Root> for App {
fn from(root: Root) -> Self {
App::Rust(root)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Bundle {
pub code: BundleCode,
pub source_map: Option<Arc<str>>,
pub policy: Policy,
pub base_url: Option<Arc<str>>,
pub chunks: Arc<Vec<Chunk>>,
pub app_id: Option<String>,
pub url_schemes: Vec<String>,
pub system_paths: nsh_core::access::TrustedPaths,
pub package: Option<Arc<PackageInfo>>,
pub updater_config: Option<Arc<[u8]>>,
pub trial: Option<Arc<dyn Trial>>,
pub main_window: Option<nsh_core::desktop::MainWindowOptions>,
}
pub const TRIAL_PERIOD: Duration = Duration::from_secs(10);
pub trait Trial: Send + Sync + std::fmt::Debug + 'static {
fn healthy(&self);
fn failed(&self, error: &AppError);
}
#[derive(Debug, Clone)]
pub struct Chunk {
pub id: String,
pub code: BundleCode,
pub source_map: Option<Arc<str>>,
}
impl Chunk {
pub fn source(id: impl Into<String>, code: String) -> Self {
Self {
id: id.into(),
code: BundleCode::Source(code),
source_map: None,
}
}
pub unsafe fn bytecode(id: impl Into<String>, bytes: Vec<u8>) -> Self {
Self {
id: id.into(),
code: BundleCode::Bytecode(bytes),
source_map: None,
}
}
pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
self.source_map = Some(map.into());
self
}
}
#[derive(Debug, Clone)]
pub struct Policy {
pub harden: bool,
pub declared: Option<Capabilities>,
pub granted: Option<Capabilities>,
}
impl Default for Policy {
fn default() -> Self {
Self {
harden: true,
declared: None,
granted: None,
}
}
}
impl Policy {
pub fn development() -> Self {
Self {
harden: false,
..Self::default()
}
}
pub fn access(&self) -> Access {
Access {
declared: self.declared.clone().unwrap_or_else(Capabilities::all),
granted: self.granted.clone(),
}
}
}
#[derive(Debug, Clone)]
pub enum BundleCode {
Bytecode(Vec<u8>),
Source(String),
}
impl Default for Bundle {
fn default() -> Self {
Self::source(String::new())
}
}
impl Bundle {
pub unsafe fn bytecode(bytes: Vec<u8>) -> Self {
Self {
code: BundleCode::Bytecode(bytes),
source_map: None,
policy: Policy::default(),
base_url: None,
chunks: Arc::default(),
app_id: None,
url_schemes: Vec::new(),
system_paths: nsh_core::access::TrustedPaths::default(),
package: None,
updater_config: None,
trial: None,
main_window: None,
}
}
pub fn source(code: String) -> Self {
Self {
code: BundleCode::Source(code),
source_map: None,
policy: Policy::default(),
base_url: None,
chunks: Arc::default(),
app_id: None,
url_schemes: Vec::new(),
system_paths: nsh_core::access::TrustedPaths::default(),
package: None,
updater_config: None,
trial: None,
main_window: None,
}
}
pub fn with_system_paths(mut self, mut paths: nsh_core::access::TrustedPaths) -> Self {
paths.plugin_dir = trusted_directory(paths.plugin_dir);
paths.home_dir = trusted_directory(paths.home_dir);
self.system_paths = paths;
self
}
pub fn with_app_id(mut self, id: Option<&str>) -> Self {
self.app_id = id.map(str::to_owned);
self
}
pub fn with_main_window(mut self, json: Option<&str>) -> Self {
self.main_window = json.and_then(|json| {
let parsed = serde_json::from_str(json)
.map_err(|e| e.to_string())
.and_then(|v| nsh_core::desktop::MainWindowOptions::from_json(&v));
parsed.map_err(|e| log::warn!("nsh.json window: {e}")).ok()
});
self
}
pub fn with_url_schemes(
mut self,
schemes: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
self.url_schemes = schemes.into_iter().map(Into::into).collect();
self
}
pub fn with_source_map(mut self, map: impl Into<Arc<str>>) -> Self {
self.source_map = Some(map.into());
self
}
pub fn with_base_url(mut self, url: impl Into<Arc<str>>) -> Self {
self.base_url = Some(url.into());
self
}
pub fn with_policy(mut self, policy: Policy) -> Self {
self.policy = policy;
self
}
pub fn with_chunks(mut self, chunks: impl IntoIterator<Item = Chunk>) -> Self {
Arc::make_mut(&mut self.chunks).extend(chunks);
self
}
pub fn read(path: &std::path::Path) -> io::Result<Bundle> {
if path.extension().is_some_and(|e| e == "nshc") {
return Err(io::Error::other(
"bytecode only loads from the app's own resources or a signed package (.nshpkg); load bundle.js",
));
}
unsafe { Self::read_trusted(path) }
}
pub unsafe fn read_trusted(path: &std::path::Path) -> io::Result<Bundle> {
let bytes = std::fs::read(path)?;
let bundle = if path.extension().is_some_and(|e| e == "nshc") {
unsafe { Bundle::bytecode(bytes) }
} else {
Bundle::source(String::from_utf8(bytes).map_err(io::Error::other)?)
};
let mut bundle = match std::fs::read_to_string(path.with_file_name("bundle.js.map")) {
Ok(map) if !map.is_empty() => bundle.with_source_map(map),
_ => bundle,
};
if let Ok(json) = std::fs::read_to_string(path.with_file_name("capabilities.json")) {
bundle.policy.declared = Some(parse_capabilities(&json).map_err(io::Error::other)?);
}
let info = read_app_json(&path.with_file_name("app.json"));
bundle.app_id = info
.as_ref()
.and_then(|info| info.get("id")?.as_str().map(str::to_owned));
if let Some(window) = info.as_ref().and_then(|info| info.get("window")) {
bundle.main_window = Some(
nsh_core::desktop::MainWindowOptions::from_json(window)
.map_err(|e| io::Error::other(format!("app.json: {e}")))?,
);
}
if let Some(url_schemes) = info.as_ref().and_then(|info| info.get("schemes")) {
let (schemes, ignored) = nsh_core::url_scheme::schemes_from_json_lenient(url_schemes);
for what in ignored {
log::warn!("app.json: {what}, ignored");
}
bundle.url_schemes = schemes;
}
if info
.as_ref()
.is_some_and(nsh_core::file_type::declares_file_types)
{
bundle
.url_schemes
.push(nsh_core::file_type::FILE_SCHEME.to_owned());
}
bundle.system_paths.plugin_dir = nsh_core::access::canonicalize(path)?
.parent()
.map(std::path::Path::to_path_buf);
Ok(bundle)
}
}
#[cfg(feature = "js-core")]
impl Bundle {
pub fn from_package(package: &nsh_package::VerifiedPackage) -> Result<Bundle, String> {
for ignored in &package.ignored {
log::warn!("package {}: ignored {ignored}", package.app.id);
}
let bundle = match package.bytecode() {
Some(bytecode) => unsafe { Bundle::bytecode(bytecode.to_vec()) },
None => Bundle::source(package.source.clone()),
};
let mut bundle = match &package.source_map {
Some(map) => bundle.with_source_map(map.clone()),
None => bundle,
};
if let Some(json) = &package.capabilities {
let (declared, dropped) = Capabilities::from_json_lenient(json)?;
for dropped in dropped {
log::warn!("package {}: not granted: {dropped}", package.app.id);
}
bundle.policy.declared = Some(declared);
}
bundle.app_id = Some(package.app.id.clone());
bundle.package = Some(Arc::new(PackageInfo {
id: package.app.id.clone(),
name: package.app.name.clone(),
version: package.app.version.clone(),
build: package.app.build,
sha256: package.sha256.clone(),
}));
Ok(bundle)
}
}
fn read_app_json(path: &std::path::Path) -> Option<serde_json::Value> {
serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
}
#[cfg(feature = "js-core")]
#[derive(Debug)]
pub struct LoadedPackage {
pub bundle: Bundle,
pub assets: std::path::PathBuf,
pub app: nsh_package::App,
pub receipt: nsh_package::PackageReceipt,
}
#[cfg(feature = "js-core")]
pub fn load_package(
trust: &mut nsh_package::TrustStore,
bytes: &[u8],
assets_root: &std::path::Path,
) -> Result<LoadedPackage, String> {
let package = verify_package(trust, bytes, assets_root)?;
accept_package(trust, &package)?;
Ok(package)
}
#[cfg(feature = "js-core")]
pub fn verify_package(
trust: &nsh_package::TrustStore,
bytes: &[u8],
assets_root: &std::path::Path,
) -> Result<LoadedPackage, String> {
let package = trust
.verify(bytes, BYTECODE_VERSION)
.map_err(|e| e.to_string())?;
let bundle = Bundle::from_package(&package)?;
let dir = assets_root.join(&package.app.id).join(&package.sha256);
let done = dir.join(".complete");
if !done.exists() {
let assets = dir.join("assets");
for (path, data) in &package.assets {
let dest = assets.join(path);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
std::fs::write(&dest, data).map_err(|e| format!("{}: {e}", dest.display()))?;
}
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
std::fs::write(&done, b"").map_err(|e| e.to_string())?;
}
Ok(LoadedPackage {
bundle,
assets: dir.join("assets"),
receipt: package.receipt(),
app: package.app,
})
}
#[cfg(feature = "js-core")]
pub fn symbolicate(source_map: &str, text: &str) -> String {
symbolicate::Symbolicator::new(Some(source_map.into())).rewrite(text)
}
#[cfg(feature = "js-core")]
pub fn accept_package(
trust: &mut nsh_package::TrustStore,
package: &LoadedPackage,
) -> Result<(), String> {
trust
.accept_receipt(&package.receipt)
.map_err(|e| e.to_string())
}
pub fn parse_capabilities(json: &str) -> Result<Capabilities, String> {
let value: serde_json::Value =
serde_json::from_str(json).map_err(|e| format!("capabilities: {e}"))?;
let (capabilities, dropped) = Capabilities::from_json_lenient(&value)?;
for dropped in dropped {
log::warn!("not granted: {dropped} (unknown to this NSH)");
}
Ok(capabilities)
}
impl Bundle {
pub fn with_capabilities_json(mut self, json: Option<&str>) -> Result<Self, String> {
self.policy.declared = json.map(parse_capabilities).transpose()?;
Ok(self)
}
}
pub trait MountSink: Send + 'static {
fn submit(&self, batch: MountBatch);
fn needs_tree_order(&self) -> bool {
false
}
fn needs_projected_states(&self) -> bool {
false
}
fn report_error(&self, _message: &str) {}
fn report(&self, error: &AppError) {
self.report_error(&error.to_string());
}
fn request_frame(&self) {}
fn hot_update_failed(&self) {}
fn run_on_main_thread(&self, task: MainThreadTask) {
task.run();
}
fn resized(&self, _size: Size<Points>) {}
fn handled(&self, _events: u64) {}
fn load_chunk(&self, _id: &str) -> bool {
false
}
}
pub type FetchEvents = Box<dyn FnMut(FetchEvent) + Send>;
pub trait FetchTask: Send {
fn send(&mut self, chunk: Vec<u8>);
fn finish(&mut self);
fn pause(&mut self, paused: bool);
fn cancel(self: Box<Self>);
}
struct UpdaterOverNetwork {
network: Arc<dyn Network>,
assets: Option<Arc<dyn Assets>>,
config: Option<Arc<[u8]>>,
running: Option<Arc<PackageInfo>>,
}
impl UpdaterOverNetwork {
#[cfg_attr(
not(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32"))),
allow(dead_code)
)]
fn host(
network: Option<Arc<dyn Network>>,
assets: Option<Arc<dyn Assets>>,
bundle: &Bundle,
) -> Option<Arc<dyn nsh_core::runtime::UpdaterHost>> {
if assets.is_none() && bundle.updater_config.is_none() {
return None;
}
Some(Arc::new(UpdaterOverNetwork {
network: network?,
assets,
config: bundle.updater_config.clone(),
running: bundle.package.clone(),
}))
}
}
impl nsh_core::runtime::UpdaterHost for UpdaterOverNetwork {
fn config(&self) -> Option<Vec<u8>> {
if let Some(config) = &self.config {
return Some(config.to_vec());
}
self.assets.as_ref()?.read("asset:/nsh-updater.json").ok()
}
fn running_package(&self) -> Option<nsh_core::runtime::PackageVersion> {
let running = self.running.as_ref()?;
let mut version = nsh_core::runtime::PackageVersion::default();
version.version = running.version.clone();
version.build = running.build;
Some(version)
}
fn runs_packages(&self) -> bool {
cfg!(all(feature = "js-core", not(target_arch = "wasm32")))
}
#[cfg(all(feature = "js-core", not(target_arch = "wasm32")))]
fn verify_package(
&self,
file: &std::path::Path,
updates: &std::path::Path,
app_id: &str,
roots: &[String],
newer_than: u64,
) -> Result<nsh_core::runtime::PackageVersion, String> {
let app = updates::verify_download(file, updates, app_id, roots, newer_than)?;
let mut version = nsh_core::runtime::PackageVersion::default();
version.version = app.version;
version.build = app.build;
Ok(version)
}
fn get(&self, url: &str, sink: nsh_core::runtime::UpdaterSink<'_>) -> Result<(), String> {
let (tx, rx) = std::sync::mpsc::channel();
let events: FetchEvents = Box::new(move |event| {
let _ = tx.send(event);
});
let task = self.network.fetch(HttpRequest::new("GET", url), events);
let mut total = None;
let result = loop {
match rx.recv() {
Ok(FetchEvent::Head(head)) => {
if !(200..300).contains(&head.status) {
break Err(format!("HTTP {}", head.status));
}
total = head
.headers
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
.and_then(|(_, value)| value.parse().ok());
}
Ok(FetchEvent::Data(chunk)) => {
if let Err(e) = sink(&chunk, total) {
break Err(e);
}
}
Ok(FetchEvent::End) => return Ok(()),
Ok(FetchEvent::Failed(e)) => break Err(e),
Ok(FetchEvent::BodyWanted) => {}
Err(_) => break Err("the network stack went away".to_owned()),
}
};
task.cancel();
result
}
}
pub trait Network: Send + Sync + 'static {
fn fetch(&self, request: HttpRequest, events: FetchEvents) -> Box<dyn FetchTask>;
}
pub trait Assets: Send + Sync + 'static {
fn read(&self, uri: &str) -> Result<Vec<u8>, String>;
fn url(&self, uri: &str) -> Option<String> {
let _ = uri;
None
}
#[cfg(not(target_arch = "wasm32"))]
fn base(&self) -> Option<nsh_core::image::loader::AssetBase> {
None
}
}
#[derive(Clone)]
pub struct EngineConfig {
pub app: App,
pub viewport: Size<Points>,
pub trace: bool,
pub content_culling: bool,
pub network: Option<Arc<dyn Network>>,
pub websocket: Option<Arc<dyn nsh_core::websocket::WebSocketTransport>>,
pub refuse_connections: Option<nsh_core::element::RefuseConnections>,
pub filesystem: Option<Arc<dyn nsh_core::filesystem::FileSystem>>,
pub assets: Option<Arc<dyn Assets>>,
pub environment: Environment,
pub header_heights: (Points, Points),
pub limits: Limits,
pub ui_sets: Vec<nsh_core::element::Registry>,
pub runtime: Option<tokio::runtime::Handle>,
pub data_dir: Option<std::path::PathBuf>,
pub cache: CacheOptions,
pub storage: Option<Arc<dyn nsh_core::storage::StorageBackend>>,
pub clock: Clock,
pub context: EngineContext,
pub pinned: EnvironmentPins,
pub clipboard: Option<Arc<dyn nsh_core::clipboard::ClipboardBackend>>,
pub host: HostChannel,
pub picker: Option<Arc<dyn nsh_core::picker::PickerBackend>>,
pub speech: Option<Arc<dyn nsh_core::speech::SpeechBackend>>,
pub audio: Option<Arc<dyn nsh_core::audio::AudioBackend>>,
pub windows: Option<Arc<dyn nsh_core::desktop::WindowBackend>>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[non_exhaustive]
pub struct EnvironmentPins {
pub locale: Option<nsh_core::platform::Locale>,
pub languages: Option<nsh_core::platform::Languages>,
pub hour_cycle: Option<nsh_core::platform::HourCycle>,
pub first_day_of_week: Option<nsh_core::platform::Weekday>,
pub measurement_system: Option<nsh_core::platform::MeasurementSystem>,
pub temperature_unit: Option<nsh_core::platform::TemperatureUnit>,
pub time_zone: Option<nsh_core::platform::TimeZone>,
pub reduce_motion: Option<bool>,
pub safe_area: Option<nsh_core::geometry::Edges<Points>>,
}
impl EnvironmentPins {
pub fn apply(&self, environment: &mut Environment) {
if let Some(locale) = self.locale {
environment.locale = locale;
}
let settings = &mut environment.locale_settings;
if let Some(languages) = self.languages {
settings.languages = languages;
}
if let Some(time_zone) = self.time_zone {
settings.time_zone = time_zone;
}
if let Some(hour_cycle) = self.hour_cycle {
settings.hour_cycle = hour_cycle;
}
if let Some(day) = self.first_day_of_week {
settings.first_day_of_week = day;
}
if let Some(system) = self.measurement_system {
settings.measurement_system = system;
}
if let Some(unit) = self.temperature_unit {
settings.temperature_unit = unit;
}
if let Some(reduce_motion) = self.reduce_motion {
environment.reduce_motion = reduce_motion;
}
if let Some(safe_area) = self.safe_area {
environment.safe_area = safe_area;
}
}
}
fn trusted_directory(path: Option<std::path::PathBuf>) -> Option<std::path::PathBuf> {
let path = path.filter(|path| path.is_absolute())?;
nsh_core::access::canonicalize(&path)
.ok()
.filter(|path| path.is_dir())
}
fn bundle_system_paths(bundle: &Bundle) -> nsh_core::access::TrustedPaths {
let mut paths = bundle.system_paths.clone();
paths.plugin_dir = trusted_directory(paths.plugin_dir);
paths.home_dir = trusted_directory(paths.home_dir);
if paths.home_dir.is_none() {
paths.home_dir = ["HOME", "USERPROFILE"]
.into_iter()
.filter_map(std::env::var_os)
.map(std::path::PathBuf::from)
.find_map(|path| trusted_directory(Some(path)));
}
if paths.plugin_dir.is_none() && !bundle.policy.harden {
paths.plugin_dir = std::env::var_os("NSH_DEV_APP_DIR")
.map(std::path::PathBuf::from)
.and_then(|path| trusted_directory(Some(path)));
}
paths
}
impl EngineConfig {
pub fn new(app: impl Into<App>) -> Self {
Self {
app: app.into(),
viewport: Size::new(Points(390.0), Points(844.0)),
trace: false,
content_culling: false,
network: None,
websocket: None,
refuse_connections: None,
filesystem: None,
assets: None,
environment: Environment::default(),
header_heights: (Points(44.0), Points(96.0)),
limits: Limits::default(),
ui_sets: Vec::new(),
runtime: None,
data_dir: None,
cache: CacheOptions::off(),
storage: None,
clock: Clock::system(),
context: EngineContext::default(),
pinned: EnvironmentPins::default(),
clipboard: None,
host: HostChannel::default(),
picker: None,
speech: None,
audio: None,
windows: None,
}
}
pub fn main_window_placement(
&self,
displays: &[nsh_core::desktop::Display],
) -> Option<nsh_core::desktop::WindowPlacement> {
let options = self.app.main_window()?;
let storage = app_storage(self)?;
options.kept_placement(&*storage, displays)
}
}
fn app_storage(config: &EngineConfig) -> Option<Arc<dyn nsh_core::storage::StorageBackend>> {
if let Some(storage) = &config.storage {
return Some(storage.clone());
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(root) = &config.data_dir {
let dir = root.join(app_dir_name(config.app.app_id()));
return Some(FileStorage::open(dir));
}
None
}
#[cfg(not(target_arch = "wasm32"))]
fn shared_runtime() -> tokio::runtime::Handle {
static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
RUNTIME
.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("nsh-tasks")
.enable_all()
.build()
.expect("the tasks' runtime starts")
})
.handle()
.clone()
}
impl std::fmt::Debug for EngineConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EngineConfig")
.field("app", &self.app)
.field("viewport", &self.viewport)
.field("trace", &self.trace)
.field("content_culling", &self.content_culling)
.field("network", &self.network.is_some())
.field("assets", &self.assets.is_some())
.field("environment", &self.environment)
.field("header_heights", &self.header_heights)
.field("limits", &self.limits)
.field("ui_sets", &self.ui_sets)
.field("clock", &self.clock)
.field("context", &self.context)
.field("pinned", &self.pinned)
.field("clipboard", &self.clipboard.is_some())
.field("host", &self.host)
.field("picker", &self.picker.is_some())
.field("speech", &self.speech.is_some())
.field("audio", &self.audio.is_some())
.field("windows", &self.windows.is_some())
.finish()
}
}
const MAX_ADVANCE_ROUNDS: usize = 100_000;
const MAX_FLUSH_ROUNDS: usize = 64;
enum Message {
Event(NodeId, EventKind, EventPayload),
Scroll(NodeId, Point<Points>, u32),
Kept(Vec<NodeId>),
ContentCulling(bool),
InputScroll(NodeId, Point<Points>, Size<Points>, Size<Points>),
Zoom(NodeId, f32),
ComponentSize(NodeId, Size<Points>),
AnimationsFinished(Vec<nsh_core::animation::Finished>),
Resize(Size<Points>),
Wake,
Environment(Box<Environment>),
ShadersUnavailable,
Displays(Arc<[nsh_core::desktop::Display]>),
RootSize(NodeId, Size<Points>, EdgeInsets),
ScreenHeader(NodeId, Option<Points>),
Frame,
States(NodeId, u16),
Modality(nsh_core::platform::InputModality),
FontsChanged,
Remount,
Fetch(Requester, u64, FetchEvent),
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
AssetRead(Requester, u64, HttpRequest, Result<Vec<u8>, String>),
Hot(HotUpdate),
Chunk(Result<Chunk, (String, String)>),
Perf(Option<Arc<perf::PerfMonitor>>),
Tokens(Option<Box<Tokens>>),
HostFont(Vec<u8>),
HostEvent(String, nsh_core::JsonValue),
HostReply(u64, Result<nsh_core::JsonValue, String>),
UrlHandled {
id: u32,
url: String,
handled: bool,
},
Advance(std::time::Duration, Box<dyn FnOnce() + Send>),
Flush(Box<dyn FnOnce(bool) + Send>),
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
Shutdown,
}
#[derive(Debug, Clone)]
pub struct HotUpdate {
pub name: String,
pub code: String,
pub source_map: Option<Arc<str>>,
}
const MAX_LIST_ROUNDS: usize = 8;
const PACED_BIND_OPS: usize = 150;
const PACED_BIND_TIME: std::time::Duration = std::time::Duration::from_millis(2);
#[derive(Clone)]
pub struct EngineControl {
tx: Sender<Message>,
modality: Arc<std::sync::atomic::AtomicU8>,
}
impl EngineControl {
pub fn dispatch_event(&self, id: NodeId, event: EventKind, payload: EventPayload) {
let _ = self.tx.send(Message::Event(id, event, payload));
}
pub fn scroll(&self, id: NodeId, offset: Point<Points>, applied: u32) {
let _ = self.tx.send(Message::Scroll(id, offset, applied));
}
pub fn keep_rendered(&self, nodes: Vec<NodeId>) {
let _ = self.tx.send(Message::Kept(nodes));
}
pub fn set_content_culling(&self, enabled: bool) {
let _ = self.tx.send(Message::ContentCulling(enabled));
}
pub fn input_scroll(
&self,
id: NodeId,
offset: Point<Points>,
content: Size<Points>,
viewport: Size<Points>,
) {
let _ = self
.tx
.send(Message::InputScroll(id, offset, content, viewport));
}
pub fn zoom(&self, id: NodeId, scale: f32) {
let _ = self.tx.send(Message::Zoom(id, scale));
}
pub fn set_component_size(&self, id: NodeId, size: Size<Points>) {
let _ = self.tx.send(Message::ComponentSize(id, size));
}
pub fn animations_finished(&self, finished: Vec<nsh_core::animation::Finished>) {
let _ = self.tx.send(Message::AnimationsFinished(finished));
}
pub fn resize(&self, size: Size<Points>) {
let _ = self.tx.send(Message::Resize(size));
}
pub fn set_environment(&self, environment: Environment) {
let _ = self.tx.send(Message::Environment(Box::new(environment)));
}
pub fn shaders_unavailable(&self) {
let _ = self.tx.send(Message::ShadersUnavailable);
}
pub fn set_displays(&self, displays: Vec<nsh_core::desktop::Display>) {
let _ = self.tx.send(Message::Displays(displays.into()));
}
pub fn set_root_size(&self, id: NodeId, size: Size<Points>, insets: EdgeInsets) {
let _ = self.tx.send(Message::RootSize(id, size, insets));
}
pub fn set_screen_header(&self, id: NodeId, height: Option<Points>) {
let _ = self.tx.send(Message::ScreenHeader(id, height));
}
pub fn hot_update(&self, update: HotUpdate) {
let _ = self.tx.send(Message::Hot(update));
}
pub fn chunk_loaded(&self, chunk: Chunk) {
let _ = self.tx.send(Message::Chunk(Ok(chunk)));
}
pub fn chunk_failed(&self, id: String, message: String) {
let _ = self.tx.send(Message::Chunk(Err((id, message))));
}
pub fn frame(&self) {
let _ = self.tx.send(Message::Frame);
}
pub fn advance_clock(&self, by: std::time::Duration, done: impl FnOnce() + Send + 'static) {
let _ = self.tx.send(Message::Advance(by, Box::new(done)));
}
pub fn flush(&self, done: impl FnOnce(bool) + Send + 'static) {
let _ = self.tx.send(Message::Flush(Box::new(done)));
}
pub fn set_input_modality(&self, modality: nsh_core::platform::InputModality) {
use std::sync::atomic::Ordering;
let code = match modality {
nsh_core::platform::InputModality::Keyboard => 1,
nsh_core::platform::InputModality::Pointer => 2,
};
if self.modality.swap(code, Ordering::Relaxed) != code {
let _ = self.tx.send(Message::Modality(modality));
}
}
pub fn set_states(&self, id: NodeId, states: u16) {
let _ = self.tx.send(Message::States(id, states));
}
pub fn fonts_changed(&self) {
let _ = self.tx.send(Message::FontsChanged);
}
pub fn remount(&self) {
let _ = self.tx.send(Message::Remount);
}
pub fn set_perf_monitor(&self, monitor: Option<Arc<perf::PerfMonitor>>) {
let _ = self.tx.send(Message::Perf(monitor));
}
pub fn set_tokens(&self, tokens: Option<Tokens>) {
let _ = self.tx.send(Message::Tokens(tokens.map(Box::new)));
}
pub fn register_font(&self, data: Vec<u8>) {
let _ = self.tx.send(Message::HostFont(data));
}
}
#[cfg(not(target_arch = "wasm32"))]
pub struct Engine {
control: EngineControl,
thread: Option<std::thread::JoinHandle<()>>,
host: HostChannel,
stop: Arc<std::sync::atomic::AtomicBool>,
quit_listeners: Arc<std::sync::atomic::AtomicBool>,
image_cache: Option<nsh_core::image::DiskCache>,
media_files: Arc<nsh_core::access::MediaFiles>,
}
#[cfg(not(target_arch = "wasm32"))]
impl Engine {
pub fn start<M, F, S>(config: EngineConfig, make_text_engine: F, sink: S) -> io::Result<Engine>
where
M: TextEngine + 'static,
F: FnOnce() -> M + Send + 'static,
S: MountSink,
{
Self::start_with(config, make_text_engine, sink, |_| {})
}
pub fn start_with<M, F, S>(
config: EngineConfig,
make_text_engine: F,
sink: S,
setup: impl FnOnce(&EngineControl),
) -> io::Result<Engine>
where
M: TextEngine + 'static,
F: FnOnce() -> M + Send + 'static,
S: MountSink,
{
let image_cache = config.cache.open_images(config.app.app_id());
let media_files = Arc::new(media_files(&config, &app_access(&config.app)));
let (tx, rx) = crossbeam_channel::unbounded();
let modality = Arc::default();
setup(&EngineControl {
tx: tx.clone(),
modality: Arc::clone(&modality),
});
let engine_tx = tx.clone();
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let engine_stop = stop.clone();
let quit_listeners = Arc::new(std::sync::atomic::AtomicBool::new(false));
let engine_quit_listeners = quit_listeners.clone();
let host = config.host.clone();
let thread = std::thread::Builder::new()
.name("nsh-engine".into())
.stack_size(ENGINE_STACK_SIZE)
.spawn(move || {
run(
config,
make_text_engine(),
sink,
engine_tx,
rx,
engine_stop,
engine_quit_listeners,
)
})?;
Ok(Engine {
control: EngineControl { tx, modality },
thread: Some(thread),
host,
stop,
quit_listeners,
image_cache,
media_files,
})
}
pub fn media_files(&self) -> Arc<nsh_core::access::MediaFiles> {
self.media_files.clone()
}
pub fn image_cache(&self) -> Option<nsh_core::image::DiskCache> {
self.image_cache.clone()
}
pub fn control(&self) -> EngineControl {
self.control.clone()
}
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for Engine {
fn drop(&mut self) {
if self
.quit_listeners
.load(std::sync::atomic::Ordering::Relaxed)
{
self.host.request_shutdown(&self.control.tx);
let deadline = Instant::now() + QUIT_TIMEOUT + QUIT_GRACE;
while self.thread.as_ref().is_some_and(|t| !t.is_finished())
&& Instant::now() < deadline
{
std::thread::sleep(Duration::from_millis(1));
}
}
self.host.shutdown(&self.control.tx, &self.stop);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
#[cfg(not(target_arch = "wasm32"))]
fn raise_thread_priority() {
#[cfg(target_vendor = "apple")]
unsafe {
libc::pthread_set_qos_class_self_np(libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE, 0);
}
}
#[cfg(not(target_arch = "wasm32"))]
use nsh_core::element::desktop::QUIT_TIMEOUT;
#[cfg(not(target_arch = "wasm32"))]
const QUIT_GRACE: Duration = Duration::from_millis(20);
const RESIZE_BURST_GAP: Duration = Duration::from_millis(120);
#[cfg(not(target_arch = "wasm32"))]
fn run<M: TextEngine + 'static, S: MountSink>(
config: EngineConfig,
text_engine: M,
sink: S,
tx: Sender<Message>,
rx: Receiver<Message>,
stop: Arc<std::sync::atomic::AtomicBool>,
quit_listeners: Arc<std::sync::atomic::AtomicBool>,
) {
raise_thread_priority();
let _clock = config.clock.enter();
let _context = config.context.enter();
let Some(mut driver) = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop) else {
return;
};
driver.quit_listeners = quit_listeners;
driver.sync_quit_listeners();
drive(&mut driver, &rx);
driver.quit(&rx);
if let Some(trial) = &driver.trial {
trial.healthy();
}
}
fn start_trial(trial: Arc<dyn Trial>) {
#[cfg(not(target_arch = "wasm32"))]
{
let spawned = std::thread::Builder::new()
.name("nsh-trial".into())
.spawn(move || {
std::thread::sleep(TRIAL_PERIOD);
trial.healthy();
});
if let Err(err) = spawned {
log::error!("cannot time the app's trial: {err}");
}
}
#[cfg(target_arch = "wasm32")]
drop(trial);
}
#[cfg(not(target_arch = "wasm32"))]
fn drive<M: TextEngine + 'static>(driver: &mut Driver<M>, rx: &Receiver<Message>) {
loop {
let message = match driver.deadline() {
Some(deadline) => match rx.recv_deadline(deadline) {
Ok(message) => Some(message),
Err(crossbeam_channel::RecvTimeoutError::Timeout) => None,
Err(crossbeam_channel::RecvTimeoutError::Disconnected) => return,
},
None => match rx.recv() {
Ok(message) => Some(message),
Err(_) => return,
},
};
let started = driver.state.perf.is_some().then(Instant::now);
if let Some(message) = message {
if !driver.handle(message, rx) {
return;
}
while let Ok(message) = rx.try_recv() {
if !driver.handle(message, rx) {
return;
}
}
}
driver.turn();
driver.state.record_perf(started);
if rx.is_empty() {
driver.collect_if_idle();
}
}
}
pub struct LocalEngine<M: TextEngine + 'static> {
driver: ManuallyDrop<Driver<M>>,
rx: Receiver<Message>,
control: EngineControl,
wake: Option<Arc<dyn Fn() + Send + Sync>>,
pumping: Arc<std::sync::atomic::AtomicBool>,
}
impl<M: TextEngine + 'static> LocalEngine<M> {
pub fn start<S: MountSink>(config: EngineConfig, text_engine: M, sink: S) -> Option<Self> {
Self::start_with(config, text_engine, sink, |_| {})
}
pub fn start_with<S: MountSink>(
config: EngineConfig,
text_engine: M,
sink: S,
setup: impl FnOnce(&EngineControl),
) -> Option<Self> {
let (tx, rx) = crossbeam_channel::unbounded();
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let control = EngineControl {
tx: tx.clone(),
modality: Arc::default(),
};
setup(&control);
let _clock = config.clock.enter();
let _context = config.context.enter();
let driver = Driver::start(config, text_engine, Rc::new(sink), tx, &rx, stop)?;
Some(LocalEngine {
driver: ManuallyDrop::new(driver),
rx,
control,
wake: None,
pumping: Arc::default(),
})
}
pub fn control(&self) -> EngineControl {
self.control.clone()
}
pub fn set_wake(&mut self, wake: Arc<dyn Fn() + Send + Sync>) {
let tx = self.control.tx.clone();
let pumping = self.pumping.clone();
let host = wake.clone();
let notify: Arc<dyn Fn() + Send + Sync> = Arc::new(move || {
let _ = tx.send(Message::Wake);
if !pumping.load(std::sync::atomic::Ordering::SeqCst) {
host();
}
});
self.driver.state.core.set_task_notify(notify.clone());
self.driver.posts.set_notify(notify);
self.wake = Some(wake);
}
pub fn extend_ui_sets(&mut self, ui_sets: &[nsh_core::element::Registry]) {
let sets: Vec<_> = nsh_core::runtime::registries()
.iter()
.chain(ui_sets)
.cloned()
.collect();
self.driver
.state
.core
.extend_components(nsh_core::element::Registry::merged(&sets));
}
pub fn pump(&mut self) -> Option<Instant> {
let _clock = self.driver.clock.enter();
let _context = self.driver.context.enter();
self.pumping
.store(true, std::sync::atomic::Ordering::SeqCst);
for _ in 0..4 {
let started = self.driver.state.perf.is_some().then(Instant::now);
while let Ok(message) = self.rx.try_recv() {
self.driver.handle(message, &self.rx);
}
self.driver.turn();
self.driver.state.record_perf(started);
if self.rx.is_empty() {
break;
}
}
self.driver.collect_if_idle();
self.pumping
.store(false, std::sync::atomic::Ordering::SeqCst);
if !self.rx.is_empty()
&& let Some(wake) = &self.wake
{
wake();
}
self.driver.deadline()
}
}
impl<M: TextEngine + 'static> Drop for LocalEngine<M> {
fn drop(&mut self) {
let _context = self.driver.context.enter();
unsafe { ManuallyDrop::drop(&mut self.driver) };
}
}
struct Driver<M: TextEngine + 'static> {
state: State<Rc<M>>,
script: Option<Script>,
sink: Rc<dyn MountSink>,
assets: Option<Arc<dyn Assets>>,
stopped: bool,
last_gc: Instant,
last_active: Instant,
posts: nsh_core::element::Posts,
clock: Clock,
context: EngineContext,
last_frame: Option<Instant>,
_host: host_channel::HostAttachment,
#[cfg(not(target_arch = "wasm32"))]
trial: Option<Arc<dyn Trial>>,
quit_listeners: Arc<std::sync::atomic::AtomicBool>,
quitting: bool,
}
impl<M: TextEngine + 'static> Driver<M> {
fn start(
mut config: EngineConfig,
text_engine: M,
sink: Rc<dyn MountSink>,
tx: Sender<Message>,
rx: &Receiver<Message>,
stop: Arc<std::sync::atomic::AtomicBool>,
) -> Option<Self> {
config.pinned.apply(&mut config.environment);
drawn_shaders(&mut config.environment, false);
let trial = match &config.app {
App::Js(bundle) => bundle.trial.clone(),
App::Rust(_) => None,
};
#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
let system_tx = tx.clone();
#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
let host_bridge = config.host.bridge(tx.clone());
let host_tx = tx.clone();
let text_engine = Rc::new(text_engine);
let access = Arc::new(app_access(&config.app));
let mut core = Core::new(text_engine.clone(), config.viewport);
core.set_content_culling(config.content_culling);
core.set_tree_order_tracking(sink.needs_tree_order());
core.set_projected_state_mounting(sink.needs_projected_states());
let sets: Vec<_> = nsh_core::runtime::registries()
.iter()
.chain(&config.ui_sets)
.cloned()
.collect();
core.set_components(nsh_core::element::Registry::merged(&sets));
let posts = nsh_core::element::Posts::new();
core.set_posts(posts.clone());
if let App::Js(_) = &config.app {
core.set_max_nodes(config.limits.max_nodes);
}
core.set_access(access.clone());
if let App::Js(bundle) = &config.app {
core.set_base_url(bundle.base_url.clone());
}
let media_files = Arc::new(media_files(&config, &access));
core.set_media_files(media_files.clone());
#[cfg(not(target_arch = "wasm32"))]
core.set_image_context(nsh_core::image::loader::Context {
asset_base: config.assets.as_ref().and_then(|a| a.base()),
read_asset: config.assets.clone().map(|assets| {
Arc::new(move |uri: &str| assets.read(uri)) as nsh_core::image::loader::ReadAsset
}),
access: access.clone(),
media_files,
disk: config.cache.open_images(config.app.app_id()),
transport: None,
});
core.set_storage(app_storage(&config));
core.set_data_dir(
config
.data_dir
.as_ref()
.map(|root| root.join(app_dir_name(config.app.app_id()))),
);
core.set_clipboard(config.clipboard.clone());
core.set_picker(config.picker.clone());
core.set_speech(config.speech.clone());
core.set_url_schemes(config.app.url_schemes().iter().cloned());
#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
let app_url = core.app_url_cell();
core.set_audio(config.audio.clone());
core.set_window_backend(config.windows.clone());
if let Some(window) = config.app.main_window() {
core.set_main_window(window);
}
core.set_font_scale(config.environment.font_scale);
core.set_class_environment(class_environment(&config.environment));
core.set_header_heights(config.header_heights.0, config.header_heights.1);
core.set_safe_area(insets(&config.environment));
core.set_environment(ui_environment(&config.environment, config.viewport));
#[cfg(not(target_arch = "wasm32"))]
let runtime = config.runtime.clone().unwrap_or_else(shared_runtime);
#[cfg(not(target_arch = "wasm32"))]
core.set_task_runtime(runtime.clone());
if let App::Rust(root) = &config.app {
if let Some(tokens) = root.tokens_ref() {
core.set_tokens(tokens.clone());
}
if let Some(appearance) = root.appearance_ref() {
core.set_appearance(appearance);
}
if let Some(translations) = root.translations_ref() {
core.set_translations(translations.clone());
}
for font in root.fonts() {
if let Err(err) = core.register_font(font) {
log::error!("font failed: {err}");
sink.report(&AppError::new(
AppErrorKind::Asset,
&format!("font failed: {err}"),
));
}
}
}
let fonts = config
.ui_sets
.iter()
.flat_map(nsh_core::element::Registry::asset_files)
.filter(|file| file.kind == nsh_core::element::AssetKind::Font);
for font in fonts {
let result = match config.assets.as_deref() {
Some(assets) => assets.read(font.uri),
None => Err("this host cannot load assets".to_owned()),
}
.and_then(|data| core.register_font(&data));
if let Err(err) = result {
log::error!("font failed: {}: {err}", font.uri);
let message = format!("font failed: {}: {err}", font.uri);
let package = match &config.app {
App::Js(bundle) => bundle.package.clone(),
App::Rust(_) => None,
};
sink.report(&AppError::new(AppErrorKind::Asset, &message).with_package(package));
}
}
let wake = tx.clone();
core.set_task_notify(Arc::new(move || {
let _ = wake.send(Message::Wake);
}));
let wake = tx.clone();
posts.set_notify(Arc::new(move || {
let _ = wake.send(Message::Wake);
}));
let mut early = Vec::new();
let mut displays: Arc<[nsh_core::desktop::Display]> = Arc::from(Vec::new());
while let Ok(message) = rx.try_recv() {
match message {
Message::Tokens(tokens) => core.set_host_tokens(tokens.map(|t| *t)),
Message::HostFont(data) => {
if let Err(err) = core.register_font(&data) {
log::error!("font failed: {err}");
}
}
Message::Displays(list) => {
core.set_displays(list.clone());
displays = list;
}
Message::Event(nsh_core::ROOT_ID, EventKind::UrlScheme, payload) => {
core.component_event(nsh_core::ROOT_ID, EventKind::UrlScheme, &payload);
}
message => early.push(message),
}
}
let js_tokens = core.tokens().clone();
let state = State {
core,
js_tokens,
frame_requested: false,
ops: Vec::new(),
binds: Vec::new(),
events: Vec::new(),
trace: config.trace,
perf: None,
perf_commit: perf::CommitTiming::default(),
committed_since_gc: false,
hot: Vec::new(),
scroll_events: FxHashMap::default(),
touch_move: None,
mouse_moves: Vec::new(),
mouse_moved: None,
sets_seen: FxHashMap::default(),
resized: None,
resize_burst_ends: None,
window_state: WindowStateReport {
shown: config.environment.window_state,
..WindowStateReport::default()
},
events_handled: 0,
events_reported: 0,
pinned: config.pinned,
environment: config.environment,
shaders_unavailable: false,
app_locale: None,
host: config.host.clone(),
url_opens: Vec::new(),
net: Net {
network: config.network.clone(),
tx,
queue: NetworkQueue::default(),
inflight: FxHashMap::default(),
tasks: Vec::new(),
abandoned: Vec::new(),
access: access.clone(),
hops: 0,
assets: config.assets.clone(),
#[cfg(not(target_arch = "wasm32"))]
runtime,
},
};
let mut environment = config.environment;
environment.window = config.viewport;
let start = Instant::now();
let mut driver = Driver {
state,
script: None,
sink: sink.clone(),
assets: config.assets.clone(),
stopped: false,
last_gc: Instant::now(),
last_active: Instant::now(),
posts: posts.clone(),
clock: config.clock.clone(),
context: config.context.clone(),
last_frame: None,
_host: config.host.attach(host_tx, rx.clone()),
#[cfg(not(target_arch = "wasm32"))]
trial: trial.clone(),
quit_listeners: Arc::default(),
quitting: false,
};
let eval_us = match &config.app {
App::Js(bundle) => {
#[cfg(any(feature = "js-core", all(feature = "browser", target_arch = "wasm32")))]
let system = {
script::SystemConfig {
access: (*access).clone(),
websocket: config.websocket.clone(),
refuse_connections: config.refuse_connections.clone(),
filesystem: config.filesystem.clone(),
updater: UpdaterOverNetwork::host(
config.network.clone(),
config.assets.clone(),
bundle,
),
app_url: app_url.clone(),
data_dir: config
.data_dir
.as_ref()
.map(|root| root.join(app_dir_name(config.app.app_id()))),
paths: bundle_system_paths(bundle),
wake: Arc::new(move || {
let _ = system_tx.send(Message::Wake);
}),
host: Rc::new(host_bridge),
lazy_rows: config.content_culling,
}
};
#[cfg(not(any(
feature = "js-core",
all(feature = "browser", target_arch = "wasm32")
)))]
let system = script::SystemConfig;
let (script, eval_us) = Script::start(
bundle,
config.limits,
&config.ui_sets,
posts,
&environment,
&displays,
driver.state.js_tokens.clone(),
driver.state.core.theme_tokens(),
text_engine,
stop,
sink,
system,
)?;
driver.script = Some(script);
eval_us
}
App::Rust(root) => {
driver.state.core.mount_root(root);
0
}
};
let Driver {
state,
script,
sink,
assets,
..
} = &mut driver;
let script = script.as_ref();
let mut moves = Vec::new();
let pending = early
.into_iter()
.chain(std::iter::from_fn(|| rx.try_recv().ok()));
for message in pending {
if let Message::Advance(..) | Message::Flush(..) = message {
moves.push(message);
} else if !handle(script, state, message) {
return None;
}
}
if let Some(script) = script {
script.run_system();
}
state.load_fonts(script, assets.as_deref(), &**sink);
if let Some(batch) = state.commit(script) {
if state.trace {
log::info!(
target: "nsh::perf",
"first frame: eval {eval_us}µs, total {}µs",
start.elapsed().as_micros()
);
}
sink.submit(batch);
}
state.run_on_main_thread(&**sink);
if let Some(trial) = trial {
start_trial(trial);
}
if let Some(size) = state.resized.take() {
sink.resized(size);
}
state.report_handled(&**sink);
state.net.pump(script, &mut state.core);
state.load_chunks(script, &**sink);
state.request_frame(script, &**sink);
driver.check_stopped();
for message in moves {
if !driver.handle(message, rx) {
return None;
}
}
Some(driver)
}
fn deadline(&self) -> Option<Instant> {
let gc_deadline =
(self.script.is_some() && self.state.committed_since_gc).then(|| self.next_gc());
let due = if self.clock.is_manual() {
None
} else {
self.due()
};
[due, gc_deadline].into_iter().flatten().min()
}
fn due(&self) -> Option<Instant> {
[
self.script.as_ref().and_then(Script::next_timer),
self.state.next_scroll_event(),
self.state.next_mouse_move(),
self.state.core.next_task_timer(),
self.state.resize_burst_ends,
self.state.window_state.settles,
]
.into_iter()
.flatten()
.min()
}
fn handle(&mut self, message: Message, rx: &Receiver<Message>) -> bool {
self.last_active = Instant::now();
match message {
Message::Advance(by, done) => {
let running = self.advance(by, rx, self.clock.moves_with_frames());
done();
running
}
Message::Flush(done) => {
let running = self.flush(rx);
done(running && self.idle(rx));
running
}
Message::Frame if self.clock.moves_with_frames() => {
self.state.frame_requested = true;
let by = self.next_frame() - self.clock.now();
self.advance(by, rx, true)
}
message => handle(self.script.as_ref(), &mut self.state, message),
}
}
fn advance(&mut self, by: std::time::Duration, rx: &Receiver<Message>, frames: bool) -> bool {
if !self.clock.is_manual() {
self.turn();
return true;
}
let to = self.clock.now() + by;
for round in 0.. {
let frame = (frames && self.state.frame_requested).then(|| self.next_frame());
let next = [self.due(), self.clock.next_alarm(), frame]
.into_iter()
.flatten()
.min()
.filter(|&at| at <= to && round < MAX_ADVANCE_ROUNDS);
if round == MAX_ADVANCE_ROUNDS {
log::warn!(
"the clock ran {MAX_ADVANCE_ROUNDS} rounds of timers without getting there: \
a timer keeps scheduling another at once"
);
}
let at = next.unwrap_or(to);
self.clock.advance_to(at);
while let Ok(message) = rx.try_recv() {
if !self.handle(message, rx) {
return false;
}
}
if frame.is_some_and(|f| f <= at && self.last_frame.is_none_or(|last| last < f))
&& self.state.frame_requested
{
self.frame();
}
self.turn();
if next.is_none() {
break;
}
}
true
}
fn flush(&mut self, rx: &Receiver<Message>) -> bool {
let frames = self.clock.moves_with_frames();
for _ in 0..MAX_FLUSH_ROUNDS {
while let Ok(message) = rx.try_recv() {
if !self.handle(message, rx) {
return false;
}
}
if !self.advance(std::time::Duration::ZERO, rx, frames) {
return false;
}
if rx.is_empty() {
break;
}
}
true
}
fn idle(&self, rx: &Receiver<Message>) -> bool {
let now = self.clock.now();
rx.is_empty()
&& self.state.net.idle()
&& [self.due(), self.clock.next_alarm()]
.into_iter()
.flatten()
.all(|at| at > now)
}
fn next_frame(&self) -> Instant {
let now = self.clock.now();
self.last_frame
.map_or(now + nsh_core::time::FRAME, |last| {
last + nsh_core::time::FRAME
})
.max(now)
}
fn frame(&mut self) {
self.last_frame = Some(self.clock.now());
handle(self.script.as_ref(), &mut self.state, Message::Frame);
}
fn turn(&mut self) {
let Driver {
state,
script,
sink,
assets,
..
} = self;
let script = script.as_ref();
if script
.and_then(Script::next_timer)
.is_some_and(|due| due <= nsh_core::time::now())
{
self.last_active = Instant::now();
}
if state
.resize_burst_ends
.is_some_and(|ends| ends <= nsh_core::time::now())
{
state.resize_burst_ends = None;
state.core.set_resizing(false);
}
if state
.window_state
.settles
.is_some_and(|due| due <= nsh_core::time::now())
&& let Some(env) = state.window_state.reported
{
state.window_state.settles = None;
state.window_state.shown = env.window_state;
apply_environment(script, state, env);
}
let turn_start = state.trace.then(Instant::now);
state.dispatch_touch_move(script);
if state
.next_mouse_move()
.is_some_and(|due| due <= nsh_core::time::now())
{
state.dispatch_mouse_moves(script);
}
state.dispatch_scroll_events(script);
let hot = std::mem::take(&mut state.hot);
if let Some(script) = script {
for update in hot {
script.hot_update(update, &**sink);
}
script.run_timers(nsh_core::time::now());
script.run_system();
}
state.core.run_component_tasks();
let tasks = turn_start.map(|s| s.elapsed());
state.load_fonts(script, assets.as_deref(), &**sink);
let batch = state.commit(script);
if let Some(batch) = batch.filter(|_| !self.quitting) {
sink.submit(batch);
if let (Some(start), Some(tasks)) = (turn_start, tasks) {
log::info!(
target: "nsh::perf",
"turn: {}µs (timers and tasks {}µs)",
start.elapsed().as_micros(),
tasks.as_micros(),
);
}
}
state.run_on_main_thread(&**sink);
if let Some(size) = state.resized.take() {
sink.resized(size);
}
state.report_handled(&**sink);
state.net.pump(script, &mut state.core);
state.load_chunks(script, &**sink);
state.request_frame(script, &**sink);
self.check_stopped();
self.sync_quit_listeners();
}
fn sync_quit_listeners(&self) {
self.quit_listeners.store(
self.state.core.has_quit_listeners(),
std::sync::atomic::Ordering::Relaxed,
);
}
#[cfg(not(target_arch = "wasm32"))]
fn quit(&mut self, rx: &Receiver<Message>) {
if !self.state.core.has_quit_listeners() {
return;
}
let deadline = Instant::now() + QUIT_TIMEOUT;
self.quitting = true;
self.state.core.start_quit();
let mut kept = Vec::new();
loop {
self.turn();
if !self.state.core.quit_pending() || self.stopped {
break;
}
let wake = self.deadline().map_or(deadline, |at| at.min(deadline));
match rx.recv_deadline(wake) {
Ok(Message::Shutdown) => {}
Ok(message @ Message::HostEvent(..)) => kept.push(message),
Ok(message) => {
self.handle(message, rx);
}
Err(crossbeam_channel::RecvTimeoutError::Timeout) => {}
Err(crossbeam_channel::RecvTimeoutError::Disconnected) => break,
}
if Instant::now() >= deadline {
log::warn!(
"the app's quit listeners did not finish in {} ms",
QUIT_TIMEOUT.as_millis()
);
break;
}
}
for message in kept {
let _ = self.state.net.tx.send(message);
}
}
fn next_gc(&self) -> Instant {
let quiet = (self.last_active + IDLE_GC_QUIET).min(self.last_gc + IDLE_GC_LONGEST);
(self.last_gc + IDLE_GC_INTERVAL).max(quiet)
}
fn collect_if_idle(&mut self) {
if let Some(script) = &self.script
&& self.state.committed_since_gc
&& Instant::now() >= self.next_gc()
{
let start = self.state.trace.then(Instant::now);
script.collect_garbage();
if let Some(start) = start {
log::info!(target: "nsh::perf", "gc: {}µs", start.elapsed().as_micros());
}
if let Some(monitor) = &self.state.perf {
let (js_heap, js_objects) = script.heap_usage();
monitor.set_memory(perf::MemorySample {
js_heap,
js_objects,
nodes: self.state.core.node_count() as u64,
node_ids: self.state.core.node_id_room() as u64,
});
}
self.last_gc = Instant::now();
self.state.committed_since_gc = false;
if let Some(batch) = self.state.commit(Some(script)) {
self.sink.submit(batch);
}
self.state.run_on_main_thread(&*self.sink);
}
}
fn check_stopped(&mut self) {
if let Some(script) = &self.script
&& !self.stopped
&& let Some(reason) = script.fatal()
{
self.stopped = true;
script.report(&*self.sink, AppErrorKind::Stopped, "stopped", &reason);
}
}
}
struct ScrollEvent {
x: f32,
y: f32,
content: Size<Points>,
viewport: Size<Points>,
zoom: f32,
throttle: Duration,
last: Option<Instant>,
pending: bool,
}
struct State<M: TextEngine> {
core: Core<M>,
js_tokens: Arc<nsh_core::element::Tokens>,
pinned: EnvironmentPins,
environment: Environment,
shaders_unavailable: bool,
app_locale: Option<nsh_core::platform::Locale>,
frame_requested: bool,
ops: Vec<Op>,
binds: Vec<ListBind>,
events: Vec<JsEvent>,
trace: bool,
perf: Option<Arc<perf::PerfMonitor>>,
perf_commit: perf::CommitTiming,
committed_since_gc: bool,
host: HostChannel,
url_opens: Vec<(u32, String)>,
net: Net,
hot: Vec<HotUpdate>,
scroll_events: FxHashMap<NodeId, ScrollEvent>,
touch_move: Option<(NodeId, Box<nsh_core::TouchEvent>)>,
mouse_moves: Vec<(NodeId, EventPayload)>,
mouse_moved: Option<Instant>,
sets_seen: FxHashMap<(u8, NodeId), usize>,
resized: Option<Size<Points>>,
resize_burst_ends: Option<Instant>,
window_state: WindowStateReport,
events_handled: u64,
events_reported: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Requester {
Js(RequestId),
Task(u32),
}
struct Net {
network: Option<Arc<dyn Network>>,
tx: Sender<Message>,
queue: NetworkQueue,
inflight: FxHashMap<Requester, Inflight>,
tasks: Vec<(u32, HttpRequest)>,
abandoned: Vec<u32>,
access: Arc<nsh_core::access::Access>,
hops: u64,
assets: Option<Arc<dyn Assets>>,
#[cfg(not(target_arch = "wasm32"))]
runtime: tokio::runtime::Handle,
}
struct AssetTask;
impl FetchTask for AssetTask {
fn send(&mut self, _: Vec<u8>) {}
fn finish(&mut self) {}
fn pause(&mut self, _: bool) {}
fn cancel(self: Box<Self>) {}
}
fn is_asset(url: &str) -> bool {
url.get(..6)
.is_some_and(|scheme| scheme.eq_ignore_ascii_case("asset:"))
}
fn asset_response_url(url: &str) -> String {
let rest = url.get(6..).unwrap_or_default();
format!("asset:{}", rest.split('#').next().unwrap_or_default())
}
fn asset_file(url: &str) -> &str {
url.split('?').next().unwrap_or_default()
}
struct Inflight {
task: Box<dyn FetchTask>,
hop: u64,
followed: Option<access::Followed>,
asset: Option<String>,
}
impl Net {
fn idle(&self) -> bool {
self.inflight.is_empty()
}
fn pump<M: TextEngine>(&mut self, script: Option<&Script>, core: &mut Core<M>) {
let mut abandoned = std::mem::take(&mut self.abandoned);
core.take_fetches(&mut self.tasks, &mut abandoned);
for id in abandoned.drain(..) {
self.cancel(Requester::Task(id));
}
self.abandoned = abandoned;
let mut tasks = std::mem::take(&mut self.tasks);
for (id, request) in tasks.drain(..) {
if let Err(refused) = self.request(Requester::Task(id), request) {
core.fetch_refused(id, refused.message, refused.url);
}
}
self.tasks = tasks;
let Some(script) = script else { return };
script.take_network(&mut self.queue);
for (id, op) in std::mem::take(&mut self.queue.ops) {
let who = Requester::Js(id);
match op {
FetchOp::Start(request) => {
if let Err(refused) = self.request(who, request) {
script.fetch_refused(id, &refused.message, &refused.url);
}
}
FetchOp::Send(chunk) => {
if let Some(i) = self.inflight.get_mut(&who) {
i.task.send(chunk);
}
}
FetchOp::Finish => {
if let Some(i) = self.inflight.get_mut(&who) {
i.task.finish();
}
}
FetchOp::Pause(paused) => {
if let Some(i) = self.inflight.get_mut(&who) {
i.task.pause(paused);
}
}
FetchOp::Cancel => self.cancel(who),
}
}
}
fn cancel(&mut self, who: Requester) {
if let Some(i) = self.inflight.remove(&who) {
i.task.cancel();
}
}
fn request(&mut self, who: Requester, mut request: HttpRequest) -> Result<(), access::Refused> {
if is_asset(&request.url) {
self.asset(who, request);
return Ok(());
}
if self.access.is_unrestricted() {
self.start(who, request, None);
return Ok(());
}
match self.access.http_url(&request.method, &request.url) {
Some(url) => request.url = url.into_owned(),
None => return Err(access::refused(&request.method, &request.url)),
}
if request.follow_redirects {
let hop = access::hop(&request);
let followed = access::Followed { request, hops: 0 };
self.start(who, hop, Some(followed));
} else {
self.start(who, request, None);
}
Ok(())
}
fn start(&mut self, id: Requester, request: HttpRequest, followed: Option<access::Followed>) {
self.hops += 1;
let hop = self.hops;
let Some(network) = &self.network else {
let failed = FetchEvent::Failed("this host has no network stack".to_owned());
let _ = self.tx.send(Message::Fetch(id, hop, failed));
return;
};
let tx = self.tx.clone();
let events: FetchEvents = Box::new(move |event| {
let _ = tx.send(Message::Fetch(id, hop, event));
});
let task = network.fetch(request, events);
self.inflight.insert(
id,
Inflight {
task,
hop,
followed,
asset: None,
},
);
}
fn asset(&mut self, who: Requester, mut request: HttpRequest) {
request.url = asset_response_url(&request.url);
let file = asset_file(&request.url).to_owned();
self.hops += 1;
let hop = self.hops;
self.inflight.insert(
who,
Inflight {
task: Box::new(AssetTask),
hop,
followed: None,
asset: None,
},
);
let refused = if !nsh_core::access::is_inside_assets(&file) {
Some(format!(
"{}: bundled files are named by a path inside the app's files",
request.url
))
} else if !matches!(request.method.as_str(), "GET" | "HEAD") {
Some(format!(
"{} {}: bundled files are read with GET",
request.method, request.url
))
} else {
None
};
if let Some(refused) = refused {
let _ = self
.tx
.send(Message::Fetch(who, hop, FetchEvent::Failed(refused)));
return;
}
let Some(assets) = &self.assets else {
let failed = Err("this host cannot load assets".to_owned());
self.asset_read(who, hop, request, failed);
return;
};
#[cfg(not(target_arch = "wasm32"))]
{
let assets = assets.clone();
let tx = self.tx.clone();
drop(self.runtime.spawn_blocking(move || {
let bytes = assets.read(&file);
let _ = tx.send(Message::AssetRead(who, hop, request, bytes));
}));
}
#[cfg(target_arch = "wasm32")]
{
let bytes = assets.read(&file);
self.asset_read(who, hop, request, bytes);
}
}
fn asset_read(
&mut self,
who: Requester,
hop: u64,
request: HttpRequest,
read: Result<Vec<u8>, String>,
) {
if self.inflight.get(&who).is_none_or(|i| i.hop != hop) {
return;
}
let events = match read {
Ok(bytes) => {
let head = HttpHead {
status: 200,
status_text: "OK".to_owned(),
headers: vec![
("content-length".to_owned(), bytes.len().to_string()),
(
"content-type".to_owned(),
content_type(asset_file(&request.url)).to_owned(),
),
],
url: request.url.clone(),
..HttpHead::default()
};
let mut events = vec![FetchEvent::Head(head)];
if request.method == "GET" && !bytes.is_empty() {
events.push(FetchEvent::Data(bytes));
}
events.push(FetchEvent::End);
events
}
Err(error) => {
match (self.assets.as_ref()).and_then(|a| a.url(asset_file(&request.url))) {
Some(url) => {
self.inflight.remove(&who);
let uri = request.url.clone();
self.start(who, HttpRequest { url, ..request }, None);
if let Some(download) = self.inflight.get_mut(&who) {
download.asset = Some(uri);
}
return;
}
None => vec![FetchEvent::Failed(error)],
}
}
};
for event in events {
let _ = self.tx.send(Message::Fetch(who, hop, event));
}
}
fn event(
&mut self,
id: Requester,
hop: u64,
event: FetchEvent,
) -> Option<Result<FetchEvent, access::Refused>> {
if self.network.is_none() {
return Some(Ok(event));
}
let inflight = self.inflight.get_mut(&id).filter(|i| i.hop == hop)?;
match event {
FetchEvent::Head(mut head) => {
let missing = (inflight.asset.as_ref())
.filter(|_| !(200..300).contains(&head.status))
.map(|uri| format!("{uri}: HTTP {}", head.status));
if let Some(missing) = missing {
if let Some(i) = self.inflight.remove(&id) {
i.task.cancel();
}
return Some(Ok(FetchEvent::Failed(missing)));
}
if let Some(uri) = &inflight.asset {
head.url = uri.clone();
head.redirected = false;
if !head
.headers
.iter()
.any(|(name, _)| name.eq_ignore_ascii_case("content-type"))
{
let file_type = content_type(asset_file(uri)).to_owned();
head.headers.push(("content-type".to_owned(), file_type));
}
}
let Some(followed) = &mut inflight.followed else {
return Some(Ok(FetchEvent::Head(head)));
};
match access::next(&self.access, followed, head) {
access::Next::Done(head) => Some(Ok(FetchEvent::Head(head))),
access::Next::Fail(message) => {
if let Some(i) = self.inflight.remove(&id) {
i.task.cancel();
}
Some(Ok(FetchEvent::Failed(message)))
}
access::Next::Refused(refused) => {
if let Some(i) = self.inflight.remove(&id) {
i.task.cancel();
}
Some(Err(refused))
}
access::Next::Hop(request) => {
let i = self.inflight.remove(&id)?;
let followed = i.followed;
i.task.cancel();
self.start(id, request, followed);
None
}
}
}
FetchEvent::End | FetchEvent::Failed(_) => {
self.inflight.remove(&id);
Some(Ok(event))
}
event => Some(Ok(event)),
}
}
}
impl<M: TextEngine> State<M> {
fn record_perf(&mut self, started: Option<Instant>) {
let (Some(started), Some(monitor)) = (started, &self.perf) else {
return;
};
let busy = started.elapsed();
monitor.record_busy(busy);
let mut commit = std::mem::take(&mut self.perf_commit);
if commit.ops > 0 || commit.items > 0 {
commit.js = busy.saturating_sub(commit.layout);
monitor.record_commit(commit);
}
}
fn dispatch_touch_move(&mut self, script: Option<&Script>) {
if let Some((id, touch)) = self.touch_move.take()
&& let Some(script) = script
{
script.dispatch_event(id, EventKind::Touch, &EventPayload::Touch(touch));
}
}
fn next_mouse_move(&self) -> Option<Instant> {
if self.mouse_moves.is_empty() {
return None;
}
Some(
self.mouse_moved
.map_or_else(nsh_core::time::now, |t| t + MOUSE_MOVE_INTERVAL),
)
}
fn dispatch_mouse_moves(&mut self, script: Option<&Script>) {
if self.mouse_moves.is_empty() {
return;
}
self.mouse_moved = Some(nsh_core::time::now());
for (id, payload) in std::mem::take(&mut self.mouse_moves) {
if self
.core
.component_event(id, EventKind::MouseMove, &payload)
{
continue;
}
if let Some(script) = script {
script.dispatch_event(id, EventKind::MouseMove, &payload);
}
}
}
fn next_scroll_event(&self) -> Option<Instant> {
self.scroll_events
.values()
.filter(|e| e.pending)
.filter_map(|e| e.last.map(|t| t + e.throttle))
.min()
}
fn dispatch_scroll_events(&mut self, script: Option<&Script>) {
if self.scroll_events.is_empty() {
return;
}
let now = nsh_core::time::now();
let core = &self.core;
self.scroll_events
.retain(|&id, _| core.scroll_listener(id).is_some());
for (&id, e) in &mut self.scroll_events {
if !e.pending || e.last.is_some_and(|t| now < t + e.throttle) {
continue;
}
e.pending = false;
e.last = Some(now);
let n = |v: f32| PayloadValue::Number(v as f64);
let payload = EventPayload::Map(vec![
(
"offset",
PayloadValue::Point(geometry::point(Points(e.x), Points(e.y))),
),
("contentSize", PayloadValue::Size(e.content)),
("size", PayloadValue::Size(e.viewport)),
("zoomScale", n(e.zoom)),
]);
if !self.core.component_event(id, EventKind::Scroll, &payload)
&& let Some(script) = script
{
script.dispatch_event(id, EventKind::Scroll, &payload);
}
}
}
fn load_chunks(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
let Some(script) = script else { return };
let mut ids = Vec::new();
script.take_chunk_requests(&mut ids);
for id in ids {
if !sink.load_chunk(&id) {
let message = "this host does not load chunks (the app was built split)".to_owned();
let _ = self.net.tx.send(Message::Chunk(Err((id, message))));
}
}
}
fn report_handled(&mut self, sink: &dyn MountSink) {
if self.events_handled != self.events_reported {
self.events_reported = self.events_handled;
sink.handled(self.events_handled);
}
}
fn request_frame(&mut self, script: Option<&Script>, sink: &dyn MountSink) {
if !self.frame_requested
&& (script.is_some_and(Script::wants_frame)
|| self.core.wants_frame()
|| self.core.has_paced_mounts()
|| (script.is_some() && self.core.has_paced_list_binds()))
{
self.frame_requested = true;
sink.request_frame();
}
}
fn run_on_main_thread(&mut self, sink: &dyn MountSink) {
for task in self.core.take_main_thread_tasks() {
sink.run_on_main_thread(task);
}
}
fn load_fonts(
&mut self,
script: Option<&Script>,
assets: Option<&dyn Assets>,
sink: &dyn MountSink,
) {
let Some(script) = script else { return };
let mut fonts = Vec::new();
script.take_fonts(&mut fonts);
for uri in fonts {
let result = match assets {
Some(assets) => assets.read(&uri),
None => Err("this host cannot load assets".to_owned()),
}
.and_then(|data| self.core.register_font(&data));
if let Err(err) = result {
script.report(
sink,
AppErrorKind::Asset,
"font failed",
&format!("{uri}: {err}"),
);
}
}
}
fn open_urls(&mut self) -> bool {
self.core.take_url_opens(&mut self.url_opens);
let mut platform = false;
for (id, url) in self.url_opens.drain(..) {
if self.host.open_url(id, url.clone(), &self.net.tx).is_none() {
self.core.open_url_on_platform(id, url);
platform = true;
}
}
platform
}
fn commit(&mut self, script: Option<&Script>) -> Option<MountBatch> {
let start = Instant::now();
let mut merged: Option<MountBatch> = None;
let mut commits = 0;
let mut op_count = 0;
let mut js = std::time::Duration::ZERO;
let mut paced = PacedBinds::default();
self.core.begin_mount_turn();
for _ in 0..MAX_LIST_ROUNDS {
let js_start = Instant::now();
let binds = self.binds.drain(..);
if let Some(script) = script {
for bind in binds {
script.bind_list(bind.list, &bind.binds);
}
script.take_ops(&mut self.ops);
let mut binds = Vec::new();
while paced.left() && self.core.has_paced_list_binds() {
let start = Instant::now();
let ops = self.ops.len();
self.core.take_paced_list_binds(1, &mut binds);
for bind in binds.drain(..) {
paced.cells += bind.binds.len();
script.bind_list(bind.list, &bind.binds);
}
script.take_ops(&mut self.ops);
paced.ops += self.ops.len() - ops;
paced.time += start.elapsed();
}
} else {
drop(binds);
}
if let Some(script) = script {
script.run_posted();
}
for event in self.events.drain(..) {
match event {
JsEvent::Event(id, event, payload) => {
if !self.core.component_event(id, event, &payload)
&& let Some(script) = script
{
script.dispatch_event(id, event, &payload);
}
}
JsEvent::LayoutListener {
host,
id,
listener,
frame,
} => {
self.core.component_layout(host, id, &listener, frame);
}
other => {
if let Some(script) = script {
script.deliver(other);
}
}
}
}
if let Some(script) = script {
script.take_ops(&mut self.ops);
}
js += js_start.elapsed();
op_count += self.ops.len();
let mut ops = self.ops.drain(..);
while let Some(op) = ops.next() {
match self.core.apply(op) {
Ok(()) => {}
Err(err) if err.is_fatal() => {
self.core.discard_ops(ops.by_ref());
let Some(script) = script else { break };
script.stop(match err {
ApplyError::TooManyNodes(max) => {
format!("the app created more than {max} nodes and was stopped")
}
other => {
format!("the app sent an invalid op ({other:?}) and was stopped")
}
});
break;
}
Err(err) => log::error!("invalid op: {err:?}"),
}
}
drop(ops);
release_spare_ops(&mut self.ops);
if let Some(batch) = self.core.commit() {
commits += 1;
match &mut merged {
Some(m) => extend_frame(&mut m.items, batch.items),
None => merged = Some(batch),
}
}
self.core.take_list_binds(&mut self.binds);
self.core.take_events(&mut self.events);
let urls = self.open_urls();
let posted = script.is_some_and(Script::has_posted);
let retheme = match script {
Some(script) if !Arc::ptr_eq(self.core.tokens(), &self.js_tokens) => {
self.js_tokens = self.core.tokens().clone();
script.set_tokens(self.js_tokens.clone());
true
}
_ => false,
};
let relocale = match self.core.take_locale_request() {
Some(locale) => {
self.app_locale = locale;
apply_environment(script, self, self.environment);
true
}
None => false,
};
let more_paced = script.is_some() && paced.left() && self.core.has_paced_list_binds();
let answers = self.core.has_due_answers();
if self.binds.is_empty()
&& self.events.is_empty()
&& !posted
&& !retheme
&& !relocale
&& !more_paced
&& !urls
&& !answers
{
break;
}
}
if commits > 1
&& let Some(batch) = &mut merged
{
keep_last_sets(&mut batch.items, &mut self.sets_seen);
}
self.committed_since_gc |= op_count > 0;
if self.perf.is_some() && (op_count > 0 || merged.is_some()) {
let c = &mut self.perf_commit;
c.layout += start.elapsed().saturating_sub(js);
c.ops += op_count as u32;
c.items += merged.as_ref().map_or(0, |b| b.items.len() as u32);
}
if self.trace && (op_count > 0 || merged.is_some()) {
log::info!(
target: "nsh::perf",
"commit: {op_count} ops, {}µs (list js {}µs), {} mount items, {} nodes",
start.elapsed().as_micros(),
js.as_micros(),
merged.as_ref().map_or(0, |b| b.items.len()),
self.core.node_count(),
);
}
merged
}
}
fn insets(env: &Environment) -> EdgeInsets {
env.safe_area
}
fn ui_environment(env: &Environment, window: Size<Points>) -> nsh_core::element::Environment {
nsh_core::element::Environment {
window,
safe_area: insets(env),
title_bar: env.title_bar,
window_state: env.window_state,
keyboard_height: env.keyboard_height,
keyboard_duration: env.keyboard_duration,
dark: env.color_scheme == ColorScheme::Dark,
font_scale: env.font_scale,
reduce_motion: env.reduce_motion,
screen_reader: env.screen_reader,
rtl: env.rtl,
pixel_ratio: env.pixel_ratio,
os: env.os,
platform: env.platform,
os_version: env.os_version,
idiom: env.idiom,
locale: env.locale,
locale_settings: env.locale_settings,
apple_keyboard: env.apple_keyboard,
ctrl_for_command: env.ctrl_for_command,
host: env.host,
lifecycle: env.lifecycle,
screen_color: env.screen_color,
file_requests: env.file_requests,
speech: env.speech,
notifications: env.notifications,
audio: env.audio,
cell: env.cell,
web_input: env.web_input,
web_evaluate: env.web_evaluate,
web_views: env.web_views,
shaders: env.shaders,
}
}
fn drawn_shaders(env: &mut Environment, unavailable: bool) {
env.shaders &= env.cell.is_none() && !unavailable && !shader::no_gpu();
}
fn class_environment(env: &Environment) -> nsh_core::tailwind::ClassEnvironment {
nsh_core::tailwind::ClassEnvironment {
dark: env.color_scheme == ColorScheme::Dark,
platform: if env.os == Os::Web {
nsh_core::tailwind::Platform::Web
} else if cfg!(target_os = "android") {
nsh_core::tailwind::Platform::Android
} else {
nsh_core::tailwind::Platform::Ios
},
reduce_motion: env.reduce_motion,
pointer: if env.desktop() {
nsh_core::tailwind::Pointer::Fine
} else {
nsh_core::tailwind::Pointer::Coarse
},
terminal: env.idiom == Idiom::Terminal,
}
}
const WINDOW_SETTLE: Duration = Duration::from_millis(150);
#[derive(Default)]
struct WindowStateReport {
shown: Option<nsh_core::desktop::WindowState>,
reported: Option<Environment>,
settles: Option<Instant>,
}
impl WindowStateReport {
fn report(&mut self, mut env: Environment, now: Instant) -> Environment {
let next = env.window_state;
let moving = match (&self.shown, &next) {
(Some(shown), Some(next)) => shown != next && moved_only(shown, next),
_ => false,
};
if moving {
let moved = self.reported.map(|r| r.window_state) != Some(next);
if moved || self.settles.is_none() {
self.settles = Some(now + WINDOW_SETTLE);
}
self.reported = Some(env);
env.window_state = self.shown;
} else {
self.reported = None;
self.settles = None;
self.shown = next;
}
env
}
}
fn moved_only(
shown: &nsh_core::desktop::WindowState,
next: &nsh_core::desktop::WindowState,
) -> bool {
shown.mode == next.mode
&& shown.placement.mode == next.placement.mode
&& shown.minimized == next.minimized
&& shown.visible == next.visible
&& shown.focused == next.focused
&& shown.display == next.display
&& shown.scale_factor == next.scale_factor
}
fn apply_environment<M: TextEngine>(
script: Option<&Script>,
state: &mut State<M>,
env: Environment,
) {
state.environment = env;
let mut env = env;
if let Some(locale) = state.app_locale {
env.locale = locale;
env.locale_settings.languages = env.locale_settings.languages.preferring(locale);
}
state.core.set_font_scale(env.font_scale);
state.core.set_class_environment(class_environment(&env));
state.core.set_safe_area(insets(&env));
let window = env.window;
state.core.set_environment(ui_environment(&env, window));
if let Some(script) = script {
script.set_environment(&env);
}
}
fn handle<M: TextEngine>(script: Option<&Script>, state: &mut State<M>, message: Message) -> bool {
match message {
Message::Event(id, event, mut payload) => {
state.events_handled += 1;
if state.trace {
log::info!(target: "nsh::perf", "event {event:?} on view {id}");
}
if event == EventKind::MouseMove {
match state.mouse_moves.iter_mut().find(|(v, _)| *v == id) {
Some((_, pending)) => *pending = payload,
None => state.mouse_moves.push((id, payload)),
}
return true;
}
if !matches!(&payload, EventPayload::Touch(t) if t.phase == nsh_core::TouchPhase::Move)
{
state.dispatch_mouse_moves(script);
}
if let (EventKind::ChangeText, EventPayload::Text { text, count }) = (event, &payload) {
state.core.input_changed(id, text, *count);
}
if event == EventKind::CaretMove {
state.core.locate_caret(id, &mut payload);
}
if event == EventKind::SelectionChange {
state.core.locate_selection(id, &mut payload);
}
if event == EventKind::Paste {
payload = payload.into_paste();
}
if let EventPayload::ContextMenu(menu) = &payload {
for (overlay, pressed) in state.core.context_menu_presses_outside(id, menu) {
if !state
.core
.component_event(overlay, EventKind::PressOutside, &pressed)
&& let Some(script) = script
{
script.dispatch_event(overlay, EventKind::PressOutside, &pressed);
}
}
}
if state.core.component_event(id, event, &payload) {
return true;
}
if let EventPayload::Touch(touch) = payload {
if touch.phase == nsh_core::TouchPhase::Move {
match &mut state.touch_move {
Some((_, pending)) => pending.merge_move(*touch),
None => state.touch_move = Some((id, touch)),
}
return true;
}
state.dispatch_touch_move(script);
if let Some(script) = script {
script.dispatch_event(id, event, &EventPayload::Touch(touch));
}
return true;
}
let Some(script) = script else { return true };
let start = state.trace.then(Instant::now);
script.dispatch_event(id, event, &payload);
if let Some(start) = start {
log::info!(target: "nsh::perf", "event js: {}µs", start.elapsed().as_micros());
}
}
Message::Scroll(id, offset, applied) => {
state.core.set_scroll_offset(id, offset, applied);
let (x, y) = (offset.x.0, offset.y.0);
if let Some((throttle_ms, content, viewport, zoom)) = state.core.scroll_listener(id) {
let event = state.scroll_events.entry(id).or_insert(ScrollEvent {
x,
y,
content,
viewport,
zoom,
throttle: Duration::from_secs_f32(throttle_ms / 1000.0),
last: None,
pending: true,
});
(event.x, event.y, event.content, event.viewport, event.zoom) =
(x, y, content, viewport, zoom);
event.throttle = Duration::from_secs_f32(throttle_ms / 1000.0);
event.pending = true;
}
}
Message::Kept(nodes) => state.core.set_kept(&nodes),
Message::ContentCulling(enabled) => {
state.core.set_content_culling(enabled);
if let Some(script) = script {
script.set_lazy_rows(enabled);
}
}
Message::InputScroll(id, offset, content, viewport) => {
state.core.set_input_scroll(id, offset, content, viewport);
}
Message::Zoom(id, scale) => state.core.set_zoom(id, scale),
Message::ComponentSize(id, size) => state.core.set_component_size(id, size),
Message::AnimationsFinished(mut finished) => {
state.core.animations_finished(&mut finished);
if let Some(script) = script {
script.animations_finished(&finished);
}
}
Message::Resize(size) => {
if !nsh_core::time::manual() {
let now = nsh_core::time::now();
if state.resize_burst_ends.is_some_and(|ends| now < ends) {
state.core.set_resizing(true);
}
state.resize_burst_ends = Some(now + RESIZE_BURST_GAP);
}
state.core.set_viewport(size);
state.resized = Some(size);
}
Message::Wake => {}
Message::Environment(mut env) => {
state.pinned.apply(&mut env);
drawn_shaders(&mut env, state.shaders_unavailable);
let env = state.window_state.report(*env, nsh_core::time::now());
apply_environment(script, state, env);
}
Message::ShadersUnavailable => {
state.shaders_unavailable = true;
if state.environment.shaders {
let env = Environment {
shaders: false,
..state.environment
};
apply_environment(script, state, env);
}
}
Message::Displays(displays) => {
state.core.set_displays(displays.clone());
if let Some(script) = script {
script.set_displays(&displays);
}
}
Message::RootSize(id, size, insets) => state.core.set_root_size(id, size, insets),
Message::ScreenHeader(id, height) => state.core.set_screen_header(id, height),
Message::Frame => {
state.frame_requested = false;
state.core.run_frame(nsh_core::time::now());
if let Some(script) = script {
script.run_frame();
}
}
Message::States(id, states) => state.core.set_states(id, states),
Message::Modality(modality) => state.core.set_input_modality(modality),
Message::FontsChanged => state.core.fonts_changed(),
Message::Remount => state.core.remount(),
Message::Fetch(who, hop, event) => match (who, state.net.event(who, hop, event)) {
(_, None) => {}
(Requester::Js(id), Some(event)) => {
if let Some(script) = script {
match event {
Ok(event) => script.fetch_event(id, event),
Err(refused) => script.fetch_refused(id, &refused.message, &refused.url),
}
}
}
(Requester::Task(id), Some(Ok(event))) => {
if !state.core.fetch_event(id, event) {
state.net.cancel(who);
}
}
(Requester::Task(id), Some(Err(refused))) => {
state.core.fetch_refused(id, refused.message, refused.url)
}
},
Message::AssetRead(who, hop, request, read) => {
state.net.asset_read(who, hop, request, read)
}
Message::Hot(update) => state.hot.push(update),
Message::Chunk(chunk) => {
if let Some(script) = script {
script.chunk(chunk);
}
}
Message::Perf(monitor) => {
state.core.set_perf_monitor(monitor.is_some());
if let Some(script) = script {
script.set_fps_enabled(monitor.is_some());
}
state.perf = monitor;
state.perf_commit = perf::CommitTiming::default();
}
Message::Tokens(tokens) => {
state.core.set_host_tokens(tokens.map(|t| *t));
if let Some(script) = script {
script.set_theme_tokens(state.core.theme_tokens());
}
}
Message::HostFont(data) => {
if let Err(err) = state.core.register_font(&data) {
log::error!("font failed: {err}");
}
}
Message::HostEvent(name, data) => {
if let Some(script) = script {
script.host_event(&name, data);
}
}
Message::HostReply(id, result) => {
if let Some(script) = script {
script.host_reply(id, result);
}
}
Message::UrlHandled { id, url, handled } => {
if handled {
state.core.answer_open_url(id, true);
} else {
state.core.open_url_on_platform(id, url);
}
}
Message::Advance(..) | Message::Flush(..) => unreachable!("the driver moves the clock"),
Message::Shutdown => return false,
}
true
}
#[derive(Default)]
struct PacedBinds {
cells: usize,
ops: usize,
time: std::time::Duration,
}
impl PacedBinds {
fn left(&self) -> bool {
self.cells == 0 || (self.ops < PACED_BIND_OPS && self.time < PACED_BIND_TIME)
}
}
fn extend_frame(frame: &mut Vec<nsh_core::MountItem>, items: Vec<nsh_core::MountItem>) {
use nsh_core::MountItem;
let start = frame.len();
frame.extend(items);
for k in start..frame.len() {
let MountItem::ScrollContent { id, size } = frame[k] else {
continue;
};
let earlier = frame[..k].iter().rposition(|m| {
matches!(m, MountItem::ScrollContent { id: e, .. } | MountItem::ScrollBy { id: e, .. } if *e == id)
});
if let Some(j) = earlier
&& let MountItem::ScrollContent { size: s, .. } = &mut frame[j]
{
*s = size;
}
}
}
fn keep_last_sets(frame: &mut Vec<nsh_core::MountItem>, last: &mut FxHashMap<(u8, NodeId), usize>) {
last.clear();
let mut repeated = false;
for (k, item) in frame.iter().enumerate() {
if let Some(key) = sets_whole(item) {
repeated |= last.insert(key, k).is_some();
}
}
if !repeated {
return;
}
let mut k = 0;
frame.retain(|item| {
k += 1;
sets_whole(item).is_none_or(|key| last[&key] == k - 1)
});
}
fn sets_whole(item: &nsh_core::MountItem) -> Option<(u8, nsh_core::NodeId)> {
use nsh_core::MountItem;
Some(match *item {
MountItem::Frame { id, .. } => (0, id),
MountItem::Overflow { id, .. } => (1, id),
MountItem::ViewStyle { id, .. } => (2, id),
MountItem::Text { id, .. } => (3, id),
MountItem::Events { id, .. } => (4, id),
MountItem::Image { id, .. } => (5, id),
_ => return None,
})
}
const RETAINED_OPS: usize = 16 * 1024;
fn release_spare_ops(ops: &mut Vec<Op>) {
debug_assert!(ops.is_empty());
if ops.capacity() > RETAINED_OPS {
ops.shrink_to(RETAINED_OPS);
}
}
fn app_access(app: &App) -> Access {
match app {
App::Js(bundle) => bundle.policy.access(),
App::Rust(_) => Policy::default().access(),
}
}
fn media_files(config: &EngineConfig, access: &Access) -> nsh_core::access::MediaFiles {
match &config.app {
App::Js(bundle) => nsh_core::access::MediaFiles::new(
access,
config
.data_dir
.as_ref()
.map(|root| root.join(app_dir_name(config.app.app_id())))
.as_deref(),
&bundle_system_paths(bundle),
nsh_core::access::native_files(config.environment.os),
),
_ => nsh_core::access::MediaFiles::default(),
}
}
#[cfg(test)]
mod tests {
#[test]
fn an_emptied_op_buffer_gives_back_what_a_large_commit_grew() {
let mut ops: Vec<super::Op> = Vec::with_capacity(super::RETAINED_OPS * 8);
super::release_spare_ops(&mut ops);
assert!(ops.capacity() <= super::RETAINED_OPS);
let mut ops: Vec<super::Op> = Vec::with_capacity(1024);
super::release_spare_ops(&mut ops);
assert_eq!(ops.capacity(), 1024);
}
#[test]
fn moves_settle_and_changes_of_mode_do_not() {
use nsh_core::{
desktop::{DisplayId, WindowMode, WindowPlacement, WindowState},
geometry::{Bounds, point, px, size},
};
let rect = |x: f32| Bounds::new(point(px(x), px(0.0)), size(px(800.0), px(600.0)));
let a = WindowState::new(
rect(0.0),
WindowPlacement::new(WindowMode::Normal, rect(0.0)),
);
let mut moved = a;
moved.bounds = rect(10.0);
moved.placement = WindowPlacement::new(WindowMode::Normal, rect(10.0));
assert!(super::moved_only(&a, &moved));
let mut maximized = a;
maximized.mode = WindowMode::Maximized;
maximized.placement = WindowPlacement::new(WindowMode::Maximized, rect(0.0));
assert!(!super::moved_only(&a, &maximized));
let mut minimized = a;
minimized.minimized = true;
assert!(!super::moved_only(&a, &minimized));
let mut hidden = a;
hidden.visible = false;
assert!(!super::moved_only(&a, &hidden));
let mut elsewhere = a;
elsewhere.display = Some(DisplayId(2));
assert!(!super::moved_only(&a, &elsewhere));
}
#[test]
fn pinned_values_hold_whatever_the_platform_reports() {
let pins = super::EnvironmentPins {
locale: nsh_core::platform::Locale::parse("de-DE"),
reduce_motion: Some(true),
..Default::default()
};
let mut reported = super::Environment {
locale: nsh_core::platform::Locale::parse("en-US").unwrap(),
font_scale: 1.5,
..Default::default()
};
pins.apply(&mut reported);
assert_eq!(reported.locale.as_str(), "de-DE");
assert!(reported.reduce_motion);
assert_eq!(reported.font_scale, 1.5);
assert_eq!(reported.safe_area, Default::default());
}
#[test]
fn bundle_default_has_no_application_selected_path_anchors() {
let bundle = super::Bundle::default();
assert!(bundle.system_paths.plugin_dir.is_none());
assert!(bundle.system_paths.home_dir.is_none());
assert!(matches!(bundle.code, super::BundleCode::Source(ref code) if code.is_empty()));
}
#[test]
fn bundle_trusted_paths_reject_relative_and_missing_directories() {
let mut paths = nsh_core::access::TrustedPaths::default();
paths.plugin_dir = Some(std::path::PathBuf::from("relative-app"));
paths.home_dir = Some(std::path::PathBuf::from("relative-home"));
let bundle = super::Bundle::default().with_system_paths(paths);
assert!(bundle.system_paths.plugin_dir.is_none());
assert!(bundle.system_paths.home_dir.is_none());
assert!(
super::trusted_directory(Some(std::path::PathBuf::from(
"/nsh-nonexistent-anchor-never-created"
)))
.is_none()
);
}
#[test]
fn local_bundle_anchors_its_canonical_parent_without_metadata_authority() {
let root = std::env::var_os("TMPDIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
std::path::PathBuf::from(std::env::var_os("HOME").expect("HOME"))
.join(".cache/nsh-benchs-test-tmp")
});
assert!(root.is_absolute() && !root.starts_with("/tmp"));
let directory = root.join(format!("nsh-bundle-anchors-{}", std::process::id()));
std::fs::create_dir_all(&directory).unwrap();
let path = directory.join("bundle.js");
std::fs::write(&path, "export default null;").unwrap();
let bundle = super::Bundle::read(&path).unwrap();
assert_eq!(
bundle.system_paths.plugin_dir,
Some(nsh_core::access::canonicalize(&directory).unwrap())
);
assert!(bundle.system_paths.home_dir.is_none());
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn rust_environment_preserves_native_title_bar_insets() {
use super::{Edges, Points};
let title_bar = Edges {
top: Points(42.0),
left: Points(78.0),
right: Points(138.0),
bottom: Points(0.0),
};
let environment = super::Environment {
title_bar,
..Default::default()
};
assert_eq!(
super::ui_environment(
&environment,
nsh_core::Size::new(Points(840.0), Points(630.0))
)
.title_bar,
title_bar
);
}
use nsh_core::{MountItem, Points, Size};
#[test]
fn a_frame_sends_a_scroll_views_last_content_size() {
let content = |height| MountItem::ScrollContent {
id: 2,
size: Size::new(Points(390.0), height),
};
let heights = |frame: &[MountItem]| -> Vec<f32> {
frame
.iter()
.filter_map(|m| match m {
MountItem::ScrollContent { size, .. } => Some(size.height.0),
_ => None,
})
.collect()
};
let mut frame = vec![content(Points(313.0))];
super::extend_frame(&mut frame, vec![content(Points(544.0))]);
assert_eq!(heights(&frame), [544.0, 544.0]);
let mut frame = vec![
content(Points(313.0)),
MountItem::ScrollBy {
id: 2,
dx: Points(0.0),
dy: Points(10.0),
},
];
super::extend_frame(&mut frame, vec![content(Points(544.0))]);
assert_eq!(heights(&frame), [313.0, 544.0]);
}
#[test]
fn a_frame_sends_a_views_last_frame_once() {
use nsh_core::{Bounds, Point};
let at = |id, y| MountItem::Frame {
id,
frame: Bounds::new(
Point::new(Points(0.0), Points(y)),
Size::new(Points(10.0), Points(10.0)),
),
};
let mut frame = vec![
MountItem::Create {
id: 4,
kind: nsh_core::ViewKind::View,
},
at(4, 0.0),
at(6, 0.0),
];
super::extend_frame(&mut frame, vec![at(4, 50.0)]);
super::keep_last_sets(&mut frame, &mut Default::default());
assert!(matches!(frame[0], MountItem::Create { id: 4, .. }));
let frames: Vec<_> = frame
.iter()
.filter_map(|m| match m {
MountItem::Frame { id, frame } => Some((*id, frame.origin.y.0)),
_ => None,
})
.collect();
assert_eq!(frames, [(6, 0.0), (4, 50.0)]);
}
}