use std::ops::Range;
use std::sync::Arc;
use canvist_scene::SceneSchemaBuilder;
use serde_json::Value as Json;
use serde_json::json;
use crate::CanvasError;
use crate::CanvasState;
use crate::inspector::Field;
use crate::inspector::Section;
use crate::tools::Outcome;
use crate::tools::Tool;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ToolId(pub(crate) usize);
impl ToolId {
pub const HAND: Self = Self(1);
pub const SELECT: Self = Self(0);
#[must_use]
pub fn index(self) -> usize {
self.0
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Registration {
tools: Range<usize>,
}
impl Registration {
#[must_use]
pub fn tool(&self, nth: usize) -> ToolId {
let id = self.tools.start + nth;
assert!(
self.tools.contains(&id),
"the extension registered no tool {nth}"
);
ToolId(id)
}
}
pub type CommandFn =
Arc<dyn Fn(&mut CanvasState, &Json) -> Result<Outcome, CanvasError> + Send + Sync>;
#[derive(Clone)]
pub struct Command {
pub name: String,
pub description: String,
pub args: Vec<Field>,
pub run: CommandFn,
}
impl std::fmt::Debug for Command {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Command")
.field("name", &self.name)
.field("args", &self.args)
.finish_non_exhaustive()
}
}
impl Command {
pub fn new(
name: &str,
description: &str,
args: Vec<Field>,
run: impl Fn(&mut CanvasState, &Json) -> Result<Outcome, CanvasError> + Send + Sync + 'static,
) -> Self {
Self {
name: name.to_owned(),
description: description.to_owned(),
args,
run: Arc::new(run),
}
}
#[must_use]
pub fn meta(&self) -> Json {
json!({
"name": self.name,
"description": self.description,
"args": self.args.iter().map(Field::meta).collect::<Vec<_>>(),
})
}
}
pub trait CanvasExtension: Send + Sync {
fn name(&self) -> &'static str;
fn schema(&self, schema: SceneSchemaBuilder) -> SceneSchemaBuilder {
schema
}
fn tools(&self) -> Vec<Box<dyn Tool>> {
Vec::new()
}
fn commands(&self) -> Vec<Command> {
Vec::new()
}
fn inspector(&self) -> Vec<Section> {
Vec::new()
}
}
pub trait TypedCanvasExtension: CanvasExtension + Sized + 'static {
type Handle: Copy;
fn handle(&self, registration: Registration) -> Self::Handle;
}
impl Registration {
pub(crate) fn new(tools: Range<usize>) -> Self {
Self { tools }
}
}