ui/src/gui_handler/gui/executable.rs

50 lines
1.3 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;
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
2024-08-29 09:09:17 +00:00
pub struct Executable<I: Send + Sync + 'static> {
callback: RwLock<Option<Arc<dyn Fn(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
F: Fn(I) -> Result<()> + Send + Sync + 'static,
{
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
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();
gui_handler.add_callback(move || (callback)(input));
2023-01-16 09:53:52 +00:00
}
Ok(())
}
}