petitcarnets 0.0.10

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
//! The runtime: a model, its messages and its commands, in one loop on
//! one thread.
//!
//! The loop owns the model and the renderer. It updates the model with
//! every message that is ready, in order, and draws once the queue is
//! empty, so a burst of messages costs one frame, and at most `fps`
//! frames a second, except that a frame after a key, mouse event or
//! paste is drawn at once. It then sleeps until the next input, task
//! result, timer or held back frame, with no periodic wakeups.

mod run;
mod sender;
mod session;

use crate::Model;
use crate::backend::Backend;
use crate::clock::{Clock, RealClock};
use crate::color::ColorProfile;
use crate::environ::Environment;
use crate::exec::{Event, Executor, Item};
use crate::msg::{Error, Msg};
use crate::renderer::Renderer;
use crate::style::{WidthMethod, set_width_method};
use run::{Frames, Loop, Settings};
pub use sender::Sender;
pub(crate) use session::Session;
use std::fmt;
use std::sync::mpsc::{self, Receiver};
use std::time::Duration;

/// Frames a second unless [`Program::with_fps`] says otherwise, as in
/// Bubble Tea.
const DEFAULT_FPS: u32 = 60;

/// The most frames a second [`Program::with_fps`] allows, as in Bubble
/// Tea.
const MAX_FPS: u32 = 120;

/// Runs a [`Model`] in a terminal. Bubble Tea's `tea.Program`.
///
/// ```no_run
/// use petitcarnets as tea;
///
/// struct Hello;
///
/// impl tea::Model for Hello {
///     type Msg = ();
///
///     fn update(&mut self, msg: tea::Msg<()>) -> tea::Cmd<()> {
///         match msg {
///             tea::Msg::KeyPress(k) if k == "q" || k == "ctrl+c" => tea::quit(),
///             _ => tea::Cmd::none(),
///         }
///     }
///
///     fn view(&self) -> tea::View {
///         "Hello! Press q to quit.".into()
///     }
/// }
///
/// tea::Program::new(Hello).run()?;
/// # Ok::<(), tea::Error>(())
/// ```
pub struct Program<M: Model> {
    model: M,
    events: mpsc::Sender<Event<M::Msg>>,
    inbox: Receiver<Event<M::Msg>>,
    fps: u32,
    environment: Option<Environment>,
    profile: Option<ColorProfile>,
    suspend_key: bool,
    accessible: Option<bool>,
}

impl<M: Model> fmt::Debug for Program<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Program").finish_non_exhaustive()
    }
}

/// How the loop ended.
#[derive(Debug)]
pub(crate) enum End {
    Quit,
    Interrupt,
    Kill,
    Panic(String),
}

impl End {
    /// The end an item asks for, if it asks for one.
    fn of<M>(item: Item<M>) -> Option<Self> {
        match item {
            Item::Quit => Some(Self::Quit),
            Item::Interrupt => Some(Self::Interrupt),
            Item::Kill => Some(Self::Kill),
            Item::Panic(message) => Some(Self::Panic(message)),
            _ => None,
        }
    }
}

impl<M: Model> Program<M> {
    /// A program for `model`. Bubble Tea's `tea.NewProgram`.
    ///
    /// ```
    /// use petitcarnets as tea;
    ///
    /// struct Hello;
    ///
    /// impl tea::Model for Hello {
    ///     type Msg = ();
    ///     fn update(&mut self, _: tea::Msg<()>) -> tea::Cmd<()> {
    ///         tea::quit()
    ///     }
    ///     fn view(&self) -> tea::View {
    ///         "hello".into()
    ///     }
    /// }
    ///
    /// let program = tea::Program::new(Hello);
    /// let test = tea::testing::TestProgram::with_terminal(program, tea::testing::TestTerminal::new(10, 1));
    /// assert!(test.is_finished());
    /// ```
    #[must_use]
    pub fn new(model: M) -> Self {
        let (events, inbox) = mpsc::channel();
        Self {
            model,
            events,
            inbox,
            fps: DEFAULT_FPS,
            environment: None,
            profile: None,
            suspend_key: true,
            accessible: None,
        }
    }

    /// Detects colours and terminal features from `environment` instead
    /// of the process's own: Bubble Tea's `tea.WithEnvironment`, for a
    /// program served over SSH, where the client's `TERM`, `COLORTERM`,
    /// `NO_COLOR` and the rest are what count.
    ///
    /// ```
    /// use petitcarnets as tea;
    ///
    /// /// Keeps the colour profile the program detected.
    /// struct M(Option<tea::ColorProfile>);
    ///
    /// impl tea::Model for M {
    ///     type Msg = ();
    ///     fn update(&mut self, msg: tea::Msg<()>) -> tea::Cmd<()> {
    ///         if let tea::Msg::ColorProfile(p) = msg {
    ///             self.0 = Some(p);
    ///         }
    ///         tea::Cmd::none()
    ///     }
    ///     fn view(&self) -> tea::View {
    ///         tea::View::default()
    ///     }
    /// }
    ///
    /// let client = [("TERM", "xterm-256color"), ("NO_COLOR", "1")];
    /// let program = tea::Program::new(M(None)).with_environment(client.into_iter().collect());
    /// let terminal = tea::testing::TestTerminal::new(20, 2).terminal();
    /// let test = tea::testing::TestProgram::with_terminal(program, terminal);
    /// assert_eq!(test.model().0, Some(tea::ColorProfile::Ascii), "NO_COLOR: no colours");
    /// ```
    #[must_use]
    pub fn with_environment(mut self, environment: Environment) -> Self {
        self.environment = Some(environment);
        self
    }

    /// Uses `profile` instead of detecting one: Bubble Tea's
    /// `tea.WithColorProfile`. It is kept even if the terminal later says
    /// it shows 24-bit colour (unlike Bubble Tea, its pull request #1773).
    #[must_use]
    pub const fn with_color_profile(mut self, profile: ColorProfile) -> Self {
        self.profile = Some(profile);
        self
    }

    /// Ctrl-Z suspends the program when `on` (the default), as it does
    /// in a shell (Bubble Tea leaves it to each program, its pull request
    /// #500); with `false` it is delivered to the model as the key
    /// `"ctrl+z"` instead. [`suspend`](crate::suspend) suspends either
    /// way, and so does a `SIGTSTP` sent from outside.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::testing::{TestProgram, TestTerminal};
    ///
    /// struct Keys(Vec<String>);
    ///
    /// impl tea::Model for Keys {
    ///     type Msg = ();
    ///     fn update(&mut self, msg: tea::Msg<()>) -> tea::Cmd<()> {
    ///         if let tea::Msg::KeyPress(k) = msg {
    ///             self.0.push(k.to_string());
    ///         }
    ///         tea::Cmd::none()
    ///     }
    ///     fn view(&self) -> tea::View {
    ///         "keys".into()
    ///     }
    /// }
    ///
    /// let program = tea::Program::new(Keys(Vec::new())).with_suspend(false);
    /// let mut test = TestProgram::with_terminal(program, TestTerminal::new(10, 1));
    /// test.press(tea::Key::ctrl('z'));
    /// assert_eq!(test.model().0, ["ctrl+z"]);
    /// ```
    #[must_use]
    pub const fn with_suspend(mut self, on: bool) -> Self {
        self.suspend_key = on;
        self
    }

    /// Prints frames as plain lines (`on`), for screen readers and
    /// braille displays, or never (`!on`): huh's `WithAccessible`, for
    /// Bubble Tea's issue #780. Without this call, a program in a real
    /// terminal prints lines when the environment's `ACCESSIBLE` is set
    /// and not empty, the variable huh tells programs to read.
    ///
    /// Each frame's lines that differ from the line in the same place
    /// in the frame before are printed once, in order, below what is
    /// already there; blank lines are left out. Nothing is redrawn, the
    /// cursor is never moved or hidden, the alternate screen is not
    /// used, frames are not wrapped in synchronized output, autowrap
    /// stays on and lines are not cut to the window's width.
    /// [`println`](crate::println) prints its lines in the same way.
    /// Colours and styles are left out unless the program sets a
    /// profile with [`Program::with_color_profile`]. Input works as it
    /// always does.
    ///
    /// So that it does, the input modes are still written: bracketed
    /// paste (`\x1b[?2004h`), modifyOtherKeys (`\x1b[>4;2m`) and the
    /// kitty keyboard flags (`\x1b[>1u`) before the first line, and their
    /// resets (`\x1b[>4m`, `\x1b[<u`, `\x1b[?2004l`) at the end; mouse
    /// tracking, focus reports and the window title too when the view
    /// asks for them. On a real terminal the terminal guard also hides the
    /// cursor on entry and shows it on exit (`\x1b[?25l`, `\x1b[?25h`),
    /// and the line printer shows it before the first line. Output
    /// captured to a file (a `script` log, or a [`Backend`] given to
    /// [`Program::run_with`] that writes to one) therefore holds these
    /// few sequences at its start and its end, around the plain lines.
    ///
    /// ```
    /// use petitcarnets as tea;
    /// use tea::testing::{TestProgram, TestTerminal};
    ///
    /// struct Count(u32);
    ///
    /// impl tea::Model for Count {
    ///     type Msg = ();
    ///     fn update(&mut self, msg: tea::Msg<()>) -> tea::Cmd<()> {
    ///         match msg {
    ///             tea::Msg::KeyPress(k) if k == "q" => tea::quit(),
    ///             tea::Msg::KeyPress(_) => {
    ///                 self.0 += 1;
    ///                 tea::Cmd::none()
    ///             }
    ///             _ => tea::Cmd::none(),
    ///         }
    ///     }
    ///     fn view(&self) -> tea::View {
    ///         tea::View::new(format!("Count: {}\n\nq: quit", self.0)).with_alt_screen(true)
    ///     }
    /// }
    ///
    /// let program = tea::Program::new(Count(0)).with_accessible(true);
    /// let mut test = TestProgram::with_terminal(program, TestTerminal::new(20, 5));
    /// test.type_text("+q");
    /// let out = String::from_utf8_lossy(test.final_output()).into_owned();
    /// // The changed line is printed again below, never redrawn in place.
    /// assert!(out.contains("Count: 0\r\nq: quit\r\nCount: 1\r\n"));
    /// assert!(!out.contains("\x1b[?1049h"), "no alternate screen");
    /// // The input modes, set before the first line and reset at the end.
    /// assert!(out.starts_with("\x1b[?2004h\x1b[>4;2m\x1b[>1uCount: 0\r\n"));
    /// assert!(out.ends_with("Count: 1\r\n\x1b[>4m\x1b[<u\x1b[?2004l"));
    /// ```
    #[must_use]
    pub const fn with_accessible(mut self, on: bool) -> Self {
        self.accessible = Some(on);
        self
    }

    /// Draws at most `fps` frames a second (60 by default), cut to 1 to
    /// 120. Bubble Tea's `tea.WithFPS`. A frame after a key, mouse event
    /// or paste is drawn at once, whatever the rate.
    #[must_use]
    pub fn with_fps(mut self, fps: u32) -> Self {
        self.fps = fps.clamp(1, MAX_FPS);
        self
    }

    /// A handle for sending the program messages from other threads,
    /// before or while it runs.
    #[must_use]
    pub fn sender(&self) -> Sender<M::Msg> {
        Sender(self.events.clone())
    }

    /// Runs in the process's terminal until the model quits, and returns
    /// the model. Ctrl-C arrives as the key `"ctrl+c"`, as in Bubble Tea:
    /// quit on it in `update` if the program should stop.
    ///
    /// # Errors
    ///
    /// [`Error::Interrupted`] on `SIGINT`, [`Error::Killed`] after
    /// [`Sender::kill`], [`Error::Panic`] when a task panics, and
    /// [`Error::Io`] when there is no terminal or it fails. The terminal
    /// is restored in every case.
    #[cfg(unix)]
    pub fn run(self) -> Result<M, Error> {
        self.run_with(crate::Terminal::new())
    }

    /// Runs on `backend` until the model quits, and returns the model.
    ///
    /// # Errors
    ///
    /// As [`Program::run`]; the backend is left in every case.
    pub fn run_with(self, mut backend: impl Backend) -> Result<M, Error> {
        backend.enter()?;
        set_width_method(WidthMethod::WcWidth);
        let result = match self.start(&mut backend, RealClock) {
            Ok(mut session) => {
                let end = session.run(&mut backend);
                let (model, ended) = session.close(end, &mut backend);
                ended.map(|()| model)
            }
            Err(err) => Err(err),
        };
        set_width_method(WidthMethod::WcWidth);
        let left = backend.leave();
        let model = result?;
        left?;
        Ok(model)
    }

    /// Starts the loop on `backend`, already entered, with `clock`: input
    /// started, the start queries written and the first messages queued.
    /// Nothing is drawn yet.
    pub(crate) fn start<C: Clock>(
        self,
        backend: &mut impl Backend,
        clock: C,
    ) -> Result<Session<M, C>, Error> {
        let Self {
            mut model,
            events,
            inbox,
            fps,
            environment,
            profile,
            suspend_key,
            accessible,
        } = self;
        let keys = events.clone();
        backend.start_input(Box::new(move |input| {
            keys.send(Event::Input(input)).is_ok()
        }));
        let size = backend.size()?;
        let environment = environment.unwrap_or_else(Environment::current);
        let terminal = backend.is_terminal();
        let accessible = accessible.unwrap_or_else(|| terminal && wants_accessible(&environment));
        let settings = Settings {
            interval: Duration::from_secs(1) / fps,
            profile: profile.unwrap_or_else(|| detect(terminal, accessible, &environment)),
            forced: profile.is_some() || accessible,
            suspend_key,
            terminal,
            frames: if accessible {
                Frames::Lines
            } else {
                Frames::Cells
            },
        };
        let colors = settings.profile;
        let mut state = Loop::new(Executor::new(events), Renderer::new(size), settings, clock);
        state.query(backend, !accessible && should_query(&environment))?;
        state.exec.push(Item::Msg(Msg::ColorProfile(colors)));
        state.exec.push(Item::Msg(Msg::WindowSize(size)));
        let now = state.now();
        state.exec.run(model.init(), now);
        Ok(Session::new(model, inbox, state))
    }
}

/// The colour profile of a real terminal (`terminal`) in `environment`;
/// anything else shows every colour as it is. Accessible output has
/// none: plain text, unless the program sets a profile.
fn detect(terminal: bool, accessible: bool, environment: &Environment) -> ColorProfile {
    if accessible {
        ColorProfile::NoTty
    } else if terminal {
        ColorProfile::detect(true, environment)
    } else {
        ColorProfile::TrueColor
    }
}

/// Whether `environment` asks for accessible output: `ACCESSIBLE` set
/// and not empty, the variable huh's documentation tells programs to
/// read (`os.Getenv("ACCESSIBLE") != ""`).
fn wants_accessible(environment: &Environment) -> bool {
    !environment.var("ACCESSIBLE").is_empty()
}

/// Whether to ask the terminal about synchronized output and grapheme
/// widths: Bubble Tea's `shouldQuerySynchronizedOutput`.
fn should_query(env: &Environment) -> bool {
    let term = env.var("TERM");
    let known = ["ghostty", "wezterm", "alacritty", "kitty", "rio"]
        .iter()
        .any(|t| term.contains(t));
    let apple = env.var("TERM_PROGRAM").contains("Apple");
    let ssh = env.get("SSH_TTY").is_some();
    (!ssh && !apple) || env.get("WT_SESSION").is_some() || known
}

#[cfg(test)]
mod tests;