111 lines
2.6 KiB
Rust
111 lines
2.6 KiB
Rust
// Copyright (c) 2022 Marceline Cramer
|
|
// SPDX-License-Identifier: LGPL-3.0-or-later
|
|
|
|
pub use canary_script::*;
|
|
use parking_lot::{Mutex, RwLock};
|
|
use slab::Slab;
|
|
use std::collections::HashMap;
|
|
use std::sync::Arc;
|
|
|
|
pub mod backend;
|
|
pub mod text;
|
|
|
|
use backend::{Backend, Instance, ScriptAbi};
|
|
use text::FontStore;
|
|
|
|
/// The main interface to Canary.
|
|
pub struct Runtime {
|
|
backend: Box<dyn Backend>,
|
|
font_store: Arc<FontStore>,
|
|
}
|
|
|
|
impl Runtime {
|
|
pub fn new(backend: Box<dyn Backend>) -> anyhow::Result<Self> {
|
|
log::info!("Initializing runtime with {} backend", backend.name());
|
|
|
|
Ok(Self {
|
|
backend,
|
|
font_store: Arc::new(FontStore::new()),
|
|
})
|
|
}
|
|
|
|
pub fn load_module(&self, module: &[u8]) -> anyhow::Result<Script> {
|
|
let abi = ScriptAbi::new(self.font_store.to_owned());
|
|
let abi = Arc::new(abi);
|
|
let instance = self.backend.load_module(abi.to_owned(), module)?;
|
|
|
|
Ok(Script {
|
|
instance,
|
|
abi,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// A loaded instance of a Canary script.
|
|
pub struct Script {
|
|
instance: Arc<dyn Instance>,
|
|
abi: Arc<ScriptAbi>,
|
|
}
|
|
|
|
impl Script {
|
|
pub fn create_panel(&mut self, protocol: &str, msg: Vec<u8>) -> anyhow::Result<Panel> {
|
|
let id = self.abi.create_panel();
|
|
let userdata = self.instance.bind_panel(id, protocol, msg);
|
|
Ok(Panel {
|
|
instance: self.instance.clone(),
|
|
abi: self.abi.clone(),
|
|
id,
|
|
userdata,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// A Canary panel.
|
|
pub struct Panel {
|
|
instance: Arc<dyn Instance>,
|
|
abi: Arc<ScriptAbi>,
|
|
id: PanelId,
|
|
userdata: u32,
|
|
}
|
|
|
|
impl Panel {
|
|
pub fn update(&self, dt: f32) {
|
|
self.instance.update(self.userdata, dt);
|
|
}
|
|
|
|
pub fn draw(&self) -> Vec<DrawCommand> {
|
|
self.instance.draw(self.userdata)
|
|
}
|
|
|
|
pub fn on_resize(&self, new_size: Vec2) {
|
|
self.instance.on_resize(self.userdata, new_size);
|
|
}
|
|
|
|
pub fn on_cursor_event(&self, kind: CursorEventKind, at: Vec2) {
|
|
self.instance.on_cursor_event(self.userdata, kind, at);
|
|
}
|
|
|
|
pub fn on_message(&self, msg: Vec<u8>) {
|
|
self.instance.on_message(self.userdata, msg);
|
|
}
|
|
|
|
pub fn recv_messages(&self) -> Vec<Vec<u8>> {
|
|
self.abi.recv_panel_messages(self.id)
|
|
}
|
|
}
|
|
|
|
/// Proportion constant between pixels (at 96dpi) to millimeters (Canary's unit measurement).
|
|
pub const PX_PER_MM: f32 = 25.4 / 96.0;
|
|
|
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
|
pub struct PanelId(pub(crate) usize);
|
|
|
|
#[non_exhaustive]
|
|
#[derive(Clone, Debug)]
|
|
pub enum DrawCommand {
|
|
Mesh {
|
|
vertices: Vec<MeshVertex>,
|
|
indices: Vec<MeshIndex>,
|
|
},
|
|
}
|