use std::collections::BTreeMap;
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use crate::document::{Document, ObjectId};
use crate::property::Property;
pub const ATTRIBUTE_REJECTION_PREFIX: &str = "AttributeError: ";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PropertyChangeError {
Value(String),
Attribute(String),
}
impl PropertyChangeError {
pub fn value(message: impl Into<String>) -> Self {
Self::Value(message.into())
}
pub fn attribute(message: impl Into<String>) -> Self {
Self::Attribute(message.into())
}
}
impl fmt::Display for PropertyChangeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Value(message) => f.write_str(message),
Self::Attribute(message) => {
f.write_str(ATTRIBUTE_REJECTION_PREFIX)?;
f.write_str(message)
}
}
}
}
impl std::error::Error for PropertyChangeError {}
pub trait ObjectType: Send + Sync {
fn default_properties(&self) -> Vec<(String, Property, u32)> {
Vec::new()
}
fn property_meta(&self, name: &str) -> Option<(String, String)> {
let _ = name;
None
}
fn execute(&self, doc: &mut Document, id: ObjectId) {
let _ = (doc, id);
}
fn on_property_change(
&self,
doc: &Document,
id: ObjectId,
name: &str,
value: &Property,
) -> Result<(), PropertyChangeError> {
let _ = (doc, id, name, value);
Ok(())
}
fn is_python_feature(&self) -> bool {
false
}
}
fn registry() -> &'static Mutex<BTreeMap<String, Arc<dyn ObjectType>>> {
static REGISTRY: OnceLock<Mutex<BTreeMap<String, Arc<dyn ObjectType>>>> = OnceLock::new();
REGISTRY.get_or_init(|| Mutex::new(BTreeMap::new()))
}
pub fn register(type_id: &str, behavior: Arc<dyn ObjectType>) {
registry()
.lock()
.unwrap()
.insert(type_id.to_string(), behavior);
}
pub fn get(type_id: &str) -> Option<Arc<dyn ObjectType>> {
registry().lock().unwrap().get(type_id).cloned()
}
pub fn is_registered(type_id: &str) -> bool {
registry().lock().unwrap().contains_key(type_id)
}
pub fn names() -> Vec<String> {
registry().lock().unwrap().keys().cloned().collect()
}
pub fn python_executor_available() -> bool {
PYTHON_EXECUTOR_AVAILABLE.load(Ordering::Relaxed)
}
pub fn set_python_executor_available(available: bool) {
PYTHON_EXECUTOR_AVAILABLE.store(available, Ordering::Relaxed);
}
static PYTHON_EXECUTOR_AVAILABLE: AtomicBool = AtomicBool::new(false);
pub fn is_python_feature(type_id: &str) -> bool {
get(type_id).is_some_and(|behavior| behavior.is_python_feature())
}
#[cfg(test)]
mod tests {
use super::*;
struct Counter;
impl ObjectType for Counter {
fn default_properties(&self) -> Vec<(String, Property, u32)> {
vec![("Count".to_string(), Property::Integer(0), 0)]
}
fn execute(&self, doc: &mut Document, id: ObjectId) {
let next = doc
.object(id)
.and_then(|o| o.properties.get("Count"))
.and_then(|p| match p {
Property::Integer(n) => Some(*n + 1),
_ => None,
})
.unwrap_or(1);
doc.set_property_raw(id, "Count", Property::Integer(next));
}
}
#[test]
fn registering_a_type_gives_defaults() {
register("Test::Counter", Arc::new(Counter));
assert!(is_registered("Test::Counter"));
let behavior = get("Test::Counter").unwrap();
assert_eq!(behavior.default_properties().len(), 1);
}
#[test]
fn a_registered_type_constructs_and_executes() {
register("Test::Counter2", Arc::new(Counter));
let mut doc = Document::new();
let id = doc.add_object("counter", "Test::Counter2");
assert_eq!(
doc.object(id).unwrap().properties.get("Count"),
Some(&Property::Integer(0))
);
doc.touch(id, false);
let _ = doc.recompute();
assert_eq!(
doc.object(id).unwrap().properties.get("Count"),
Some(&Property::Integer(1))
);
}
#[test]
fn unknown_type_has_no_behaviour() {
assert!(get("Nope::Nope").is_none());
}
struct Guard;
impl ObjectType for Guard {
fn on_property_change(
&self,
_doc: &Document,
_id: ObjectId,
name: &str,
_value: &Property,
) -> Result<(), PropertyChangeError> {
if name == "Locked" {
Err(PropertyChangeError::attribute("Locked is immutable"))
} else {
Ok(())
}
}
}
#[test]
fn the_property_change_hook_vetoes_before_commit() {
register("Test::Guard", Arc::new(Guard));
let mut doc = Document::new();
let id = doc.add_object("guard", "Test::Guard");
doc.set_property(id, "Count", Property::Integer(1)).unwrap();
let error = doc
.set_property(id, "Locked", Property::Integer(2))
.unwrap_err();
assert!(error.starts_with(ATTRIBUTE_REJECTION_PREFIX), "{error}");
assert!(error.contains("Locked is immutable"), "{error}");
assert_eq!(doc.object(id).unwrap().properties.get("Locked"), None);
assert_eq!(
doc.object(id).unwrap().properties.get("Count"),
Some(&Property::Integer(1))
);
}
#[test]
fn a_value_rejection_has_no_attribute_marker() {
let error = PropertyChangeError::value("bad value").to_string();
assert_eq!(error, "bad value");
assert!(!error.starts_with(ATTRIBUTE_REJECTION_PREFIX));
}
struct PythonFeature;
impl ObjectType for PythonFeature {
fn execute(&self, doc: &mut Document, id: ObjectId) {
doc.mark_python_pending(id);
}
fn is_python_feature(&self) -> bool {
true
}
}
#[test]
fn a_python_feature_requests_execution_after_the_recompute() {
register("Test::PythonFeature", Arc::new(PythonFeature));
assert!(is_python_feature("Test::PythonFeature"));
assert!(!is_python_feature("Test::Counter2"));
let mut doc = Document::new();
let id = doc.add_object("python", "Test::PythonFeature");
doc.touch(id, false);
let _ = doc.recompute();
assert!(doc.python_pending(id));
assert_eq!(doc.take_python_pending(), vec![id]);
assert!(!doc.python_pending(id));
assert!(doc.take_python_pending().is_empty());
}
#[test]
fn the_interpreter_availability_flag_is_process_wide() {
set_python_executor_available(true);
assert!(python_executor_available());
set_python_executor_available(false);
assert!(!python_executor_available());
}
}