minitel_ratatui/
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
use backend::WindowSize;

use ratatui::backend::Backend;
use ratatui::prelude::*;

use minitel_stum::{
    videotex::{GrayScale, SIChar, C0, C1, G0, G1},
    Minitel, MinitelRead, MinitelWrite,
};

/// Keep track of the contextual data
///
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CharKind {
    None,
    /// Last char was a normal char
    Alphabet(SIChar),
    /// Last char was a semi-graphic char
    SemiGraphic(G1),
}

impl CharKind {
    pub fn escape_code(&self) -> C0 {
        match self {
            CharKind::None => C0::NUL,
            CharKind::Alphabet(_) => C0::SI,
            CharKind::SemiGraphic(_) => C0::SO,
        }
    }
}

/// Ratatui minitel backend
pub struct MinitelBackend<S: MinitelRead + MinitelWrite> {
    pub minitel: Minitel<S>,

    cursor_position: (u16, u16),
    last_char_kind: CharKind,
    char_attributes: Vec<C1>,
    zone_attributes: Vec<C1>,
}

impl<S: MinitelRead + MinitelWrite> MinitelBackend<S> {
    pub fn new(minitel: Minitel<S>) -> Self {
        Self {
            minitel,
            cursor_position: (255, 255),
            last_char_kind: CharKind::None,
            char_attributes: Vec::new(),
            zone_attributes: Vec::new(),
        }
    }
}

impl<S: MinitelRead + MinitelWrite> Backend for MinitelBackend<S> {
    #[inline(always)]
    fn draw<'a, I>(&mut self, content: I) -> std::io::Result<()>
    where
        I: Iterator<Item = (u16, u16, &'a ratatui::buffer::Cell)>,
    {
        for (x, y, cell) in content {
            self.cursor_position.0 += 1;

            // Zone attributes: background color, invert, ...
            let mut zone_attributes = vec![match cell.bg {
                Color::Black => C1::BgBlack,
                Color::Red => C1::BgRed,
                Color::Green => C1::BgGreen,
                Color::Yellow => C1::BgYellow,
                Color::Blue => C1::BgBlue,
                Color::Magenta => C1::BgMagenta,
                Color::Cyan => C1::BgCyan,
                Color::Gray => GrayScale::Gray50.char(),
                Color::DarkGray => GrayScale::Gray40.char(),
                Color::LightRed => C1::BgRed,
                Color::LightGreen => C1::BgGreen,
                Color::LightYellow => C1::BgYellow,
                Color::LightBlue => C1::BgBlue,
                Color::LightMagenta => C1::BgMagenta,
                Color::LightCyan => C1::BgCyan,
                Color::White => C1::BgWhite,
                _ => C1::BgBlack,
            }];
            zone_attributes.push(match cell.modifier.contains(Modifier::UNDERLINED) {
                true => C1::BeginUnderline,
                false => C1::EndUnderline,
            });
            zone_attributes.push(match cell.modifier.contains(Modifier::REVERSED) {
                true => C1::InvertBg,
                false => C1::NormalBg,
            });

            // Char attributes: foreground color, blink, ...
            let mut char_attributes = Vec::new();
            char_attributes.push(match cell.fg {
                Color::Black => C1::CharBlack,
                Color::Red => C1::CharRed,
                Color::Green => C1::CharGreen,
                Color::Yellow => C1::CharYellow,
                Color::Blue => C1::CharBlue,
                Color::Magenta => C1::CharMagenta,
                Color::Cyan => C1::CharCyan,
                Color::Gray => GrayScale::Gray50.char(),
                Color::DarkGray => GrayScale::Gray40.char(),
                Color::LightRed => C1::CharRed,
                Color::LightGreen => C1::CharGreen,
                Color::LightYellow => C1::CharYellow,
                Color::LightBlue => C1::CharBlue,
                Color::LightMagenta => C1::CharMagenta,
                Color::LightCyan => C1::CharCyan,
                Color::White => C1::CharWhite,
                _ => C1::CharWhite,
            });

            if cell.modifier.contains(Modifier::RAPID_BLINK)
                || cell.modifier.contains(Modifier::SLOW_BLINK)
            {
                char_attributes.push(C1::Blink);
            }

            // Chose between a char or a semi graphic
            // The crossed out modifier is taken as prefering a semi graphic char
            let c = cell.symbol().chars().next().unwrap();
            let char_kind = if cell.modifier.contains(Modifier::CROSSED_OUT) {
                G1::approximate_char(c)
                    .map(CharKind::SemiGraphic)
                    .unwrap_or_else(|| {
                        SIChar::try_from(c)
                            .map(CharKind::Alphabet)
                            .unwrap_or(CharKind::None)
                    })
            } else {
                SIChar::try_from(c)
                    .map(CharKind::Alphabet)
                    .unwrap_or_else(|_| {
                        G1::approximate_char(c)
                            .map(CharKind::SemiGraphic)
                            .unwrap_or(CharKind::None)
                    })
            };

            // Check if the previous context is invalidated
            if self.cursor_position != (x, y)
                || std::mem::discriminant(&self.last_char_kind)
                    != std::mem::discriminant(&char_kind)
            {
                // Invalidated, we can start from scratch
                self.cursor_position = (x, y);
                self.char_attributes = Vec::new();
                self.zone_attributes = Vec::new();
                self.last_char_kind = char_kind;

                // Move the cursor to the right position, select the char set
                self.minitel.set_pos(x as u8, y as u8)?;
                self.minitel.write_byte(char_kind.escape_code() as u8)?;
            }

            match char_kind {
                CharKind::Alphabet(SIChar::G0(G0(0x20))) => {
                    // Empty char, update the zone attributes if necessary
                    if self.zone_attributes != zone_attributes {
                        for attr in &zone_attributes {
                            self.minitel.c1(*attr)?;
                        }
                        self.zone_attributes.clone_from(&zone_attributes);
                    }
                    self.minitel.write_byte(0x20)?;
                }
                CharKind::Alphabet(c) => {
                    // Alphabetic char, update the char attributes if necessary
                    if self.char_attributes != char_attributes {
                        for attr in &char_attributes {
                            self.minitel.c1(*attr)?;
                        }
                        self.char_attributes.clone_from(&char_attributes);
                    }

                    self.minitel.si_char(c)?;
                }
                CharKind::SemiGraphic(c) => {
                    // Semigraphic char, update both the zone and char attributes if necessary
                    if self.zone_attributes != zone_attributes {
                        for attr in &zone_attributes {
                            self.minitel.c1(*attr)?;
                        }
                        self.zone_attributes.clone_from(&zone_attributes);
                    }
                    if self.char_attributes != char_attributes {
                        for attr in &char_attributes {
                            self.minitel.c1(*attr)?;
                        }
                        self.char_attributes.clone_from(&char_attributes);
                    }
                    // Write the semi graphic char
                    self.minitel.write_byte(c)?;
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn hide_cursor(&mut self) -> std::io::Result<()> {
        self.minitel.hide_cursor()?;
        Ok(())
    }

    fn show_cursor(&mut self) -> std::io::Result<()> {
        self.minitel.show_cursor()?;
        Ok(())
    }

    fn get_cursor_position(&mut self) -> std::io::Result<ratatui::prelude::Position> {
        let (x, y) = self.minitel.get_pos()?;
        Ok(Position::new(x as u16, y as u16))
    }

    fn set_cursor_position<P: Into<ratatui::prelude::Position>>(
        &mut self,
        position: P,
    ) -> std::io::Result<()> {
        let position: Position = position.into();
        self.minitel.set_pos(position.x as u8, position.y as u8)?;
        Ok(())
    }

    fn clear(&mut self) -> std::io::Result<()> {
        self.minitel.clear_screen()?;
        Ok(())
    }

    fn size(&self) -> std::io::Result<ratatui::prelude::Size> {
        Ok(Size::new(40, 24))
    }

    fn window_size(&mut self) -> std::io::Result<ratatui::backend::WindowSize> {
        Ok(WindowSize {
            columns_rows: self.size()?,
            pixels: self.size()?,
        })
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.minitel.flush()?;
        Ok(())
    }
}

pub mod border {
    use ratatui::symbols::border;

    /// Variation on ONE_EIGHTH_WIDE offsetting it on the right to allow
    /// a consistent background transition in videotex mode.
    pub const ONE_EIGHTH_WIDE_OFFSET: border::Set = border::Set {
        top_right: "▁",
        top_left: " ",
        bottom_right: "▔",
        bottom_left: " ",
        vertical_left: "▕",
        vertical_right: "▕",
        horizontal_top: "▁",
        horizontal_bottom: "▔",
    };

    pub const ONE_EIGHTH_WIDE_BEVEL: border::Set = border::Set {
        top_right: "\\",
        top_left: "/",
        bottom_right: "/",
        bottom_left: "\\",
        vertical_left: "▏",
        vertical_right: "▕",
        horizontal_top: "▔",
        horizontal_bottom: "▁",
    };
}