ui/src/elements/callback_builder.rs

71 lines
1.8 KiB
Rust
Raw Normal View History

2024-04-04 07:11:42 +00:00
use std::any::Any;
use anyhow::Result;
2025-03-04 17:18:08 +00:00
use ecs::World;
2024-04-04 07:11:42 +00:00
use super::ControllerButton;
2025-03-04 15:03:57 +00:00
use crate::prelude::*;
2024-04-04 07:11:42 +00:00
macro_rules! callbacks {
($name:ident, $($cb:tt)*) => {
#[derive(Default)]
pub struct $name<'a> {
callbacks: Vec<(&'a str, Box<dyn $($cb)*>)>,
}
impl<'a> $name<'a> {
pub fn add(mut self, name: &'a str, callback: impl $($cb)* + 'static)->Self {
self.callbacks.push((name, Box::new(callback)));
self
}
}
impl<'a> Into<Vec<(&'a str, Box<dyn $($cb)*>)>> for $name<'a> {
fn into(self) -> Vec<(&'a str, Box<dyn $($cb)*>)> {
self.callbacks
}
}
};
}
2025-03-04 17:18:08 +00:00
callbacks!(ClickCallbacks, Fn(&mut World, &mut GuiHandler) -> Result<()> + Send + Sync);
callbacks!(SelectCallbacks, Fn(&mut World, &mut GuiHandler, bool) -> anyhow::Result<()> + Send + Sync);
callbacks!(CustomCallbacks, Fn(&mut World, &mut GuiHandler, ControllerButton) -> anyhow::Result<bool> + Send + Sync);
callbacks!(
VecCallbacks,
Fn(&mut World, &mut GuiHandler, &dyn Any) -> Result<()> + Send + Sync
);
2024-04-04 07:11:42 +00:00
2024-04-04 08:35:00 +00:00
#[cfg(test)]
mod test {
use super::*;
use anyhow::Result;
2025-03-04 17:18:08 +00:00
fn normal_fn() -> impl Fn(&mut World, &mut GuiHandler) -> Result<()> + Send + Sync {
|_, _| Ok(())
2024-04-04 07:11:42 +00:00
}
2024-04-04 08:35:00 +00:00
#[test]
fn test_click_callback_builder() {
struct Test;
2024-04-04 07:11:42 +00:00
2024-04-04 08:35:00 +00:00
impl Test {
fn set_click_callbacks(
&self,
2025-03-04 15:03:57 +00:00
_callbacks: Vec<(
&str,
2025-03-04 17:18:08 +00:00
Box<dyn Fn(&mut World, &mut GuiHandler) -> Result<()> + Send + Sync>,
2025-03-04 15:03:57 +00:00
)>,
2024-04-04 08:35:00 +00:00
) -> Result<()> {
Ok(())
}
}
2024-04-04 07:11:42 +00:00
2024-04-04 08:35:00 +00:00
let t = Test;
let cbs = ClickCallbacks::default().add("normal_test", normal_fn());
t.set_click_callbacks(cbs.into()).unwrap();
}
2024-04-04 07:11:42 +00:00
}