use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
pub type PlatformFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeptShot {
pub path: String,
pub manifest: Option<String>,
}
pub trait Platform: Send + Sync {
fn now_ms(&self) -> f64;
fn sleep(&self, ms: u64) -> PlatformFuture<'_, ()>;
fn spawn(&self, task: Pin<Box<dyn Future<Output = ()> + Send + 'static>>);
fn stamp(&self) -> String;
fn session_dir(&self, root: &std::path::Path, id: &str) -> Result<PathBuf, String>;
fn append_log(&self, dir: &std::path::Path, line: &str);
fn read_text(&self, path: String) -> PlatformFuture<'_, Result<String, String>>;
fn read_bytes(&self, path: String) -> PlatformFuture<'_, Result<Vec<u8>, String>>;
fn write_file(&self, path: String, bytes: Vec<u8>, overwrite: bool) -> PlatformFuture<'_, Result<String, String>>;
fn keep_shot(&self, dir: &std::path::Path, n: u64, png: &[u8], manifest: Option<&Value>) -> Result<KeptShot, String>;
}
#[cfg(feature = "server")]
#[derive(Debug, Default, Clone, Copy)]
pub struct NativePlatform;
#[cfg(feature = "server")]
impl NativePlatform {
fn epoch() -> &'static std::time::Instant {
static EPOCH: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
EPOCH.get_or_init(std::time::Instant::now)
}
}
#[cfg(feature = "server")]
impl Platform for NativePlatform {
fn now_ms(&self) -> f64 {
Self::epoch().elapsed().as_secs_f64() * 1000.0
}
fn sleep(&self, ms: u64) -> PlatformFuture<'_, ()> {
Box::pin(tokio::time::sleep(std::time::Duration::from_millis(ms)))
}
fn spawn(&self, task: Pin<Box<dyn Future<Output = ()> + Send + 'static>>) {
tokio::spawn(task);
}
fn stamp(&self) -> String {
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
format!("{secs}-{}", std::process::id())
}
fn session_dir(&self, root: &std::path::Path, id: &str) -> Result<PathBuf, String> {
let dir = root.join(id);
for sub in ["shots", "exports", "config"] {
std::fs::create_dir_all(dir.join(sub)).map_err(|e| format!("session dir {}: {e}", dir.display()))?;
}
Ok(dir)
}
fn append_log(&self, dir: &std::path::Path, line: &str) {
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("log.jsonl")) {
use std::io::Write;
let _ = writeln!(f, "{line}");
}
}
fn read_text(&self, path: String) -> PlatformFuture<'_, Result<String, String>> {
Box::pin(std::future::ready(std::fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))))
}
fn read_bytes(&self, path: String) -> PlatformFuture<'_, Result<Vec<u8>, String>> {
Box::pin(std::future::ready(std::fs::read(&path).map_err(|e| format!("{path}: {e}"))))
}
fn write_file(&self, path: String, bytes: Vec<u8>, overwrite: bool) -> PlatformFuture<'_, Result<String, String>> {
let result = (|| {
if !overwrite && std::path::Path::new(&path).exists() {
return Err(format!("{path} exists; pass overwrite: true"));
}
if let Some(parent) = std::path::Path::new(&path).parent() {
let _ = std::fs::create_dir_all(parent);
}
std::fs::write(&path, &bytes).map_err(|e| format!("{path}: {e}"))?;
Ok(path.clone())
})();
Box::pin(std::future::ready(result))
}
fn keep_shot(&self, dir: &std::path::Path, n: u64, png: &[u8], manifest: Option<&Value>) -> Result<KeptShot, String> {
let path = dir.join("shots").join(format!("{n:04}.png"));
std::fs::write(&path, png).map_err(|e| format!("{}: {e}", path.display()))?;
let manifest = match manifest {
Some(m) => {
let mpath = path.with_extension("json");
std::fs::write(&mpath, serde_json::to_vec_pretty(m).map_err(|e| e.to_string())?)
.map_err(|e| format!("{}: {e}", mpath.display()))?;
Some(mpath.display().to_string())
}
None => None,
};
Ok(KeptShot { path: path.display().to_string(), manifest })
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Envelope {
pub id: u64,
pub cmd: String,
#[serde(default)]
pub args: Value,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Reply {
pub id: u64,
pub frame: u64,
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub notices: Vec<Value>,
#[serde(skip)]
pub blob: Option<Vec<u8>>,
}
impl Reply {
pub fn err(id: u64, frame: u64, error: impl Into<String>) -> Self {
Self { id, frame, ok: false, result: None, error: Some(error.into()), notices: Vec::new(), blob: None }
}
pub fn from_app(value: Value, blob: Option<Vec<u8>>) -> Result<Self, String> {
let mut reply: Reply = serde_json::from_value(value).map_err(|e| format!("app reply: {e}"))?;
reply.blob = blob;
Ok(reply)
}
}
pub enum HostRequest {
Command { envelope: Envelope, reply: oneshot::Sender<Reply> },
Screenshot { region: Value, reply: oneshot::Sender<Result<(Value, Vec<u8>), String>> },
Annotate { spec: Value, reply: oneshot::Sender<Result<Value, String>> },
Stop,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct HostInfo {
pub backend: &'static str,
pub adapter: String,
pub platform: &'static str,
pub width: f32,
pub height: f32,
pub ppp: f32,
}
#[derive(Debug, Clone)]
pub struct HostConfig {
pub width: f32,
pub height: f32,
pub ppp: f32,
pub seed: bool,
pub store_dir: PathBuf,
}
pub type SpawnFn = Arc<dyn Fn(HostConfig) -> Result<HostHandle, String> + Send + Sync>;
#[derive(Clone)]
pub enum Backend {
Spawn { name: &'static str, spawn: SpawnFn },
Attached { tx: mpsc::UnboundedSender<HostRequest>, info: HostInfo, platform: Arc<dyn Platform> },
}
impl Backend {
pub fn name(&self) -> &'static str {
match self {
Backend::Spawn { name, .. } => name,
Backend::Attached { info, .. } => info.backend,
}
}
pub fn is_attached(&self) -> bool {
matches!(self, Backend::Attached { .. })
}
pub fn attached_handle(&self) -> Option<HostHandle> {
match self {
Backend::Attached { tx, info, platform } => Some(HostHandle::attached_on(tx.clone(), info.clone(), platform.clone())),
Backend::Spawn { .. } => None,
}
}
}
pub struct HostHandle {
pub tx: mpsc::UnboundedSender<HostRequest>,
pub info: HostInfo,
pub platform: Arc<dyn Platform>,
join: Option<std::thread::JoinHandle<()>>,
owned: bool,
next_id: std::sync::atomic::AtomicU64,
}
impl HostHandle {
#[cfg(feature = "server")]
pub fn new(tx: mpsc::UnboundedSender<HostRequest>, info: HostInfo, join: std::thread::JoinHandle<()>) -> Self {
Self::new_on(tx, info, join, Arc::new(NativePlatform))
}
pub fn new_on(tx: mpsc::UnboundedSender<HostRequest>, info: HostInfo, join: std::thread::JoinHandle<()>, platform: Arc<dyn Platform>) -> Self {
Self { tx, info, platform, join: Some(join), owned: true, next_id: std::sync::atomic::AtomicU64::new(1) }
}
#[cfg(feature = "server")]
pub fn attached(tx: mpsc::UnboundedSender<HostRequest>, info: HostInfo) -> Self {
Self::attached_on(tx, info, Arc::new(NativePlatform))
}
pub fn attached_on(tx: mpsc::UnboundedSender<HostRequest>, info: HostInfo, platform: Arc<dyn Platform>) -> Self {
Self { tx, info, platform, join: None, owned: false, next_id: std::sync::atomic::AtomicU64::new(1) }
}
pub fn is_owned(&self) -> bool {
self.owned
}
pub async fn call(&self, cmd: &str, args: Value) -> Result<Reply, String> {
let id = self.next_id.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let (tx, rx) = oneshot::channel();
self.tx
.send(HostRequest::Command { envelope: Envelope { id, cmd: cmd.to_string(), args }, reply: tx })
.map_err(|_| "the app host has stopped".to_string())?;
rx.await.map_err(|_| "the app host dropped the reply (did it panic?)".to_string())
}
pub async fn call_ok(&self, cmd: &str, args: Value) -> Result<Reply, String> {
let r = self.call(cmd, args).await?;
if r.ok {
Ok(r)
} else {
Err(r.error.unwrap_or_else(|| "command failed".into()))
}
}
pub async fn screenshot(&self, region: Value) -> Result<(Value, Vec<u8>), String> {
let (tx, rx) = oneshot::channel();
self.tx
.send(HostRequest::Screenshot { region, reply: tx })
.map_err(|_| "the app host has stopped".to_string())?;
rx.await.map_err(|_| "the app host dropped the screenshot reply".to_string())?
}
pub async fn annotate(&self, spec: Value) -> Result<Value, String> {
let (tx, rx) = oneshot::channel();
self.tx
.send(HostRequest::Annotate { spec, reply: tx })
.map_err(|_| "the app host has stopped".to_string())?;
rx.await.map_err(|_| "the app host dropped the annotate reply".to_string())?
}
pub fn stop(mut self) {
if !self.owned {
return;
}
let _ = self.tx.send(HostRequest::Stop);
if let Some(j) = self.join.take() {
let _ = j.join();
}
}
}