petitcarnets 0.0.11

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
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
//! Terminal modes a view turns on and off (the alternate screen, mouse,
//! focus, bracketed paste, keyboard enhancements, the cursor's look, the
//! window title, colours, the progress bar), and the replies a terminal
//! sends about modes.

mod active;

pub(crate) use active::Modes;

use crate::color::Rgb;
use crate::view::{ProgressBar, ProgressBarState};

/// A terminal mode a program can turn on and off. Bubble Tea turns them
/// on and off from each [`View`](crate::View)'s fields; a
/// [`Backend`](crate::Backend) writes them.
///
/// ```
/// use petitcarnets as tea;
/// use tea::TerminalMode;
///
/// assert_eq!(TerminalMode::AltScreen.sequence(true), b"\x1b[?1049h");
/// assert_eq!(TerminalMode::AltScreen.sequence(false), b"\x1b[?1049l");
/// assert_eq!(TerminalMode::CursorStyle(5).sequence(true), b"\x1b[5 q");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TerminalMode {
    /// Bracketed paste (mode 2004): pasted text arrives as one paste.
    BracketedPaste,
    /// Focus reports (mode 1004).
    ReportFocus,
    /// Mouse clicks, wheel and drags (modes 1002 and 1006).
    MouseCellMotion,
    /// Every mouse event, plain motion included (modes 1003 and 1006).
    MouseAllMotion,
    /// xterm's modifyOtherKeys level 2 and a kitty keyboard entry with
    /// these flags pushed on the terminal's stack.
    KeyboardEnhancements(u8),
    /// New flags for the kitty keyboard entry already pushed by
    /// [`TerminalMode::KeyboardEnhancements`], set in place. Turning it
    /// off does nothing: turn off `KeyboardEnhancements` instead.
    KeyboardFlags(u8),
    /// The alternate screen (mode 1049), saving the main screen's cursor.
    AltScreen,
    /// Autowrap turned off (DECAWM, mode 7): on writes `CSI ?7l`, off
    /// `CSI ?7h`. On while a program draws, so writing the last column
    /// never wraps or scrolls.
    NoAutowrap,
    /// Grapheme cluster widths (mode 2027), where the terminal has them.
    UnicodeCore,
    /// The window title saved on the terminal's title stack (XTWINOPS 22
    /// and 23): off clears the title, then pops the saved one back.
    SavedTitle,
    /// A cursor shape (DECSCUSR 1 to 6); off is the terminal's default.
    CursorStyle(u8),
    /// The terminal's default text colour (OSC 10); off resets it.
    ForegroundColor(Rgb),
    /// The terminal's default background colour (OSC 11); off resets it.
    BackgroundColor(Rgb),
    /// The cursor's colour (OSC 12); off resets it.
    CursorColor(Rgb),
    /// A progress bar (OSC 9;4); off removes it.
    ProgressBar(ProgressBar),
}

impl TerminalMode {
    /// The bytes that turn the mode on (`on`) or off.
    #[must_use]
    pub fn sequence(self, on: bool) -> Vec<u8> {
        if on {
            self.enter_sequence()
        } else {
            self.disable().to_vec()
        }
    }

    /// The bytes that turn the mode on.
    fn enter_sequence(self) -> Vec<u8> {
        match self {
            Self::KeyboardEnhancements(flags) => format!("\x1b[>4;2m\x1b[>{flags}u").into_bytes(),
            Self::KeyboardFlags(flags) => format!("\x1b[>4;2m\x1b[={flags};1u").into_bytes(),
            Self::CursorStyle(n) => format!("\x1b[{n} q").into_bytes(),
            Self::ForegroundColor(c) => osc_colour(10, c),
            Self::BackgroundColor(c) => osc_colour(11, c),
            Self::CursorColor(c) => osc_colour(12, c),
            Self::ProgressBar(bar) => bar.sequence().into_bytes(),
            mode => mode.entry().1.to_vec(),
        }
    }

    /// The mode's row in [`SEQUENCES`].
    fn entry(self) -> &'static (TerminalMode, &'static [u8], &'static [u8]) {
        let kind = self.kind();
        SEQUENCES
            .iter()
            .find(|e| e.0 == kind)
            .unwrap_or(&SEQUENCES[0])
    }

    /// The bytes that turn the mode off; Bubble Tea turns every mouse
    /// mode off at once.
    pub(crate) fn disable(self) -> &'static [u8] {
        self.entry().2
    }

    /// The same mode whatever its flags, to tell modes apart.
    pub(crate) const fn kind(self) -> Self {
        const BLACK: Rgb = Rgb::new(0, 0, 0);
        match self {
            Self::KeyboardEnhancements(_) => Self::KeyboardEnhancements(0),
            Self::KeyboardFlags(_) => Self::KeyboardFlags(0),
            Self::CursorStyle(_) => Self::CursorStyle(0),
            Self::ForegroundColor(_) => Self::ForegroundColor(BLACK),
            Self::BackgroundColor(_) => Self::BackgroundColor(BLACK),
            Self::CursorColor(_) => Self::CursorColor(BLACK),
            Self::ProgressBar(_) => Self::ProgressBar(ProgressBar {
                state: ProgressBarState::None,
                value: 0,
            }),
            mode => mode,
        }
    }
}

/// Each kind of mode, the bytes that turn it on (when they do not
/// depend on its value) and the bytes that turn it off.
const SEQUENCES: [(TerminalMode, &[u8], &[u8]); 15] = {
    use TerminalMode as M;
    const BLACK: Rgb = Rgb::new(0, 0, 0);
    const NO_BAR: ProgressBar = ProgressBar {
        state: ProgressBarState::None,
        value: 0,
    };
    const MOUSE_OFF: &[u8] = b"\x1b[?1002l\x1b[?1003l\x1b[?1006l";
    [
        (M::BracketedPaste, b"\x1b[?2004h", b"\x1b[?2004l"),
        (M::ReportFocus, b"\x1b[?1004h", b"\x1b[?1004l"),
        (M::MouseCellMotion, b"\x1b[?1002h\x1b[?1006h", MOUSE_OFF),
        (M::MouseAllMotion, b"\x1b[?1003h\x1b[?1006h", MOUSE_OFF),
        (M::KeyboardEnhancements(0), b"", b"\x1b[>4m\x1b[<u"),
        (M::KeyboardFlags(0), b"", b""),
        (M::AltScreen, b"\x1b[?1049h", b"\x1b[?1049l"),
        (M::NoAutowrap, b"\x1b[?7l", b"\x1b[?7h"),
        (M::UnicodeCore, b"\x1b[?2027h", b"\x1b[?2027l"),
        (M::SavedTitle, b"\x1b[22;2t", b"\x1b]2;\x07\x1b[23;2t"),
        (M::CursorStyle(0), b"", b"\x1b[0 q"),
        (M::ForegroundColor(BLACK), b"", b"\x1b]110\x07"),
        (M::BackgroundColor(BLACK), b"", b"\x1b]111\x07"),
        (M::CursorColor(BLACK), b"", b"\x1b]112\x07"),
        (M::ProgressBar(NO_BAR), b"", b"\x1b]9;4;0\x07"),
    ]
};

/// An OSC that sets colour `n` (10, 11 or 12), as Go writes it.
fn osc_colour(n: u8, c: Rgb) -> Vec<u8> {
    format!("\x1b]{n};#{:02x}{:02x}{:02x}\x07", c.r, c.g, c.b).into_bytes()
}

/// The keyboard enhancements a view asks for, on top of the kitty
/// protocol's key disambiguation, which is always on. Bubble Tea's
/// `KeyboardEnhancements`: where Go sets a field, as in
/// `KeyboardEnhancements{ReportEventTypes: true}`, chain the method of
/// the same name, as in `KeyboardEnhancements::new().report_event_types(true)`.
///
/// ```
/// use petitcarnets as tea;
/// use tea::{KeyboardEnhancements, TerminalMode};
///
/// let keys = KeyboardEnhancements::new()
///     .report_event_types(true)
///     .report_alternate_keys(true);
/// assert_eq!(keys.flags(), 1 | 2 | 4);
/// assert_eq!(KeyboardEnhancements::default().flags(), 1);
/// let mode = TerminalMode::KeyboardEnhancements(keys.flags());
/// assert_eq!(mode.sequence(true), b"\x1b[>4;2m\x1b[>7u");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct KeyboardEnhancements(u8);

impl Default for KeyboardEnhancements {
    fn default() -> Self {
        Self::new()
    }
}

impl KeyboardEnhancements {
    /// Disambiguation only (kitty flag 1).
    #[must_use]
    pub const fn new() -> Self {
        Self(1)
    }

    /// Also report key repeats and releases
    /// ([`Msg::KeyRelease`](crate::Msg::KeyRelease)) when `on`. Go's
    /// `ReportEventTypes`.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::KeyboardEnhancements;
    ///
    /// let on = KeyboardEnhancements::new().report_event_types(true);
    /// assert_eq!(on.flags(), 1 | 2);
    /// assert_eq!(on.report_event_types(false), KeyboardEnhancements::new());
    /// ```
    #[must_use]
    pub const fn report_event_types(self, on: bool) -> Self {
        self.with(2, on)
    }

    /// Also report the shifted key and the key on a US layout when
    /// `on`. Go's `ReportAlternateKeys`.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::KeyboardEnhancements;
    ///
    /// let on = KeyboardEnhancements::new().report_alternate_keys(true);
    /// assert_eq!(on.flags(), 1 | 4);
    /// assert_eq!(on.report_alternate_keys(false), KeyboardEnhancements::new());
    /// ```
    #[must_use]
    pub const fn report_alternate_keys(self, on: bool) -> Self {
        self.with(4, on)
    }

    /// Report every key as an escape code, plain text included, when
    /// `on`. Go's `ReportAllKeysAsEscapeCodes`.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::KeyboardEnhancements;
    ///
    /// let on = KeyboardEnhancements::new().report_all_keys_as_escape_codes(true);
    /// assert_eq!(on.flags(), 1 | 8);
    /// assert_eq!(on.report_all_keys_as_escape_codes(false), KeyboardEnhancements::new());
    /// ```
    #[must_use]
    pub const fn report_all_keys_as_escape_codes(self, on: bool) -> Self {
        self.with(8, on)
    }

    /// With all keys as escape codes, report the text keys type when
    /// `on`. Go's `ReportAssociatedText`.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::KeyboardEnhancements;
    ///
    /// let on = KeyboardEnhancements::new().report_associated_text(true);
    /// assert_eq!(on.flags(), 1 | 16);
    /// assert_eq!(on.report_associated_text(false), KeyboardEnhancements::new());
    /// ```
    #[must_use]
    pub const fn report_associated_text(self, on: bool) -> Self {
        self.with(16, on)
    }

    /// With the flag `bit` set when `on`, cleared when not.
    const fn with(self, bit: u8, on: bool) -> Self {
        if on {
            Self(self.0 | bit)
        } else {
            Self(self.0 & !bit)
        }
    }

    /// The kitty protocol flags: 1 (disambiguate) always, plus 2, 4, 8
    /// and 16 for the enhancements asked for.
    #[must_use]
    pub const fn flags(self) -> u8 {
        self.0
    }
}

/// The terminal's reply about its keyboard enhancements. Bubble Tea's
/// `KeyboardEnhancementsMsg`.
///
/// ```
/// use petitcarnets as tea;
/// use tea::KeyboardEnhancementsReport;
///
/// let report = KeyboardEnhancementsReport::new(1 | 2);
/// assert!(report.supports_key_disambiguation());
/// assert!(report.supports_event_types());
/// assert!(!report.supports_alternate_keys());
/// assert!(!KeyboardEnhancementsReport::new(-1).supports_key_disambiguation());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct KeyboardEnhancementsReport {
    /// The kitty protocol flags in force; -1 when the reply had none.
    pub flags: i32,
}

impl KeyboardEnhancementsReport {
    /// A report of the kitty protocol `flags` in force; -1 when the
    /// reply had none.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::KeyboardEnhancementsReport;
    ///
    /// assert_eq!(KeyboardEnhancementsReport::new(3).flags, 3);
    /// ```
    #[must_use]
    pub const fn new(flags: i32) -> Self {
        Self { flags }
    }

    /// Whether keys are disambiguated: any flag at all.
    #[must_use]
    pub const fn supports_key_disambiguation(self) -> bool {
        self.flags > 0
    }

    /// Whether repeats and releases are reported.
    #[must_use]
    pub const fn supports_event_types(self) -> bool {
        self.flags & 2 != 0
    }

    /// Whether alternate keys are reported.
    #[must_use]
    pub const fn supports_alternate_keys(self) -> bool {
        self.flags & 4 != 0
    }

    /// Whether every key is reported as an escape code.
    #[must_use]
    pub const fn supports_all_keys_as_escape_codes(self) -> bool {
        self.flags & 8 != 0
    }

    /// Whether associated text is reported.
    #[must_use]
    pub const fn supports_associated_text(self) -> bool {
        self.flags & 16 != 0
    }
}

/// A mode a terminal reported on: a DEC private mode (`CSI ? n $ y`) or
/// an ANSI one.
///
/// ```
/// use petitcarnets as tea;
/// use tea::testing::TestProgram;
/// use tea::{ModeSetting, ReportedMode};
///
/// /// Keeps every message it gets.
/// struct Log(Vec<tea::Msg<()>>);
///
/// impl tea::Model for Log {
///     type Msg = ();
///
///     fn update(&mut self, msg: tea::Msg<()>) -> tea::Cmd<()> {
///         self.0.push(msg);
///         tea::Cmd::none()
///     }
/// #
/// #     fn view(&self) -> tea::View {
/// #         tea::View::default()
/// #     }
/// }
///
/// let mut test = TestProgram::new(Log(Vec::new()), 20, 1);
/// // The terminal says bracketed paste (DEC mode 2004) is on.
/// test.bytes("\x1b[?2004;1$y");
/// let report = tea::Msg::ModeReport {
///     mode: ReportedMode::Dec(2004),
///     value: ModeSetting::Set,
/// };
/// assert_eq!(test.model().0.last(), Some(&report));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReportedMode {
    /// A DEC private mode, such as 2004 for bracketed paste.
    Dec(u32),
    /// An ANSI mode.
    Ansi(u32),
}

/// What a terminal says about a mode. Go's `ansi.ModeSetting`.
///
/// ```
/// use petitcarnets as tea;
/// use tea::ModeSetting;
///
/// assert_eq!(ModeSetting::from(1), ModeSetting::Set);
/// assert_eq!(ModeSetting::from(9), ModeSetting::Other(9));
/// assert_eq!(u8::from(ModeSetting::PermanentlyReset), 4);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ModeSetting {
    /// The terminal does not know the mode.
    NotRecognized,
    /// On.
    Set,
    /// Off.
    Reset,
    /// On, and cannot be changed.
    PermanentlySet,
    /// Off, and cannot be changed.
    PermanentlyReset,
    /// Any other value.
    Other(u8),
}

impl From<u8> for ModeSetting {
    fn from(value: u8) -> Self {
        match value {
            0 => Self::NotRecognized,
            1 => Self::Set,
            2 => Self::Reset,
            3 => Self::PermanentlySet,
            4 => Self::PermanentlyReset,
            v => Self::Other(v),
        }
    }
}

impl From<ModeSetting> for u8 {
    fn from(setting: ModeSetting) -> Self {
        match setting {
            ModeSetting::NotRecognized => 0,
            ModeSetting::Set => 1,
            ModeSetting::Reset => 2,
            ModeSetting::PermanentlySet => 3,
            ModeSetting::PermanentlyReset => 4,
            ModeSetting::Other(v) => v,
        }
    }
}

#[cfg(test)]
mod tests;