#[cfg(target_arch = "wasm32")]
compile_error!("This module should not be included when compiling to wasm");
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};
use crate::state::{DrawingState, Path, TurtleState};
pub type Shared<T> = Arc<RwLock<T>>;
pub type ReadOnlyRef<'a, T> = RwLockReadGuard<'a, T>;
pub type MutableRef<'a, T> = RwLockWriteGuard<'a, T>;
pub struct ReadOnly {
turtle: Shared<TurtleState>,
drawing: Shared<DrawingState>,
temporary_path: Shared<Option<Path>>,
}
impl ReadOnly {
pub fn turtle(&self) -> ReadOnlyRef<'_, TurtleState> {
self.turtle.read().expect("bug: Lock was poisoned")
}
pub fn drawing(&self) -> ReadOnlyRef<'_, DrawingState> {
self.drawing.read().expect("bug: Lock was poisoned")
}
pub fn temporary_path(&self) -> ReadOnlyRef<'_, Option<Path>> {
self.temporary_path.read().expect("bug: Lock was poisoned")
}
}
#[derive(Clone)]
pub struct TurtleApp {
turtle: Shared<TurtleState>,
drawing: Shared<DrawingState>,
temporary_path: Shared<Option<Path>>,
}
impl TurtleApp {
pub fn new() -> Self {
Self {
turtle: Arc::new(RwLock::new(TurtleState::default())),
drawing: Arc::new(RwLock::new(DrawingState::default())),
temporary_path: Arc::new(RwLock::new(None)),
}
}
pub fn read_only(&self) -> ReadOnly {
ReadOnly {
turtle: Arc::clone(&self.turtle),
drawing: Arc::clone(&self.drawing),
temporary_path: Arc::clone(&self.temporary_path),
}
}
pub fn turtle(&self) -> ReadOnlyRef<'_, TurtleState> {
self.turtle.read().expect("bug: Lock was poisoned")
}
pub fn turtle_mut(&mut self) -> MutableRef<'_, TurtleState> {
self.turtle.write().expect("bug: Lock was poisoned")
}
pub fn drawing(&self) -> ReadOnlyRef<'_, DrawingState> {
self.drawing.read().expect("bug: Lock was poisoned")
}
pub fn drawing_mut(&mut self) -> MutableRef<'_, DrawingState> {
self.drawing.write().expect("bug: Lock was poisoned")
}
pub fn set_temporary_path(&mut self, path: Option<Path>) {
let mut temp = self.temporary_path.write().expect("bug: Lock was poisoned");
*temp = path;
}
}