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
use crate::control_queue::ControlQueue;
use crate::poll::{PollCrossterm, PollEvents, PollTasks, PollTimers};
use crate::terminal::{CrosstermTerminal, Terminal};
use crate::threadpool::ThreadPool;
use crate::timer::Timers;
use crate::{AppContext, AppEvents, AppWidget, Control};
use crossbeam::channel::{SendError, TryRecvError};
use std::cell::RefCell;
use std::cmp::min;
use std::collections::VecDeque;
use std::fmt::{Debug, Formatter};
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
use std::time::Duration;
use std::{io, thread};

/// Captures some parameters for [crate::run_tui()].
pub struct RunConfig<App, Global, Action, Error>
where
    App: AppWidget<Global, Action, Error>,
    Action: 'static + Send + Debug,
    Error: 'static + Send + Debug,
{
    /// How many worker threads are wanted?
    /// Most of the time 1 should be sufficient to offload any gui-blocking tasks.
    pub n_threats: usize,
    /// This is the renderer that connects to the backend, and calls out
    /// for rendering the application.
    ///
    /// Defaults to RenderCrossterm.
    pub term: Box<dyn Terminal<App, Global, Action, Error>>,
    /// List of all event-handlers for the application.
    ///
    /// Defaults to PollTimers, PollCrossterm, PollTasks. Add yours here.
    pub poll: Vec<Box<dyn PollEvents<App, Global, Action, Error>>>,
}

impl<App, Global, Action, Error> Debug for RunConfig<App, Global, Action, Error>
where
    App: AppWidget<Global, Action, Error>,
    Action: 'static + Send + Debug,
    Error: 'static + Send + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RunConfig")
            .field("n_threads", &self.n_threats)
            .field("render", &"...")
            .field("events", &"...")
            .finish()
    }
}

impl<App, Global, Action, Error> RunConfig<App, Global, Action, Error>
where
    App: AppWidget<Global, Action, Error>,
    Action: 'static + Send + Debug,
    Error: 'static + Send + Debug + From<io::Error> + From<TryRecvError>,
{
    /// New configuration with some defaults.
    #[allow(clippy::should_implement_trait)]
    pub fn default() -> Result<Self, Error> {
        Ok(Self {
            n_threats: 1,
            term: Box::new(CrosstermTerminal::new()?),
            poll: vec![
                Box::new(PollTimers),
                Box::new(PollCrossterm),
                Box::new(PollTasks),
            ],
        })
    }

    /// Number of threads.
    pub fn threads(mut self, n: usize) -> Self {
        self.n_threats = n;
        self
    }

    /// Terminal is a rat-salsa::terminal::Terminal not a ratatui::Terminal.
    pub fn term(mut self, term: impl Terminal<App, Global, Action, Error> + 'static) -> Self {
        self.term = Box::new(term);
        self
    }

    /// Remove default PollEvents.
    pub fn no_poll(mut self) -> Self {
        self.poll.clear();
        self
    }

    /// Add poll
    pub fn poll(mut self, poll: impl PollEvents<App, Global, Action, Error> + 'static) -> Self {
        self.poll.push(Box::new(poll));
        self
    }
}

/// Handle for which EventPoll wants to be read.
#[derive(Debug)]
struct PollHandle(usize);

/// Queue for which EventPoll wants to be read.
#[derive(Debug, Default)]
struct PollQueue {
    queue: RefCell<VecDeque<PollHandle>>,
}

impl PollQueue {
    /// Empty
    fn is_empty(&self) -> bool {
        self.queue.borrow().is_empty()
    }

    /// Take the next handle.
    fn take(&self) -> Option<PollHandle> {
        self.queue.borrow_mut().pop_front()
    }

    /// Push a handle to the queue.
    fn push(&self, poll: PollHandle) {
        self.queue.borrow_mut().push_back(poll);
    }
}

fn _run_tui<App, Global, Action, Error>(
    mut app: App,
    global: &mut Global,
    state: &mut App::State,
    cfg: &mut RunConfig<App, Global, Action, Error>,
) -> Result<(), Error>
where
    App: AppWidget<Global, Action, Error>,
    Action: Send + 'static + Debug,
    Error: Send + 'static + Debug + From<TryRecvError> + From<io::Error> + From<SendError<()>>,
{
    let term = cfg.term.as_mut();
    let poll = &mut cfg.poll;

    let timers = Timers::default();
    let tasks = ThreadPool::new(cfg.n_threats);
    let queue = ControlQueue::default();

    let mut appctx = AppContext {
        g: global,
        timeout: None,
        timers: &timers,
        tasks: &tasks,
        queue: &queue,
    };

    let poll_queue = PollQueue::default();
    let mut poll_sleep = Duration::from_millis(10);

    // init state
    state.init(&mut appctx)?;

    // initial render
    term.render(&mut app, state, &mut appctx)?;

    'ui: loop {
        // panic on worker panic
        if !tasks.check_liveness() {
            dbg!("worker panicked");
            break 'ui;
        }

        if queue.is_empty() {
            if poll_queue.is_empty() {
                for (n, p) in poll.iter_mut().enumerate() {
                    match p.poll(&mut appctx) {
                        Ok(true) => {
                            poll_queue.push(PollHandle(n));
                        }
                        Ok(false) => {}
                        Err(e) => {
                            appctx.queue_result(Err(e));
                        }
                    }
                }
            }

            if poll_queue.is_empty() {
                let t = if let Some(timer_sleep) = timers.sleep_time() {
                    min(timer_sleep, poll_sleep)
                } else {
                    poll_sleep
                };
                thread::sleep(t);
                if poll_sleep < Duration::from_millis(10) {
                    // Back off slowly.
                    poll_sleep += Duration::from_micros(100);
                }
            } else {
                // Shorter sleep immediately after an event.
                poll_sleep = Duration::from_micros(100);
            }
        }

        if queue.is_empty() {
            if let Some(h) = poll_queue.take() {
                let r = poll[h.0].read_exec(&mut app, state, term, &mut appctx);
                appctx.queue_result(r);
            }
        }

        let n = queue.take();
        match n {
            None => {}
            Some(Err(e)) => {
                let r = state.error(e, &mut appctx);
                appctx.queue_result(r);
            }
            Some(Ok(Control::Continue)) => {}
            Some(Ok(Control::Break)) => {}
            Some(Ok(Control::Repaint)) => {
                if let Err(e) = term.render(&mut app, state, &mut appctx) {
                    appctx.queue_result(Err(e));
                }
            }
            Some(Ok(Control::Action(mut a))) => {
                let r = state.action(&mut a, &mut appctx);
                appctx.queue_result(r);
            }
            Some(Ok(Control::Quit)) => {
                break 'ui;
            }
        }
    }

    Ok(())
}

/// Run the event-loop
///
/// The shortest version I can come up with:
/// ```
/// use crossterm::event::Event;
/// use rat_salsa::event::{ct_event, flow_ok};
/// use rat_salsa::{run_tui, AppContext, AppEvents, AppWidget, Control, RenderContext, RunConfig};
/// use ratatui::buffer::Buffer;
/// use ratatui::layout::Rect;
/// use ratatui::style::Stylize;
/// use ratatui::text::Span;
/// use ratatui::widgets::Widget;
///
/// #[derive(Debug)]
/// struct MainApp;
///
/// #[derive(Debug)]
/// struct MainState;
///
/// impl AppWidget<(), (), anyhow::Error> for MainApp {
///     type State = MainState;
///
///     fn render(
///         &self,
///         area: Rect,
///         buf: &mut Buffer,
///         _state: &mut Self::State,
///         _ctx: &mut RenderContext<'_, ()>,
///     ) -> Result<(), anyhow::Error> {
///         Span::from("Hello world")
///             .white()
///             .on_blue()
///             .render(area, buf);
///         Ok(())
///     }
/// }
///
/// impl AppEvents<(), (), anyhow::Error> for MainState {
///     fn crossterm(
///         &mut self,
///         event: &Event,
///         _ctx: &mut AppContext<'_, (), (), anyhow::Error>,
///     ) -> Result<Control<()>, anyhow::Error> {
///         flow_ok!(match event {
///             ct_event!(key press 'q') => Control::Quit,
///             _ => Control::Continue,
///         });
///
///         Ok(Control::Continue)
///     }
/// }
///
/// fn main() -> Result<(), anyhow::Error> {
///     run_tui(MainApp, &mut (), &mut MainState, RunConfig::default()?)?;
///     Ok(())
/// }
///
/// ```
///
/// Maybe `examples/minimal.rs` is more useful.
///
pub fn run_tui<Widget, Global, Action, Error>(
    app: Widget,
    global: &mut Global,
    state: &mut Widget::State,
    mut cfg: RunConfig<Widget, Global, Action, Error>,
) -> Result<(), Error>
where
    Widget: AppWidget<Global, Action, Error>,
    Action: Send + 'static + Debug,
    Error: Send + 'static + Debug + From<TryRecvError> + From<io::Error> + From<SendError<()>>,
{
    cfg.term.init()?;

    let r = match catch_unwind(AssertUnwindSafe(|| _run_tui(app, global, state, &mut cfg))) {
        Ok(v) => v,
        Err(e) => {
            _ = cfg.term.shutdown();
            resume_unwind(e);
        }
    };

    cfg.term.shutdown()?;

    r
}