use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use ashlar_command::{CommandError, CommandInfo, CommandSpec, Dispatch, Registry};
use ashlar_fs::AppDirs;
use ashlar_store::Format;
use serde_json::Value;
use crate::builtins;
use crate::runtime::{Cx, Runtime};
use crate::session::{Document, Session};
use crate::telemetry::TelemetryConfig;
pub type ViewFn<D> = Box<dyn FnMut(&mut egui::Ui, &mut Cx<'_, D>)>;
pub type SetupFn = Box<dyn FnOnce(&egui::Context)>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("could not open the window: {0}")]
Window(String),
#[error("{0}")]
Io(#[from] std::io::Error),
}
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub(crate) struct Shared<D: Document> {
pub name: String,
pub version: String,
pub title: String,
pub env_prefix: String,
pub registry: Registry<Session<D>>,
pub format: Arc<Format<D>>,
pub extensions: Vec<String>,
pub dirs: Option<AppDirs>,
pub autosave: Option<Duration>,
pub telemetry: Option<TelemetryConfig>,
pub instructions: String,
pub window_size: [f32; 2],
pub control_port: Option<u16>,
}
pub struct App<D: Document> {
name: String,
version: String,
title: Option<String>,
qualifier: String,
org: String,
format: Option<Format<D>>,
extensions: Vec<String>,
commands: Vec<CommandSpec<Session<D>>>,
view: Option<ViewFn<D>>,
setup: Option<SetupFn>,
autosave: Option<Duration>,
telemetry: Option<TelemetryConfig>,
instructions: String,
dirs: Option<AppDirs>,
window_size: [f32; 2],
control_port: Option<u16>,
}
impl<D: Document> App<D> {
pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
App {
name: name.into(),
version: version.into(),
title: None,
qualifier: "org".into(),
org: "ashlar".into(),
format: None,
extensions: Vec::new(),
commands: Vec::new(),
view: None,
setup: None,
autosave: Some(Duration::from_secs(60)),
telemetry: None,
instructions: String::new(),
dirs: None,
window_size: [960.0, 640.0],
control_port: None,
}
}
pub fn organization(mut self, qualifier: impl Into<String>, org: impl Into<String>) -> Self {
self.qualifier = qualifier.into();
self.org = org.into();
self
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn format(mut self, format: Format<D>) -> Self {
self.format = Some(format);
self
}
pub fn file_extension(mut self, ext: impl Into<String>) -> Self {
self.extensions.push(ext.into());
self
}
pub fn commands(mut self, specs: impl IntoIterator<Item = CommandSpec<Session<D>>>) -> Self {
self.commands.extend(specs);
self
}
pub fn command(mut self, spec: CommandSpec<Session<D>>) -> Self {
self.commands.push(spec);
self
}
pub fn view(mut self, view: impl FnMut(&mut egui::Ui, &mut Cx<'_, D>) + 'static) -> Self {
self.view = Some(Box::new(view));
self
}
pub fn setup(mut self, f: impl FnOnce(&egui::Context) + 'static) -> Self {
self.setup = Some(Box::new(f));
self
}
pub fn autosave(mut self, every: Option<Duration>) -> Self {
self.autosave = every;
self
}
pub fn telemetry(mut self, key: impl Into<String>, endpoint: Option<&str>) -> Self {
self.telemetry = Some(TelemetryConfig { key: key.into(), endpoint: endpoint.map(str::to_string) });
self
}
pub fn instructions(mut self, text: impl Into<String>) -> Self {
self.instructions = text.into();
self
}
pub fn dirs(mut self, dirs: AppDirs) -> Self {
self.dirs = Some(dirs);
self
}
pub fn window_size(mut self, width: f32, height: f32) -> Self {
self.window_size = [width, height];
self
}
pub fn control_port(mut self, port: u16) -> Self {
self.control_port = Some(port);
self
}
pub(crate) fn split(self) -> (Arc<Shared<D>>, Option<ViewFn<D>>, Option<SetupFn>) {
let env_prefix: String = self.name.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_uppercase() } else { '_' }).collect();
let format = self.format.unwrap_or_else(|| Format::new(format!("{}.document", self.name), format!("{} {}", self.name, self.version)));
let mut specs = builtins::leading::<D>();
specs.extend(self.commands);
specs.extend(builtins::trailing::<D>());
let registry = Registry::new(specs);
for dup in registry.duplicates() {
log::warn!("command `{dup}` is declared twice; the first one wins");
}
let dirs = self.dirs.or_else(|| AppDirs::new(&self.qualifier, &self.org, &self.name));
let shared = Shared {
title: self.title.unwrap_or_else(|| self.name.clone()),
name: self.name,
version: self.version,
env_prefix,
registry,
format: Arc::new(format),
extensions: self.extensions,
dirs,
autosave: self.autosave,
telemetry: self.telemetry,
instructions: self.instructions,
window_size: self.window_size,
control_port: self.control_port,
};
(Arc::new(shared), self.view, self.setup)
}
pub fn headless(self) -> Headless<D> {
let (shared, _, _) = self.split();
Headless::new(shared)
}
pub fn runtime(self) -> Runtime<D> {
let (shared, view, setup) = self.split();
let mut launch = crate::runtime::Launch::default();
if let (Some(cfg), Some(d)) = (&shared.telemetry, &shared.dirs) {
launch.telemetry = crate::telemetry::Telemetry::start(cfg, &shared.name, &shared.version, &d.data, true);
}
Runtime::new(shared, view, setup, launch)
}
pub fn cli(self) -> ashlar_cli::Cli {
let (shared, _, _) = self.split();
let factory = Arc::clone(&shared);
let mut cli = ashlar_cli::Cli::new(shared.name.clone(), shared.version.clone(), move || {
Box::new(Headless::new(Arc::clone(&factory))) as Box<dyn Dispatch>
});
if let Some(d) = &shared.dirs {
cli = cli.key_dir(d.config.clone());
}
if !shared.instructions.is_empty() {
cli = cli.instructions(shared.instructions.clone());
}
cli
}
pub fn run(self) -> Result<(), Error> {
crate::runtime::run_native(self)
}
}
pub fn cli_main<D: Document>(app: App<D>) -> std::process::ExitCode {
app.cli().run()
}
pub struct Headless<D: Document> {
shared: Arc<Shared<D>>,
session: Session<D>,
}
impl<D: Document> Headless<D> {
pub(crate) fn new(shared: Arc<Shared<D>>) -> Self {
let session = Session::new(Arc::clone(&shared.format));
Headless { shared, session }
}
pub fn session(&self) -> &Session<D> {
&self.session
}
pub fn session_mut(&mut self) -> &mut Session<D> {
&mut self.session
}
pub fn registry(&self) -> &Registry<Session<D>> {
&self.shared.registry
}
pub fn dirs(&self) -> Option<&AppDirs> {
self.shared.dirs.as_ref()
}
pub fn name(&self) -> &str {
&self.shared.name
}
pub fn default_dir(&self) -> Option<PathBuf> {
self.shared.dirs.as_ref().map(|d| d.data.clone())
}
}
impl<D: Document> Dispatch for Headless<D> {
fn commands(&self) -> Vec<CommandInfo> {
self.shared.registry.infos(&self.session)
}
fn execute(&mut self, id: &str, params: Value) -> Result<Value, CommandError> {
let r = self.shared.registry.execute(&mut self.session, id, params);
self.session.drain_headless();
r
}
}