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
358
359
360
361
362
363
364
365
366
367
368
369
370
#![doc = include_str!("../readme.md")]

use crossbeam::channel::{SendError, Sender};
use rat_widget::button::ButtonOutcome;
use rat_widget::event::{
    CalOutcome, ConsumedEvent, DoubleClickOutcome, EditOutcome, FileOutcome, Outcome,
    ScrollOutcome, TabbedOutcome, TextOutcome,
};
use rat_widget::menuline::MenuOutcome;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use std::fmt::Debug;

pub(crate) mod control_queue;
mod framework;
pub mod poll;
pub(crate) mod poll_queue;
mod run_config;
pub mod terminal;
mod threadpool;
pub mod timer;

use crate::control_queue::ControlQueue;
use crate::threadpool::ThreadPool;
use crate::timer::{TimeOut, TimerDef, TimerHandle, Timers};
use rat_widget::focus::Focus;

pub use framework::*;
pub use run_config::*;
pub use threadpool::Cancel;

/// Result of event-handling.
///
/// The macro
/// [rat-event::flow!](https://docs.rs/rat-event/latest/rat_event/macro.flow.html)
/// provides control-flow using this enum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[must_use]
pub enum Control<Message> {
    /// Continue with event-handling.
    /// In the event-loop this waits for the next event.
    Continue,
    /// Break event-handling without repaint.
    /// In the event-loop this waits for the next event.
    Unchanged,
    /// Break event-handling and repaints/renders the application.
    /// In the event-loop this calls `render`.
    Changed,
    /// Handle an application defined event. This calls `message`
    /// to distribute the message throughout the application.
    ///
    /// This helps with interactions between parts of the
    /// application.
    Message(Message),
    /// Quit the application.
    Quit,
}

impl<Message> ConsumedEvent for Control<Message> {
    fn is_consumed(&self) -> bool {
        !matches!(self, Control::Continue)
    }
}

impl<Message> From<Outcome> for Control<Message> {
    fn from(value: Outcome) -> Self {
        match value {
            Outcome::Continue => Control::Continue,
            Outcome::Unchanged => Control::Unchanged,
            Outcome::Changed => Control::Changed,
        }
    }
}

impl<Message> From<bool> for Control<Message> {
    fn from(value: bool) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<MenuOutcome> for Control<Message> {
    fn from(value: MenuOutcome) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<ButtonOutcome> for Control<Message> {
    fn from(value: ButtonOutcome) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<TextOutcome> for Control<Message> {
    fn from(value: TextOutcome) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<ScrollOutcome> for Control<Message> {
    fn from(value: ScrollOutcome) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<DoubleClickOutcome> for Control<Message> {
    fn from(value: DoubleClickOutcome) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<EditOutcome> for Control<Message> {
    fn from(value: EditOutcome) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<FileOutcome> for Control<Message> {
    fn from(value: FileOutcome) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<TabbedOutcome> for Control<Message> {
    fn from(value: TabbedOutcome) -> Self {
        Outcome::from(value).into()
    }
}

impl<Message> From<CalOutcome> for Control<Message> {
    fn from(value: CalOutcome) -> Self {
        Outcome::from(value).into()
    }
}

///
/// A trait for application level widgets.
///
/// This trait is an anlog to ratatui's StatefulWidget, and
/// does only the rendering part. It's extended with all the
/// extras needed in an application.
///
#[allow(unused_variables)]
pub trait AppWidget<Global, Message, Error>
where
    Message: 'static + Send + Debug,
    Error: 'static + Send + Debug,
{
    /// Type of the State.
    type State: AppState<Global, Message, Error> + Debug;

    /// Renders an application widget.
    fn render(
        &self,
        area: Rect,
        buf: &mut Buffer,
        state: &mut Self::State,
        ctx: &mut RenderContext<'_, Global>,
    ) -> Result<(), Error>;
}

///
/// Eventhandling for application level widgets.
///
/// This one collects all currently defined events.
/// Implement this one on the state struct.
///
#[allow(unused_variables)]
pub trait AppState<Global, Message, Error>
where
    Message: 'static + Send + Debug,
    Error: 'static + Send + Debug,
{
    /// Initialize the application. Runs before the first repaint.
    fn init(&mut self, ctx: &mut AppContext<'_, Global, Message, Error>) -> Result<(), Error> {
        Ok(())
    }

    /// Timeout event.
    fn timer(
        &mut self,
        event: &TimeOut,
        ctx: &mut AppContext<'_, Global, Message, Error>,
    ) -> Result<Control<Message>, Error> {
        Ok(Control::Continue)
    }

    /// Crossterm event.
    fn crossterm(
        &mut self,
        event: &crossterm::event::Event,
        ctx: &mut AppContext<'_, Global, Message, Error>,
    ) -> Result<Control<Message>, Error> {
        Ok(Control::Continue)
    }

    /// Process a message.
    fn message(
        &mut self,
        event: &mut Message,
        ctx: &mut AppContext<'_, Global, Message, Error>,
    ) -> Result<Control<Message>, Error> {
        Ok(Control::Continue)
    }

    /// Do error handling.
    fn error(
        &self,
        event: Error,
        ctx: &mut AppContext<'_, Global, Message, Error>,
    ) -> Result<Control<Message>, Error> {
        Ok(Control::Continue)
    }
}

/// A collection of context data used by the application.
#[derive(Debug)]
pub struct AppContext<'a, Global, Message, Error>
where
    Message: 'static + Send + Debug,
    Error: 'static + Send + Debug,
{
    /// Some global state for the application.
    pub g: &'a mut Global,
    /// Can be set to hold a Focus, if needed.
    pub focus: Option<Focus>,

    /// Application timers.
    pub(crate) timers: &'a Timers,
    /// Background tasks.
    pub(crate) tasks: &'a ThreadPool<Message, Error>,
    /// Queue foreground tasks.
    pub(crate) queue: &'a ControlQueue<Message, Error>,
}

/// A collection of context data used for rendering.
#[derive(Debug)]
pub struct RenderContext<'a, Global> {
    /// Some global state for the application.
    pub g: &'a mut Global,
    /// Current timeout that triggered the repaint.
    pub timeout: Option<TimeOut>,
    /// Frame counter.
    pub count: usize,
    /// Output cursor position. Set after rendering is complete.
    pub cursor: Option<(u16, u16)>,

    /// Application timers.
    pub(crate) timers: &'a Timers,
}

impl<'a, Global, Message, Error> AppContext<'a, Global, Message, Error>
where
    Message: 'static + Send + Debug,
    Error: 'static + Send + Debug,
{
    /// Add a timer.
    #[inline]
    pub fn add_timer(&self, t: TimerDef) -> TimerHandle {
        self.timers.add(t)
    }

    /// Remove a timer.
    #[inline]
    pub fn remove_timer(&self, tag: TimerHandle) {
        self.timers.remove(tag);
    }

    /// Replace a timer.
    /// Remove the old timer and create a new one.
    /// If the old timer no longer exists it just creates the new one.
    #[inline]
    pub fn replace_timer(&self, h: Option<TimerHandle>, t: TimerDef) -> TimerHandle {
        if let Some(h) = h {
            self.remove_timer(h);
        }
        self.add_timer(t)
    }

    /// Add a background worker task.
    ///
    /// ```rust ignore
    /// let cancel = ctx.spawn(|cancel, send| {
    ///     // ... do stuff
    ///     Ok(Control::Continue)
    /// });
    /// ```
    #[inline]
    pub fn spawn(
        &self,
        task: impl FnOnce(
                Cancel,
                &Sender<Result<Control<Message>, Error>>,
            ) -> Result<Control<Message>, Error>
            + Send
            + 'static,
    ) -> Result<Cancel, SendError<()>>
    where
        Message: 'static + Send + Debug,
        Error: 'static + Send + Debug,
    {
        self.tasks.send(Box::new(task))
    }

    /// Queue additional results.
    #[inline]
    pub fn queue(&self, ctrl: impl Into<Control<Message>>) {
        self.queue.push(Ok(ctrl.into()), None);
    }

    /// Queue an error.
    #[inline]
    pub fn queue_err(&self, err: Error) {
        self.queue.push(Err(err), None);
    }

    /// Access the focus-field.
    ///
    /// # Panic
    /// Panics if no focus has been set.
    #[inline]
    pub fn focus(&self) -> &Focus {
        self.focus.as_ref().expect("focus")
    }

    /// Access the focus-field.
    ///
    /// # Panic
    /// Panics if no focus has been set.
    #[inline]
    pub fn focus_mut(&mut self) -> &mut Focus {
        self.focus.as_mut().expect("focus")
    }
}

impl<'a, Global> RenderContext<'a, Global> {
    /// Add a timer.
    #[inline]
    pub fn add_timer(&self, t: TimerDef) -> TimerHandle {
        self.timers.add(t)
    }

    /// Remove a timer.
    #[inline]
    pub fn remove_timer(&self, tag: TimerHandle) {
        self.timers.remove(tag)
    }

    /// Replace a timer.
    #[inline]
    pub fn replace_timer(&self, h: Option<TimerHandle>, t: TimerDef) -> TimerHandle {
        if let Some(h) = h {
            self.remove_timer(h);
        }
        self.add_timer(t)
    }

    /// Set the cursor, if the given value is Some.
    pub fn set_screen_cursor(&mut self, cursor: Option<(u16, u16)>) {
        if let Some(c) = cursor {
            self.cursor = Some(c);
        }
    }
}

///
/// Event-handler traits and Keybindings.
///
pub mod event {
    pub use rat_widget::event::{ct_event, try_flow};
}