rat_event/
lib.rs

1#![doc = include_str!("../readme.md")]
2
3use std::cmp::max;
4
5pub mod crossterm;
6pub mod util;
7
8/// All the regular and expected event-handling a widget can do.
9///
10/// All the normal key-handling, maybe dependent on an internal
11/// focus-state, all the mouse-handling.
12#[derive(Debug, Default, Clone, Copy)]
13pub struct Regular;
14
15/// Handle mouse-events only. Useful whenever you want to write new key-bindings,
16/// but keep the mouse-events.
17#[derive(Debug, Default, Clone, Copy)]
18pub struct MouseOnly;
19
20/// Popup/Overlays are a bit difficult to handle, as there is no z-order/area tree,
21/// which would direct mouse interactions. We can simulate a z-order in the
22/// event-handler by trying the things with a higher z-order first.
23///
24/// If a widget should be seen as pure overlay, it would define only a Popup
25/// event-handler. In the event-handling functions you would call all Popup
26/// event-handlers before the regular ones.
27///
28/// Example:
29/// * Context menu. If the context-menu is active, it can consume all mouse-events
30///   that fall into its range, and the widgets behind it only get the rest.
31/// * Menubar. Would define _two_ event-handlers, a regular one for all events
32///   on the main menu bar, and a popup event-handler for the menus. The event-handling
33///   function calls the popup handler first and the regular one at some time later.
34#[derive(Debug, Default, Clone, Copy)]
35pub struct Popup;
36
37/// Event-handling for a dialog like widget.
38///
39/// Similar to [Popup] but with the extra that it consumes _all_ events when active.
40/// No regular widget gets any event, and we have modal behaviour.
41#[derive(Debug, Default, Clone, Copy)]
42pub struct Dialog;
43
44/// Event-handler for double-click on a widget.
45///
46/// Events for this handler must be processed *before* calling
47/// any other event-handling routines for the same widget.
48/// Otherwise, the regular event-handling might interfere with
49/// recognition of double-clicks by consuming the first click.
50///
51/// This event-handler doesn't consume the first click, just
52/// the second one.
53#[derive(Debug, Default, Clone, Copy)]
54pub struct DoubleClick;
55
56///
57/// A very broad trait for an event handler.
58///
59/// Ratatui widgets have two separate structs, one that implements
60/// Widget/StatefulWidget and the associated State. As the StatefulWidget
61/// has a lifetime and is not meant to be kept, HandleEvent should be
62/// implemented for the state struct. It can then modify some state and
63/// the tui can be rendered anew with that changed state.
64///
65/// HandleEvent is not limited to State structs of course, any Type
66/// that wants to interact with events can implement it.
67///
68/// * Event - The actual event type.
69/// * Qualifier - The qualifier allows creating more than one event-handler
70///         for a widget.
71///
72///   This can be used as a variant of type-state, where the type given
73///   selects the widget's behaviour, or to give some external context
74///   to the widget, or to write your own key-bindings for a widget.
75///
76/// * R - Result of event-handling. This can give information to the
77///   application what changed due to handling the event. This can
78///   be very specific for each widget, but there is one general [Outcome]
79///   that describes a minimal set of results.
80///
81///   There should be one value that indicates 'I don't know this event'.
82///   This is expressed with the ConsumedEvent trait.
83///
84pub trait HandleEvent<Event, Qualifier, Return>
85where
86    Return: ConsumedEvent,
87{
88    /// Handle an event.
89    ///
90    /// * self - The widget state.
91    /// * event - Event type.
92    /// * qualifier - Event handling qualifier.
93    ///   This library defines some standard values [Regular], [MouseOnly].
94    ///   Further ideas:
95    ///     * ReadOnly
96    ///     * Special behaviour like DoubleClick, HotKey.
97    /// * Returns some result, see [Outcome]
98    fn handle(&mut self, event: &Event, qualifier: Qualifier) -> Return;
99}
100
101/// Catch all event-handler for the null state `()`.
102impl<E, Q> HandleEvent<E, Q, Outcome> for () {
103    fn handle(&mut self, _event: &E, _qualifier: Q) -> Outcome {
104        Outcome::Continue
105    }
106}
107
108/// When calling multiple event-handlers, the minimum information required
109/// from the result is consumed the event/didn't consume the event.
110///
111/// See also [flow] and [try_flow] macros.
112pub trait ConsumedEvent {
113    /// Is this the 'consumed' result.
114    fn is_consumed(&self) -> bool;
115
116    /// Or-Else chaining with `is_consumed()` as the split.
117    #[inline(always)]
118    fn or_else<F>(self, f: F) -> Self
119    where
120        F: FnOnce() -> Self,
121        Self: Sized,
122    {
123        if self.is_consumed() {
124            self
125        } else {
126            f()
127        }
128    }
129
130    /// Or-Else chaining with `is_consumed()` as the split.
131    #[inline(always)]
132    fn or_else_try<F, E>(self, f: F) -> Result<Self, E>
133    where
134        Self: Sized,
135        F: FnOnce() -> Result<Self, E>,
136    {
137        if self.is_consumed() {
138            Ok(self)
139        } else {
140            Ok(f()?)
141        }
142    }
143
144    /// And_then-chaining based on is_consumed().
145    /// Returns max(self, f()).
146    #[inline(always)]
147    fn and_then<F>(self, f: F) -> Self
148    where
149        Self: Sized + Ord,
150        F: FnOnce() -> Self,
151    {
152        if self.is_consumed() {
153            max(self, f())
154        } else {
155            self
156        }
157    }
158
159    /// And_then-chaining based on is_consumed().
160    /// Returns max(self, f()).
161    #[inline(always)]
162    fn and_then_try<F, E>(self, f: F) -> Result<Self, E>
163    where
164        Self: Sized + Ord,
165        F: FnOnce() -> Result<Self, E>,
166    {
167        if self.is_consumed() {
168            Ok(max(self, f()?))
169        } else {
170            Ok(self)
171        }
172    }
173
174    /// Then-chaining. Returns max(self, f()).
175    #[inline(always)]
176    #[deprecated(since = "1.2.2", note = "use and_then()")]
177    fn and<F>(self, f: F) -> Self
178    where
179        Self: Sized + Ord,
180        F: FnOnce() -> Self,
181    {
182        if self.is_consumed() {
183            max(self, f())
184        } else {
185            self
186        }
187    }
188
189    /// Then-chaining. Returns max(self, f()).
190    #[inline(always)]
191    #[deprecated(since = "1.2.2", note = "use and_then_try()")]
192    fn and_try<F, E>(self, f: F) -> Result<Self, E>
193    where
194        Self: Sized + Ord,
195        F: FnOnce() -> Result<Self, E>,
196    {
197        if self.is_consumed() {
198            Ok(max(self, f()?))
199        } else {
200            Ok(self)
201        }
202    }
203}
204
205impl<V, E> ConsumedEvent for Result<V, E>
206where
207    V: ConsumedEvent,
208{
209    fn is_consumed(&self) -> bool {
210        match self {
211            Ok(v) => v.is_consumed(),
212            Err(_) => true,
213        }
214    }
215}
216
217/// The baseline outcome for an event-handler.
218///
219/// A widget can define its own type, if it has more things to report.
220/// It would be nice if those types are convertible to/from Outcome.
221#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
222pub enum Outcome {
223    /// The given event has not been used at all.
224    #[default]
225    Continue,
226    /// The event has been recognized, but nothing noticeable has changed.
227    /// Further processing for this event may stop.
228    /// Rendering the ui is not necessary.
229    Unchanged,
230    /// The event has been recognized and there is some change due to it.
231    /// Further processing for this event may stop.
232    /// Rendering the ui is advised.
233    Changed,
234}
235
236impl ConsumedEvent for Outcome {
237    fn is_consumed(&self) -> bool {
238        *self != Outcome::Continue
239    }
240}
241
242/// Widgets often define functions that return bool to indicate a changed state.
243/// This converts `true` / `false` to `Outcome::Changed` / `Outcome::Unchanged`.
244impl From<bool> for Outcome {
245    fn from(value: bool) -> Self {
246        if value {
247            Outcome::Changed
248        } else {
249            Outcome::Unchanged
250        }
251    }
252}
253
254/// Breaks the control-flow if the block returns a value
255/// for which [ConsumedEvent::is_consumed] is true.
256///
257/// It does the classic `into()`-conversion and returns the result.
258///
259/// *The difference to [try_flow] is that this on doesn't Ok-wrap the result.*
260///
261/// Extras: If you add a marker as in `flow!(log ident: {...});`
262/// the result of the operation is written to the log.
263#[macro_export]
264macro_rules! flow {
265    (log $n:ident: $x:expr) => {{
266        use log::debug;
267        use $crate::ConsumedEvent;
268        let r = $x;
269        if r.is_consumed() {
270            debug!("{} {:#?}", stringify!($n), r);
271            return r.into();
272        } else {
273            debug!("{} continue", stringify!($n));
274            _ = r;
275        }
276    }};
277    ($x:expr) => {{
278        use $crate::ConsumedEvent;
279        let r = $x;
280        if r.is_consumed() {
281            return r.into();
282        } else {
283            _ = r;
284        }
285    }};
286}
287
288/// Breaks the control-flow if the block returns a value
289/// for which [ConsumedEvent::is_consumed] is true.
290///
291/// It does the classic `into()`-conversion and returns the result.
292///
293/// *The difference to [flow] is that this one Ok-wraps the result.*
294///
295/// Extras: If you add a marker as in `try_flow!(log ident: {...});`
296/// the result of the operation is written to the log.
297#[macro_export]
298macro_rules! try_flow {
299    (log $n:ident: $x:expr) => {{
300        use log::debug;
301        use $crate::ConsumedEvent;
302        let r = $x;
303        if r.is_consumed() {
304            debug!("{} {:#?}", stringify!($n), r);
305            return Ok(r.into());
306        } else {
307            debug!("{} continue", stringify!($n));
308            _ = r;
309        }
310    }};
311    ($x:expr) => {{
312        use $crate::ConsumedEvent;
313        let r = $x;
314        if r.is_consumed() {
315            return Ok(r.into());
316        } else {
317            _ = r;
318        }
319    }};
320}