tty-interface 4.0.2

Provides simple TTY-based interface capabilities including partial re-renders of multi-line displays.
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
use std::collections::{BTreeMap, BTreeSet};

use crate::{Position, Style};

/// A cell in the terminal's column/line grid composed of text and optional style.
#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) struct Cell {
    grapheme: String,
    style: Option<Style>,
}

impl Cell {
    /// This cell's text content.
    pub(crate) fn grapheme(&self) -> &str {
        &self.grapheme
    }

    /// If available, this cell's styling.
    pub(crate) fn style(&self) -> Option<&Style> {
        self.style.as_ref()
    }
}

/// The terminal interface's contents with comparison capabilities.
#[derive(Clone)]
pub(crate) struct State {
    cells: BTreeMap<Position, Cell>,
    dirty: BTreeSet<Position>,
}

impl State {
    /// Initialize a new, empty terminal state.
    pub(crate) fn new() -> State {
        State {
            cells: BTreeMap::new(),
            dirty: BTreeSet::new(),
        }
    }

    /// Update a particular cell's grapheme.
    pub(crate) fn set_text(&mut self, position: Position, grapheme: &str) {
        self.handle_cell_update(position, grapheme, None);
    }

    /// Update a particular cell's grapheme and styling.
    pub(crate) fn set_styled_text(&mut self, position: Position, grapheme: &str, style: Style) {
        self.handle_cell_update(position, grapheme, Some(style));
    }

    /// Updates state and queues dirtied positions, if they've changed.
    fn handle_cell_update(&mut self, position: Position, grapheme: &str, style: Option<Style>) {
        let new_cell = Cell {
            grapheme: grapheme.to_string(),
            style,
        };

        // If this cell is unchanged, do not mark it dirty
        if Some(&new_cell) == self.cells.get(&position) {
            return;
        }

        self.dirty.insert(position);
        self.cells.insert(position, new_cell);
    }

    /// Clears all cells in the specified line.
    pub(crate) fn clear_line(&mut self, line: u16) {
        self.handle_cell_clears(|position| position.y() == line);
    }

    /// Clears cells in the line from the specified position.
    pub(crate) fn clear_rest_of_line(&mut self, from: Position) {
        self.handle_cell_clears(|position| position.y() == from.y() && position.x() >= from.x());
    }

    /// Clears cells in the interface from the specified position.
    pub(crate) fn clear_rest_of_interface(&mut self, from: Position) {
        self.handle_cell_clears(|position| *position >= &from);
    }

    /// Clears cells matching the specified predicate, marking them dirtied for re-render.
    fn handle_cell_clears<P: FnMut(&&Position) -> bool>(&mut self, filter_predicate: P) {
        let cells = self.cells.keys();
        let deleted_cells = cells.filter(filter_predicate);
        let cell_positions: Vec<Position> = deleted_cells.copied().collect();

        for position in cell_positions {
            self.cells.remove(&position);
            self.dirty.insert(position);
        }
    }

    /// Marks any dirty cells as clean.
    pub(crate) fn clear_dirty(&mut self) {
        self.dirty.clear()
    }

    /// Create an iterator for this state's dirty cells.
    pub(crate) fn dirty_iter(&self) -> StateIter<'_> {
        StateIter::new(self, self.dirty.clone().into_iter().collect())
    }

    /// Get the last cell's position.
    pub(crate) fn get_last_position(&self) -> Option<Position> {
        self.cells.keys().last().copied()
    }
}

/// Iterates through a subset of cells in the state.
pub(crate) struct StateIter<'a> {
    state: &'a State,
    positions: Vec<Position>,
    index: usize,
}

impl StateIter<'_> {
    /// Create a new state iterator with the specified positions starting from the first position.
    fn new(state: &State, positions: Vec<Position>) -> StateIter<'_> {
        StateIter {
            state,
            positions,
            index: 0,
        }
    }
}

impl Iterator for StateIter<'_> {
    type Item = (Position, Option<Cell>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.positions.len() {
            let position = self.positions[self.index];
            let cell = self.state.cells.get(&position).cloned();

            self.index += 1;
            Some((position, cell))
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{Color, Position, Style, pos};

    use super::{Cell, State};

    #[test]
    fn state_set_text() {
        let mut state = State::new();

        state.set_text(pos!(0, 0), "A");
        state.set_text(pos!(2, 0), "B");
        state.set_text(pos!(1, 1), "C");

        assert_eq!(3, state.cells.len());
        assert_eq!(
            Cell {
                grapheme: "A".to_string(),
                style: None
            },
            state.cells[&pos!(0, 0)]
        );
        assert_eq!(
            Cell {
                grapheme: "B".to_string(),
                style: None
            },
            state.cells[&pos!(2, 0)]
        );
        assert_eq!(
            Cell {
                grapheme: "C".to_string(),
                style: None
            },
            state.cells[&pos!(1, 1)]
        );

        let dirty_positions: Vec<_> = state.dirty.clone().into_iter().collect();
        assert_eq!(3, dirty_positions.len());
        assert_eq!(pos!(0, 0), dirty_positions[0]);
        assert_eq!(pos!(2, 0), dirty_positions[1]);
        assert_eq!(pos!(1, 1), dirty_positions[2]);
    }

    #[test]
    fn state_set_styled_text() {
        let mut state = State::new();

        state.set_styled_text(pos!(0, 0), "X", Style::new().set_bold(true));
        state.set_styled_text(pos!(1, 3), "Y", Style::new().set_italic(true));
        state.set_styled_text(pos!(2, 2), "Z", Style::new().set_foreground(Color::Blue));

        assert_eq!(3, state.cells.len());
        assert_eq!(
            Cell {
                grapheme: "X".to_string(),
                style: Some(Style::new().set_bold(true)),
            },
            state.cells[&pos!(0, 0)],
        );
        assert_eq!(
            Cell {
                grapheme: "Y".to_string(),
                style: Some(Style::new().set_italic(true)),
            },
            state.cells[&pos!(1, 3)],
        );
        assert_eq!(
            Cell {
                grapheme: "Z".to_string(),
                style: Some(Style::new().set_foreground(Color::Blue)),
            },
            state.cells[&pos!(2, 2)],
        );

        let dirty_positions: Vec<_> = state.dirty.clone().into_iter().collect();
        assert_eq!(3, dirty_positions.len());
        assert_eq!(pos!(0, 0), dirty_positions[0]);
        assert_eq!(pos!(2, 2), dirty_positions[1]);
        assert_eq!(pos!(1, 3), dirty_positions[2]);
    }

    #[test]
    fn state_clear_line() {
        let mut state = State::new();

        state.set_text(pos!(0, 0), "A");
        state.set_text(pos!(2, 0), "B");
        state.set_text(pos!(1, 1), "C");
        state.set_text(pos!(3, 1), "D");
        state.clear_dirty();

        assert_eq!(4, state.cells.len());
        assert_eq!(
            Cell {
                grapheme: "A".to_string(),
                style: None
            },
            state.cells[&pos!(0, 0)]
        );
        assert_eq!(
            Cell {
                grapheme: "B".to_string(),
                style: None
            },
            state.cells[&pos!(2, 0)]
        );
        assert_eq!(
            Cell {
                grapheme: "C".to_string(),
                style: None
            },
            state.cells[&pos!(1, 1)]
        );
        assert_eq!(
            Cell {
                grapheme: "D".to_string(),
                style: None
            },
            state.cells[&pos!(3, 1)]
        );

        state.clear_line(1);

        let dirty_positions: Vec<_> = state.dirty.clone().into_iter().collect();
        assert_eq!(2, dirty_positions.len());
        assert_eq!(pos!(1, 1), dirty_positions[0]);
        assert_eq!(pos!(3, 1), dirty_positions[1]);

        let line_two_cell_count = state.cells.keys().filter(|pos| pos.y() == 1).count();
        assert_eq!(0, line_two_cell_count);
    }

    #[test]
    fn state_clear_dirty() {
        let mut state = State::new();

        state.set_text(pos!(0, 0), "A");
        state.set_text(pos!(2, 0), "B");
        state.set_text(pos!(1, 1), "C");

        assert_eq!(3, state.cells.len());
        assert_eq!(
            Cell {
                grapheme: "A".to_string(),
                style: None
            },
            state.cells[&pos!(0, 0)]
        );
        assert_eq!(
            Cell {
                grapheme: "B".to_string(),
                style: None
            },
            state.cells[&pos!(2, 0)]
        );
        assert_eq!(
            Cell {
                grapheme: "C".to_string(),
                style: None
            },
            state.cells[&pos!(1, 1)]
        );
    }

    #[test]
    fn state_clear_rest_of_line() {
        let mut state = State::new();

        let content = ["ABC", "DEF", "GHI"];

        for (row, text) in content.iter().enumerate() {
            for column in 0..text.len() {
                state.set_text(
                    pos!(column as u16, row as u16),
                    text.get(column..column + 1).unwrap(),
                );
            }
        }

        state.clear_dirty();

        assert_eq!(9, state.cells.len());

        state.clear_rest_of_line(pos!(1, 1));

        assert_eq!(7, state.cells.len());

        let dirty_positions: Vec<_> = state.dirty.clone().into_iter().collect();
        assert_eq!(2, dirty_positions.len());
        assert_eq!(pos!(1, 1), dirty_positions[0]);
        assert_eq!(pos!(2, 1), dirty_positions[1]);

        let line_two_cell_count = state.cells.keys().filter(|pos| pos.y() == 1).count();
        assert_eq!(1, line_two_cell_count);
    }

    #[test]
    fn state_clear_rest_of_interface() {
        let mut state = State::new();

        let content = ["ABC", "DEF", "GHI"];

        for (row, text) in content.iter().enumerate() {
            for column in 0..text.len() {
                state.set_text(
                    pos!(column as u16, row as u16),
                    text.get(column..column + 1).unwrap(),
                );
            }
        }

        state.clear_dirty();

        assert_eq!(9, state.cells.len());

        state.clear_rest_of_interface(pos!(1, 1));

        assert_eq!(4, state.cells.len());

        let dirty_positions: Vec<_> = state.dirty.clone().into_iter().collect();
        assert_eq!(5, dirty_positions.len());
        assert_eq!(pos!(1, 1), dirty_positions[0]);
        assert_eq!(pos!(2, 1), dirty_positions[1]);
        assert_eq!(pos!(0, 2), dirty_positions[2]);
        assert_eq!(pos!(1, 2), dirty_positions[3]);
        assert_eq!(pos!(2, 2), dirty_positions[4]);
    }

    #[test]
    fn state_dirty_iter() {
        let mut state = State::new();

        state.set_text(pos!(0, 0), "A");
        state.clear_dirty();

        state.set_text(pos!(2, 0), "B");
        state.set_text(pos!(1, 1), "C");
        state.set_text(pos!(0, 2), "D");
        state.clear_line(1);

        let mut iter = state.dirty_iter();
        assert_eq!(
            Some((
                pos!(2, 0),
                Some(Cell {
                    grapheme: "B".to_string(),
                    style: None
                })
            )),
            iter.next()
        );
        assert_eq!(Some((pos!(1, 1), None,)), iter.next());
        assert_eq!(
            Some((
                pos!(0, 2),
                Some(Cell {
                    grapheme: "D".to_string(),
                    style: None
                })
            )),
            iter.next()
        );
        assert_eq!(None, iter.next());
    }

    #[test]
    fn state_get_last_position() {
        let mut state = State::new();

        state.set_text(pos!(3, 1), "D");
        state.set_text(pos!(1, 1), "C");
        state.set_text(pos!(0, 0), "A");
        state.set_text(pos!(2, 0), "B");

        assert_eq!(pos!(3, 1), state.get_last_position().unwrap());
    }
}