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
use crate::ants::Ants;
use crate::aquarium::Aquarium;
use crate::blank::Blank;
use crate::boids::Boids;
use crate::buffer::Cell;
use crate::clock::Clock;
use crate::common::TerminalEffect;
use crate::config::Config;
use crate::crab::Crab;
use crate::cube::Cube;
use crate::donut::Donut;
use crate::dvd::Dvd;
use crate::fire::Fire;
use crate::flyover::Flyover;
use crate::ink::AsciiField;
use crate::life::ConwayLife;
use crate::mandelbrot::Mandelbrot;
use crate::maze::Maze;
use crate::newton::Newton;
use crate::physarum::Physarum;
use crate::pipes::Pipes;
use crate::plasma::Plasma;
use crate::rain::digital_rain::DigitalRain;
use crate::ripple::Ripple;
use crate::runtime::{FrameContext, InputEvent};
use crate::solarsystem::SolarSystem;
use crate::terrain::Terrain;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
)]
#[serde(into = "String", try_from = "String")]
pub enum EffectId {
    Matrix,
    Life,
    Mandelbrot,
    Maze,
    Boids,
    Blank,
    Cube,
    Crab,
    Donut,
    Dvd,
    Pipes,
    Plasma,
    Fire,
    SolarSystem,
    Ink,
    Terrain,
    Ants,
    Flyover,
    Physarum,
    Ripple,
    Newton,
    Aquarium,
    /// Last, because the catalogue is ordered by when an effect arrived and
    /// `n`/`p` walk it. Inserting anywhere else moves `Life`'s neighbour and
    /// breaks `pressing_next_advances_and_wraps` for a reason that has nothing to
    /// do with wrapping -- see the note on `KNOWN_IDS`.
    Clock,
}

/// Everything the CLI needs to know about an effect, in one place.
///
/// This table is the single source of truth. It used to be five separate
/// hand-maintained lists -- the `ALL` array, `as_str`, `description`,
/// `default_duration` and `needs_mouse` -- and forgetting to update the `ALL`
/// array was the dangerous one: the effect still compiled, but became invisible
/// to `--help`, to argument parsing and to playlists, with nothing to say so.
///
/// Adding an effect is now one entry here. A variant with no entry is caught by
/// `every_effect_id_has_a_spec_entry`.
pub struct EffectSpec {
    pub id: EffectId,
    /// Name accepted on the command line and in the config file.
    pub name: &'static str,
    /// One line shown in `--help`.
    pub description: &'static str,
    /// Seconds this effect runs for in a playlist that does not say.
    pub default_duration: f32,
    /// Whether the effect reads the mouse and so needs capture enabled.
    pub needs_mouse: bool,
    /// Key of this effect's section in the config file.
    pub config_section: &'static str,
    /// The palettes shuffle mode may draw from for this effect.
    ///
    /// Empty for an effect that takes no palette at all, and that is the *only*
    /// kind of empty: the effects with no `palette` option, and `newton`, which
    /// has one conceptually and not as a config field. Newton colours by *which
    /// root* a sample converges to, built from an OKLab wheel so hue and
    /// lightness are independent -- picking a ramp out of a table would replace
    /// the thing the effect encodes rather than restyle it.
    ///
    /// Not every effect reads a ramp the same way, which is why this is a
    /// per-effect list rather than one shared pool. See the constants below.
    pub shuffle_palettes: &'static [&'static str],
}

/// Every named ramp, for a consumer that *cycles* through it.
///
/// `mandelbrot` is the only one, because it is the only one that wraps: it
/// samples its ramp with the cycling sampler, so a ramp that climbs back down
/// is what it wants and any of them suits it.
const CYCLING_PALETTES: &[&str] = &["depth", "ember", "ocean", "magma", "contrast"];

/// Every named ramp except `contrast`, for a consumer that reads a ramp as a
/// *brightness scale* and stops at the top.
///
/// `contrast` is excluded because its own note calls it "a pure boundary map
/// with no interior shading". As a cycling ramp that is exactly right -- the
/// boundaries are the picture. As a brightness scale it has nothing between its
/// two extremes, so an effect that exists to show veins, crests, a trail or
/// depth fog would show two flat regions instead.
///
/// `donut` is in this group, so shuffle mode will not reach its `contrast` path.
/// That path is deliberate and documented at `donut_colors` -- a floor-to-white
/// two-tone torus is a legitimate thing to ask for -- so if you want it in the
/// shuffle, `donut` is a one-line change to this list.
const SHADED_PALETTES: &[&str] = &["depth", "ember", "ocean", "magma"];

/// The single-hue brightness ramps, for `ink`.
///
/// A separate table because `ink` indexes a ramp by field value and stops at the
/// top, so its ramps have to end on white -- which none of the multi-hue ones
/// do. It is why a user who typed `palette = "ember"` there would get a field
/// that is supposed to end on white and ends on amber instead.
const FIELD_PALETTES: &[&str] = &["green", "orange", "blue", "magenta"];

pub static EFFECT_SPECS: &[EffectSpec] = &[
    EffectSpec {
        id: EffectId::Matrix,
        name: "matrix",
        description: "Matrix digital rain",
        default_duration: 15.0,
        needs_mouse: false,
        config_section: "matrix",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Life,
        name: "life",
        description: "Conway's Game of Life",
        default_duration: 20.0,
        needs_mouse: false,
        config_section: "life",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Mandelbrot,
        name: "mandelbrot",
        description: "Escape-time Mandelbrot set, slowly zooming",
        default_duration: 20.0,
        needs_mouse: false,
        config_section: "mandelbrot",
        shuffle_palettes: CYCLING_PALETTES,
    },
    EffectSpec {
        id: EffectId::Maze,
        name: "maze",
        description: "Maze generation",
        default_duration: 20.0,
        needs_mouse: false,
        config_section: "maze",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Boids,
        name: "boids",
        description: "Boids flocking simulation, scattered by clicking",
        default_duration: 20.0,
        // A click drops a shockwave into the flock, so this effect reads the
        // mouse. Not optional bookkeeping: `main.rs` decides whether to enable
        // capture from *the playlist's own effects*, so a playlist of `boids`
        // alone would otherwise never enable it and the effect would be
        // interactive in exactly one of the three ways it can be run.
        needs_mouse: true,
        config_section: "boids",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Blank,
        name: "blank",
        description: "Blank screen",
        default_duration: 2.0,
        needs_mouse: false,
        config_section: "blank",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Cube,
        name: "cube",
        description: "3D cube rotation",
        default_duration: 18.0,
        needs_mouse: false,
        config_section: "cube",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Crab,
        name: "crab",
        description: "ASCII crab animation",
        default_duration: 15.0,
        needs_mouse: false,
        config_section: "crab",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Donut,
        name: "donut",
        description: "3D donut rotation",
        default_duration: 18.0,
        needs_mouse: false,
        config_section: "donut",
        shuffle_palettes: SHADED_PALETTES,
    },
    EffectSpec {
        id: EffectId::Dvd,
        name: "dvd",
        description: "Bouncing DVD logo",
        default_duration: 12.0,
        needs_mouse: false,
        config_section: "dvd",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Pipes,
        name: "pipes",
        description: "Pipe maze animation",
        default_duration: 15.0,
        needs_mouse: false,
        config_section: "pipes",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Plasma,
        name: "plasma",
        description: "Plasma color wave effect",
        default_duration: 15.0,
        needs_mouse: false,
        config_section: "plasma",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Fire,
        name: "fire",
        description: "Fire simulation",
        default_duration: 12.0,
        needs_mouse: false,
        config_section: "fire",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::SolarSystem,
        name: "solarsystem",
        description: "A solar system on tilted orbits, real orbital periods",
        default_duration: 20.0,
        needs_mouse: false,
        config_section: "solarsystem",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Ink,
        // Was "ascii", which named the medium rather than the effect: it draws
        // characters, but so do eleven others, and the thing you interact with is
        // ink poured into a field. Renamed with no alias, so an old `[ascii]`
        // config section is ignored and an old `effect = "ascii"` playlist entry
        // is dropped -- see `build_slots`, which now reports the latter rather
        // than swallowing it.
        name: "ink",
        description: "Interactive generative field you pour ink into",
        default_duration: 20.0,
        needs_mouse: true,
        config_section: "ink",
        shuffle_palettes: FIELD_PALETTES,
    },
    EffectSpec {
        id: EffectId::Terrain,
        name: "terrain",
        description: "Terrain generation",
        default_duration: 4.0,
        needs_mouse: false,
        config_section: "terrain",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Ants,
        name: "ants",
        // "Langton's ants" rather than "Langton's ant": the effect is several of
        // them on one board, and the whole point of that is that they read each
        // other's flips and wreck each other's highways. Naming it in the singular
        // would describe a ten-line effect that is not this one.
        description: "Several Langton's ants sharing one board",
        default_duration: 30.0,
        needs_mouse: false,
        config_section: "ants",
        shuffle_palettes: SHADED_PALETTES,
    },
    EffectSpec {
        id: EffectId::Flyover,
        name: "flyover",
        description: "First-person flight over a fractal height field",
        default_duration: 25.0,
        needs_mouse: false,
        config_section: "flyover",
        shuffle_palettes: SHADED_PALETTES,
    },
    EffectSpec {
        id: EffectId::Physarum,
        name: "physarum",
        description: "Slime-mould agents building a transport network",
        default_duration: 30.0,
        needs_mouse: false,
        config_section: "physarum",
        shuffle_palettes: SHADED_PALETTES,
    },
    EffectSpec {
        id: EffectId::Ripple,
        name: "ripple",
        description: "Interfering waves from a few point sources",
        default_duration: 20.0,
        needs_mouse: false,
        config_section: "ripple",
        shuffle_palettes: SHADED_PALETTES,
    },
    EffectSpec {
        id: EffectId::Newton,
        // "Newton's method", and the description carries the part that matters.
        // A name alone does not say what is on screen: the mandelbrot is also an
        // iteration on the complex plane, and the two are close enough that
        // "Newton fractal" as a bare name would leave a user who has just watched
        // `mandelbrot` with no reason to expect a different picture. What
        // distinguishes this one is the colour, so that is what the line says.
        name: "newton",
        description: "Newton's method basins, coloured by which root each sample finds",
        default_duration: 25.0,
        needs_mouse: false,
        config_section: "newton",
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Aquarium,
        // "A fish tank" and not a list of contents. Every entry here names the
        // thing on screen, and "fish" names what is *in* the scene rather than the
        // scene itself -- and the scene is the part that makes it read. The
        // description carries the two cues that do the work, because neither is
        // guessable from a braille dot grid: the depth shading and the lit backs.
        name: "aquarium",
        description: "A freshwater tank: seven species, shoaling, shaded by depth",
        default_duration: 30.0,
        // Drops a flake of food where you click and the shoal goes for it. Same
        // reason as `boids` and `ink`: capture is enabled from the *playlist's* own
        // effects, so a playlist of `aquarium` alone has to turn it on or the effect
        // is interactive in exactly one of the three ways it can be run.
        needs_mouse: true,
        config_section: "aquarium",
        // It owns three colours -- surface, deep and gravel -- rather than naming a
        // preset, and they have to move together to keep the gradient monotonic, so
        // there is nothing here for shuffle mode to draw from.
        shuffle_palettes: &[],
    },
    EffectSpec {
        id: EffectId::Clock,
        // "A large clock", and the description carries the part that is not
        // guessable from the name: the rule is what makes it a *screensaver*
        // rather than a clock, because a clock that only redraws on the second
        // is a still picture for fifty-nine frames out of every sixty and a
        // playlist slot would show a frozen face for its whole duration.
        name: "clock",
        description: "A large clock, with a rule showing the seconds",
        // Long, and on purpose against `blank`'s 2.0. This is the other thing a
        // playlist uses as a rest -- a quiet frame with something in it -- and
        // the whole point of a rest is that it outlasts the urge to skip it.
        default_duration: 20.0,
        needs_mouse: false,
        config_section: "clock",
        // No palette, and deliberately: there is a `color` and an `accent` rather
        // than a ramp, because a clock's two colours mark two *kinds* of thing --
        // digits and furniture -- and a ramp over a five-glyph face would be
        // shading one of them.
        shuffle_palettes: &[],
    },
];

impl EffectId {
    /// Every registered effect, in the order they appear in `--help` and in a
    /// playlist that does not choose.
    pub fn all() -> impl Iterator<Item = EffectId> {
        EFFECT_SPECS.iter().map(|spec| spec.id)
    }

    pub fn len() -> usize {
        EFFECT_SPECS.len()
    }

    pub fn is_empty() -> bool {
        EFFECT_SPECS.is_empty()
    }

    /// The spec for this effect.
    ///
    /// Panics if a variant has no entry, which is a programming error rather
    /// than a user error. `every_effect_id_has_a_spec_entry` turns that panic
    /// into a test failure.
    pub fn spec(self) -> &'static EffectSpec {
        EFFECT_SPECS
            .iter()
            .find(|spec| spec.id == self)
            .unwrap_or_else(|| panic!("{self:?} has no entry in EFFECT_SPECS"))
    }

    pub fn as_str(self) -> &'static str {
        self.spec().name
    }

    pub fn description(self) -> &'static str {
        self.spec().description
    }

    pub fn default_duration(self) -> f32 {
        self.spec().default_duration
    }

    pub fn needs_mouse(self) -> bool {
        self.spec().needs_mouse
    }

    /// Key of this effect's section in the config file.
    pub fn config_section(self) -> &'static str {
        self.spec().config_section
    }
}

impl From<EffectId> for String {
    fn from(value: EffectId) -> Self {
        value.as_str().to_string()
    }
}

impl TryFrom<String> for EffectId {
    type Error = String;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        value.parse()
    }
}

impl FromStr for EffectId {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        EFFECT_SPECS
            .iter()
            .find(|spec| spec.name == value)
            .map(|spec| spec.id)
            .ok_or_else(|| format!("Unknown effect: {value}"))
    }
}

pub enum AnyEffect {
    Matrix(DigitalRain),
    Life(ConwayLife),
    Mandelbrot(Mandelbrot),
    Maze(Maze),
    Boids(Boids),
    Blank(Blank),
    Cube(Cube),
    Crab(Crab),
    Donut(Donut),
    Dvd(Dvd),
    Pipes(Pipes),
    Plasma(Plasma),
    Fire(Fire),
    SolarSystem(SolarSystem),
    Ink(AsciiField),
    Terrain(Terrain),
    Ants(Ants),
    Flyover(Flyover),
    Physarum(Physarum),
    Ripple(Ripple),
    Newton(Newton),
    Aquarium(Aquarium),
    Clock(Clock),
}

impl AnyEffect {
    pub fn id(&self) -> EffectId {
        match self {
            Self::Matrix(_) => EffectId::Matrix,
            Self::Life(_) => EffectId::Life,
            Self::Mandelbrot(_) => EffectId::Mandelbrot,
            Self::Maze(_) => EffectId::Maze,
            Self::Boids(_) => EffectId::Boids,
            Self::Blank(_) => EffectId::Blank,
            Self::Cube(_) => EffectId::Cube,
            Self::Crab(_) => EffectId::Crab,
            Self::Donut(_) => EffectId::Donut,
            Self::Dvd(_) => EffectId::Dvd,
            Self::Pipes(_) => EffectId::Pipes,
            Self::Plasma(_) => EffectId::Plasma,
            Self::Fire(_) => EffectId::Fire,
            Self::SolarSystem(_) => EffectId::SolarSystem,
            Self::Ink(_) => EffectId::Ink,
            Self::Terrain(_) => EffectId::Terrain,
            Self::Ants(_) => EffectId::Ants,
            Self::Flyover(_) => EffectId::Flyover,
            Self::Physarum(_) => EffectId::Physarum,
            Self::Ripple(_) => EffectId::Ripple,
            Self::Newton(_) => EffectId::Newton,
            Self::Aquarium(_) => EffectId::Aquarium,
            Self::Clock(_) => EffectId::Clock,
        }
    }

    pub fn build(id: EffectId, config: &Config, screen_size: (u16, u16)) -> Self {
        match id {
            EffectId::Matrix => Self::Matrix(DigitalRain::new(
                config.get_matrix_options(screen_size),
                screen_size,
            )),
            EffectId::Life => Self::Life(ConwayLife::new(
                config.get_life_options(screen_size),
                screen_size,
            )),
            EffectId::Mandelbrot => Self::Mandelbrot(Mandelbrot::new(
                config.get_mandelbrot_options(),
                screen_size,
            )),
            EffectId::Maze => Self::Maze(Maze::new(
                config.get_maze_options(screen_size),
                screen_size,
            )),
            EffectId::Boids => {
                Self::Boids(Boids::new(config.get_boids_options(screen_size)))
            }
            EffectId::Blank => {
                Self::Blank(Blank::new(config.get_blank_options(), screen_size))
            }
            EffectId::Cube => {
                Self::Cube(Cube::new(config.get_cube_options(), screen_size))
            }
            EffectId::Crab => Self::Crab(Crab::new(
                config.get_crab_options(screen_size),
                screen_size,
            )),
            EffectId::Donut => Self::Donut(Donut::new(
                config.get_donut_options(screen_size),
                screen_size,
            )),
            EffectId::Dvd => {
                Self::Dvd(Dvd::new(config.get_dvd_options(), screen_size))
            }
            EffectId::Pipes => {
                Self::Pipes(Pipes::new(config.get_pipes_options(), screen_size))
            }
            EffectId::Plasma => {
                Self::Plasma(Plasma::new(config.get_plasma_options(), screen_size))
            }
            EffectId::Fire => {
                Self::Fire(Fire::new(config.get_fire_options(), screen_size))
            }
            EffectId::SolarSystem => Self::SolarSystem(SolarSystem::new(
                config.get_solarsystem_options(),
                screen_size,
            )),
            EffectId::Ink => {
                Self::Ink(AsciiField::new(config.get_ink_options(), screen_size))
            }
            EffectId::Terrain => Self::Terrain(Terrain::new(
                config.get_terrain_options(),
                screen_size,
            )),
            EffectId::Ants => Self::Ants(Ants::new(
                config.get_ants_options(screen_size),
                screen_size,
            )),
            EffectId::Flyover => Self::Flyover(Flyover::new(
                config.get_flyover_options(),
                screen_size,
            )),
            EffectId::Physarum => Self::Physarum(Physarum::new(
                config.get_physarum_options(screen_size),
                screen_size,
            )),
            EffectId::Ripple => {
                Self::Ripple(Ripple::new(config.get_ripple_options(), screen_size))
            }
            EffectId::Newton => {
                Self::Newton(Newton::new(config.get_newton_options(), screen_size))
            }
            EffectId::Aquarium => Self::Aquarium(Aquarium::new(
                config.get_aquarium_options(),
                screen_size,
            )),
            EffectId::Clock => {
                Self::Clock(Clock::new(config.get_clock_options(), screen_size))
            }
        }
    }
}

/// Forwards every `TerminalEffect` method to the wrapped effect.
///
/// The six forwarding methods used to be written out by hand, sixteen arms
/// each, which is ninety-six near-identical lines. The variant list below is the
/// only thing that has to be maintained.
///
/// Forgetting a variant is a compile error rather than a silent gap: the
/// `match` inside each method stops being exhaustive, and `AnyEffect` is used as
/// a `TerminalEffect` everywhere.
macro_rules! impl_terminal_effect_for_any {
    ($($variant:ident),+ $(,)?) => {
        impl TerminalEffect for AnyEffect {
            fn get_diff(&mut self) -> Vec<(usize, usize, Cell)> {
                match self {
                    $(Self::$variant(effect) => effect.get_diff(),)+
                }
            }

            fn update(&mut self) {
                match self {
                    $(Self::$variant(effect) => effect.update(),)+
                }
            }

            fn update_size(&mut self, width: u16, height: u16) {
                match self {
                    $(Self::$variant(effect) => effect.update_size(width, height),)+
                }
            }

            fn reset(&mut self) {
                match self {
                    $(Self::$variant(effect) => effect.reset(),)+
                }
            }

            fn handle_input(&mut self, event: &InputEvent) {
                match self {
                    $(Self::$variant(effect) => effect.handle_input(event),)+
                }
            }

            fn get_diff_with_context(
                &mut self,
                context: &FrameContext,
            ) -> Vec<(usize, usize, Cell)> {
                match self {
                    $(Self::$variant(effect) => effect.get_diff_with_context(context),)+
                }
            }

            fn update_with_context(&mut self, context: &FrameContext) {
                match self {
                    $(Self::$variant(effect) => effect.update_with_context(context),)+
                }
            }
        }
    };
}

impl_terminal_effect_for_any!(
    Matrix,
    Life,
    Mandelbrot,
    Maze,
    Boids,
    Blank,
    Cube,
    Crab,
    Donut,
    Dvd,
    Pipes,
    Plasma,
    Fire,
    SolarSystem,
    Ink,
    Terrain,
    Ants,
    Flyover,
    Physarum,
    Ripple,
    Newton,
    Aquarium,
    Clock,
);

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

    /// Every effect id, written out.
    ///
    /// This is the one place a new effect has to be added twice, and that is
    /// deliberate: it is a change detector. Adding an effect without adding it
    /// here fails the build's test run rather than passing quietly.
    const KNOWN_IDS: &[EffectId] = &[
        EffectId::Matrix,
        EffectId::Life,
        EffectId::Mandelbrot,
        EffectId::Maze,
        EffectId::Boids,
        EffectId::Blank,
        EffectId::Cube,
        EffectId::Crab,
        EffectId::Donut,
        EffectId::Dvd,
        EffectId::Pipes,
        EffectId::Plasma,
        EffectId::Fire,
        EffectId::SolarSystem,
        EffectId::Ink,
        EffectId::Terrain,
        EffectId::Ants,
        EffectId::Flyover,
        EffectId::Physarum,
        EffectId::Ripple,
        EffectId::Newton,
        EffectId::Aquarium,
        EffectId::Clock,
    ];

    #[test]
    fn every_effect_id_has_a_spec_entry() {
        // A variant with no entry would panic at runtime, and in the meantime be
        // invisible to `--help`, to argument parsing and to playlists.
        for id in KNOWN_IDS {
            let spec = id.spec();
            assert_eq!(spec.id, *id);
        }
        assert_eq!(
            EFFECT_SPECS.len(),
            KNOWN_IDS.len(),
            "EFFECT_SPECS has {} entries but there are {} effect ids",
            EFFECT_SPECS.len(),
            KNOWN_IDS.len()
        );
    }

    #[test]
    fn the_table_lists_each_effect_exactly_once() {
        let mut seen = HashSet::new();
        for spec in EFFECT_SPECS {
            assert!(
                seen.insert(spec.id),
                "{} appears twice in EFFECT_SPECS",
                spec.id.as_str()
            );
        }
    }

    #[test]
    fn names_and_sections_are_unique_and_well_formed() {
        let mut names = HashSet::new();
        let mut sections = HashSet::new();

        for spec in EFFECT_SPECS {
            assert!(
                names.insert(spec.name),
                "two effects share the name {:?}",
                spec.name
            );
            assert!(
                sections.insert(spec.config_section),
                "two effects share the config section {:?}",
                spec.config_section
            );
            assert!(
                spec.name.chars().all(|c| c.is_ascii_alphanumeric()),
                "{:?} is not a plain lowercase name",
                spec.name
            );
            assert_eq!(
                spec.config_section, spec.name,
                "{} should use its own name as its config section",
                spec.name
            );
        }
    }

    #[test]
    fn every_effect_has_usable_metadata() {
        for spec in EFFECT_SPECS {
            assert!(
                !spec.description.trim().is_empty(),
                "{} has an empty description, which would render a blank help line",
                spec.name
            );
            assert!(
                spec.default_duration.is_finite() && spec.default_duration > 0.0,
                "{} has a non-positive playlist duration ({})",
                spec.name,
                spec.default_duration
            );
        }
    }

    #[test]
    fn names_round_trip_through_parsing() {
        for spec in EFFECT_SPECS {
            let parsed: EffectId = spec.name.parse().expect("parses");
            assert_eq!(parsed, spec.id, "{} did not round-trip", spec.name);
            assert_eq!(parsed.as_str(), spec.name);
        }
    }

    #[test]
    fn unknown_names_are_rejected() {
        assert!("not-an-effect".parse::<EffectId>().is_err());
        assert!("".parse::<EffectId>().is_err());
        // A near miss must not resolve.
        assert!("Matrix".parse::<EffectId>().is_err());
        assert!("dvd ".parse::<EffectId>().is_err());
    }

    #[test]
    fn the_conversion_into_a_string_uses_the_registered_name() {
        for spec in EFFECT_SPECS {
            assert_eq!(String::from(spec.id), spec.name);
            assert_eq!(EffectId::try_from(spec.name.to_string()), Ok(spec.id));
        }
    }
}