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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! The loop itself: updates, frames, output in program order, and
//! waiting.

mod handover;
mod translate;

use super::End;
use crate::backend::Backend;
use crate::clock::{Clock, Now};
use crate::cmd::{Handover, Output};
use crate::color::ColorProfile;
use crate::exec::{Event, Executor, Item};
use crate::mode::{ModeSetting, Modes, ReportedMode};
use crate::msg::{Error, Msg};
use crate::renderer::Renderer;
use crate::style::{WidthMethod, set_width_method};
use crate::view::View;
use crate::{Cmd, Model};
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant};

/// Asks whether the terminal has synchronized output (mode 2026) and
/// grapheme widths (mode 2027), as Bubble Tea does at the start.
const QUERY: &[u8] = b"\x1b[?2026$p\x1b[?2027$p";

/// How the loop is set up.
pub(super) struct Settings {
    /// The shortest time between frames.
    pub(super) interval: Duration,
    /// The colour profile.
    pub(super) profile: ColorProfile,
    /// Whether the profile was set by the program, so it is kept.
    pub(super) forced: bool,
    /// Whether Ctrl-Z suspends.
    pub(super) suspend_key: bool,
    /// Whether the backend is a real terminal.
    pub(super) terminal: bool,
    /// How frames reach the terminal.
    pub(super) frames: Frames,
}

/// How frames reach the terminal.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Frames {
    /// Drawn in cells, only what changed: the default.
    Cells,
    /// Printed as plain lines, for screen readers.
    Lines,
}

/// The loop's state besides the model.
pub(super) struct Loop<M, C> {
    pub(super) exec: Executor<M>,
    renderer: Renderer,
    pub(super) modes: Modes,
    settings: Settings,
    clock: C,
    dirty: bool,
    urgent: bool,
    last_frame: Option<Instant>,
    frame_due: Option<Instant>,
    /// When a query was last written; its reply may be on its way.
    queried: Option<Instant>,
    /// Whether the terminal is handed over until a restore.
    released: bool,
    /// Output that waits while the terminal is handed over.
    held_back: Vec<Output>,
}

impl<A: Send + 'static, C: Clock> Loop<A, C> {
    /// A loop set up as `settings` say, on `clock`.
    pub(super) fn new(
        exec: Executor<A>,
        mut renderer: Renderer,
        settings: Settings,
        clock: C,
    ) -> Self {
        let mut modes = Modes::default();
        if settings.frames == Frames::Lines {
            renderer.set_accessible(settings.terminal);
            modes.keep_autowrap();
        }
        renderer.set_color_profile(settings.profile);
        modes.set_color_profile(settings.profile);
        Self {
            exec,
            renderer,
            modes,
            settings,
            clock,
            dirty: true,
            urgent: false,
            last_frame: None,
            frame_due: None,
            queried: None,
            released: false,
            held_back: Vec::new(),
        }
    }

    /// The time on the loop's clock.
    pub(super) fn now(&self) -> Now {
        self.clock.now()
    }

    /// Asks the terminal about its output modes, if it is one and `ask`
    /// says to. The replies arrive as input; nothing waits for them.
    pub(super) fn query(&mut self, backend: &mut impl Backend, ask: bool) -> Result<(), Error> {
        if self.settings.terminal && ask {
            self.write_query(QUERY, backend)?;
        }
        Ok(())
    }

    /// Writes a query and remembers when.
    fn write_query(&mut self, bytes: &[u8], backend: &mut impl Backend) -> Result<(), Error> {
        let out = backend.output();
        out.write_all(bytes)?;
        out.flush()?;
        self.queried = Some(self.clock.now().at);
        Ok(())
    }

    /// Updates, draws and waits until something ends the program.
    pub(super) fn run<M: Model<Msg = A>>(
        &mut self,
        model: &mut M,
        inbox: &Receiver<Event<A>>,
        backend: &mut impl Backend,
    ) -> Result<End, Error> {
        loop {
            if let Some(end) = self.step(model, inbox, backend)? {
                return Ok(end);
            }
            self.wait(inbox);
        }
    }

    /// Updates the model with everything ready and draws, if the frame
    /// rate allows; how the program ended, if it did, after its last
    /// frame.
    pub(super) fn step<M: Model<Msg = A>>(
        &mut self,
        model: &mut M,
        inbox: &Receiver<Event<A>>,
        backend: &mut impl Backend,
    ) -> Result<Option<End>, Error> {
        if let Some(end) = self.update(model, inbox, backend)? {
            return self.end(end, model, inbox, backend).map(Some);
        }
        self.frame(model, backend)?;
        Ok(None)
    }

    /// When the loop next has something to do with no event: the
    /// earliest timer, or a held back frame.
    pub(super) fn next_wake(&self) -> Option<Instant> {
        [self.exec.next_deadline(), self.frame_due]
            .into_iter()
            .flatten()
            .min()
    }

    /// The terminal taken back if it was handed over, with the output
    /// that waited unless killed or panicked; the last frame (likewise),
    /// replies still on their way, and the renderer's goodbye.
    fn end<M: Model<Msg = A>>(
        &mut self,
        end: End,
        model: &M,
        inbox: &Receiver<Event<A>>,
        backend: &mut impl Backend,
    ) -> Result<End, Error> {
        let graceful = matches!(end, End::Quit | End::Interrupt);
        if self.released {
            self.take_back_at_end(graceful, model, backend)?;
        }
        if graceful {
            self.draw(&self.view_of(model), backend)?;
            self.drain(inbox, backend, false)?;
            self.renderer.finish(backend.output())?;
        } else {
            self.drain(inbox, backend, false)?;
            self.renderer.abandon(backend.output())?;
        }
        Ok(end)
    }

    /// Takes the terminal back for the end: with the output that waited
    /// if the end is `graceful`, without it otherwise.
    fn take_back_at_end<M: Model<Msg = A>>(
        &mut self,
        graceful: bool,
        model: &M,
        backend: &mut impl Backend,
    ) -> Result<(), Error> {
        if graceful {
            self.restore(model, backend)
        } else {
            self.take_back(backend)
        }
    }

    /// Updates the model with everything ready, in order, and applies
    /// output and hand-overs in the same order; how the program ends,
    /// if it does.
    fn update<M: Model<Msg = A>>(
        &mut self,
        model: &mut M,
        inbox: &Receiver<Event<A>>,
        backend: &mut impl Backend,
    ) -> Result<Option<End>, Error> {
        while let Some(item) = self.exec.pop() {
            match item {
                Item::Msg(msg) => self.message(model, msg, backend)?,
                Item::Output(output) => self.output(model, output, backend)?,
                Item::Handover(handover) => self.lifecycle(handover, model, inbox, backend)?,
                end => return Ok(End::of(end)),
            }
        }
        Ok(None)
    }

    /// One message for the model; the renderer hears sizes, mode
    /// reports and capabilities first.
    fn message<M: Model<Msg = A>>(
        &mut self,
        model: &mut M,
        msg: Msg<A>,
        backend: &mut impl Backend,
    ) -> Result<(), Error> {
        match &msg {
            Msg::WindowSize(size) => self.renderer.resize(*size),
            Msg::ModeReport { mode, value } => self.mode_report(*mode, *value, backend)?,
            Msg::Capability(capability) => self.capability(capability),
            _ => {}
        }
        let cmd: Cmd<A> = model.update(msg);
        self.exec.run(cmd, self.clock.now());
        self.dirty = true;
        Ok(())
    }

    /// Acts on a reply to the start query, as Bubble Tea does.
    fn mode_report(
        &mut self,
        mode: ReportedMode,
        value: ModeSetting,
        backend: &mut impl Backend,
    ) -> Result<(), Error> {
        match mode {
            ReportedMode::Dec(2026) => self.renderer.set_sync(value == ModeSetting::Reset),
            ReportedMode::Dec(2027) => {
                let set = [
                    ModeSetting::Reset,
                    ModeSetting::Set,
                    ModeSetting::PermanentlySet,
                ];
                if set.contains(&value) {
                    self.renderer.set_width_method(WidthMethod::GraphemeWidth);
                    set_width_method(WidthMethod::GraphemeWidth);
                    self.modes.unicode_core(backend)?;
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// A terminal that says it has `RGB` or `Tc` shows 24-bit colour, as
    /// Bubble Tea decides; unlike Bubble Tea (its pull request #1773), a profile
    /// the program set is kept.
    fn capability(&mut self, capability: &str) {
        let name = capability.split('=').next().unwrap_or_default();
        let upgrade = matches!(name, "RGB" | "Tc")
            && !self.settings.forced
            && self.settings.profile != ColorProfile::TrueColor;
        if upgrade {
            self.settings.profile = ColorProfile::TrueColor;
            self.renderer.set_color_profile(ColorProfile::TrueColor);
            self.modes.set_color_profile(ColorProfile::TrueColor);
            let msg = Msg::ColorProfile(ColorProfile::TrueColor);
            self.exec.push(Item::Msg(msg));
        }
    }

    /// Output from a command, applied now, between frames; it waits
    /// while the terminal is handed over.
    fn output<M: Model<Msg = A>>(
        &mut self,
        model: &M,
        output: Output,
        backend: &mut impl Backend,
    ) -> Result<(), Error> {
        if self.released {
            self.held_back.push(output);
            return Ok(());
        }
        match output {
            Output::Raw(bytes) | Output::Query(bytes) => self.write_query(&bytes, backend),
            Output::Print(text) => self.print(model, &text, backend),
            other => self.redraw(&other, backend),
        }
    }

    /// Clears the screen or repaints, with the modes written again; or
    /// reads the window's size for the model.
    fn redraw(&mut self, output: &Output, backend: &mut impl Backend) -> Result<(), Error> {
        match output {
            Output::ClearScreen => {
                self.renderer.clear_screen();
                self.modes.reassert(backend)?;
            }
            Output::Repaint => {
                self.modes.release(backend)?;
                self.modes.resume(backend)?;
                self.renderer.repaint();
            }
            _ => {
                let size = backend.size()?;
                self.exec.push_front(Item::Msg(Msg::WindowSize(size)));
            }
        }
        self.dirty = true;
        Ok(())
    }

    /// Prints above the frame. The frame for the state the lines follow
    /// goes on screen first, unless it enters the alternate screen: then
    /// the lines go on the normal screen, where they stay. A frame the
    /// lines pushed off the screen is drawn again.
    fn print<M: Model<Msg = A>>(
        &mut self,
        model: &M,
        text: &str,
        backend: &mut impl Backend,
    ) -> Result<(), Error> {
        let view = self.view_of(model);
        if self.dirty && !view.alt_screen {
            self.draw(&view, backend)?;
        }
        self.renderer.insert_above(text, backend.output())?;
        // Lines taller than the room above the frame push it off the
        // screen: draw it again (Bubble Tea's issue #1822).
        self.dirty |= self.renderer.must_draw();
        Ok(())
    }

    /// Draws if something changed and the frame rate allows: at once
    /// after input, else no sooner than one interval after the last.
    /// Nothing is drawn while the terminal is handed over, and a frame
    /// held back then is forgotten (taking the terminal back draws one at
    /// once), so it cannot wake the loop over and over.
    fn frame<M: Model<Msg = A>>(
        &mut self,
        model: &M,
        backend: &mut impl Backend,
    ) -> Result<(), Error> {
        if !self.dirty || self.released {
            self.frame_due = None;
            return Ok(());
        }
        if !self.urgent {
            if let Some(last) = self.last_frame {
                let due = last + self.settings.interval;
                if self.clock.now().at < due {
                    self.frame_due = Some(due);
                    return Ok(());
                }
            }
        }
        self.draw(&self.view_of(model), backend)
    }

    /// Draws the frame the frame rate holds back, if there is one, at
    /// once.
    pub(super) fn show<M: Model<Msg = A>>(
        &mut self,
        model: &M,
        backend: &mut impl Backend,
    ) -> Result<(), Error> {
        if self.frame_due.is_none() {
            return Ok(());
        }
        self.draw(&self.view_of(model), backend)
    }

    /// What `model` shows now; printed as lines, a view stays on the
    /// normal screen and has no cursor.
    fn view_of<M: Model<Msg = A>>(&self, model: &M) -> View {
        let mut view = model.view();
        if self.settings.frames == Frames::Lines {
            view.alt_screen = false;
            view.cursor = None;
        }
        view
    }

    /// Draws `view`: screen switch, modes, then content.
    fn draw(&mut self, view: &View, backend: &mut impl Backend) -> Result<(), Error> {
        if view.alt_screen != self.renderer.is_alt() {
            self.modes.switch_screen(view.alt_screen, backend)?;
            self.renderer.switch_screen(view.alt_screen);
        }
        self.modes.apply(view, backend)?;
        self.renderer.render(view, backend.output())?;
        self.dirty = false;
        self.urgent = false;
        self.last_frame = Some(self.clock.now().at);
        self.frame_due = None;
        Ok(())
    }

    /// Sleeps until an event arrives, a timer is due or a held back
    /// frame may be drawn, then takes in everything that is ready.
    pub(super) fn wait(&mut self, inbox: &Receiver<Event<A>>) {
        let events = self.clock.wait(inbox, self.next_wake(), self.exec.tasks());
        for event in events {
            self.take(event);
        }
        self.exec.fire_due(self.clock.now());
    }

    /// Queues what one event means for the model. Keys, mouse events and
    /// pastes make the next frame go out at once; Ctrl-Z suspends unless
    /// the program says not to.
    fn take(&mut self, event: Event<A>) {
        let item = match event {
            Event::Input(input) => {
                self.urgent |= translate::is_urgent(&input);
                if self.settings.suspend_key && translate::is_suspend_key(&input) {
                    Item::Handover(Handover::Suspend)
                } else {
                    translate::input_item(input)
                }
            }
            Event::Done(task, msg) => return self.exec.task_done(task, msg, self.clock.now()),
            Event::Panic(_, message) => {
                self.exec.task_panicked();
                Item::Panic(message)
            }
            Event::Send(msg) => Item::Msg(Msg::App(msg)),
            Event::Quit => Item::Quit,
            Event::Kill => Item::Kill,
        };
        self.exec.push(item);
    }
}