rat_salsa/
lib.rs

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
//! Current status: BETA
//!
#![doc = include_str!("../readme.md")]

use crossbeam::channel::{SendError, Sender};
use rat_widget::event::{ConsumedEvent, Outcome};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use std::cmp::Ordering;
use std::fmt::Debug;
use std::mem;

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 enum for event handling.
///
/// The result of an event is processed immediately after the
/// function returns, before polling new events. This way an action
/// can trigger another action which triggers the repaint without
/// other events intervening.
///
/// If you ever need to return more than one result from event-handling,
/// you can hand it to AppContext/RenderContext::queue(). Events
/// in the queue are processed in order, and the return value of
/// the event-handler comes last. If an error is returned, everything
/// send to the queue will be executed nonetheless.
///
/// __See__
///
/// - [flow!](rat_widget::event::flow)
/// - [try_flow!](rat_widget::event::try_flow)
/// - [ConsumedEvent]
#[derive(Debug, Clone, Copy)]
#[must_use]
#[non_exhaustive]
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> Eq for Control<Message> {}

impl<Message> PartialEq for Control<Message> {
    fn eq(&self, other: &Self) -> bool {
        mem::discriminant(self) == mem::discriminant(other)
    }
}

impl<Message> Ord for Control<Message> {
    fn cmp(&self, other: &Self) -> Ordering {
        match self {
            Control::Continue => match other {
                Control::Continue => Ordering::Equal,
                Control::Unchanged => Ordering::Less,
                Control::Changed => Ordering::Less,
                Control::Message(_) => Ordering::Less,
                Control::Quit => Ordering::Less,
            },
            Control::Unchanged => match other {
                Control::Continue => Ordering::Greater,
                Control::Unchanged => Ordering::Equal,
                Control::Changed => Ordering::Less,
                Control::Message(_) => Ordering::Less,
                Control::Quit => Ordering::Less,
            },
            Control::Changed => match other {
                Control::Continue => Ordering::Greater,
                Control::Unchanged => Ordering::Greater,
                Control::Changed => Ordering::Equal,
                Control::Message(_) => Ordering::Less,
                Control::Quit => Ordering::Less,
            },
            Control::Message(_) => match other {
                Control::Continue => Ordering::Greater,
                Control::Unchanged => Ordering::Greater,
                Control::Changed => Ordering::Greater,
                Control::Message(_) => Ordering::Equal,
                Control::Quit => Ordering::Less,
            },
            Control::Quit => match other {
                Control::Continue => Ordering::Greater,
                Control::Unchanged => Ordering::Greater,
                Control::Changed => Ordering::Greater,
                Control::Message(_) => Ordering::Greater,
                Control::Quit => Ordering::Equal,
            },
        }
    }
}

impl<Message> PartialOrd for Control<Message> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

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

impl<Message, T: Into<Outcome>> From<T> for Control<Message> {
    fn from(value: T) -> Self {
        let r = value.into();
        match r {
            Outcome::Continue => Control::Continue,
            Outcome::Unchanged => Control::Unchanged,
            Outcome::Changed => Control::Changed,
        }
    }
}

///
/// AppWidget mimics StatefulWidget and adds a [RenderContext]
///
pub trait AppWidget<Global, Message, Error>
where
    Message: 'static + Send,
    Error: 'static + Send,
{
    /// Type of the State.
    type State: AppState<Global, Message, Error> + ?Sized;

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

///
/// AppState packs together the currently supported event-handlers.
///
#[allow(unused_variables)]
pub trait AppState<Global, Message, Error>
where
    Message: 'static + Send,
    Error: 'static + Send,
{
    /// 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)
    }
}

///
/// Application context for event handling.
///
#[derive(Debug)]
pub struct AppContext<'a, Global, Message, Error>
where
    Message: 'static + Send,
    Error: 'static + Send,
{
    /// 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>,
}

///
/// Application context for rendering.
///
#[derive(Debug)]
pub struct RenderContext<'a, Global> {
    /// Some global state for the application.
    pub g: &'a mut Global,
    /// Frame counter.
    pub count: usize,
    /// Output cursor position. Set after rendering is complete.
    pub cursor: Option<(u16, u16)>,
}

impl<'a, Global, Message, Error> AppContext<'a, Global, Message, Error>
where
    Message: 'static + Send,
    Error: 'static + Send,
{
    /// 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,
        Error: 'static + Send,
    {
        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()));
    }

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

    /// 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> {
    /// 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);
        }
    }
}