ui/src/gui_handler/gui/executable.rs

51 lines
1.4 KiB
Rust
Raw Normal View History

2023-01-16 09:53:52 +00:00
//! `Executable` is a property to execute a closure
use anyhow::Result;
2025-03-04 17:18:08 +00:00
use ecs::World;
2023-01-16 09:53:52 +00:00
use std::sync::{Arc, RwLock};
2024-08-29 09:09:17 +00:00
use crate::prelude::*;
2023-01-16 09:53:52 +00:00
/// `Executable` holds a closure which can be executed
2025-03-04 11:25:02 +00:00
pub struct Executable<I: Send + Sync> {
2025-03-04 17:18:08 +00:00
callback: RwLock<Option<Arc<dyn Fn(&mut World, I) -> Result<()> + Send + Sync>>>,
2023-01-16 09:53:52 +00:00
}
2024-08-29 09:09:17 +00:00
impl<I: Send + Sync + 'static> Executable<I> {
2023-01-16 09:53:52 +00:00
/// Factory method for `Executable`, returns `Arc<Executable>`
pub fn new() -> Arc<Self> {
2023-01-16 09:53:52 +00:00
Arc::new(Executable {
callback: RwLock::new(None),
})
}
/// Set callback closure
///
/// # Arguments
///
/// * `callback` is a `Option<Callback>` closure
pub fn set_callback<F>(&self, callback: impl Into<Option<F>>)
where
2025-03-04 17:18:08 +00:00
F: Fn(&mut World, I) -> Result<()> + Send + Sync + 'static,
2023-01-16 09:53:52 +00:00
{
let mut function = self.callback.write().unwrap();
match callback.into() {
2024-08-29 09:09:17 +00:00
Some(f) => *function = Some(Arc::new(f)),
2023-01-16 09:53:52 +00:00
None => *function = None,
}
}
/// Execute the callback closure if possible
2025-03-04 11:25:02 +00:00
pub fn execute(&self, gui_handler: &mut GuiHandler, input: I) -> Result<()> {
2023-01-16 09:53:52 +00:00
if let Some(callback) = self.callback.read().unwrap().as_ref() {
2024-08-29 09:09:17 +00:00
let callback = callback.clone();
2025-03-04 11:25:02 +00:00
gui_handler.add_callback(move |gui_handler| (callback)(gui_handler, input));
2023-01-16 09:53:52 +00:00
}
Ok(())
}
}