handlers and ids

This commit is contained in:
2025-07-05 06:28:50 +02:00
parent 921bfa27c1
commit 661756eccd
8 changed files with 112 additions and 39 deletions
+31
View File
@@ -0,0 +1,31 @@
use std::sync::{Arc, Mutex};
use crate::{component, extensions::Extension, widget::Widget};
pub struct IdExtension(Mutex<Vec<Arc<Widget>>>);
impl Extension for Arc<IdExtension> {
fn init(&mut self, widgets: &Vec<Arc<Widget>>) {
self.0.lock().unwrap().append(&mut widgets.clone());
}
}
impl IdExtension {
pub fn new() -> Arc<Self> {
Arc::new(Self(Mutex::new(Vec::new())))
}
pub fn get_element(self: &Arc<IdExtension>, id: usize) -> Option<Arc<Widget>> {
for elem in self.0.lock().unwrap().iter() {
if let Some(current_id) = elem.get::<Id>() {
if current_id.0 == id {
return Some(elem.clone());
}
}
}
None
}
}
component!(Id(pub usize));
+27 -4
View File
@@ -1,11 +1,34 @@
pub mod id;
pub mod tick;
pub mod velocity;
use std::sync::Arc;
use std::{
fmt::Debug,
sync::{Arc, Mutex},
};
use crate::widget::Widget;
use crate::{render_scope::RenderScope, widget::Widget};
pub trait Extension {
fn init(&self, _widgets: &Vec<Arc<Widget>>) {}
fn render(&self, _widget: &Arc<Widget>) {}
fn init(&mut self, _widgets: &Vec<Arc<Widget>>) {}
fn render_widget(&mut self, _scope: &mut RenderScope, _widget: &Arc<Widget>) {}
}
#[derive(Clone)]
pub struct Handler(pub Arc<Mutex<dyn FnMut(&Arc<Widget>) + Send + Sync>>);
impl Handler {
pub fn new<F: FnMut(&Arc<Widget>) + Send + Sync + 'static>(f: F) -> Handler {
Handler(Arc::new(Mutex::new(f)))
}
pub fn call(&self, w: &Arc<Widget>) {
(self.0.lock().unwrap())(w)
}
}
impl Debug for Handler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Handler")
}
}
+5 -4
View File
@@ -1,18 +1,19 @@
use std::sync::Arc;
use std::{fmt::Debug, sync::Arc};
use crate::extensions::Handler;
use crate::{component, extensions::Extension, widget::Widget};
pub struct TickExtension(pub u16);
impl Extension for TickExtension {
fn init(&self, widgets: &Vec<Arc<Widget>>) {
fn init(&mut self, widgets: &Vec<Arc<Widget>>) {
let rate_dur = 1000 / self.0 as u64;
std::thread::spawn({
let widgets = widgets.clone();
move || loop {
for w in &widgets {
if let Some(on_tick) = w.get::<OnTick>() {
(on_tick.0)(&w)
on_tick.0.call(&w)
}
}
std::thread::sleep(std::time::Duration::from_millis(rate_dur));
@@ -21,4 +22,4 @@ impl Extension for TickExtension {
}
}
component!(OnTick(pub fn(&Arc<Widget>)));
component!(OnTick(pub Handler));
+1 -1
View File
@@ -42,7 +42,7 @@ impl VelocityExtension {
}
impl Extension for VelocityExtension {
fn init(&self, widgets: &Vec<Arc<Widget>>) {
fn init(&mut self, widgets: &Vec<Arc<Widget>>) {
std::thread::spawn({
let widgets = widgets.clone();
move || {