tui-additions 0.4.3

Additions to the Rust TUI crate
Documentation
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::{any::Any, collections::HashMap, error::Error, fmt::Display};

use crossterm::event::KeyEvent;
use ratatui::{layout::Rect, Frame};

use super::{
    CursorState, FrameworkClean, FrameworkData, FrameworkDirection, FrameworkHistory, ItemInfo,
    State,
};

/// Struct for a declarative TUI framework
///
/// Copy & paste examples can be found
/// [here](https://github.com/siriusmart/tui-additions/tree/master/examples/framework)

#[derive(Clone)]
pub struct Framework {
    /// Selectable items, auto generated when `state` is set with `new()` or `set_state()`
    pub selectables: Vec<Vec<(usize, usize)>>,
    /// Global data store for the framework
    pub data: FrameworkData,
    /// Defines the layout of items on screen
    pub state: State,
    /// The state and position of cursor
    pub cursor: CursorState,
    /// Stores saved states
    pub history: Vec<FrameworkHistory>,
    /// Stores the area of the previous frame
    pub frame_area: Option<Rect>,
}

impl Framework {
    /// Clears `self.history`
    pub fn clear_history(&mut self) {
        self.history.clear();
    }

    /// Save current state
    pub fn push_history(&mut self) {
        self.history.push(FrameworkHistory {
            selectables: self.selectables.clone(),
            data: self.data.state.clone(),
            state: self.state.clone(),
            cursor: self.cursor,
        });
    }

    /// Removes the last history and returns it
    pub fn pop_history(&mut self) -> Option<FrameworkHistory> {
        self.history.pop()
    }

    /// Revert self to last save (if there is)
    pub fn revert_last_history(&mut self) -> Result<(), FrameworkError> {
        let history = match self.history.pop() {
            None => return Err(FrameworkError::NoSuchSave),
            Some(history) => history,
        };

        self.selectables = history.selectables;
        self.data.state = history.data;
        self.state = history.state;
        self.cursor = history.cursor;

        Ok(())
    }

    /// Revert self to history at index
    pub fn revert_history(&mut self, index: usize) -> Result<(), FrameworkError> {
        if index >= self.history.len() {
            return Err(FrameworkError::NoSuchSave);
        }

        let history = self.history.remove(index);

        self.selectables = history.selectables;
        self.data.state = history.data;
        self.state = history.state;
        self.cursor = history.cursor;

        Ok(())
    }
}

impl Framework {
    pub fn is_selected(&self) -> bool {
        self.cursor.is_selected()
    }

    pub fn is_hover(&self) -> bool {
        self.cursor.is_hover()
    }

    pub fn is_none(&self) -> bool {
        self.cursor.is_none()
    }
}

impl Framework {
    /// Create a new Framework struct
    pub fn new(state: State) -> Self {
        Self {
            selectables: state.selectables(),
            data: FrameworkData::default(),
            state,
            frame_area: None,
            cursor: CursorState::default(),
            history: Vec::new(),
        }
    }

    /// Set `self.state` and also update `self.selectables`
    pub fn set_state(&mut self, state: State) {
        self.state = state;
        self.selectables = self.state.selectables();
    }

    /// Render every item to screen
    pub fn render(&mut self, frame: &mut Frame) {
        let area = frame.area();
        self.frame_area = Some(area);

        let chunks = self.state.get_chunks(area);

        let selected = self.cursor.selected(&self.selectables);
        let hover = self.cursor.hover(&self.selectables);

        // actually rendering the stuff
        self.render_raw(frame, &chunks, selected, hover, false);
        self.render_raw(frame, &chunks, selected, hover, true);
    }

    /// Render to screen with more controls
    pub fn render_raw(
        &mut self,
        frame: &mut Frame,
        chunks: &[Vec<Rect>],
        selected: Option<(usize, usize)>,
        hover: Option<(usize, usize)>,
        popup_render: bool,
    ) {
        let (mut frameworkclean, state) = self.split_clean();

        for (y, (row, row_chunks)) in state.0.iter_mut().zip(chunks.iter()).enumerate() {
            for (x, (row_item, item_chunk)) in
                row.items.iter_mut().zip(row_chunks.iter()).enumerate()
            {
                row_item.item.render(
                    frame,
                    &mut frameworkclean,
                    *item_chunk,
                    // Some((x, y)) == selected,
                    // Some((x, y)) == hover,
                    popup_render,
                    ItemInfo {
                        selected: Some((x, y)) == selected,
                        hover: Some((x, y)) == hover,
                        x,
                        y,
                    },
                );
            }
        }
    }

    /// Render only one item
    pub fn render_only(&mut self, frame: &mut Frame, x: usize, y: usize) {
        let chunk = self.state.get_chunks(frame.area())[y][x];

        let selected = self.cursor.selected(&self.selectables);
        let hover = self.cursor.hover(&self.selectables);

        self.render_only_raw(frame, x, y, chunk, false, selected, hover);
        self.render_only_raw(frame, x, y, chunk, true, selected, hover);
    }

    /// Render multiple items
    ///
    /// Location is in a format of `Vec<(x, y)>`
    pub fn render_only_multiple(&mut self, frame: &mut Frame, locations: &[(usize, usize)]) {
        let chunks = self.state.get_chunks(frame.area());

        let selected = self.cursor.selected(&self.selectables);
        let hover = self.cursor.hover(&self.selectables);

        locations.iter().for_each(|(x, y)| {
            self.render_only_raw(frame, *x, *y, chunks[*y][*x], false, selected, hover);
        });

        locations.iter().for_each(|(x, y)| {
            self.render_only_raw(frame, *x, *y, chunks[*y][*x], true, selected, hover);
        });
    }

    /// Render only with more controls
    pub fn render_only_raw(
        &mut self,
        frame: &mut Frame,
        x: usize,
        y: usize,
        chunk: Rect,
        popup_render: bool,
        selected: Option<(usize, usize)>,
        hover: Option<(usize, usize)>,
    ) {
        let (mut frameworkclean, state) = self.split_clean();
        state.get_mut(x, y).render(
            frame,
            &mut frameworkclean,
            chunk,
            popup_render,
            ItemInfo {
                selected: selected == Some((x, y)),
                hover: hover == Some((x, y)),
                x,
                y,
            },
        )
    }

    /// Send key input to selected object, returns an `Err(())` when no objct is selected
    pub fn key_input(&mut self, key: KeyEvent) -> Result<(), Box<dyn Error>> {
        let selected = self.cursor.selected(&self.selectables);
        let (mut frameworkclean, state) = self.split_clean();

        if let Some((x, y)) = selected {
            state.get_mut(x, y).key_event(
                &mut frameworkclean,
                key,
                ItemInfo {
                    selected: true,
                    hover: false,
                    x,
                    y,
                },
            )?;
        }

        Ok(())
    }

    /// Handles when mouse is clicked
    pub fn mouse_event(&mut self, col: u16, row: u16) -> bool {
        let chunks = match self.frame_area {
            Some(area) => self.state.get_chunks(area),
            None => return false,
        };

        // loops over selectable items only
        for (y, row_items) in self.state.0.iter().enumerate() {
            for x in 0..row_items.items.len() {
                let chunk = chunks[y][x];
                // guard gate to only do stuff if clicking on item
                if !chunk.intersects(Rect::new(col, row, 1, 1)) {
                    continue;
                }

                // pass click event to item only if it is already selected
                if self.cursor.selected(&self.selectables) == Some((x, y)) {
                    let (mut clean, state) = self.split_clean();
                    let a = state.get_mut(x, y).mouse_passthrough(
                        &mut clean,
                        true,
                        col - chunk.x,
                        row - chunk.y,
                        col,
                        row,
                    );
                    let b = state.get_mut(x, y).mouse_event(
                        &mut clean,
                        col - chunk.x,
                        row - chunk.y,
                        col,
                        row,
                    );
                    return a || b;
                } else {
                    let (mut clean, state) = self.split_clean();
                    state.get_mut(x, y).mouse_passthrough(
                        &mut clean,
                        false,
                        col - chunk.x,
                        row - chunk.y,
                        col,
                        row,
                    );
                }

                if self.cursor.hover(&self.selectables) == Some((x, y)) {
                    return self.select().is_ok();
                }

                let mut selectable_index = None;

                for (sel_row, row_items) in self.selectables.iter().enumerate() {
                    for (sel_col, (x2, y2)) in row_items.iter().enumerate() {
                        if (x2, y2) == (&x, &y) {
                            selectable_index = Some((sel_col, sel_row))
                        }
                    }
                }

                if let Some(sel_index) = selectable_index {
                    self.deselect().ok();
                    self.cursor = CursorState::to_hover(sel_index);
                }

                return true;
            }
        }

        self.deselect().ok();
        self.cursor = CursorState::default();
        true
    }

    /// Send message to selected object, returns true if anything updated
    pub fn message(&mut self, data: HashMap<String, Box<dyn Any>>) -> bool {
        let selected = self.cursor.selected(&self.selectables);
        let (mut frameworkclean, state) = self.split_clean();

        if let Some((x, y)) = selected {
            return state.get_mut(x, y).message(&mut frameworkclean, data);
        }

        false
    }

    pub fn load(&mut self) -> Result<(), Box<dyn Error>> {
        let selected = self.cursor.selected(&self.selectables);
        let hover = self.cursor.hover(&self.selectables);
        let (mut frameworkclean, state) = self.split_clean();

        for (y, row) in state.0.iter_mut().enumerate() {
            for (x, row_item) in row.items.iter_mut().enumerate() {
                row_item.item.load_item(
                    &mut frameworkclean,
                    ItemInfo {
                        selected: Some((x, y)) == selected,
                        hover: Some((x, y)) == hover,
                        x,
                        y,
                    },
                )?;
            }
        }

        Ok(())
    }

    pub fn load_only(&mut self, x: usize, y: usize) -> Result<(), Box<dyn Error>> {
        let selected = self.cursor.selected(&self.selectables);
        let hover = self.cursor.hover(&self.selectables);
        let (mut frameworkclean, state) = self.split_clean();

        state.get_mut(x, y).load_item(
            &mut frameworkclean,
            ItemInfo {
                selected: Some((x, y)) == selected,
                hover: Some((x, y)) == hover,
                x,
                y,
            },
        )
    }

    pub fn load_only_multiple(&mut self, locations: &[(usize, usize)]) {
        let selected = self.cursor.selected(&self.selectables);
        let hover = self.cursor.hover(&self.selectables);
        let (mut frameworkclean, state) = self.split_clean();

        locations.iter().for_each(|(x, y)| {
            let _ = state.get_mut(*x, *y).load_item(
                &mut frameworkclean,
                ItemInfo {
                    selected: Some((*x, *y)) == selected,
                    hover: Some((*x, *y)) == hover,
                    x: *x,
                    y: *y,
                },
            );
        })
    }
}

impl Framework {
    /// Split `Framework` into `FrameworkClean` and `&mut State`
    pub fn split_clean(&mut self) -> (FrameworkClean<'_>, &mut State) {
        self.into()
    }
}

impl Framework {
    /// Move cursor in corresponding direction, will return an `Err(E)` if something is selected
    /// and the cursor is not free to move around
    pub fn r#move(&mut self, direction: FrameworkDirection) -> Result<(), FrameworkError> {
        self.cursor.r#move(direction, &self.selectables)
    }

    /// Select the hovering item
    pub fn select(&mut self) -> Result<(), Box<dyn Error>> {
        if let Some((x, y)) = self.cursor.hover(&self.selectables) {
            let (mut frameworkclean, state) = self.split_clean();
            let item = state.get_mut(x, y);
            if item.select(&mut frameworkclean) {
                self.cursor.select()?;
            }
        } else {
            Err(FrameworkError::CursorStateMismatch)?;
        }

        Ok(())
    }

    /// Deselect the hovering item
    pub fn deselect(&mut self) -> Result<(), Box<dyn Error>> {
        if let Some((x, y)) = self.cursor.selected(&self.selectables) {
            let (mut frameworkclean, state) = self.split_clean();
            let item = state.get_mut(x, y);
            if item.deselect(&mut frameworkclean) {
                self.cursor.deselect()?;
            }
        } else {
            Err(FrameworkError::CursorStateMismatch)?;
        }

        Ok(())
    }
}

/// Errors that may be returned by `Framework`
#[derive(Debug)]
pub enum FrameworkError {
    /// Moving the cursor when something is selected (not allowed)
    MoveSelected,
    /// Calling `self.select()` when not hovering and `self.deselect()` when nothing is selected
    CursorStateMismatch,
    /// Not found in `self.history`, caused by incorrect index or `self.history` is empty
    NoSuchSave,
}

impl Display for FrameworkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{:?}", self))
    }
}

impl Error for FrameworkError {}