1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
// SPDX-License-Identifier: GPL-3.0-or-later

use std::{cell::Cell, sync::Mutex};

#[cfg(feature = "latest-gtk")]
use gdk4::prelude::ActionExt;

use crate::print_perf;

mod action;
pub use action::*;

mod widgets;
pub use widgets::*;

/// A global Store
///
/// The store holds global app app data with static lifetime.
///
/// It can be manipulated by dispatching actions (See [Action](crate::Action)).
///
/// Each action is handled by the reducer - A function which matches the
/// action and has a mutable ref to the state in the store.
///
/// The reducer must not have any side effects (E.g. saving the state to a file).
///
/// Side effects are implemented in middlewares (See [Middleware](crate::Middleware)).
pub struct Store<S: std::fmt::Debug + Clone + Default + PartialEq + Eq + 'static> {
    state: S,
    middlewares: Vec<Box<dyn Middleware<S>>>,
    reducer: Box<dyn Fn(&Action, &mut S) + 'static>,
    selectors: Vec<Selector<S>>,
    reduce_lock: Mutex<u8>,
    reduce_depth: Cell<u64>,
}

impl<S: std::fmt::Debug + Clone + Default + PartialEq + Eq + 'static> std::fmt::Debug for Store<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Store")
            .field("state", &self.state)
            .field("selectors", &self.selectors)
            .finish()
    }
}

impl<S: std::fmt::Debug + Clone + Default + PartialEq + Eq> Store<S> {
    /// Create a new Store.
    /// # Arguments
    /// - default_state: The initial state of the store.
    /// - reducer: The root reducer for this store.
    /// - middlewares: A list of [Middleware](crate::Middleware).
    pub fn new(
        default_state: S,
        reducer: impl Fn(&Action, &mut S) + 'static,
        middlewares: Vec<Box<dyn Middleware<S>>>,
    ) -> Self {
        Store {
            state: default_state,
            middlewares,
            reducer: Box::new(reducer),
            selectors: Default::default(),
            reduce_lock: Default::default(),
            reduce_depth: Cell::new(0),
        }
    }

    fn select_internal(
        &mut self,
        name: &str,
        selector: impl Fn(&S) -> S + 'static,
        callback: impl Fn(&S) + 'static,
        select_full_state: bool,
    ) {
        callback(&self.state);
        let last_selector_state = selector(&self.state);
        trace!("Adding selector for 'state[{}]'.", name);
        self.selectors.push(Selector::new(
            name,
            select_full_state,
            selector,
            last_selector_state,
            callback,
        ));
    }

    /// Select a slice of the state where everything else is Default::default().
    pub fn select(
        &mut self,
        name: &str,
        selector: impl Fn(&S) -> S + 'static,
        callback: impl Fn(&S) + 'static,
    ) {
        print_perf!(
            self.select_internal(name, selector, callback, false);
            format!("Call selector {}", name)
        )
    }

    /// Select a slice of the state with receiving the whole state.
    pub fn select_full(
        &mut self,
        name: &str,
        selector: impl Fn(&S) -> S + 'static,
        callback: impl Fn(&S) + 'static,
    ) {
        print_perf!(
            self.select_internal(name, selector, callback, true);
            format!("Call full state selector {}", name)
        )
    }

    /// Dispatch the given arguments as an [Action](crate::Action).
    ///
    /// **NOTE:**
    ///
    /// **This is a placeholder since rustdoc server can not compile latest gtk yet
    /// The actual signature looks like this:**
    /// ```rust
    /// pub fn dispatch(&self, action: String, argument: Option<glib::Variant>)
    /// ```
    #[cfg(not(feature = "glib"))]
    pub fn dispatch(&self, action: String, argument: Option<String>) {}

    /// Dispatch the given arguments as an [Action](crate::Action).
    #[cfg(feature = "glib")]
    pub fn dispatch(&mut self, action: String, argument: Option<glib::Variant>) {
        let lock = self.reduce_lock.try_lock();
        if lock.is_err() {
            error!("Can not dispatch '{}' during reduce", action);
            return;
        }
        drop(lock);

        self.reduce_depth.set(self.reduce_depth.take() + 1);

        let message = format!("Dispatch action {:?} with argument {:?}", action, argument);
        print_perf! (
            {
                let action = Action::new(action, argument);
                // let state = &mut self.state1;

                trace!(
                    "Reduce action {:?} for state {:?}.",
                    action.name().to_string(),
                    &self.state
                );

                print_perf!(
                    for middleware in &self.middlewares {
                        middleware.pre_reduce(&action, &self.state);
                    };
                    format!("Call {} middlewares pre_reduce", self.middlewares.len())
                );

                // reducing phase
                {
                    let lock = self.reduce_lock.try_lock();
                    if lock.is_err() {
                        error!("Can not dispatch '{}' during reduce", action.name());
                        return;
                    }
                    let reducer = &self.reducer;
                    print_perf!(
                        reducer(&action, &mut self.state);
                        format!("Reduce action {:?}", action.name())
                    );
                    trace!("Reduced to: {:?}", &self.state);
                    drop(lock);
                    print_perf!(
                        {
                            for selector in self.selectors.iter_mut() {
                                let sel = &selector.selector;
                                let selected_state = sel(&self.state);
                                if selector.last_state != selected_state {
                                    let callb = &selector.callback;
                                    if selector.full {
                                        callb(&self.state);
                                    } else {
                                        callb(&selected_state);
                                    }
                                    selector.last_state = selected_state;
                                }
                            }
                        };
                        format!("Determine n of {} selectors for action {:?}", self.selectors.len(), action.name())
                    );
                }

                print_perf!(
                    for middleware in &self.middlewares {
                        middleware.post_reduce(&action, &self.state);
                    };
                    format!("Call {} middlewares post_reduce", self.middlewares.len())
                );
            };
            message
        );

        self.reduce_depth.set(self.reduce_depth.take() - 1);
    }

    pub fn is_last_reduce_phase(&self) -> bool {
        self.reduce_depth.get() == 1
    }

    /// Delegate GTK actions as gstore::Actions to this store.
    ///
    /// **NOTE:**
    ///
    /// **This is a placeholder since rustdoc server can not compile latest gtk yet
    /// The actual signature looks like this:**
    /// ```rust
    /// pub fn delegate(&'static self) -> glib::Sender<(gdk4::gio::SimpleAction, Option<glib::Variant>)>
    /// ```
    #[cfg(not(feature = "latest-gtk"))]
    pub fn delegate(&'static self) {}

    /// Delegate GTK actions as gstore::Actions to this store.
    #[cfg(feature = "latest-gtk")]
    pub fn delegate(
        &'static mut self,
    ) -> glib::Sender<(gdk4::gio::SimpleAction, Option<glib::Variant>)> {
        let (sender, receiver) = glib::MainContext::channel::<(
            gdk4::gio::SimpleAction,
            Option<glib::Variant>,
        )>(glib::PRIORITY_HIGH);
        receiver.attach(None, move |(action, argument)| {
            debug!("Delegate gtk action {:?} {:?}.", action, argument);
            self.dispatch(action.name().to_string(), argument);
            glib::Continue(true)
        });
        sender
    }
}

struct Selector<S: std::fmt::Debug + Clone + Default + 'static> {
    name: String,
    full: bool,
    selector: Box<dyn Fn(&S) -> S + 'static>,
    last_state: S,
    callback: Box<dyn Fn(&S) + 'static>,
}

impl<S: std::fmt::Debug + Clone + Default + 'static> Selector<S> {
    fn new(
        name: &str,
        full: bool,
        selector: impl Fn(&S) -> S + 'static,
        last_state: S,
        callback: impl Fn(&S) + 'static,
    ) -> Self {
        Selector {
            name: name.to_string(),
            full,
            selector: Box::new(selector),
            last_state,
            callback: Box::new(callback),
        }
    }
}

impl<S: std::fmt::Debug + Clone + Default + 'static> std::fmt::Debug for Selector<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Selector")
            .field("name", &self.name)
            .finish()
    }
}

/// A Middleware allows to handle actions before and after state mutation.
///
/// This allows implementing side effects for actions.
pub trait Middleware<S: std::fmt::Debug + Clone + Default + PartialEq + Eq + 'static> {
    fn pre_reduce(&self, _: &Action, _: &S) {}
    fn post_reduce(&self, _: &Action, _: &S) {}
}

#[macro_export]
macro_rules! dispatch {
    (
        $action:expr $(, $argument:expr)?
    ) => {{
        let action = $action;
        let mut argument = None;
        $(
        argument = Some(glib::ToVariant::to_variant(&$argument));
        )?
        store().dispatch(action.to_string(), argument);
    }};
}

#[macro_export]
macro_rules! select_state {
    (
        $name:expr, $selector:expr, $callback:expr
    ) => {
        store().select($name, $selector, $callback);
    };
}

#[macro_export]
macro_rules! select {
    (
        |$state:ident| $($selector:expr),*$(,)? => $callback:expr
    ) => {
        #[allow(clippy::redundant_closure_call)]
        store().select(
            vec![
                $(
                stringify!($selector)
                ),*
            ].join(", ").as_str(),
            |s| {
                let mut $state: State = Default::default();
                $(
                let sel = |$state: &State| $selector.clone();
                $selector = sel(s);
                )*
                $state
            },
            $callback,
        );
    };
}

#[macro_export]
macro_rules! store {
    (
        $state:ty
    ) => {
        pub type Store = gstore::Store<$state>;

        static mut STORE: Option<Store> = None;

        /// Initialize the store and global state
        ///
        /// # Arguments
        /// - default_state: The initial state.
        /// - reducer: Handle actions and mutate the state
        /// - middlewares: Pre- and post-reduce handlers
        pub fn init_store(
            default_state: $state,
            reducer: impl Fn(&gstore::Action, &mut $state) + 'static,
            middlewares: Vec<Box<dyn gstore::Middleware<$state>>>,
        ) {
            unsafe {
                STORE = Some(Store::new(default_state, reducer, middlewares));
                STORE.as_mut().unwrap().dispatch(gstore::INIT.into(), None);
            }
        }

        /// Get a static reference to the store
        pub fn store() -> &'static mut Store {
            unsafe { STORE.as_mut().expect("Store is not initialized!") }
        }
    };
}