pub mod id; pub mod input_handling; pub mod tick; pub mod velocity; pub use id::*; pub use input_handling::*; pub use tick::*; pub use velocity::*; use std::{ any::{type_name, Any}, fmt::Debug, sync::{Arc, Mutex, MutexGuard}, }; use crate::{ render_scope::RenderScope, widget::{Component, Widget}, Screen, }; pub trait Extension { fn init(&mut self, _ctx: &ExtensionContext) {} fn event(&mut self, _ctx: &ExtensionContext, _event: &dyn Event) {} fn on_close(&mut self) {} fn render_widget(&mut self, _scope: &mut RenderScope, _widget: &Arc) {} } pub trait Event: Send + Sync { fn as_any(&self) -> &dyn Any; } #[derive(Clone)] pub struct ExtensionContext { screen: Arc, } #[derive(Clone)] pub struct Handler(Arc, &E) + Send + Sync>>); impl Component for Handler { fn as_any(&self) -> &dyn Any { self } fn as_any_mut(&mut self) -> &mut dyn Any { self } } impl Handler { pub fn new, &E) + Send + Sync + 'static>(f: F) -> Handler { Handler(Arc::new(Mutex::new(f))) } pub fn call(&self, w: &Arc, e: &E) { (self.0.lock().unwrap())(w, e) } } impl Debug for Handler { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Handler({})", type_name::()) } } impl<'a> dyn Event + 'a { pub fn get(&self) -> Option<&T> { self.as_any().downcast_ref() } } impl ExtensionContext { pub fn new(screen: Arc) -> Self { Self { screen } } pub fn event(&self, e: &E) { for widget in self.screen.widgets.lock().unwrap().iter() { widget.event(e); } for ext in self.screen.extensions.lock().unwrap().iter() { ext.lock().unwrap().event(self, e); } } pub fn get_widgets(&self) -> MutexGuard>> { self.screen.widgets.lock().unwrap() } pub fn iter_components, Option)>( &self, mut iterator: F, ) { for widget in self.screen.widgets.lock().unwrap().iter() { iterator(widget, widget.get()); } } pub fn get_components(&self) -> Vec { let mut components = Vec::new(); for widget in self.screen.widgets.lock().unwrap().iter() { if let Some(c) = widget.get() { components.push(c); } } components } }