terminal-control 0.1.0

Control and test terminal applications through stable visible state
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

use crate::frame::{Frame, from_screen};
use crate::render;

const MAX_VIDEO_FPS: u32 = 1000;
/// Schema version written in the header of every `.termctrl` recording.
pub const FORMAT_VERSION: u8 = 1;

/// One JSON Lines entry in a `.termctrl` recording timeline.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum Entry {
    Header {
        version: u8,
        cols: u16,
        rows: u16,
        cell_width: u16,
        cell_height: u16,
    },
    Output {
        at_ms: u64,
        bytes: Vec<u8>,
    },
    Input {
        at_ms: u64,
        origin: InputOrigin,
        bytes: Vec<u8>,
    },
    Resize {
        at_ms: u64,
        cols: u16,
        rows: u16,
        cell_width: u16,
        cell_height: u16,
    },
}

/// Source of bytes written to the application while recording a session.
#[derive(Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InputOrigin {
    Client,
    Host,
}

pub struct Writer {
    file: fs::File,
    started: Instant,
}

impl Writer {
    pub fn new(
        path: &Path,
        started: Instant,
        cols: u16,
        rows: u16,
        cell_width: u16,
        cell_height: u16,
    ) -> Result<Self> {
        crate::shot::validate_geometry(rows, cols)?;
        if let Some(parent) = path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
        {
            fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
        }
        let mut open = OpenOptions::new();
        open.create(true).write(true).truncate(true);
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            open.mode(0o600);
        }
        let mut file = open
            .open(path)
            .with_context(|| format!("create {}", path.display()))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(path, fs::Permissions::from_mode(0o600))
                .with_context(|| format!("secure {}", path.display()))?;
        }
        serde_json::to_writer(
            &mut file,
            &Entry::Header {
                version: FORMAT_VERSION,
                cols,
                rows,
                cell_width,
                cell_height,
            },
        )
        .context("write recording header")?;
        file.write_all(b"\n").context("write recording newline")?;
        file.flush().context("flush recording header")?;
        Ok(Self { file, started })
    }

    pub fn output(&mut self, at_ms: u64, bytes: &[u8]) -> Result<()> {
        self.write(Entry::Output {
            at_ms,
            bytes: bytes.to_vec(),
        })
    }

    pub fn input(&mut self, origin: InputOrigin, bytes: &[u8]) -> Result<()> {
        self.write(Entry::Input {
            at_ms: self.started.elapsed().as_millis() as u64,
            origin,
            bytes: bytes.to_vec(),
        })
    }

    pub fn resize(
        &mut self,
        cols: u16,
        rows: u16,
        cell_width: u16,
        cell_height: u16,
    ) -> Result<()> {
        crate::shot::validate_geometry(rows, cols)?;
        self.write(Entry::Resize {
            at_ms: self.started.elapsed().as_millis() as u64,
            cols,
            rows,
            cell_width,
            cell_height,
        })
    }

    fn write(&mut self, entry: Entry) -> Result<()> {
        serde_json::to_writer(&mut self.file, &entry).context("write recording event")?;
        self.file
            .write_all(b"\n")
            .context("write recording newline")?;
        self.file.flush().context("flush recording event")
    }
}

pub struct VideoOptions {
    pub out: PathBuf,
    pub cell_width: Option<u16>,
    pub cell_height: Option<u16>,
    pub padding: f32,
    pub font_family: String,
    pub pixel_ratio: f32,
    pub hide_cursor: bool,
    pub fps: u32,
    pub max_idle: Option<Duration>,
    pub tail: Duration,
    pub include_startup: bool,
}

pub fn video(path: &Path, options: &VideoOptions) -> Result<()> {
    if options.fps == 0 {
        bail!("--fps must be greater than zero");
    }
    if options.fps > MAX_VIDEO_FPS {
        bail!("--fps must not exceed {MAX_VIDEO_FPS}");
    }
    let recording = read(path)?;
    let states = states(&recording);
    let states = visible_states(&states, options.include_startup);
    if states.is_empty() {
        bail!("recording contains no visible output frames");
    }
    let frames = common_canvas(samples(states, options));
    if let Some(parent) = options
        .out
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
    }
    let temp = std::env::temp_dir().join(format!(
        "termctrl-video-{}-{}",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos()
    ));
    fs::create_dir_all(&temp).with_context(|| format!("create {}", temp.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(&temp, fs::Permissions::from_mode(0o700))
            .with_context(|| format!("secure {}", temp.display()))?;
    }
    let result = render_video_frames(&temp, &recording, &frames, options);
    let _ = fs::remove_dir_all(&temp);
    result
}

/// Parsed recording metadata and timeline entries.
pub struct Recording {
    pub cols: u16,
    pub rows: u16,
    pub cell_width: u16,
    pub cell_height: u16,
    pub events: Vec<Entry>,
}

/// Read and validate a versioned `.termctrl` JSON Lines recording.
pub fn read(path: &Path) -> Result<Recording> {
    let file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
    let mut lines = BufReader::new(file).lines();
    let Some(header) = lines.next() else {
        bail!("recording is empty");
    };
    let Entry::Header {
        version,
        cols,
        rows,
        cell_width,
        cell_height,
        ..
    } = serde_json::from_str(&header.context("read recording header")?)
        .context("parse recording header")?
    else {
        bail!("recording does not start with a header");
    };
    if version != FORMAT_VERSION {
        bail!("unsupported recording version {version}");
    }
    crate::shot::validate_geometry(rows, cols)?;
    let events = lines
        .map(|line| {
            serde_json::from_str(&line.context("read recording event")?)
                .context("parse recording event")
        })
        .collect::<Result<Vec<Entry>>>()?;
    if events
        .iter()
        .any(|entry| matches!(entry, Entry::Header { .. }))
    {
        bail!("recording contains a header after the first line");
    }
    Ok(Recording {
        cols,
        rows,
        cell_width,
        cell_height,
        events,
    })
}

struct VideoFrame {
    at_ms: u64,
    frame: Frame,
}

fn states(recording: &Recording) -> Vec<VideoFrame> {
    let mut parser = crate::shot::terminal(recording.rows, recording.cols);
    let mut output = Vec::new();
    let mut frames: Vec<VideoFrame> = Vec::new();
    frames.push(VideoFrame {
        at_ms: 0,
        frame: from_screen(parser.screen()),
    });
    for event in &recording.events {
        let at_ms = match event {
            Entry::Output { at_ms, bytes } => {
                output.extend_from_slice(bytes);
                parser.process(bytes);
                *at_ms
            }
            Entry::Resize {
                at_ms, cols, rows, ..
            } => {
                parser = crate::shot::terminal(*rows, *cols);
                parser.process(&output);
                *at_ms
            }
            Entry::Input { .. } | Entry::Header { .. } => continue,
        };
        let frame = from_screen(parser.screen());
        if frames
            .last()
            .is_some_and(|previous| previous.frame == frame)
        {
            continue;
        }
        frames.push(VideoFrame { at_ms, frame });
    }
    frames
}

fn common_canvas(mut frames: Vec<Frame>) -> Vec<Frame> {
    let cols = frames.iter().map(|frame| frame.cols).max().unwrap_or(0);
    let rows = frames.iter().map(|frame| frame.rows).max().unwrap_or(0);
    for frame in &mut frames {
        frame.cols = cols;
        frame.rows = rows;
    }
    frames
}

fn visible_states(states: &[VideoFrame], include_startup: bool) -> &[VideoFrame] {
    if include_startup {
        return states;
    }
    let visible = states
        .iter()
        .position(|frame| has_non_whitespace_text(&frame.frame))
        .or_else(|| {
            states
                .iter()
                .position(|frame| frame.frame.has_visible_content())
        })
        .unwrap_or(states.len());
    &states[visible..]
}

fn has_non_whitespace_text(frame: &Frame) -> bool {
    frame.cells.iter().any(|cell| !cell.text.trim().is_empty())
}

fn samples(states: &[VideoFrame], options: &VideoOptions) -> Vec<Frame> {
    if states.is_empty() {
        return Vec::new();
    }
    let mut timeline = Vec::with_capacity(states.len());
    let mut at_ms = 0_u64;
    for (index, state) in states.iter().enumerate() {
        timeline.push(at_ms);
        if let Some(next) = states.get(index + 1) {
            let gap = Duration::from_millis(next.at_ms.saturating_sub(state.at_ms));
            let gap = options.max_idle.map_or(gap, |max| gap.min(max));
            at_ms = at_ms.saturating_add(gap.as_millis() as u64);
        }
    }
    let end_ms = at_ms.saturating_add(options.tail.as_millis() as u64);
    let mut output = Vec::new();
    let mut state = 0;
    let mut sample = 0_u64;
    loop {
        let sample_ms = u128::from(sample) * 1000 / u128::from(options.fps);
        if sample_ms > u128::from(end_ms) {
            break;
        }
        let sample_ms = sample_ms as u64;
        while state + 1 < timeline.len() && timeline[state + 1] <= sample_ms {
            state += 1;
        }
        output.push(states[state].frame.clone());
        sample += 1;
    }
    if output.last() != states.last().map(|state| &state.frame) {
        output.push(states.last().expect("non-empty states").frame.clone());
    }
    output
}

fn render_video_frames(
    temp: &Path,
    recording: &Recording,
    frames: &[Frame],
    options: &VideoOptions,
) -> Result<()> {
    for (index, frame) in frames.iter().enumerate() {
        let path = temp.join(format!("frame-{index:06}.png"));
        render::png(
            &render::svg(
                frame,
                &render::Options {
                    cell_width: f32::from(options.cell_width.unwrap_or(recording.cell_width)),
                    cell_height: f32::from(options.cell_height.unwrap_or(recording.cell_height)),
                    font_size: f32::from(options.cell_height.unwrap_or(recording.cell_height))
                        * 0.78,
                    padding: options.padding,
                    font_family: options.font_family.clone(),
                    show_cursor: !options.hide_cursor,
                },
            ),
            &path,
            options.pixel_ratio,
        )?;
    }
    let status = Command::new("ffmpeg")
        .args(["-y", "-loglevel", "error", "-framerate"])
        .arg(options.fps.to_string())
        .arg("-i")
        .arg(temp.join("frame-%06d.png"))
        .args(["-vf", "format=yuv420p", "-movflags", "+faststart"])
        .arg(&options.out)
        .status()
        .context("run ffmpeg; install ffmpeg to export recorded sessions as video")?;
    if !status.success() {
        bail!("ffmpeg failed while exporting {}", options.out.display());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn frame(text: &str) -> Frame {
        Frame {
            version: 1,
            cols: 2,
            rows: 1,
            foreground: crate::frame::DEFAULT_FOREGROUND,
            background: crate::frame::DEFAULT_BACKGROUND,
            cursor: None,
            cells: (!text.is_empty())
                .then(|| crate::frame::Cell {
                    x: 0,
                    y: 0,
                    text: text.to_owned(),
                    width: 1,
                    foreground: crate::frame::DEFAULT_FOREGROUND,
                    background: crate::frame::DEFAULT_BACKGROUND,
                    attributes: crate::frame::Attributes::default(),
                })
                .into_iter()
                .collect(),
        }
    }

    fn options() -> VideoOptions {
        VideoOptions {
            out: PathBuf::from("video.mp4"),
            cell_width: None,
            cell_height: None,
            padding: 0.0,
            font_family: String::new(),
            pixel_ratio: 1.0,
            hide_cursor: true,
            fps: 20,
            max_idle: None,
            tail: Duration::ZERO,
            include_startup: false,
        }
    }

    fn painted_frame() -> Frame {
        let mut parser = crate::shot::terminal(1, 2);
        parser.process(b"\x1b[48;2;30;34;42m ");
        from_screen(parser.screen())
    }

    #[test]
    fn idle_compression_caps_sampled_frame_duration() {
        let initial = frame("a");
        let final_frame = frame("b");
        let mut options = options();
        options.max_idle = Some(Duration::from_millis(500));

        let frames = samples(
            &[
                VideoFrame {
                    at_ms: 0,
                    frame: initial,
                },
                VideoFrame {
                    at_ms: 4000,
                    frame: final_frame.clone(),
                },
            ],
            &options,
        );

        assert_eq!(frames.len(), 11);
        assert_eq!(frames.last(), Some(&final_frame));
    }

    #[test]
    fn preserves_input_origin_and_binary_output() {
        let temp =
            std::env::temp_dir().join(format!("termctrl-recording-test-{}", std::process::id()));
        let mut writer = Writer::new(&temp, Instant::now(), 2, 1, 9, 18).unwrap();
        writer.output(1, &[0, 255, b'A']).unwrap();
        writer.input(InputOrigin::Host, b"reply").unwrap();
        drop(writer);

        let recording = read(&temp).unwrap();
        let _ = fs::remove_file(temp);
        assert!(matches!(
            &recording.events[0],
            Entry::Output { at_ms: 1, bytes } if bytes == &[0, 255, b'A']
        ));
        assert!(matches!(
            &recording.events[1],
            Entry::Input { origin: InputOrigin::Host, bytes, .. } if bytes == b"reply"
        ));
    }

    #[test]
    fn replays_resized_recordings_on_a_stable_video_canvas() {
        let recording = Recording {
            cols: 2,
            rows: 1,
            cell_width: 9,
            cell_height: 18,
            events: vec![
                Entry::Output {
                    at_ms: 1,
                    bytes: b"a".to_vec(),
                },
                Entry::Resize {
                    at_ms: 2,
                    cols: 4,
                    rows: 2,
                    cell_width: 9,
                    cell_height: 18,
                },
            ],
        };

        let frames = common_canvas(samples(&states(&recording), &options()));

        assert!(
            frames
                .iter()
                .all(|frame| (frame.cols, frame.rows) == (4, 2))
        );
        assert_eq!(frames.last().unwrap().text(), "a");
    }

    #[test]
    fn preserves_background_only_output_when_no_text_is_recorded() {
        let painted = painted_frame();
        let frames = vec![
            VideoFrame {
                at_ms: 0,
                frame: frame(""),
            },
            VideoFrame {
                at_ms: 1,
                frame: painted.clone(),
            },
        ];

        assert_eq!(visible_states(&frames, false)[0].frame, painted);
    }

    #[test]
    fn keeps_final_change_between_sampling_ticks() {
        let initial = frame("a");
        let final_frame = frame("b");
        let frames = samples(
            &[
                VideoFrame {
                    at_ms: 0,
                    frame: initial.clone(),
                },
                VideoFrame {
                    at_ms: 1,
                    frame: final_frame.clone(),
                },
            ],
            &options(),
        );

        assert_eq!(frames, vec![initial, final_frame]);
    }

    #[test]
    fn samples_fractional_frame_intervals_without_an_early_transition() {
        let initial = frame("a");
        let final_frame = frame("b");
        let mut options = options();
        options.fps = 30;

        let frames = samples(
            &[
                VideoFrame {
                    at_ms: 0,
                    frame: initial.clone(),
                },
                VideoFrame {
                    at_ms: 100,
                    frame: final_frame.clone(),
                },
            ],
            &options,
        );

        assert_eq!(
            frames,
            vec![initial.clone(), initial.clone(), initial, final_frame]
        );
    }

    #[test]
    fn rejects_excessive_video_frame_rates_before_reading_input() {
        let mut options = options();
        options.fps = MAX_VIDEO_FPS + 1;

        assert_eq!(
            video(Path::new("not-read.termctrl"), &options)
                .unwrap_err()
                .to_string(),
            "--fps must not exceed 1000"
        );
    }

    #[test]
    fn rejects_invalid_geometry_and_repeated_headers() {
        let invalid =
            std::env::temp_dir().join(format!("termctrl-invalid-recording-{}", std::process::id()));
        fs::write(&invalid, "{\"type\":\"header\",\"version\":1,\"cols\":0,\"rows\":1,\"cell_width\":9,\"cell_height\":18}\n").unwrap();
        assert!(read(&invalid).is_err());
        fs::write(&invalid, "{\"type\":\"header\",\"version\":1,\"cols\":1,\"rows\":1,\"cell_width\":9,\"cell_height\":18}\n{\"type\":\"header\",\"version\":1,\"cols\":1,\"rows\":1,\"cell_width\":9,\"cell_height\":18}\n").unwrap();
        assert!(read(&invalid).is_err());
        let _ = fs::remove_file(invalid);
    }
}