noctiluca 0.0.3

A terminal web browser: page text as terminal text, media as media
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
//! A scripted [`Engine`] for tests: pages from saved snapshots, actions
//! recorded, and a hook to change the page when an action runs. No
//! browser.

use std::collections::HashMap;
use std::io;
use std::sync::{Arc, Mutex};

use rich_embed::{PageState, ScreencastFrame};
use serde_json::Value;

use crate::engine::{
    Engine, EngineEvent, Format, Frame, HistoryStep, MediaOp, Metrics, PageAction, PageSnapshot,
    Playback, Rect, TabId,
};

/// What a [`FakeEngine`] shows, shared with the test.
#[derive(Default)]
pub struct FakeState {
    /// Snapshots by name (`"reader"`); a URL opens the one whose name its
    /// last path segment starts with.
    pub pages: HashMap<String, PageSnapshot>,
    pub current: Option<String>,
    pub history: Vec<String>,
    pub at: usize,
    /// Every action the engine was asked for, in order.
    pub actions: Vec<PageAction>,
    pub opened: Vec<String>,
    pub events: Vec<EngineEvent>,
    /// Media elements' playback, by node; media ops change it.
    pub media: HashMap<i64, Playback>,
    /// The CSS pixels above the viewport: scrolling and the wheel move it,
    /// within the document.
    pub scroll_y: f64,
    /// The viewport's height in CSS pixels.
    pub viewport_height: f64,
    /// Image nodes whose picture has not loaded (lazy, below the fold).
    pub not_loaded: std::collections::HashSet<i64>,
    /// Whether the screencast is on.
    pub screencast: bool,
    /// The screencast's scale, as last asked for (0 until it is).
    pub screencast_scale: f64,
    /// Screencast frames waiting to be taken, oldest first: a test pushes
    /// them.
    pub frames: Vec<ScreencastFrame>,
    /// `canPlayType`'s answers by media type.
    pub codecs: HashMap<String, String>,
    /// Resources the page loaded, by address: an image's original bytes.
    pub resources: HashMap<String, Vec<u8>>,
    /// Where resources not in [`resources`](Self::resources) are read
    /// from: a fixture directory, by the address's path after its last
    /// `/fixtures/` (else its last segment). Saved snapshots name their
    /// fixtures `file:///noctiluca/fixtures/…`.
    pub resource_root: Option<std::path::PathBuf>,
    /// Chrome's recorded frames of videos (`STEM-NN.jpg`, the capture
    /// example's `--frames`, evenly spaced over the video's length): with
    /// them, the page's videos play as Chrome played them, autoplaying
    /// ones from the start, and the screencast shows them in their boxes,
    /// each the frame at the video's clock. `None`: a test pushes its own
    /// frames.
    pub recorded: Option<std::path::PathBuf>,
    /// The recorded frames read so far, by stem.
    recorded_frames: HashMap<String, Vec<image::RgbImage>>,
    /// When each playing video's clock started.
    playing_since: HashMap<i64, std::time::Instant>,
    /// The viewport's width in CSS pixels.
    pub viewport_width: f64,
}

impl FakeState {
    /// The bytes of the resource at `url`, if the test has them.
    pub fn resource(&self, url: &str) -> Option<Vec<u8>> {
        if let Some(bytes) = self.resources.get(url) {
            return Some(bytes.clone());
        }
        let root = self.resource_root.as_ref()?;
        let path = url.split(['?', '#']).next().unwrap_or(url);
        let relative = match path.rfind("/fixtures/") {
            Some(at) => &path[at + "/fixtures/".len()..],
            None => path.rsplit('/').next().unwrap_or(path),
        };
        // Never above the root.
        if relative
            .split('/')
            .any(|part| part == ".." || part.is_empty())
        {
            return None;
        }
        std::fs::read(root.join(relative)).ok()
    }
}

impl FakeState {
    /// The current page's height in CSS pixels.
    pub fn content_height(&self) -> f64 {
        self.current
            .as_ref()
            .and_then(|name| self.pages.get(name))
            .and_then(|s| s.dom["documents"][0]["contentHeight"].as_f64())
            .unwrap_or(0.0)
    }
}

/// A snapshot of a feed page at `url`: a heading, then `posts` paragraphs
/// ("Post 1", "Post 2", …), each 36 CSS pixels below the last, laid out
/// as Chrome would report them, with no accessibility tree. A test grows
/// it to stand for a page whose IntersectionObserver appended more.
pub fn feed_snapshot(url: &str, posts: usize) -> PageSnapshot {
    feed_snapshot_of(url, 1, posts as i64)
}

/// [`feed_snapshot`] with posts `first` to `last`: posts before 1 stand
/// for posts the page inserted above. Each post's nodes keep their
/// `backendNodeId` whatever is around them, as Chrome's do.
pub fn feed_snapshot_of(url: &str, first: i64, last: i64) -> PageSnapshot {
    let posts = (last - first + 1).max(0) as usize;
    use serde_json::json;
    // Strings: 0 url, 1 title, then names and style values.
    let mut strings: Vec<String> = [
        url,
        "Feed",
        "#document",
        "HTML",
        "BODY",
        "H1",
        "P",
        "#text",
        "block",
        "visible",
        "rgb(0, 0, 0)",
        "rgba(0, 0, 0, 0)",
        "400",
        "normal",
        "none",
        "1",
        "700",
        "inline",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    let block = json!([8, 9, 10, 11, 12, 13, 14, 13, 15]);
    let bold = json!([8, 9, 10, 11, 16, 13, 14, 13, 15]);
    let inline = json!([17, 9, 10, 11, 12, 13, 14, 13, 15]);
    let (mut parent, mut kind, mut name, mut value, mut backend) = (
        vec![-1, 0, 1],
        vec![9, 1, 1],
        vec![2, 3, 4],
        vec![-1, -1, -1],
        vec![1, 2, 3],
    );
    let height = 60.0 + 36.0 * posts as f64;
    let mut layout_node = vec![0, 1, 2];
    let mut styles = vec![json!([]), block.clone(), block.clone()];
    let mut bounds = vec![
        json!([0, 0, 800, height]),
        json!([0, 0, 800, height]),
        json!([8, 8, 784, height - 16.0]),
    ];
    let mut text = vec![-1i64, -1, -1];
    let mut push = |tag: i64, id: i64, words: String, y: f64, style: &serde_json::Value| {
        let element = parent.len() as i64;
        parent.push(2);
        kind.push(1);
        name.push(tag);
        value.push(-1);
        backend.push(id);
        let at = strings.len() as i64;
        strings.push(words);
        parent.push(element);
        kind.push(3);
        name.push(7);
        value.push(at);
        backend.push(id + 1);
        layout_node.push(element);
        styles.push(style.clone());
        bounds.push(json!([8, y, 784, 18]));
        text.push(-1);
        layout_node.push(element + 1);
        styles.push(inline.clone());
        bounds.push(json!([8, y, 60, 18]));
        text.push(at);
    };
    push(5, 10, "Feed".into(), 8.0, &bold);
    for (k, post) in (first..=last).enumerate() {
        let id = 100_000 + 2 * post;
        push(
            6,
            id,
            format!("Post {post}"),
            60.0 + 36.0 * k as f64,
            &block,
        );
    }
    let n = parent.len();
    let empty = || json!({"index": [], "value": []});
    let dom = json!({
        "documents": [{
            "documentURL": 0, "title": 1, "baseURL": 0,
            "contentWidth": 800, "contentHeight": height,
            "scrollOffsetX": 0, "scrollOffsetY": 0,
            "nodes": {
                "parentIndex": parent, "nodeType": kind, "nodeName": name,
                "nodeValue": value, "backendNodeId": backend,
                "attributes": vec![json!([]); n],
                "textValue": empty(), "inputValue": empty(),
                "inputChecked": {"index": []}, "optionSelected": {"index": []},
                "currentSourceURL": empty(),
            },
            "layout": {
                "nodeIndex": layout_node, "styles": styles, "bounds": bounds, "text": text,
            },
        }],
        "strings": strings,
    });
    PageSnapshot {
        dom,
        ax: Value::Null,
    }
}

/// A page's snapshot written by hand, in the shape Chrome gives one: for
/// a reduced fixture page whose layout a test states (each box's place
/// in CSS pixels), when no browser can capture it. Elements take their
/// computed styles by name (any of [`SNAPSHOT_STYLES`](crate::cdp::SNAPSHOT_STYLES)),
/// the inherited ones from their parent as CSS does; a text node takes
/// its parent's, as Chrome reports a text's style. Nodes are in document
/// order, each `backendNodeId` its index plus one.
pub struct PageBuilder {
    url: String,
    title: String,
    width: f64,
    height: f64,
    parent: Vec<i64>,
    kind: Vec<i64>,
    name: Vec<String>,
    value: Vec<Option<String>>,
    attrs: Vec<Vec<(String, String)>>,
    /// Each node's computed styles (in [`SNAPSHOT_STYLES`](crate::cdp::SNAPSHOT_STYLES)'s order) and
    /// box, when it has a layout box.
    layout: Vec<Option<(Vec<String>, Rect)>>,
    current_source: Vec<(usize, String)>,
}

/// The computed styles CSS inherits, among the snapshot's.
const INHERITED: &[&str] = &[
    "visibility",
    "color",
    "font-weight",
    "font-style",
    "white-space",
];

/// A style's initial value, as Chrome computes it.
fn initial(name: &str) -> &'static str {
    match name {
        "display" => "block",
        "visibility" => "visible",
        "color" => "rgb(0, 0, 0)",
        "background-color" => "rgba(0, 0, 0, 0)",
        "font-weight" => "400",
        "font-style" | "white-space" => "normal",
        "text-decoration-line" | "background-image" => "none",
        "opacity" => "1",
        "overflow-y" | "overflow-x" => "visible",
        "flex-wrap" => "nowrap",
        "clip" => "auto",
        "clip-path" => "none",
        "position" => "static",
        _ => "",
    }
}

impl PageBuilder {
    /// A page at `url`, `width` by `height` CSS pixels: the document, its
    /// `<html>` and its `<body>` (see [`body`](Self::body)), both the
    /// page's size.
    pub fn new(url: &str, title: &str, width: f64, height: f64) -> PageBuilder {
        let mut page = PageBuilder {
            url: url.to_string(),
            title: title.to_string(),
            width,
            height,
            parent: Vec::new(),
            kind: Vec::new(),
            name: Vec::new(),
            value: Vec::new(),
            attrs: Vec::new(),
            layout: Vec::new(),
            current_source: Vec::new(),
        };
        let all = Rect::new(0.0, 0.0, width, height);
        page.push(-1, 9, "#document", None, &[], Some(all));
        page.element(0, "HTML", &[], &[], Some(all));
        page.element(1, "BODY", &[], &[], Some(all));
        page
    }

    /// The `<body>`'s node.
    pub fn body(&self) -> usize {
        2
    }

    fn push(
        &mut self,
        parent: i64,
        kind: i64,
        name: &str,
        value: Option<&str>,
        styles: &[(&str, &str)],
        rect: Option<Rect>,
    ) -> usize {
        let at = self.parent.len();
        let from = usize::try_from(parent)
            .ok()
            .and_then(|p| self.layout.get(p).cloned().flatten())
            .map(|(s, _)| s);
        let computed = crate::cdp::SNAPSHOT_STYLES
            .iter()
            .enumerate()
            .map(|(k, &style)| {
                if let Some((_, v)) = styles.iter().find(|(n, _)| *n == style) {
                    return v.to_string();
                }
                match &from {
                    Some(from) if kind == 3 || INHERITED.contains(&style) => from[k].clone(),
                    _ => initial(style).to_string(),
                }
            })
            .collect();
        self.parent.push(parent);
        self.kind.push(kind);
        self.name.push(name.to_string());
        self.value.push(value.map(str::to_string));
        self.attrs.push(Vec::new());
        self.layout.push(rect.map(|r| (computed, r)));
        at
    }

    /// An element under `parent`: its tag, attributes, the computed
    /// styles that are not their initial or inherited values (`display`
    /// is `block` unless given), and its box; `None` for no layout box
    /// (`display: none`).
    pub fn element(
        &mut self,
        parent: usize,
        tag: &str,
        attrs: &[(&str, &str)],
        styles: &[(&str, &str)],
        rect: Option<Rect>,
    ) -> usize {
        // A box under a parent with none has none either.
        let rect = rect.filter(|_| self.layout[parent].is_some());
        let at = self.push(parent as i64, 1, tag, None, styles, rect);
        self.attrs[at] = attrs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        at
    }

    /// Set one computed style of a laid-out node (the `<body>`'s
    /// background, say); its children made after take what they inherit.
    pub fn set_style(&mut self, node: usize, style: &str, value: &str) {
        let at = crate::cdp::SNAPSHOT_STYLES.iter().position(|s| *s == style);
        if let (Some(at), Some((styles, _))) = (at, self.layout[node].as_mut()) {
            styles[at] = value.to_string();
        }
    }

    /// A text node under `parent`, laid out in `rect` (the union of its
    /// line boxes) unless its parent has no box.
    pub fn text(&mut self, parent: usize, text: &str, rect: Rect) -> usize {
        let rect = self.layout[parent].is_some().then_some(rect);
        self.push(parent as i64, 3, "#text", Some(text), &[], rect)
    }

    /// An `<img>` under `parent`: its `src`, `alt` and box.
    pub fn image(&mut self, parent: usize, src: &str, alt: &str, rect: Rect) -> usize {
        let at = self.element(
            parent,
            "IMG",
            &[("src", src), ("alt", alt)],
            &[("display", "inline")],
            Some(rect),
        );
        self.current_source.push((at, src.to_string()));
        at
    }

    /// The snapshot, as `DOMSnapshot.captureSnapshot` shapes it, with no
    /// accessibility tree.
    pub fn snapshot(&self) -> PageSnapshot {
        use serde_json::json;
        let mut strings: Vec<String> = Vec::new();
        let mut index: HashMap<String, i64> = HashMap::new();
        let mut s = |text: &str| -> i64 {
            if let Some(&i) = index.get(text) {
                return i;
            }
            strings.push(text.to_string());
            index.insert(text.to_string(), strings.len() as i64 - 1);
            strings.len() as i64 - 1
        };
        let url = s(&self.url);
        let title = s(&self.title);
        let names: Vec<i64> = self.name.iter().map(|n| s(n)).collect();
        let values: Vec<i64> = self
            .value
            .iter()
            .map(|v| v.as_deref().map_or(-1, &mut s))
            .collect();
        let attrs: Vec<Vec<i64>> = self
            .attrs
            .iter()
            .map(|list| list.iter().flat_map(|(k, v)| [s(k), s(v)]).collect())
            .collect();
        let (mut node_index, mut styles, mut bounds, mut text) =
            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
        for (i, layout) in self.layout.iter().enumerate() {
            let Some((computed, rect)) = layout else {
                continue;
            };
            node_index.push(i as i64);
            styles.push(computed.iter().map(|v| s(v)).collect::<Vec<_>>());
            bounds.push(json!([rect.x, rect.y, rect.width, rect.height]));
            text.push(if self.kind[i] == 3 { values[i] } else { -1 });
        }
        let source = (
            self.current_source
                .iter()
                .map(|(i, _)| *i as i64)
                .collect::<Vec<_>>(),
            self.current_source
                .iter()
                .map(|(_, u)| s(u))
                .collect::<Vec<_>>(),
        );
        let n = self.parent.len();
        let empty = || json!({"index": [], "value": []});
        let dom = json!({
            "documents": [{
                "documentURL": url, "title": title, "baseURL": url,
                "contentWidth": self.width, "contentHeight": self.height,
                "scrollOffsetX": 0, "scrollOffsetY": 0,
                "nodes": {
                    "parentIndex": self.parent, "nodeType": self.kind,
                    "nodeName": names, "nodeValue": values,
                    "backendNodeId": (1..=n as i64).collect::<Vec<_>>(),
                    "attributes": attrs,
                    "textValue": empty(), "inputValue": empty(),
                    "inputChecked": {"index": []}, "optionSelected": {"index": []},
                    "currentSourceURL": {"index": source.0, "value": source.1},
                },
                "layout": {
                    "nodeIndex": node_index, "styles": styles, "bounds": bounds, "text": text,
                },
            }],
            "strings": strings,
        });
        PageSnapshot {
            dom,
            ax: Value::Null,
        }
    }
}

/// What a test does when an action runs.
pub type OnAct = Box<dyn FnMut(&PageAction, &mut FakeState) + Send>;

/// A browser that is not one.
pub struct FakeEngine {
    pub state: Arc<Mutex<FakeState>>,
    on_act: Option<OnAct>,
}

/// A saved snapshot (`{"dom": …, "ax": …}`) from a JSON file.
pub fn snapshot_file(path: &std::path::Path) -> io::Result<PageSnapshot> {
    let all: Value = serde_json::from_str(&std::fs::read_to_string(path)?)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    Ok(PageSnapshot {
        dom: all["dom"].clone(),
        ax: all["ax"].clone(),
    })
}

impl FakeEngine {
    /// An engine over the snapshots in `dir` (`NAME.json` each), showing
    /// none yet. Resources come from the `fixtures` directory beside it,
    /// when there is one.
    pub fn from_dir(dir: &std::path::Path) -> io::Result<FakeEngine> {
        let mut state = FakeState::default();
        let fixtures = dir.join("..").join("fixtures");
        if fixtures.is_dir() {
            state.resource_root = Some(fixtures);
        }
        for entry in std::fs::read_dir(dir)? {
            let path = entry?.path();
            if path.extension().is_some_and(|e| e == "json") {
                let name = path
                    .file_stem()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string();
                state.pages.insert(name, snapshot_file(&path)?);
            }
        }
        Ok(FakeEngine {
            state: Arc::new(Mutex::new(state)),
            on_act: None,
        })
    }

    /// Play videos from Chrome's recorded frames in `dir` (see
    /// [`FakeState::recorded`]).
    #[must_use]
    pub fn replaying(self, dir: &std::path::Path) -> FakeEngine {
        self.lock().recorded = Some(dir.to_path_buf());
        self
    }

    /// Run `hook` on each action, to change the page as a browser would.
    #[must_use]
    pub fn on_act(
        mut self,
        hook: impl FnMut(&PageAction, &mut FakeState) + Send + 'static,
    ) -> FakeEngine {
        self.on_act = Some(Box::new(hook));
        self
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, FakeState> {
        self.state.lock().unwrap_or_else(|e| e.into_inner())
    }
}

impl FakeState {
    /// Go to the page `url` names, as a new history entry.
    pub fn go(&mut self, url: &str) {
        let name = url
            .rsplit('/')
            .next()
            .unwrap_or(url)
            .split(['.', '?', '#'])
            .next()
            .unwrap_or_default()
            .to_string();
        self.history
            .truncate(self.at + usize::from(!self.history.is_empty()));
        self.history.push(name.clone());
        self.at = self.history.len() - 1;
        self.current = Some(name);
        self.events.push(EngineEvent::Navigated(url.to_string()));
        if self.recorded.is_some() {
            self.ready_videos();
        }
    }

    /// The current page's videos, ready to play as the recording did:
    /// five seconds long, muted, the `autoplay` ones playing.
    fn ready_videos(&mut self) {
        let Some(page) = self.current.as_ref().and_then(|n| self.pages.get(n)) else {
            return;
        };
        let model = crate::model::build(page, &mut crate::model::Revisions::new());
        for video in model
            .media
            .iter()
            .filter(|m| m.kind == crate::model::MediaKind::Video)
        {
            self.media.entry(video.node).or_insert(Playback {
                paused: !video.autoplay,
                muted: true,
                volume: 1.0,
                duration: Some(5.0),
                ready: 4,
                ..Playback::default()
            });
            if video.autoplay {
                self.playing_since
                    .insert(video.node, std::time::Instant::now());
            }
        }
    }

    /// A recorded video's length in seconds.
    fn length(&self, node: i64) -> f64 {
        self.media
            .get(&node)
            .and_then(|p| p.duration)
            .unwrap_or(5.0)
            .max(0.1)
    }

    /// A playing recorded video's clock: the seconds since it started
    /// playing (or as far as it had played), looping over its length.
    fn clock(&self, node: i64) -> Option<f64> {
        let since = self.playing_since.get(&node)?;
        Some(since.elapsed().as_secs_f64() % self.length(node))
    }

    /// A frame with each playing video's recorded frame in its box, as
    /// Chrome's screencast paints it. It spans the playing videos (its
    /// scroll at their top), wherever the scripted view is.
    fn recorded_frame(&mut self) -> Option<ScreencastFrame> {
        let dir = self.recorded.clone()?;
        let page = self.current.as_ref().and_then(|n| self.pages.get(n))?;
        let model = crate::model::build(page, &mut crate::model::Revisions::new());
        let playing: Vec<_> = model
            .media
            .iter()
            .filter(|m| m.kind == crate::model::MediaKind::Video)
            .filter(|m| self.media.get(&m.node).is_some_and(|p| !p.paused))
            .cloned()
            .collect();
        let top = playing.iter().map(|m| m.rect.y).fold(f64::MAX, f64::min);
        let bottom = playing.iter().map(|m| m.rect.bottom()).fold(0.0, f64::max);
        if playing.is_empty() || bottom <= top {
            return None;
        }
        let width = self.viewport_width.max(80.0) as u32;
        let height = (bottom - top).ceil().max(1.0) as u32;
        let mut canvas = image::RgbImage::new(width, height);
        for video in &playing {
            let stem = video
                .src
                .rsplit('/')
                .next()
                .and_then(|name| name.split('.').next())
                .unwrap_or_default()
                .to_string();
            // The frame at the clock the status line shows: the frames
            // span the video's length.
            let at = self.clock(video.node).unwrap_or(0.0) / self.length(video.node);
            let frames = self.recorded_frames.entry(stem.clone()).or_insert_with(|| {
                (0..100)
                    .map_while(|k| image::open(dir.join(format!("{stem}-{k:02}.jpg"))).ok())
                    .map(|i| i.to_rgb8())
                    .collect()
            });
            if frames.is_empty() {
                continue;
            }
            let frame = &frames[((at * frames.len() as f64) as usize).min(frames.len() - 1)];
            let (w, h) = (video.rect.width.max(1.0), video.rect.height.max(1.0));
            let scaled = image::imageops::resize(
                frame,
                w as u32,
                h as u32,
                image::imageops::FilterType::Triangle,
            );
            image::imageops::overlay(
                &mut canvas,
                &scaled,
                video.rect.x as i64,
                (video.rect.y - top) as i64,
            );
        }
        let scroll_y = top;
        Some(ScreencastFrame {
            pixels: rich_embed::Pixels::new(width, height, canvas.into_raw())?,
            meta: rich_embed::FrameMeta {
                scroll_x: 0.0,
                scroll_y,
                offset_top: 0.0,
                page_scale: 1.0,
                device_width: width as f64,
                device_height: height as f64,
                timestamp: None,
            },
        })
    }
}

/// What a click does when a test says nothing else: a link goes where
/// it points, to the saved page its address's last segment names.
pub fn follow(action: &PageAction, state: &mut FakeState) {
    let PageAction::Click(node) = action else {
        return;
    };
    let Some(page) = state
        .current
        .as_ref()
        .and_then(|name| state.pages.get(name))
    else {
        return;
    };
    let model = crate::model::build(page, &mut crate::model::Revisions::new());
    if let Some(href) = model.control(*node).and_then(|c| c.href.clone()) {
        let target = href.rsplit('/').next().unwrap_or_default().to_string();
        state.go(&target);
    }
}

impl Engine for FakeEngine {
    fn resize(&mut self, columns: u16, rows: u16) -> io::Result<()> {
        let mut state = self.lock();
        state.viewport_height = rows as f64 * crate::cdp::CELL.1 as f64;
        state.viewport_width = columns as f64 * crate::cdp::CELL.0 as f64;
        Ok(())
    }

    fn open(&mut self, _tab: TabId, url: &str) -> io::Result<()> {
        let mut state = self.lock();
        state.opened.push(url.to_string());
        state.go(url);
        Ok(())
    }

    fn history(&mut self, _tab: TabId, step: HistoryStep) -> io::Result<()> {
        let mut state = self.lock();
        match step {
            HistoryStep::Back if state.at > 0 => state.at -= 1,
            HistoryStep::Forward if state.at + 1 < state.history.len() => state.at += 1,
            _ => {}
        }
        let at = state.at;
        state.current = state.history.get(at).cloned();
        state.events.push(EngineEvent::Loaded);
        Ok(())
    }

    fn state(&self, _tab: TabId) -> PageState {
        let state = self.lock();
        let url = state
            .current
            .as_ref()
            .and_then(|name| state.pages.get(name))
            .map(|s| {
                let strings = &s.dom["strings"];
                s.dom["documents"][0]["documentURL"]
                    .as_u64()
                    .and_then(|i| strings[i as usize].as_str())
                    .unwrap_or_default()
                    .to_string()
            })
            .unwrap_or_default();
        PageState {
            url,
            can_go_back: state.at > 0,
            can_go_forward: state.at + 1 < state.history.len(),
            ..PageState::default()
        }
    }

    fn snapshot(&mut self, _tab: TabId) -> io::Result<PageSnapshot> {
        let state = self.lock();
        state
            .current
            .as_ref()
            .and_then(|name| state.pages.get(name))
            .cloned()
            .ok_or_else(|| io::Error::other("no page"))
    }

    fn capture(&mut self, _tab: TabId, region: Rect, format: Format) -> io::Result<Frame> {
        // A blue picture of the region's size, as PNG.
        let (w, h) = (region.width.max(1.0) as u32, region.height.max(1.0) as u32);
        let image = image::RgbImage::from_pixel(w, h, image::Rgb([30, 90, 220]));
        let mut bytes = Vec::new();
        image
            .write_to(
                &mut std::io::Cursor::new(&mut bytes),
                image::ImageFormat::Png,
            )
            .map_err(io::Error::other)?;
        Ok(Frame { format, bytes })
    }

    fn act(&mut self, _tab: TabId, action: &PageAction) -> io::Result<()> {
        let mut hook = self.on_act.take();
        {
            let mut state = self.lock();
            state.actions.push(action.clone());
            // Scrolling moves within the document, as a browser's does.
            let bottom = (state.content_height() - state.viewport_height).max(0.0);
            match action {
                PageAction::ScrollTo(y) => state.scroll_y = y.clamp(0.0, bottom),
                PageAction::Wheel(d) => state.scroll_y = (state.scroll_y + d).clamp(0.0, bottom),
                _ => {}
            }
            if let PageAction::Media { node, op } = action {
                // A recorded video's clock stops where it is; a play, or a
                // seek while playing, starts it again from its time.
                let recorded = state.recorded.is_some();
                if recorded {
                    if let Some(time) = state.clock(*node)
                        && let Some(p) = state.media.get_mut(node)
                    {
                        p.time = time;
                    }
                    state.playing_since.remove(node);
                }
                if let Some(p) = state.media.get_mut(node) {
                    match op {
                        MediaOp::Play => p.paused = false,
                        MediaOp::Pause => p.paused = true,
                        MediaOp::Mute(on) => p.muted = *on,
                        MediaOp::Volume(v) => p.volume = *v,
                        MediaOp::Seek(d) => {
                            let end = p.duration.unwrap_or(p.time);
                            p.time = (p.time + d).clamp(0.0, end);
                        }
                    }
                }
                if let Some(p) = state.media.get(node).filter(|p| recorded && !p.paused) {
                    let start = std::time::Instant::now()
                        .checked_sub(std::time::Duration::from_secs_f64(p.time))
                        .unwrap_or_else(std::time::Instant::now);
                    state.playing_since.insert(*node, start);
                }
                state.events.push(EngineEvent::Changed);
            }
            match hook.as_mut() {
                Some(hook) => hook(action, &mut state),
                None => follow(action, &mut state),
            }
        }
        self.on_act = hook;
        Ok(())
    }

    fn playback(&mut self, _tab: TabId, node: i64) -> io::Result<Playback> {
        let state = self.lock();
        let mut playback = state
            .media
            .get(&node)
            .copied()
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no media"))?;
        // A recorded video's clock runs while it plays, looping.
        if let Some(time) = state.clock(node).filter(|_| !playback.paused) {
            playback.time = time;
        }
        Ok(playback)
    }

    fn image_ready(&mut self, _tab: TabId, node: i64) -> io::Result<bool> {
        Ok(!self.lock().not_loaded.contains(&node))
    }

    fn resource(&mut self, _tab: TabId, url: &str) -> io::Result<Vec<u8>> {
        self.lock()
            .resource(url)
            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no such resource"))
    }

    fn metrics(&mut self, _tab: TabId) -> io::Result<Metrics> {
        let state = self.lock();
        Ok(Metrics {
            scroll_y: state.scroll_y,
            content_height: state.content_height(),
            viewport_height: state.viewport_height,
        })
    }

    fn set_screencast(&mut self, _tab: TabId, on: bool) -> io::Result<()> {
        self.lock().screencast = on;
        Ok(())
    }

    fn set_screencast_scale(&mut self, _tab: TabId, scale: f64) -> io::Result<()> {
        self.lock().screencast_scale = scale;
        Ok(())
    }

    fn screencast_frame(&mut self, _tab: TabId) -> Option<ScreencastFrame> {
        let mut state = self.lock();
        if state.screencast && state.frames.is_empty() && state.recorded.is_some() {
            return state.recorded_frame();
        }
        if !state.screencast || state.frames.is_empty() {
            return None;
        }
        // The newest, as a browser that paints faster than it is asked.
        let last = state.frames.pop();
        state.frames.clear();
        last
    }

    fn can_play(&mut self, _tab: TabId, types: &[&str]) -> io::Result<Vec<String>> {
        let state = self.lock();
        Ok(types
            .iter()
            .map(|t| state.codecs.get(*t).cloned().unwrap_or_default())
            .collect())
    }

    fn events(&mut self) -> Vec<EngineEvent> {
        std::mem::take(&mut self.lock().events)
    }
}