feather_tui/
callback.rs

1/// This macro generates a function that take a reference to a `Box<dyn Any>`
2/// as an argument and return nothing. The function body (`$body`) is the code
3/// that will be execute when the callback is trigger.
4///
5/// # Usage
6/// Use for defining functions required to create a `Callback` object,  
7/// 
8/// # Example
9/// ```rust
10/// use feather_tui as tui;
11/// 
12/// // Define a callback function that print out the argument that is was given
13/// tui::tui_cbk_new_callback_func!(function_name, argument_name, {
14///     println!(
15///         "Callback received: {}",
16///         argument_name.downcast_ref::<u32>().unwrap());
17/// });
18/// ```
19#[macro_export]
20macro_rules! cbk_new_callback_func {
21    ($func_name:ident, $arg_name:ident, $body:block) => {
22        fn $func_name($arg_name: &Box<dyn std::any::Any>) $body
23    };
24}
25
26/// A generic callback handler for executing functions with stored arguments.
27/// 
28/// `Callback` allows you to associate a function with an argument and invoke 
29/// it later. 
30///
31/// # Usage
32/// `Callback` is use for creating a `Option` component. The callback will be
33/// trigger when the `Option` component is selected.
34/// 
35/// # Example
36/// ```rust
37/// use feather_tui as tui;
38/// 
39/// // Define a callback function that print out the argument that is was given 
40/// tui::tui_cbk_new_callback_func!(callback_func, argument, {
41///     println!(
42///         "Callback Argument: {}", 
43///         argument.downcast_ref::<u32>().unwrap());
44/// });
45/// 
46/// let cb = tui::cbk::Callback::new(callback_func, 42u32);
47/// cb.call(); // Prints: Callback Argument: 42
48/// ```
49pub struct Callback {
50    func: fn(&Box<dyn std::any::Any>) -> (),
51    arg: Box<dyn std::any::Any>,
52}
53
54impl Callback {
55    pub fn new<T>(func: fn(&Box<dyn std::any::Any>), arg: T) -> Self 
56    where
57        T: 'static,
58    {
59        Callback {
60            func,
61            arg: Box::new(arg),
62        }
63    }
64
65    pub fn call(&self) {
66        (self.func)(&self.arg);
67    }
68}