termzzz 0.0.2

Screen savers and visual effects for terminal
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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
use crate::buffer::{Buffer, Cell};
use crate::common::{DEFAULT_SEED, EffectRng, TerminalEffect, seeded_rng};
use crate::config::Config;
use crate::registry::{AnyEffect, EffectId};
use crate::render::wipe::blank_cell;
use crate::runtime::{FrameContext, InputEvent, InputState};
use rand::RngExt;
use rand::seq::SliceRandom;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// One playlist entry: an effect name and an optional duration override.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PlaylistEntry {
    pub effect: String,
    #[serde(default)]
    pub duration: Option<f32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PlaylistOptions {
    /// Effects to play, in order. Empty means every registered effect.
    pub effects: Vec<PlaylistEntry>,
    /// Play entries in a random order, reshuffling once every effect has run.
    pub shuffle: bool,
    /// Seconds of blank wipe between effects.
    pub transition: f32,
    /// Seed for the shuffle order.
    ///
    /// Present because `--seed N` promises a reproducible run, and it was not
    /// one: the bag drew from `rand::rng()`, which is OS entropy, so
    /// `--seed 1234 --shuffle` gave a reproducible *picture* in a random
    /// *order*. The same `DEFAULT_SEED` convention as every effect, so a
    /// config pinning 42 means "shuffle it differently each launch" and
    /// `--seed 42` pins the order too.
    pub seed: u64,
}

impl Default for PlaylistOptions {
    /// Hand-written so it is the single source of truth.
    ///
    /// The builder carried the real defaults while the derived `Default`
    /// produced zeros, and serde used the derived one, so a config file
    /// that omitted a section silently zeroed it.
    fn default() -> Self {
        Self {
            effects: Default::default(),
            shuffle: false,
            transition: 0.6,
            seed: DEFAULT_SEED,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct Slot {
    id: EffectId,
    duration: f32,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum Phase {
    Running,
    WipeOut,
    WipeIn,
}

/// Runs a queue of effects, wiping to blank between each one.
pub struct Playlist {
    config: Config,
    screen_size: (u16, u16),
    options: PlaylistOptions,
    slots: Vec<Slot>,
    order: Vec<usize>,
    bag: Vec<usize>,
    /// Held rather than re-seeded per refill -- see [`Playlist::refill`].
    bag_rng: EffectRng,
    /// Draws the colour palette for each effect in shuffle mode.
    ///
    /// A *separate* generator from [`Self::bag_rng`] even though both come from
    /// the same seed, and that is the point. One generator for both would make
    /// the effect *order* depend on how many palettes are in the pool, so adding
    /// a palette would reshuffle every seeded user's playlist. Two streams, each
    /// reproducible on its own, neither able to move the other.
    ///
    /// Not reseeded per effect, for the reason `bag_rng` is not: a reseed from
    /// the same value would give every effect the same palette.
    palette_rng: EffectRng,
    /// The palette the running effect was built with, for inspection.
    ///
    /// `None` in sequential mode, and `None` for an effect with no pool. Stored
    /// rather than recomputed for the reason `Dvd::corner_this_frame` and
    /// `Physarum::last_churn` are: the value exists to be read, and a test that
    /// reimplemented the draw to find it would be testing a second copy of the
    /// rule rather than the one that ran.
    current_palette: Option<&'static str>,
    position: usize,
    elapsed: f32,
    phase: Phase,
    phase_progress: f32,
    current: AnyEffect,
    /// The frame being built: the frame the terminal is showing plus every
    /// change the running effect has reported since.
    ///
    /// This was a `Canvas`, which is built for an effect that redraws its whole
    /// surface every frame. `Canvas::commit` swaps its two surfaces, so what it
    /// hands back to draw on next is the frame from *before* the one it just
    /// emitted -- one commit too old to accumulate a diff onto. A playlist
    /// accumulates diffs, so every cell the effect did not redraw was reported
    /// as going blank and then redrawn on the frame after: the screen flickered
    /// between the frame and a mostly empty one, sixty times a second.
    frame: Buffer,
    /// The frame the terminal is showing. The diff is against this, and it is
    /// what lets a wipe blank a cell the effect did not redraw this frame: the
    /// cell is on the screen whether or not it is in the diff.
    shown: Buffer,
    /// A wiped copy of `frame`, allocated only while a transition is running.
    ///
    /// The wipe goes on this rather than on `frame` so the undimmed frame
    /// survives underneath and the wipe can be taken back as the front retreats,
    /// instead of being baked in permanently. `clone_from` reuses the
    /// allocation, so a transition frame costs no memory after the first.
    wiped: Option<Buffer>,
}

impl TerminalEffect for Playlist {
    fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
        self.render_full_frame(Vec::new())
    }

    fn update(&mut self) {
        let size = self.screen_size;
        self.update_with_context(&FrameContext::new(
            size,
            0,
            Duration::ZERO,
            Duration::from_secs_f64(1.0 / 60.0),
            InputState::default(),
        ));
    }

    fn get_diff_with_context(
        &mut self,
        context: &FrameContext,
    ) -> Vec<(usize, usize, Cell)> {
        let delta = self.current.get_diff_with_context(context);
        self.render_full_frame(delta)
    }

    fn update_with_context(&mut self, context: &FrameContext) {
        self.current.update_with_context(context);
        self.advance(context.delta.as_secs_f32());
    }

    fn update_size(&mut self, width: u16, height: u16) {
        self.screen_size = (width.max(1), height.max(1));
        self.rebuild_buffers();
        self.current.update_size(width, height);
    }

    fn reset(&mut self) {
        self.current.reset();
        self.elapsed = 0.0;
        self.phase = Phase::Running;
        self.phase_progress = 0.0;
        self.rebuild_buffers();
    }

    fn handle_input(&mut self, event: &InputEvent) {
        self.current.handle_input(event);
    }
}

impl Playlist {
    pub fn new(
        options: PlaylistOptions,
        config: Config,
        screen_size: (u16, u16),
    ) -> Self {
        let screen_size = (screen_size.0.max(1), screen_size.1.max(1));
        let slots = Self::build_slots(&options);
        let order: Vec<usize> = (0..slots.len()).collect();
        // The opening effect is *drawn*, not assumed to be the first entry.
        //
        // It used to be `let position = 0`, and that is the whole of
        // "every --shuffle starts from matrix": the bag is only consulted by
        // `next_index`, which handles transitions, so the run always opened on
        // slot 0. With no `--playlist`, `build_slots` falls back to
        // `EffectId::all()`, whose first entry is `matrix` -- so a bare
        // `--shuffle` looked like it did nothing at all.
        //
        // Drawn from the bag rather than by shuffling `order`, so the opening
        // effect comes from the same distribution as every later one and the
        // "never the same effect twice running" rule holds from the first
        // transition instead of starting one step in.
        let mut bag_rng = seeded_rng(options.seed, "playlist.shuffle");
        let mut palette_rng = seeded_rng(options.seed, "playlist.palette");
        let mut bag: Vec<usize> = Vec::new();
        let position = if options.shuffle && order.len() > 1 {
            bag = Self::refill(&order, &mut bag_rng);
            bag.remove(0)
        } else {
            0
        };
        // The opening effect's palette is drawn here, by the same code path every
        // later effect goes through, rather than being left at the config's value
        // until the first transition. One implementation, so the opening draw is
        // the same kind of draw and cannot drift from the rest.
        let opening_id = slots[order[position]].id;
        let mut palette_config = config.clone();
        let current_palette = if options.shuffle {
            Self::draw_palette(opening_id, &mut palette_config, &mut palette_rng)
        } else {
            None
        };
        let current = AnyEffect::build(opening_id, &palette_config, screen_size);
        let (width, height) = (screen_size.0 as usize, screen_size.1 as usize);
        let mut playlist = Self {
            config,
            screen_size,
            options,
            slots,
            order,
            bag,
            bag_rng,
            palette_rng,
            current_palette,
            position,
            elapsed: 0.0,
            phase: Phase::Running,
            phase_progress: 0.0,
            current,
            frame: Buffer::new(width, height),
            shown: Buffer::new(width, height),
            wiped: None,
        };
        playlist.rebuild_buffers();
        playlist
    }

    fn build_slots(options: &PlaylistOptions) -> Vec<Slot> {
        let mut unresolvable: Vec<&str> = Vec::new();
        let mut slots: Vec<Slot> = options
            .effects
            .iter()
            .filter_map(|entry| {
                let Ok(id) = entry.effect.parse::<EffectId>() else {
                    unresolvable.push(entry.effect.as_str());
                    return None;
                };
                Some(Slot {
                    id,
                    duration: entry
                        .duration
                        .filter(|duration| duration.is_finite() && *duration > 0.0)
                        .unwrap_or_else(|| id.default_duration()),
                })
            })
            .collect();

        // A name this code cannot resolve used to be dropped in silence, which
        // shortens the playlist with no indication that anything was wrong. That
        // is how a renamed effect takes a user's playlist apart without them
        // finding out until the run looks wrong: `effect = "ascii"` in a file
        // written before the rename to `ink` is now a name that parses to nothing,
        // and the entry simply vanishes.
        //
        // Not an error -- a playlist naming an effect that does not exist is a
        // config mistake, not a crash, and the rest of the playlist is still
        // perfectly playable. But it is reported, because a silent shortening is
        // the worst of the three outcomes.
        if !unresolvable.is_empty() {
            eprintln!(
                "termzzz: ignoring {} playlist entr{} this build cannot resolve: {}",
                unresolvable.len(),
                if unresolvable.len() == 1 { "y" } else { "ies" },
                unresolvable.join(", ")
            );
            let known: Vec<&str> = EffectId::all().map(|id| id.as_str()).collect();
            eprintln!(
                "termzzz: the effects this build knows are: {}",
                known.join(", ")
            );
        }

        if slots.is_empty() {
            slots = EffectId::all()
                .map(|id| Slot {
                    id,
                    duration: id.default_duration(),
                })
                .collect();
        }

        slots
    }

    fn current_id(&self) -> EffectId {
        self.slots[self.order[self.position]].id
    }

    fn current_duration(&self) -> f32 {
        self.slots[self.order[self.position]].duration
    }

    fn transition_duration(&self) -> f32 {
        self.options.transition.max(0.01)
    }

    /// Resizes both frames, and starts a new effect from a blank screen.
    ///
    /// Only the frame being built is blanked. `shown` is the record of what the
    /// terminal is showing, so blanking it would be a lie the next diff cannot
    /// correct: the last frame of a wipe-out is a fraction short of blank, and
    /// declaring it blank meant the leftover was never erased. What the terminal
    /// really shows is the next diff's business, and it erases it.
    ///
    /// It used to blank the surface and then establish the baseline, which is a
    /// commit, which swaps the two -- so the blank became the baseline and the
    /// surface being drawn into kept the outgoing effect's frame. Every swap
    /// then re-emitted that frame, and an effect whose diff is always empty,
    /// like `blank` or `terrain`, repainted the previous effect's image
    /// underneath itself for its whole slot.
    fn rebuild_buffers(&mut self) {
        let (width, height) =
            (self.screen_size.0 as usize, self.screen_size.1 as usize);
        if (self.frame.width, self.frame.height) != (width, height) {
            // Neither frame describes dimensions that no longer exist, and a
            // resize is a full repaint, so neither can be trusted. The terminal
            // is in an unknown state too, which is the one case where `shown`
            // does get blanked.
            self.frame = Buffer::new(width, height);
            self.shown = Buffer::new(width, height);
            self.wiped = None;
            return;
        }
        // This effect's blank is `Color::Reset`, not the `Cell::default()` black
        // a buffer clears to, so it is filled explicitly.
        self.frame.fill_with(&blank_cell());
    }

    /// Wipes the effect away, swaps it, then wipes the next one in.
    fn advance(&mut self, delta: f32) {
        self.elapsed += delta;

        match self.phase {
            Phase::Running => {
                if self.elapsed >= self.current_duration() {
                    self.elapsed = 0.0;
                    if self.options.transition > 0.0 {
                        self.phase = Phase::WipeOut;
                        self.phase_progress = 0.0;
                    } else {
                        self.step_to_next();
                    }
                }
            }
            Phase::WipeOut => {
                self.phase_progress += delta / self.transition_duration();
                if self.phase_progress >= 1.0 {
                    self.step_to_next();
                    self.phase = Phase::WipeIn;
                    self.phase_progress = 0.0;
                }
            }
            Phase::WipeIn => {
                self.phase_progress += delta / self.transition_duration();
                if self.phase_progress >= 1.0 {
                    self.phase = Phase::Running;
                    self.phase_progress = 0.0;
                    // The transition is over, so the copy the wipe was using can
                    // go. A playlist holds this between transitions rather than
                    // for the whole session.
                    self.wiped = None;
                }
            }
        }
    }

    fn step_to_next(&mut self) {
        self.position = self.next_index();
        let id = self.current_id();
        // The palette is part of which effect this is, so it is drawn on the same
        // path as the opening effect's and by the same rule: shuffled in shuffle
        // mode, and left at whatever the config says otherwise.
        let mut config = self.config.clone();
        self.current_palette = if self.options.shuffle {
            Self::draw_palette(id, &mut config, &mut self.palette_rng)
        } else {
            None
        };
        self.current = AnyEffect::build(id, &config, self.screen_size);
        self.rebuild_buffers();
    }

    /// Draws a palette for `id`, applies it to `config`, and reports which.
    ///
    /// A no-op returning `None` for an effect with an empty pool, which is every
    /// effect that takes no palette and `newton` -- whose colour *is* its
    /// encoding rather than a ramp applied to one, so a name from a table has
    /// nothing to say to it.
    ///
    /// The `None` is load-bearing rather than cosmetic: an effect with no pool
    /// must consume *nothing* from the stream. If `newton` drew a number and
    /// threw it away, every effect after it would shift palette relative to a run
    /// that did not contain newton, and the sequence would depend on which
    /// effects a given playlist happened to hold.
    ///
    /// Returns the name so the caller can record it, and is a free function over
    /// the generator rather than a method on `self` because the opening effect is
    /// drawn before `Self` exists -- two copies of this would be two places the
    /// rule lives.
    fn draw_palette(
        id: EffectId,
        config: &mut Config,
        rng: &mut EffectRng,
    ) -> Option<&'static str> {
        let pool = id.spec().shuffle_palettes;
        if pool.is_empty() {
            return None;
        }
        let name = pool[rng.random_range(0..pool.len())];
        config.set_palette(id, name);
        Some(name)
    }

    /// A fresh, shuffled bag of every index in `order`, drawn from the
    /// playlist's own generator.
    ///
    /// That generator is *held* rather than re-seeded per refill, and the
    /// distinction is load-bearing: reseeding from the same value would produce
    /// the same permutation every round, so a long shuffled playlist would cycle
    /// through one order forever. Holding it means successive refills differ
    /// while the whole sequence is still reproducible from the seed.
    ///
    /// The bag used to draw from `rand::rng()`, which is OS entropy, so
    /// `--seed 1234 --shuffle` was not the reproducible run the flag promises:
    /// the effects looked the same and arrived in a different order each time.
    ///
    /// One call site, used by both the opening draw and every refill, so the
    /// opening effect is drawn the same way as every later one.
    fn refill(order: &[usize], rng: &mut EffectRng) -> Vec<usize> {
        let mut bag = order.to_vec();
        bag.shuffle(rng);
        bag
    }

    /// Sequential order steps forward; shuffle order draws from a reshuffling bag.
    fn next_index(&mut self) -> usize {
        if !self.options.shuffle || self.order.len() < 2 {
            return (self.position + 1) % self.order.len();
        }

        if self.bag.is_empty() {
            self.bag = Self::refill(&self.order, &mut self.bag_rng);
        }

        let current = self.order[self.position];

        // Keep drawing until something other than the effect we are on comes
        // up, so a shuffled playlist never shows the same effect twice running.
        // This used to retry exactly once, which still returned the current
        // effect one time in fourteen, and the test that checks this failed
        // about that often.
        for _ in 0..=self.bag.len() {
            let next = self.bag.remove(0);
            if next != current {
                return next;
            }
            self.bag.push(next);
        }

        // Only reachable if the bag holds nothing but the current effect, which
        // a bag holding every index once cannot do unless there is only one.
        self.bag.remove(0)
    }

    /// Applies the effect delta to the accumulated frame, masks it for the
    /// current wipe phase, and emits the difference against what is on screen.
    fn render_full_frame(
        &mut self,
        delta: Vec<(usize, usize, Cell)>,
    ) -> Vec<(usize, usize, Cell)> {
        let (width, height) =
            (self.screen_size.0 as usize, self.screen_size.1 as usize);
        if (self.frame.width, self.frame.height) != (width, height) {
            self.rebuild_buffers();
        }

        // The frame accumulates: each effect's diff lands on top of the frame it
        // is building, which is what lets an effect that draws nothing this
        // frame keep the one before it. `Buffer::set` only debug-asserts its
        // bounds, so a coordinate from outside the screen is dropped rather than
        // written past the end.
        for (x, y, cell) in delta {
            if x < width && y < height {
                self.frame.set(x, y, cell);
            }
        }

        let wipe = match self.phase {
            Phase::Running => 0.0,
            Phase::WipeOut => self.phase_progress,
            Phase::WipeIn => 1.0 - self.phase_progress,
        };
        let outgoing = if wipe > 0.0 {
            // Wiped on a copy, so the undimmed frame underneath survives and the
            // wipe can be taken back rather than being baked in permanently --
            // which is also what lets the wipe-in reveal an effect that has
            // nothing new to draw.
            let wiped = self.wiped.get_or_insert_with(|| self.frame.clone());
            wiped.clone_from(&self.frame);
            crate::render::wipe::apply(wiped, width, height, wipe);
            wiped
        } else {
            &self.frame
        };

        let cells = self.shown.diff(outgoing);
        for (x, y, cell) in &cells {
            self.shown.set(*x, *y, *cell);
        }
        cells
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::buffer::Buffer;
    use crossterm::style;
    use std::collections::BTreeMap;

    fn playlist_with(
        entries: &[(&str, Option<f32>)],
        transition: f32,
        shuffle: bool,
    ) -> Playlist {
        playlist_seeded(entries, transition, shuffle, DEFAULT_SEED)
    }

    /// [`playlist_with`] with the seed spelled out, for the tests where the
    /// order itself is the subject.
    fn playlist_seeded(
        entries: &[(&str, Option<f32>)],
        transition: f32,
        shuffle: bool,
        seed: u64,
    ) -> Playlist {
        let options = PlaylistOptions {
            seed,
            effects: entries
                .iter()
                .map(|(effect, duration)| PlaylistEntry {
                    effect: (*effect).to_string(),
                    duration: *duration,
                })
                .collect(),
            transition,
            shuffle,
        };
        Playlist::new(options, Config::default(), (40, 12))
    }

    /// The opening effect is drawn, not assumed to be the first entry.
    ///
    /// This is the whole of "every `--shuffle` starts from matrix".
    /// `Playlist::new` hardcoded `let position = 0`, and the bag is only
    /// consulted for *transitions*, so a run always opened on slot 0. With no
    /// `--playlist` that slot is `EffectId::all()[0]`, which is `matrix` — so a
    /// bare `--shuffle` looked like it did nothing at all.
    ///
    /// Asserted as a distribution rather than as "not matrix", because "not
    /// matrix" is satisfiable by an order that is biased some other way. Two
    /// hundred seeds, and every effect has to turn up.
    #[test]
    fn a_shuffled_playlist_opens_on_a_drawn_effect() {
        let entries: Vec<(&str, Option<f32>)> =
            EffectId::all().map(|id| (id.as_str(), None)).collect();
        let mut firsts: std::collections::BTreeMap<String, usize> =
            Default::default();
        for seed in 0..200u64 {
            let playlist = playlist_seeded(&entries, 0.6, true, seed);
            *firsts
                .entry(playlist.current_id().as_str().to_string())
                .or_default() += 1;
        }

        assert_eq!(
            firsts.len(),
            entries.len(),
            "across 200 seeds only {} of the {} effects ever opened the playlist: \
             {:?}",
            firsts.len(),
            entries.len(),
            firsts
        );
        // And not one of them is doing all the work, which is what a shuffled
        // *order* with a fixed *first* entry would look like from further away.
        let busiest = firsts.values().copied().max().unwrap_or(0);
        assert!(
            busiest < 40,
            "one effect opened {busiest} of 200 shuffled playlists, so the order \
             is random but the opening effect is not"
        );
    }

    /// `--seed N` pins the order, not only the pictures.
    ///
    /// The bag drew from `rand::rng()` — OS entropy — so `--seed 1234
    /// --shuffle` was not the reproducible run the flag promises: the effects
    /// looked the same and arrived in a different order. The generator is now
    /// held rather than re-seeded per refill, because re-seeding from the same
    /// value would repeat one permutation forever.
    #[test]
    fn a_seeded_shuffle_reproduces_its_whole_order() {
        let entries: Vec<(&str, Option<f32>)> =
            EffectId::all().map(|id| (id.as_str(), None)).collect();
        let order_of = |seed: u64| -> Vec<String> {
            let mut playlist = playlist_seeded(&entries, 0.0, true, seed);
            let mut seen = vec![playlist.current_id().as_str().to_string()];
            for _ in 0..entries.len() {
                playlist.step_to_next();
                seen.push(playlist.current_id().as_str().to_string());
            }
            seen
        };
        assert_eq!(
            order_of(7),
            order_of(7),
            "two runs at the same seed produced different orders, so --seed does \
             not pin the playlist"
        );
        assert_ne!(
            order_of(7),
            order_of(8),
            "seeds 7 and 8 produced the same order, so the seed is not reaching \
             the shuffle at all"
        );
    }

    /// Successive refills differ, so a long shuffled playlist does not cycle
    /// through one order forever.
    ///
    /// This is the failure a *held* generator was chosen over a per-refill
    /// re-seed, and it is invisible in a test that only looks at the first few
    /// entries.
    #[test]
    fn a_long_shuffled_playlist_does_not_repeat_one_order() {
        let entries: Vec<(&str, Option<f32>)> =
            EffectId::all().map(|id| (id.as_str(), None)).collect();
        let count = entries.len();
        let mut playlist = playlist_seeded(&entries, 0.0, true, 3);
        let mut orders: std::collections::BTreeSet<Vec<usize>> = Default::default();
        for _ in 0..6 {
            let mut round: Vec<usize> = Vec::new();
            for _ in 0..=count {
                round.push(playlist.position);
                playlist.step_to_next();
            }
            orders.insert(round);
        }
        assert!(
            orders.len() >= 3,
            "six full rounds of a shuffled playlist produced only {} distinct \
             orders, so it is cycling rather than shuffling",
            orders.len()
        );
    }

    /// A playlist too short to shuffle still works.
    ///
    /// A shuffled playlist gives its effects different colours.
    ///
    /// The point of the feature, so it is asserted as the observable rather than
    /// as a property of the draw: what lands on the terminal has to differ, and
    /// the only way to see that without a terminal is to read the palette the
    /// effect was built with.
    #[test]
    fn a_shuffled_playlist_varies_the_palette() {
        let entries: Vec<(&str, Option<f32>)> =
            EffectId::all().map(|id| (id.as_str(), None)).collect();
        let mut seen: BTreeMap<String, usize> = BTreeMap::new();
        let mut without_one = 0;
        for seed in 0..60u64 {
            let mut playlist = playlist_seeded(&entries, 0.0, true, seed);
            for _ in 0..entries.len() {
                match playlist.current_palette {
                    Some(name) => *seen.entry(name.to_string()).or_default() += 1,
                    None => without_one += 1,
                }
                playlist.step_to_next();
            }
        }

        assert!(
            seen.len() > 1,
            "every shuffled effect got the same palette across 60 seeds, so the \
             shuffle is not reaching the palette: {seen:?}"
        );
        // And the effects with no pool are not being handed one, which is the
        // half that would be a regression rather than a missing feature.
        assert!(
            without_one > 0,
            "every effect reported a palette, so effects with no pool are being \
             given one: {seen:?}"
        );
    }

    /// The palette comes from the effect's own pool, and an effect with an empty
    /// pool has none to draw from.
    ///
    /// This is the failure a single shared pool would have: `ink` indexing a
    /// multi-hue ramp ends on amber where the field is supposed to end on white,
    /// and a brightness consumer handed `contrast` has no interior shading to
    /// show at all. It also pins the pool to the setter, which are two lists that
    /// would otherwise drift apart silently.
    #[test]
    fn every_shuffled_palette_comes_from_that_effect_s_own_pool() {
        let mut config = Config::default();
        let mut with_a_pool = 0;
        for id in EffectId::all() {
            let pool = id.spec().shuffle_palettes;
            if pool.is_empty() {
                assert!(
                    config.palette_of(id).is_none(),
                    "{id:?} has an empty shuffle pool but does have a palette \
                     option, so a name could be drawn for it and set nowhere"
                );
                continue;
            }
            with_a_pool += 1;
            for name in pool {
                config.set_palette(id, name);
                assert_eq!(
                    config.palette_of(id),
                    Some(*name),
                    "{id:?} has {name} in its shuffle pool but setting it did not \
                     take, so the pool and the setter have drifted apart"
                );
            }
        }
        assert_eq!(
            with_a_pool, 7,
            "the number of effects with a palette to shuffle changed; the pool \
             table has not been updated to match"
        );
    }

    /// Every name in every pool resolves against the table its effect reads.
    ///
    /// A typo in a pool is otherwise invisible: the effect falls back to its
    /// default on an unrecognised name, so a misspelt palette would look like a
    /// shuffle that quietly did nothing for that effect.
    #[test]
    fn every_palette_in_every_pool_resolves() {
        for id in EffectId::all() {
            for name in id.spec().shuffle_palettes {
                if id == EffectId::Ink {
                    assert!(
                        crate::ink::FIELD_PALETTES
                            .iter()
                            .any(|(candidate, _)| *candidate == *name),
                        "ink's pool has {name:?}, which is not in FIELD_PALETTES"
                    );
                } else {
                    assert!(
                        crate::render::palette::presets::by_name(name).is_some(),
                        "{id:?}'s pool has {name:?}, which is not a named ramp"
                    );
                }
            }
        }
    }

    /// `--seed N` pins the palettes, not only the order.
    ///
    /// The shuffle order was reproducible and the colours were not, which is the
    /// same bug the order had once: a `--seed N --shuffle` run that looks the
    /// same twice is the whole promise of the flag.
    #[test]
    fn a_seeded_palette_shuffle_reproduces() {
        let entries: Vec<(&str, Option<f32>)> =
            EffectId::all().map(|id| (id.as_str(), None)).collect();
        let palettes_of = |seed: u64| {
            let mut playlist = playlist_seeded(&entries, 0.0, true, seed);
            let mut seen = Vec::new();
            for _ in 0..entries.len() {
                seen.push((
                    playlist.current_id().as_str().to_string(),
                    playlist.current_palette,
                ));
                playlist.step_to_next();
            }
            seen
        };
        assert_eq!(
            palettes_of(7),
            palettes_of(7),
            "two runs at the same seed chose different palettes, so --seed does \
             not pin the colours"
        );
        assert_ne!(
            palettes_of(7),
            palettes_of(8),
            "seeds 7 and 8 chose the same palettes, so the palette draw is not \
             reaching the seed"
        );
    }

    /// Sequential mode leaves every effect on the palette the config asked for.
    ///
    /// The flag is `shuffle`; a run without it has to look exactly as it did
    /// before this feature existed, or `--playlist` has become a way to lose a
    /// deliberate choice.
    #[test]
    fn a_sequential_playlist_keeps_the_configured_palette() {
        let mut config = Config::default();
        config.set_palette(EffectId::Ants, "ember");
        let options = PlaylistOptions {
            seed: 3,
            effects: vec![
                PlaylistEntry {
                    effect: "ants".to_string(),
                    duration: None,
                },
                PlaylistEntry {
                    effect: "donut".to_string(),
                    duration: None,
                },
            ],
            transition: 0.0,
            shuffle: false,
        };
        let mut playlist = Playlist::new(options, config.clone(), (40, 12));

        for _ in 0..6 {
            assert_eq!(
                playlist.current_palette,
                None,
                "{} was given a palette in sequential mode",
                playlist.current_id().as_str()
            );
            playlist.step_to_next();
        }
    }

    /// Shuffle mode replaces a palette the config pinned on purpose.
    ///
    /// Not an accident, and the reason it is worth a test: the alternative --
    /// honouring an explicit config -- is what most people would expect and is
    /// strictly more code, because `palette` is a `String` with no way to say
    /// "unset" short of comparing against each effect's shipped default. Once
    /// decided, the decision needs pinning or a later well-meaning change passes
    /// silently.
    #[test]
    fn shuffle_overrides_a_configured_palette() {
        let entries: Vec<(&str, Option<f32>)> =
            EffectId::all().map(|id| (id.as_str(), None)).collect();
        let mut ever_ember = 0;
        for seed in 0..80u64 {
            let mut playlist = playlist_seeded(&entries, 0.0, true, seed);
            for _ in 0..entries.len() {
                if playlist.current_palette == Some("ember") {
                    ever_ember += 1;
                }
                playlist.step_to_next();
            }
        }
        assert!(
            ever_ember > 0,
            "no shuffled effect was ever given `ember`, so the draw is not \
             reaching past the effect's configured default"
        );
    }

    /// An effect with no pool consumes nothing from the palette stream.
    ///
    /// The palette draw runs off its own generator rather than `bag_rng`, so it
    /// cannot move the effect *order* at all. But it can still make the palette
    /// *sequence* depend on which effects a playlist happened to contain: if
    /// `newton` drew a number and threw it away, then adding a `newton` to a
    /// playlist would shift every palette after it. So the draw has to leave a
    /// no-pool effect's slot in the stream untouched, and that is a property of
    /// the generator rather than something an end-to-end run can show -- two
    /// playlists with different effect lists legitimately shuffle to different
    /// orders, so the order cannot be compared across them.
    #[test]
    fn an_effect_with_no_pool_consumes_nothing() {
        // Two generators from the same seed. One is asked to draw for an effect
        // with no pool before it is read; the other is not touched. The next
        // value each produces has to be the same number.
        let mut skipped = seeded_rng(11, "playlist.palette");
        let mut untouched = seeded_rng(11, "playlist.palette");

        let mut config = Config::default();
        assert_eq!(
            Playlist::draw_palette(EffectId::Newton, &mut config, &mut skipped),
            None,
            "newton has a palette to shuffle, so this test is not testing what \
             it says"
        );
        assert_eq!(
            skipped.random_range(0..1_000_000),
            untouched.random_range(0..1_000_000),
            "a no-pool draw moved the palette stream, so every later effect's \
             palette would depend on which palette-less effects a playlist holds"
        );

        // And an effect that *does* have a pool does consume, or the sequence
        // would be constant. Compared on the stream position rather than on the
        // names drawn: two draws landing on the same one of four ramps is a
        // one-in-four coincidence, and a name comparison would therefore be
        // flaky in exactly the direction that hides a reseed.
        let first =
            Playlist::draw_palette(EffectId::Ants, &mut config, &mut skipped);
        let second =
            Playlist::draw_palette(EffectId::Ants, &mut config, &mut skipped);
        assert!(
            first.is_some() && second.is_some(),
            "ants has a palette to shuffle, so this test is not testing what it \
             says"
        );
        assert_ne!(
            skipped.random_range(0..1_000_000),
            untouched.random_range(0..1_000_000),
            "two draws for an effect that has a pool left the stream where it \
             started, so the generator is being reseeded per effect"
        );
    }

    /// The opening draw is new code on a path that used to be a constant, and a
    /// single-entry list is the case where an off-by-one in it would panic
    /// rather than merely look wrong.
    #[test]
    fn a_single_effect_playlist_still_opens_on_that_effect() {
        for shuffle in [false, true] {
            let mut playlist = playlist_with(&[("matrix", None)], 0.0, shuffle);
            assert_eq!(playlist.current_id().as_str(), "matrix");
            playlist.step_to_next();
            assert_eq!(
                playlist.current_id().as_str(),
                "matrix",
                "a one-entry playlist moved to something else"
            );
        }
    }

    /// The opening effect is not repeated by the first transition.
    ///
    /// The bag's own rule is "keep drawing until something other than the
    /// current effect comes up". It used to start one entry late, so the run
    /// opened on slot 0 and could then draw slot 0 again immediately.
    #[test]
    fn the_first_transition_does_not_repeat_the_opening_effect() {
        let entries: Vec<(&str, Option<f32>)> =
            EffectId::all().map(|id| (id.as_str(), None)).collect();
        for seed in 0..100u64 {
            let mut playlist = playlist_seeded(&entries, 0.0, true, seed);
            let first = playlist.current_id();
            playlist.step_to_next();
            assert_ne!(
                playlist.current_id(),
                first,
                "seed {seed} opened on {} and then stayed on it",
                first.as_str()
            );
        }
    }

    fn filled_buffer(width: usize, height: usize) -> Buffer {
        let mut buffer = Buffer::new(width, height);
        buffer.fill_with(&Cell::new(
            '#',
            style::Color::Green,
            style::Attribute::Reset,
        ));
        buffer
    }

    /// One frame of the real loop: the effect is advanced, then asked for its
    /// diff, and the result lands on `screen`.
    fn tick(
        playlist: &mut Playlist,
        frame: u64,
        screen: &mut Buffer,
    ) -> Vec<(usize, usize, Cell)> {
        let context = FrameContext::new(
            (40, 12),
            frame,
            Duration::ZERO,
            Duration::from_secs_f64(1.0 / 60.0),
            InputState::default(),
        );
        playlist.update_with_context(&context);
        let cells = playlist.get_diff_with_context(&context);
        for (x, y, cell) in &cells {
            screen.set(*x, *y, *cell);
        }
        cells
    }

    /// How much of the screen is showing something other than a space.
    fn lit(buffer: &Buffer) -> usize {
        (0..buffer.height)
            .flat_map(|y| (0..buffer.width).map(move |x| (x, y)))
            .filter(|(x, y)| buffer.get(*x, *y).symbol != ' ')
            .count()
    }

    #[test]
    fn empty_playlist_plays_every_effect() {
        let playlist =
            Playlist::new(PlaylistOptions::default(), Config::default(), (40, 12));
        assert_eq!(playlist.slots.len(), EffectId::len());
    }

    #[test]
    fn unknown_effects_fall_back_to_every_effect() {
        let playlist = playlist_with(&[("nope", None)], 0.6, false);
        assert_eq!(playlist.slots.len(), EffectId::len());
    }

    #[test]
    fn entries_use_configured_durations() {
        let playlist =
            playlist_with(&[("matrix", Some(3.0)), ("dvd", None)], 0.6, false);

        assert_eq!(playlist.slots.len(), 2);
        assert_eq!(playlist.slots[0].duration, 3.0);
        assert_eq!(playlist.slots[1].duration, EffectId::Dvd.default_duration());
    }

    #[test]
    fn invalid_durations_fall_back_to_defaults() {
        let playlist = playlist_with(
            &[("matrix", Some(-4.0)), ("dvd", Some(f32::NAN))],
            0.6,
            false,
        );

        assert_eq!(
            playlist.slots[0].duration,
            EffectId::Matrix.default_duration()
        );
        assert_eq!(playlist.slots[1].duration, EffectId::Dvd.default_duration());
    }

    #[test]
    fn advances_to_the_next_effect_after_its_duration() {
        let mut playlist =
            playlist_with(&[("blank", Some(1.0)), ("dvd", Some(5.0))], 0.0, false);
        assert_eq!(playlist.current_id(), EffectId::Blank);

        playlist.advance(1.1);

        assert_eq!(playlist.current_id(), EffectId::Dvd);
        assert_eq!(playlist.phase, Phase::Running);
    }

    #[test]
    fn transition_wipes_out_before_swapping() {
        let mut playlist =
            playlist_with(&[("blank", Some(1.0)), ("dvd", Some(5.0))], 0.6, false);

        playlist.advance(1.0);
        assert_eq!(playlist.phase, Phase::WipeOut);
        assert_eq!(playlist.current_id(), EffectId::Blank);

        playlist.advance(0.3);
        assert_eq!(playlist.phase, Phase::WipeOut);
        assert_eq!(playlist.current_id(), EffectId::Blank);

        playlist.advance(0.3);
        assert_eq!(playlist.phase, Phase::WipeIn);
        assert_eq!(playlist.current_id(), EffectId::Dvd);

        playlist.advance(0.6);
        assert_eq!(playlist.phase, Phase::Running);
    }

    #[test]
    fn wipe_clears_cells_the_front_has_passed() {
        let mut buffer = filled_buffer(10, 10);

        crate::render::wipe::apply(&mut buffer, 10, 10, 0.0);
        assert_eq!(buffer.get(0, 0).symbol, '#');
        assert_eq!(buffer.get(9, 9).symbol, '#');

        buffer = filled_buffer(10, 10);
        crate::render::wipe::apply(&mut buffer, 10, 10, 0.5);
        assert_eq!(buffer.get(0, 0).symbol, ' ');
        assert_eq!(buffer.get(9, 9).symbol, '#');

        buffer = filled_buffer(10, 10);
        crate::render::wipe::apply(&mut buffer, 10, 10, 1.0);
        assert_eq!(buffer.get(0, 0).symbol, ' ');
        assert_eq!(buffer.get(9, 9).symbol, ' ');
    }

    #[test]
    fn full_wipe_fully_clears_the_screen() {
        let mut playlist =
            playlist_with(&[("matrix", Some(1.0)), ("dvd", Some(5.0))], 0.6, false);
        for _ in 0..5 {
            playlist.advance(1.0 / 60.0);
        }
        playlist.advance(1.0);
        assert_eq!(playlist.phase, Phase::WipeOut);

        playlist.advance(0.6);
        assert_eq!(playlist.phase, Phase::WipeIn);

        let mut buffer = filled_buffer(40, 12);
        crate::render::wipe::apply(&mut buffer, 40, 12, 1.0);
        for y in 0..12 {
            for x in 0..40 {
                assert_eq!(buffer.get(x, y).symbol, ' ');
            }
        }
    }

    #[test]
    fn diff_stays_within_screen_bounds() {
        let mut playlist =
            playlist_with(&[("matrix", Some(0.2)), ("dvd", Some(0.2))], 0.2, false);

        for _ in 0..300 {
            playlist.advance(1.0 / 60.0);
            for (x, y, _) in playlist.get_diff() {
                assert!(x < 40 && y < 12);
            }
        }
    }

    #[test]
    fn shuffle_visits_every_effect_in_a_round() {
        let mut playlist = Playlist::new(
            PlaylistOptions {
                shuffle: true,
                transition: 0.1,
                ..Default::default()
            },
            Config::default(),
            (40, 12),
        );

        let mut seen: Vec<EffectId> = vec![playlist.current_id()];
        let mut guard = 0;
        while seen.len() < EffectId::len() && guard < 10_000 {
            guard += 1;
            playlist.advance(1.0);
            let id = playlist.current_id();
            if !seen.contains(&id) {
                seen.push(id);
            }
        }

        assert_eq!(seen.len(), EffectId::len());
    }

    #[test]
    fn sequential_order_follows_the_playlist() {
        let mut playlist = playlist_with(
            &[
                ("dvd", Some(1.0)),
                ("matrix", Some(2.0)),
                ("life", Some(3.0)),
            ],
            0.0,
            false,
        );

        let mut order = vec![playlist.current_id()];
        for _ in 0..2 {
            playlist.advance(playlist.current_duration() + 0.1);
            order.push(playlist.current_id());
        }
        playlist.advance(playlist.current_duration() + 0.1);

        assert_eq!(order, vec![EffectId::Dvd, EffectId::Matrix, EffectId::Life]);
        assert_eq!(playlist.current_id(), EffectId::Dvd);
    }

    #[test]
    fn shuffle_bag_empties_only_after_a_full_round() {
        let mut playlist = Playlist::new(
            PlaylistOptions {
                shuffle: true,
                ..Default::default()
            },
            Config::default(),
            (40, 12),
        );

        for index in 0..EffectId::len() {
            playlist.position = index;
            playlist.bag.clear();
            let next = playlist.next_index();
            assert!(next != index || EffectId::len() == 1);
        }
    }

    #[test]
    fn resize_rebuilds_buffers_for_the_active_effect() {
        let mut playlist = playlist_with(&[("dvd", Some(5.0))], 0.6, false);

        playlist.update_size(20, 8);

        assert_eq!(playlist.screen_size, (20, 8));
        assert_eq!(playlist.frame.get_size(), (20, 8));
        assert_eq!(playlist.shown.get_size(), (20, 8));
    }

    /// The accumulated frame is the frame, not a frame behind it.
    ///
    /// The playlist accumulates the running effect's *diff*, so the base it
    /// accumulates onto has to be the frame the terminal is showing. It was a
    /// `Canvas`, whose commit swaps its two surfaces and so hands back the frame
    /// from before the one it just emitted -- one commit too old. Every cell the
    /// effect did not redraw that frame was therefore reported as going blank
    /// and redrawn on the frame after, and the screen flickered between the
    /// frame and an almost empty one, sixty times a second. The bare effect
    /// emits about fifteen times as many cells as this did.
    #[test]
    fn the_accumulated_frame_keeps_up_with_the_terminal() {
        let mut playlist = playlist_with(&[("life", Some(20.0))], 0.6, false);
        let mut screen = Buffer::new(40, 12);

        // What a bare effect draws in the same number of frames, for scale.
        let mut bare =
            AnyEffect::build(EffectId::Life, &Config::default(), (40, 12));
        let mut bare_screen = Buffer::new(40, 12);
        let context = FrameContext::new(
            (40, 12),
            0,
            Duration::ZERO,
            Duration::from_secs_f64(1.0 / 60.0),
            InputState::default(),
        );
        let mut bare_cells = 0;
        for _ in 0..60 {
            bare.update_with_context(&context);
            let diff = bare.get_diff_with_context(&context);
            bare_cells += diff.len();
            for (x, y, cell) in &diff {
                bare_screen.set(*x, *y, *cell);
            }
        }

        let mut cells = 0;
        let mut frame = 0;
        while frame < 60 {
            cells += tick(&mut playlist, frame, &mut screen).len();
            frame += 1;
        }

        assert!(
            cells * 4 > bare_cells,
            "the playlist emitted {cells} cells where the effect on its own \
             emits {bare_cells}, so it is not keeping up with the screen"
        );
        // And the two agree about what the screen looks like, which is the part
        // that actually matters: the playlist is not losing the frame.
        assert_eq!(screen.buffer, bare_screen.buffer);
    }

    #[test]
    fn input_is_forwarded_to_the_active_effect() {
        let mut playlist = playlist_with(&[("ink", Some(5.0))], 0.6, false);
        let is_paused = |playlist: &mut Playlist| match &playlist.current {
            AnyEffect::Ink(field) => field.paused,
            _ => false,
        };
        assert!(!is_paused(&mut playlist));

        playlist.handle_input(&InputEvent::Key {
            key: crate::runtime::Key::Space,
            phase: crate::runtime::KeyPhase::Pressed,
        });

        assert!(is_paused(&mut playlist));
    }

    /// A static effect is still revealed by the wipe.
    ///
    /// `terrain` draws one frame and then reports nothing at all for the rest of
    /// its slot, so the wipe-in has to reveal the frame it already has rather
    /// than wait for changes that never come. That only works if the
    /// accumulation survives the wipe, which is what applying the wipe to a copy
    /// is for -- and it did not: the wipe was baked into the surface the next
    /// frame accumulated onto, so the static effect's one and only frame was
    /// destroyed by the first frame of its own wipe-in and the slot was blank.
    #[test]
    fn a_static_effect_is_revealed_by_the_wipe_in() {
        let mut playlist = playlist_with(
            &[("dvd", Some(0.05)), ("terrain", Some(5.0))],
            0.6,
            false,
        );
        let mut screen = Buffer::new(40, 12);
        let mut frame = 0;

        while playlist.current_id() != EffectId::Terrain {
            tick(&mut playlist, frame, &mut screen);
            frame += 1;
            assert!(frame < 1000, "the playlist never reached the second slot");
        }

        // From the swap onwards, the most the screen ever holds. Terrain fills
        // most of the screen, so a slot that shows less than a third of it never
        // revealed the effect.
        let mut fullest = 0;
        for _ in 0..200 {
            tick(&mut playlist, frame, &mut screen);
            fullest = fullest.max(lit(&screen));
            frame += 1;
        }

        assert!(
            fullest > 40 * 12 / 3,
            "a static effect's frame was never revealed: the screen held at \
             most {fullest} of {} cells",
            40 * 12
        );
    }

    /// A rebuilt playlist starts from a blank screen, not from the frame the
    /// outgoing effect was leaving.
    ///
    /// `rebuild_buffers` blanked the surface and established the baseline, and
    /// establishing a baseline is a commit, and a commit swaps the canvas's two
    /// surfaces -- so the frame on screen became the blank while the surface
    /// being drawn into kept the outgoing effect. `render_full_frame` then
    /// accumulated onto that, so every swap re-emitted the outgoing frame, and
    /// an effect whose diff is always empty painted the previous effect's image
    /// underneath itself for its whole slot. `blank` is that effect.
    #[test]
    fn a_rebuilt_effect_does_not_re_emit_the_outgoing_frame() {
        let mut playlist =
            playlist_with(&[("dvd", Some(0.05)), ("blank", Some(5.0))], 0.6, false);
        let mut screen = Buffer::new(40, 12);

        // Run the first slot out and the wipe through into the second, keeping
        // the most the screen ever had on it: by the time the swap lands the
        // screen is blank again, which is the point.
        let mut frame = 0;
        let mut fullest = 0;
        while playlist.current_id() != EffectId::Blank {
            tick(&mut playlist, frame, &mut screen);
            frame += 1;
            fullest = fullest.max(lit(&screen));
            assert!(frame < 1000, "the playlist never reached the second slot");
        }
        assert!(fullest > 0, "nothing was ever drawn to carry over");

        // The surface the new effect's frame is built on is blank. The effect's
        // first frame covers every cell it draws and nothing at all for the
        // cells it leaves blank, so an accumulation still holding the outgoing
        // effect shows it through underneath for the whole slot.
        assert_eq!(
            lit(&playlist.frame),
            0,
            "the outgoing effect is still in the frame the new effect builds on"
        );

        // And from here the playlist is showing `blank`, which draws nothing at
        // all, so everything it reports has to be blank.
        for _ in 0..120 {
            for (x, y, cell) in tick(&mut playlist, frame, &mut screen) {
                assert_eq!(
                    cell.symbol, ' ',
                    "the outgoing effect's frame was re-emitted at ({x},{y})"
                );
            }
            frame += 1;
        }

        assert_eq!(
            lit(&screen),
            0,
            "the previous effect stayed on screen through the whole slot"
        );
    }
}