device-envoy-core 0.1.3

Shared traits and data types for device-envoy platform crates
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
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
//! In-memory implementations for fast, deterministic native desktop tests.
//!
//! Enable the `host` feature when testing in an ordinary Windows, macOS, or
//! Linux process.
//!
//! ## Implementations
//!
//! - [`CydMemory`] provides in-memory display and touch through the portable
//!   [`cyd`](crate::cyd) interfaces.
//! - [`ButtonMemory`] provides scripted button input.
//! - [`assert_framebuffer_matches_expected_png`] compares a rendered framebuffer
//!   with a golden PNG.

#[cfg(test)]
use core::ops::Range;
use core::{
    cell::{Cell, RefCell},
    convert::Infallible,
    future::{Future, ready},
};
use std::{
    fs,
    io::BufWriter,
    path::{Path, PathBuf},
    process,
    rc::Rc,
    time::{SystemTime, UNIX_EPOCH},
    vec::Vec,
};

#[cfg(test)]
use crate::cyd::backend::TouchUncalibrated;
#[cfg(test)]
use crate::cyd::touch::flow::{MIN_SAMPLES_PER_POINT, SAMPLES_DISCARDED_AFTER_DOWN};
use crate::cyd::{
    Cyd, CydDisplay, CydTouch,
    backend::{CalibrationConfig, RawTouchEvent},
    display::{CydFrame, Orientation},
    touch::TouchEvent,
};
#[cfg(test)]
use crate::flash_block::{
    Error as FlashBlockError, FlashBlock, FlashDevice, clear_block, load_block, save_block,
};
use crate::{
    UnwrapInfallible,
    button::{__ButtonMonitor, Button},
    pixel_target::{PixelTarget, rgb888_from_rgb565},
};
use embedded_graphics::pixelcolor::{Rgb888, RgbColor};
use embedded_graphics::{
    Drawable, Pixel,
    mono_font::{MonoFont, MonoTextStyle, ascii::FONT_9X15_BOLD},
    pixelcolor::{IntoStorage, Rgb565, raw::RawU16},
    prelude::{Dimensions, DrawTarget, Point, Size},
    primitives::Rectangle,
    text::{Baseline, Text},
};
#[cfg(test)]
use serde::{Deserialize, Serialize};

const DEFAULT_FRAME_BUDGET: usize = 1000;
#[cfg(test)]
const FLASH_BLOCK_SIZE: usize = 4096;
#[cfg(test)]
const FLASH_BLOCK_OFFSET: u32 = 0;
#[cfg(test)]
const FLASH_ERASED_BYTE: u8 = 0xFF;

const fn identity_calibration_config() -> CalibrationConfig {
    CalibrationConfig::new(1.0, 0.0, 0.0, 0.0, 1.0, 0.0)
}

#[derive(Clone)]
pub(crate) struct FrameClockMemory {
    frame_index: Rc<Cell<usize>>,
}

impl FrameClockMemory {
    #[must_use]
    pub fn frame_index(&self) -> usize {
        self.frame_index.get()
    }
}

/// Error from the in-memory CYD test surface.
///
/// [`OutOfFrames`](Self::OutOfFrames) means that the configured frame budget
/// has been exhausted. It is returned by a frame flush instead of silently
/// dropping a rendered frame.
/// See [`CydMemory::set_frame_budget`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// The configured number of frame flushes has already been used.
    /// See [`CydMemory::set_frame_budget`].
    OutOfFrames,
}
#[cfg_attr(
    feature = "doc-images",
    doc = ::embed_doc_image::embed_image!("cyd_memory_bitmap", "docs/assets/cyd_memory_bitmap.png")
)]
/// In-memory CYD device for fast, deterministic native desktop tests and screenshots.
///
/// Enable the `host` feature to use this in an ordinary Windows, macOS, or Linux
/// process. Tests can draw through the portable [`Cyd`]
/// interface, inject touch and button input, inspect pixels and flush counts,
/// and compare the complete framebuffer with a golden PNG.
///
/// # Example
///
/// ```rust,no_run
/// use device_envoy_core::{
///     button::Button,
///     cyd::{
///         Cyd, CydDisplay, CydTouch,
///         display::{CydFrame, DrawItem, Image565Fixed, tga},
///         touch::TouchEvent,
///     },
///     memory::{CydMemory, assert_framebuffer_matches_expected_png},
/// };
/// use embedded_graphics::{
///     mono_font::ascii::FONT_9X15_BOLD,
///     pixelcolor::{Rgb888, RgbColor},
///     prelude::{Point, Size},
/// };
/// use futures_executor::block_on;
///
/// const BITMAP: Image565Fixed<45, 73, { 45 * 73 }> = tga!(concat!(
///     env!("CARGO_MANIFEST_DIR"),
///     "/docs/assets/cyd_fill_contiguous.tga"
/// ))
/// .to_565();
///
/// let mut cyd_memory = CydMemory::new(
///     Size::new(320, 240),
///     Rgb888::BLACK,
///     Rgb888::WHITE,
///     &FONT_9X15_BOLD,
/// );
/// cyd_memory.push_touch_event(TouchEvent::Up);
/// assert!(matches!(
///     cyd_memory.touch().try_read()?,
///     Some(TouchEvent::Up)
/// ));
/// let mut button = cyd_memory.button_memory();
/// button.set_pressed(true);
/// button.set_pressed_for_frame(1, false);
/// let mut display = cyd_memory.display();
/// let mut frame = display.full_frame_mut();
/// frame.write_text("Hello CYD");
/// DrawItem::Bitmap {
///     view: BITMAP.view(),
///     top_left: Point::new(128, 88),
/// }
/// .draw(&mut frame);
/// block_on(frame.flush())?;
/// assert!(!button.is_pressed());
/// assert_eq!(cyd_memory.flush_count(), 1);
/// let golden_result = assert_framebuffer_matches_expected_png(
///     &cyd_memory,
///     env!("CARGO_MANIFEST_DIR"),
///     "cyd_memory_bitmap.png",
/// );
/// assert!(golden_result.is_ok(), "{golden_result:?}");
/// # Ok::<(), device_envoy_core::memory::Error>(())
/// ```
///
/// ![CydMemory framebuffer preview][cyd_memory_bitmap]
pub struct CydMemory {
    display: CydDisplayMemory,
    touch: CydTouchMemory,
    shared: Rc<RefCell<CydMemoryShared>>,
    orientation: Orientation,
}

struct CydMemoryShared {
    framebuffer: Vec<u16>,
    flush_count: usize,
    last_flush_rectangle: Option<Rectangle>,
    frame_budget: usize,
    raw_touch_script: FrameScript<RawTouchEvent>,
    touch_script: FrameScript<TouchEvent>,
    frame_clock: FrameClockMemory,
}

/// Owned display half of [`CydMemory`].
#[derive(Clone)]
pub struct CydDisplayMemory {
    size: Size,
    background_color: Rgb888,
    foreground_color: Rgb888,
    background565: Rgb565,
    foreground565: Rgb565,
    font: &'static MonoFont<'static>,
    shared: Rc<RefCell<CydMemoryShared>>,
}

/// Owned calibrated touch half of [`CydMemory`].
#[derive(Clone)]
pub struct CydTouchMemory {
    shared: Rc<RefCell<CydMemoryShared>>,
    calibration_config: CalibrationConfig,
}

/// Owned uncalibrated touch half used by calibration tests.
#[cfg(test)]
pub(crate) struct CydTouchUncalibratedMemory {
    shared: Rc<RefCell<CydMemoryShared>>,
}

/// In-progress in-memory frame that flushes into an in-memory framebuffer.
pub struct CydFrameMemory {
    shared: Rc<RefCell<CydMemoryShared>>,
    screen_size: Size,
    rectangle: Rectangle,
    background565: Rgb565,
    foreground565: Rgb565,
    font: &'static MonoFont<'static>,
    pixels: Vec<u16>,
}

struct FrameScript<Event> {
    current_frame: Vec<Event>,
    future_frames: Vec<Vec<Event>>,
    current_read_index: usize,
}

#[cfg(test)]
pub(crate) struct FlashBlockMemory {
    flash_device_memory: FlashDeviceMemory,
    save_count: usize,
}

#[cfg(test)]
struct FlashDeviceMemory {
    bytes: [u8; FLASH_BLOCK_SIZE],
}

/// Native desktop button test double returned by [`CydMemory::button_memory`].
///
/// # Example
///
/// ```rust,no_run
/// use device_envoy_core::{button::Button, memory::ButtonMemory};
///
/// let mut button = ButtonMemory::new();
/// assert!(!button.is_pressed());
/// button.set_pressed(true);
/// assert!(button.is_pressed());
/// ```
pub struct ButtonMemory {
    pressed: bool,
    pressed_frames: Vec<(usize, bool)>,
    frame_clock: Option<FrameClockMemory>,
}

impl CydMemory {
    /// Construct an empty in-memory CYD surface with the given screen style.
    ///
    /// The [`CydMemory` example](CydMemory) demonstrates the canonical
    /// construction and complete host-test workflow.
    #[must_use]
    pub fn new(
        size: Size,
        background_color: Rgb888,
        foreground_color: Rgb888,
        font: &'static MonoFont<'static>,
    ) -> Self {
        let orientation = if size.width > size.height {
            Orientation::Landscape
        } else {
            Orientation::Portrait
        };
        Self::new_inner(size, orientation, background_color, foreground_color, font)
    }

    /// Construct an in-memory CYD surface with an oriented logical screen.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use device_envoy_core::{
    ///     cyd::{Cyd, CydDisplay, display::{CydFrame, Orientation}},
    ///     memory::{CydMemory, Error},
    /// };
    /// use embedded_graphics::{
    ///     mono_font::ascii::FONT_9X15_BOLD,
    ///     pixelcolor::{Rgb565, Rgb888},
    ///     prelude::{Point, RgbColor, Size},
    ///     primitives::Rectangle,
    /// };
    /// use futures_executor::block_on;
    ///
    /// let mut cyd_memory = CydMemory::new_with_orientation(
    ///     Orientation::LandscapeInverted,
    ///     Rgb888::BLACK,
    ///     Rgb888::WHITE,
    ///     &FONT_9X15_BOLD,
    /// );
    /// assert_eq!(cyd_memory.orientation(), Orientation::LandscapeInverted);
    ///
    /// let pixel = Rectangle::new(Point::zero(), Size::new(1, 1));
    /// let mut display = cyd_memory.display();
    /// let mut first_frame = display.frame_mut(pixel);
    /// first_frame.fill(Rgb565::RED);
    /// block_on(first_frame.flush())?;
    /// drop(first_frame);
    /// assert_eq!(cyd_memory.pixel(0, 0), Rgb565::RED);
    /// cyd_memory.rotate_framebuffer_180();
    /// assert_eq!(cyd_memory.pixel(319, 239), Rgb565::RED);
    /// # Ok::<(), Error>(())
    /// ```
    #[must_use]
    pub fn new_with_orientation(
        orientation: Orientation,
        background_color: Rgb888,
        foreground_color: Rgb888,
        font: &'static MonoFont<'static>,
    ) -> Self {
        Self::new_inner(
            orientation.size(),
            orientation,
            background_color,
            foreground_color,
            font,
        )
    }

    fn new_inner(
        size: Size,
        orientation: Orientation,
        background_color: Rgb888,
        foreground_color: Rgb888,
        font: &'static MonoFont<'static>,
    ) -> Self {
        let background565 = Rgb565::from(background_color);
        let pixel_count = size.width as usize * size.height as usize;
        let shared = Rc::new(RefCell::new(CydMemoryShared {
            framebuffer: vec![background565.into_storage(); pixel_count],
            flush_count: 0,
            last_flush_rectangle: None,
            frame_budget: DEFAULT_FRAME_BUDGET,
            raw_touch_script: FrameScript::default(),
            touch_script: FrameScript::default(),
            frame_clock: FrameClockMemory {
                frame_index: Rc::new(Cell::new(0)),
            },
        }));
        let display = CydDisplayMemory {
            size,
            background_color,
            foreground_color,
            background565,
            foreground565: Rgb565::from(foreground_color),
            font,
            shared: shared.clone(),
        };
        let touch = CydTouchMemory {
            shared: shared.clone(),
            calibration_config: identity_calibration_config(),
        };
        Self {
            display,
            touch,
            shared,
            orientation,
        }
    }

    #[must_use]
    /// Clone the device's display component for an independent test task.
    pub fn display(&self) -> CydDisplayMemory {
        self.display.clone()
    }

    /// Clone owned calibrated parts that share this harness's backing state.
    #[must_use]
    pub fn owned_parts(&self) -> (CydDisplayMemory, CydTouchMemory) {
        (self.display.clone(), self.touch.clone())
    }

    #[must_use]
    #[cfg(test)]
    pub(crate) fn parts_uncalibrated(&self) -> (CydDisplayMemory, CydTouchUncalibratedMemory) {
        (
            self.display.clone(),
            CydTouchUncalibratedMemory {
                shared: Rc::clone(&self.touch.shared),
            },
        )
    }
}

impl Cyd for CydMemory {
    type Error = Error;
    type Display = CydDisplayMemory;
    type Touch = CydTouchMemory;

    fn parts(&mut self) -> (&mut Self::Display, &mut Self::Touch) {
        (&mut self.display, &mut self.touch)
    }

    fn orientation(&self) -> Orientation {
        self.orientation
    }
}

impl CydMemory {
    /// Limit how many frames may flush before [`Error::OutOfFrames`].
    ///
    /// ```rust,no_run
    /// use device_envoy_core::{
    ///     cyd::{CydDisplay, display::CydFrame},
    ///     memory::{CydMemory, Error},
    /// };
    /// use embedded_graphics::{
    ///     mono_font::ascii::FONT_9X15_BOLD,
    ///     pixelcolor::{Rgb888, RgbColor},
    ///     prelude::Size,
    /// };
    ///
    /// let mut cyd_memory = CydMemory::new(
    ///     Size::new(320, 240),
    ///     Rgb888::BLACK,
    ///     Rgb888::WHITE,
    ///     &FONT_9X15_BOLD,
    /// );
    /// cyd_memory.set_frame_budget(1);
    /// let mut display = cyd_memory.display();
    ///
    /// let mut first_frame = display.full_frame_mut();
    /// futures_executor::block_on(first_frame.flush())?;
    /// drop(first_frame);
    /// let mut second_frame = display.full_frame_mut();
    /// assert_eq!(
    ///     futures_executor::block_on(second_frame.flush()),
    ///     Err(Error::OutOfFrames),
    /// );
    /// # Ok::<(), Error>(())
    /// ```
    pub fn set_frame_budget(&mut self, frame_budget: usize) {
        self.shared.borrow_mut().frame_budget = frame_budget;
    }

    #[must_use]
    pub(crate) fn frame_clock(&self) -> FrameClockMemory {
        self.shared.borrow().frame_clock.clone()
    }

    /// Create a native desktop test button tied to this device's frame clock.
    ///
    /// The [`CydMemory` example](CydMemory) demonstrates button state changing
    /// when a frame flush advances the shared clock.
    #[must_use]
    pub fn button_memory(&self) -> ButtonMemory {
        ButtonMemory::with_frame_clock(self.frame_clock())
    }

    #[cfg(test)]
    pub(crate) fn script_raw_frames(&mut self, raw_touch_frames: &[&[RawTouchEvent]]) {
        self.shared
            .borrow_mut()
            .raw_touch_script
            .replace_frames(raw_touch_frames);
    }

    #[cfg(test)]
    pub(crate) fn script_raw_frames_owned(&mut self, raw_touch_frames: Vec<Vec<RawTouchEvent>>) {
        self.shared
            .borrow_mut()
            .raw_touch_script
            .replace_owned_frames(raw_touch_frames);
    }

    #[cfg(test)]
    pub(crate) fn push_raw_touch_event(&mut self, raw_touch_event: RawTouchEvent) {
        self.shared
            .borrow_mut()
            .raw_touch_script
            .push_current_frame_event(raw_touch_event);
    }

    /// Queue one calibrated touch event for the current frame.
    ///
    /// The [`CydMemory` example](CydMemory) demonstrates injecting an event and
    /// reading it through the portable [`CydTouch`] API.
    pub fn push_touch_event(&mut self, touch_event: TouchEvent) {
        self.shared
            .borrow_mut()
            .touch_script
            .push_current_frame_event(touch_event);
    }

    /// Return how many frames have flushed so far.
    #[must_use]
    pub fn flush_count(&self) -> usize {
        self.shared.borrow().flush_count
    }

    /// Return the rectangle flushed most recently, if any.
    #[must_use]
    pub fn last_flush_rectangle(&self) -> Option<Rectangle> {
        self.shared.borrow().last_flush_rectangle
    }

    /// Read one pixel from the in-memory framebuffer.
    #[must_use]
    pub fn pixel(&self, position_x: usize, position_y: usize) -> Rgb565 {
        assert!(
            position_x < self.display.size.width as usize,
            "position_x must stay within the screen"
        );
        assert!(
            position_y < self.display.size.height as usize,
            "position_y must stay within the screen"
        );
        let stride = self.display.size.width as usize;
        let shared = self.shared.borrow();
        Rgb565::from(RawU16::new(
            shared.framebuffer[position_y * stride + position_x],
        ))
    }

    /// Apply the physical 180-degree presentation used by an inverted CYD orientation.
    ///
    /// The [`new_with_orientation`](CydMemory::new_with_orientation) example
    /// demonstrates rotating an inverted framebuffer and inspecting a pixel.
    ///
    /// Hardware display drivers and browser shells apply this transform outside the logical
    /// application framebuffer. Native desktop previews can call this after rendering to compare the
    /// user-facing presentation rather than the untransformed logical buffer.
    #[cfg(feature = "host")]
    pub fn rotate_framebuffer_180(&self) {
        let mut shared = self.shared.borrow_mut();
        let width = self.display.size.width as usize;
        let height = self.display.size.height as usize;
        for row_index in 0..height / 2 {
            let opposite_row_index = height - 1 - row_index;
            for column_index in 0..width {
                let first_index = row_index * width + column_index;
                let second_index = opposite_row_index * width + (width - 1 - column_index);
                shared.framebuffer.swap(first_index, second_index);
            }
        }
        if height % 2 == 1 {
            let row_start = (height / 2) * width;
            let row_end = row_start + width;
            shared.framebuffer[row_start..row_end].reverse();
        }
    }

    /// Write the framebuffer as an RGB PNG for native desktop previews and assertions.
    pub(crate) fn write_framebuffer_png(
        &self,
        path: impl AsRef<Path>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let width = self.display.size.width;
        let height = self.display.size.height;
        let mut rgb_bytes = Vec::with_capacity(width as usize * height as usize * 3);
        let shared = self.shared.borrow();
        for pixel in &shared.framebuffer {
            let color = rgb888_from_rgb565(*pixel);
            rgb_bytes.push(color.r());
            rgb_bytes.push(color.g());
            rgb_bytes.push(color.b());
        }

        let path = path.as_ref();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let file = fs::File::create(path)?;
        let writer = BufWriter::new(file);
        let mut encoder = png::Encoder::new(writer, width, height);
        encoder.set_color(png::ColorType::Rgb);
        encoder.set_depth(png::BitDepth::Eight);
        let mut png_writer = encoder.write_header()?;
        png_writer.write_image_data(&rgb_bytes)?;
        Ok(())
    }
}

/// Compare a rendered [`CydMemory`] framebuffer with an expected PNG.
///
/// The [`CydMemory` example](CydMemory) demonstrates the complete golden-image
/// workflow.
///
/// # Expected image
///
/// Pass `env!("CARGO_MANIFEST_DIR")` as `manifest_dir` to compare against:
///
/// `<manifest_dir>/tests/assets/<relative_filename>`
///
/// # Updating the expected image
///
/// Set `DEVICE_ENVOY_UPDATE_CYD_PNGS=1` to replace the expected PNG with the
/// current framebuffer. Use this only when accepting an intentional visual
/// change.
///
/// # Exporting a preview
///
/// Set `DEVICE_ENVOY_PREVIEW_OUTPUT_PATH` to also write the current framebuffer
/// to another path. The normal comparison or update behavior still runs.
///
/// # Errors
///
/// Returns an error when PNG encoding or file access fails, when the expected
/// image does not exist, or when its bytes differ from the current framebuffer.
pub fn assert_framebuffer_matches_expected_png(
    cyd_memory: &CydMemory,
    manifest_dir: &str,
    relative_filename: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    // The Pages xtask `build-pages` command reuses these exact tests to render gallery
    // preview images: no browser needed, since this crate already renders
    // the real example logic onto a native in-memory framebuffer. Set this
    // env var to also copy the freshly rendered frame out to an arbitrary
    // path, on top of (not instead of) the normal golden-image comparison
    // below, so a preview build still catches a real rendering regression.
    if let Some(preview_output_path) = std::env::var_os("DEVICE_ENVOY_PREVIEW_OUTPUT_PATH") {
        cyd_memory.write_framebuffer_png(preview_output_path)?;
    }

    let mut expected_path = PathBuf::from(manifest_dir);
    expected_path.push("tests");
    expected_path.push("assets");
    expected_path.push(relative_filename);

    if std::env::var_os("DEVICE_ENVOY_UPDATE_CYD_PNGS").is_some() {
        cyd_memory.write_framebuffer_png(&expected_path)?;
        std::println!("updated PNG at {}", expected_path.display());
        return Ok(());
    }

    if !expected_path.exists() {
        return Err(std::format!(
            "expected PNG is missing at {}; rerun with DEVICE_ENVOY_UPDATE_CYD_PNGS=1 to create it",
            expected_path.display()
        )
        .into());
    }

    let unix_nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or(0);
    let temp_path = std::env::temp_dir().join(std::format!(
        "{}-{}-{unix_nanos}",
        relative_filename.replace('/', "_"),
        process::id()
    ));
    cyd_memory.write_framebuffer_png(&temp_path)?;

    let expected_bytes = fs::read(&expected_path)?;
    let actual_bytes = fs::read(&temp_path)?;
    if let Err(error) = fs::remove_file(&temp_path)
        && error.kind() != std::io::ErrorKind::NotFound
    {
        return Err(error.into());
    }

    if expected_bytes != actual_bytes {
        return Err(std::format!(
            "PNG bytes differ from {}; rerun with DEVICE_ENVOY_UPDATE_CYD_PNGS=1 to accept the new image",
            expected_path.display()
        )
        .into());
    }
    Ok(())
}

impl Default for CydMemory {
    fn default() -> Self {
        Self::new(
            Size::new(320, 240),
            Rgb888::BLACK,
            Rgb888::WHITE,
            &FONT_9X15_BOLD,
        )
    }
}

impl core::fmt::Debug for CydMemory {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter.debug_struct("CydMemory").finish_non_exhaustive()
    }
}

impl core::fmt::Debug for CydTouchMemory {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("CydTouchMemory")
            .field("calibration_config", &self.calibration_config)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
impl core::fmt::Debug for CydTouchUncalibratedMemory {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("CydTouchUncalibratedMemory")
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
impl TouchUncalibrated for CydTouchUncalibratedMemory {
    type Error = Error;
    type Calibrated = CydTouchMemory;

    fn read_raw_touch_event(&mut self) -> Result<Option<RawTouchEvent>, Self::Error> {
        Ok(self
            .shared
            .borrow_mut()
            .raw_touch_script
            .pop_current_frame_event())
    }

    fn calibrate(
        self,
        calibration_config: CalibrationConfig,
        _orientation: Orientation,
    ) -> Self::Calibrated {
        CydTouchMemory {
            shared: self.shared,
            calibration_config,
        }
    }
}

impl crate::cyd::backend::DisplayBackend for CydDisplayMemory {
    type Error = Error;

    type Frame<'a> = CydFrameMemory;

    fn create_frame_mut(&mut self, rectangle: Rectangle) -> Self::Frame<'_> {
        let pixel_count = rectangle.size.width as usize * rectangle.size.height as usize;
        CydFrameMemory {
            shared: self.shared.clone(),
            screen_size: self.size,
            rectangle,
            background565: self.background565,
            foreground565: self.foreground565,
            font: self.font,
            pixels: vec![self.background565.into_storage(); pixel_count],
        }
    }
}

impl CydDisplay for CydDisplayMemory {
    fn screen_size(&self) -> Size {
        self.size
    }

    fn background_color(&self) -> Rgb888 {
        self.background_color
    }

    fn foreground_color(&self) -> Rgb888 {
        self.foreground_color
    }

    fn background_565(&self) -> Rgb565 {
        self.background565
    }

    fn foreground_565(&self) -> Rgb565 {
        self.foreground565
    }

    fn fill_rectangle(&mut self, rectangle: Rectangle, color: Rgb565) -> Result<(), Self::Error> {
        fill_rectangle_in_framebuffer(
            &mut self.shared.borrow_mut().framebuffer,
            self.size,
            rectangle,
            color.into_storage(),
        );
        Ok(())
    }

    fn fill_contiguous<I>(&mut self, rectangle: Rectangle, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Rgb565>,
    {
        fill_contiguous_in_framebuffer(
            &mut self.shared.borrow_mut().framebuffer,
            self.size,
            rectangle,
            pixels.into_iter().map(IntoStorage::into_storage),
        );
        Ok(())
    }
}

impl CydTouch for CydTouchMemory {
    type Error = Error;

    fn try_read(&mut self) -> Result<Option<TouchEvent>, Self::Error> {
        Ok(self
            .shared
            .borrow_mut()
            .touch_script
            .pop_current_frame_event())
    }
}

impl CydFrameMemory {
    fn width(&self) -> usize {
        self.rectangle.size.width as usize
    }

    fn height(&self) -> usize {
        self.rectangle.size.height as usize
    }

    fn local_x(&self, position_x: i32) -> Option<usize> {
        usize::try_from(position_x.checked_sub(self.rectangle.top_left.x)?).ok()
    }

    fn local_y(&self, position_y: i32) -> Option<usize> {
        usize::try_from(position_y.checked_sub(self.rectangle.top_left.y)?).ok()
    }

    fn flush_now(&mut self) -> Result<(), Error> {
        let mut shared = self.shared.borrow_mut();
        if shared.flush_count >= shared.frame_budget {
            return Err(Error::OutOfFrames);
        }

        blit_frame_to_screen(
            &mut shared.framebuffer,
            self.screen_size,
            self.rectangle,
            &self.pixels,
        );
        shared.last_flush_rectangle = Some(self.rectangle);
        shared.flush_count += 1;
        shared.raw_touch_script.advance_frame();
        shared.touch_script.advance_frame();
        shared
            .frame_clock
            .frame_index
            .set(shared.frame_clock.frame_index.get() + 1);
        Ok(())
    }
}

impl DrawTarget for CydFrameMemory {
    type Color = Rgb565;
    type Error = Infallible;

    fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
        self.fill(color);
        Ok(())
    }

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        for Pixel(point, color) in pixels {
            let Some(local_x) = self.local_x(point.x) else {
                continue;
            };
            let Some(local_y) = self.local_y(point.y) else {
                continue;
            };
            if local_x >= self.width() || local_y >= self.height() {
                continue;
            }
            let stride = self.width();
            self.pixels[local_y * stride + local_x] = color.into_storage();
        }
        Ok(())
    }
}

impl Dimensions for CydFrameMemory {
    fn bounding_box(&self) -> Rectangle {
        self.rectangle
    }
}

impl PixelTarget for CydFrameMemory {
    fn width(&self) -> usize {
        usize::try_from(self.rectangle.top_left.x)
            .expect("frame top-left x must be non-negative")
            .checked_add(self.width())
            .expect("frame width must fit in usize")
    }

    fn height(&self) -> usize {
        usize::try_from(self.rectangle.top_left.y)
            .expect("frame top-left y must be non-negative")
            .checked_add(self.height())
            .expect("frame height must fit in usize")
    }

    fn put_pixel(&mut self, x: usize, y: usize, color: Rgb888) {
        self.put_pixel_565(x, y, Rgb565::from(color).into_storage());
    }

    fn put_pixel_565(&mut self, x: usize, y: usize, rgb565: u16) {
        let Some(local_x) = self.local_x(x as i32) else {
            return;
        };
        let Some(local_y) = self.local_y(y as i32) else {
            return;
        };
        if local_x >= self.width() || local_y >= self.height() {
            return;
        }
        let stride = self.width();
        self.pixels[local_y * stride + local_x] = rgb565;
    }
}

impl CydFrame for CydFrameMemory {
    type Error = Error;

    fn rectangle(&self) -> Rectangle {
        self.rectangle
    }

    fn fill(&mut self, color: Rgb565) -> &mut Self {
        self.pixels.fill(color.into_storage());
        self
    }

    fn clear(&mut self) -> &mut Self {
        self.fill(self.background565)
    }

    fn write_text(&mut self, text: &str) -> &mut Self {
        Text::with_baseline(
            text,
            self.rectangle.top_left,
            MonoTextStyle::new(self.font, self.foreground565),
            Baseline::Top,
        )
        .draw(self)
        .unwrap_infallible();
        self
    }

    fn copy_from_565(&mut self, src: &[u16]) -> crate::Result<()> {
        if self.pixels.len() != src.len() {
            return Err(crate::Error::CopySize {
                src_len: src.len(),
                frame_len: self.pixels.len(),
            });
        }
        self.pixels.copy_from_slice(src);
        Ok(())
    }

    fn flush(&mut self) -> impl Future<Output = Result<(), <Self as CydFrame>::Error>> {
        ready(self.flush_now())
    }
}

impl<Event> Default for FrameScript<Event> {
    fn default() -> Self {
        Self {
            current_frame: Vec::new(),
            future_frames: Vec::new(),
            current_read_index: 0,
        }
    }
}

impl<Event: Clone> FrameScript<Event> {
    #[cfg(test)]
    fn replace_frames(&mut self, frames: &[&[Event]]) {
        self.current_frame.clear();
        self.future_frames.clear();
        self.current_read_index = 0;
        if let Some((first_frame, remaining_frames)) = frames.split_first() {
            self.current_frame = first_frame.to_vec();
            self.future_frames = remaining_frames
                .iter()
                .map(|frame| frame.to_vec())
                .collect();
        }
    }

    #[cfg(test)]
    fn replace_owned_frames(&mut self, mut frames: Vec<Vec<Event>>) {
        self.current_frame.clear();
        self.future_frames.clear();
        self.current_read_index = 0;
        if frames.is_empty() {
            return;
        }
        self.current_frame = frames.remove(0);
        self.future_frames = frames;
    }

    fn push_current_frame_event(&mut self, event: Event) {
        self.current_frame.push(event);
    }

    fn pop_current_frame_event(&mut self) -> Option<Event> {
        let event = self.current_frame.get(self.current_read_index).cloned();
        if event.is_some() {
            self.current_read_index += 1;
        }
        event
    }

    fn advance_frame(&mut self) {
        if self.current_read_index >= self.current_frame.len() {
            if let Some(next_frame) = self.future_frames.first().cloned() {
                self.current_frame = next_frame;
                self.future_frames.remove(0);
            } else {
                self.current_frame.clear();
            }
            self.current_read_index = 0;
            return;
        }

        self.current_frame.drain(0..self.current_read_index);
        self.current_read_index = 0;
    }
}

#[cfg(test)]
impl FlashBlockMemory {
    #[must_use]
    pub fn new() -> Self {
        Self {
            flash_device_memory: FlashDeviceMemory::new(),
            save_count: 0,
        }
    }

    #[must_use]
    pub fn with_value<T>(value: &T) -> Self
    where
        T: Serialize + for<'de> Deserialize<'de>,
    {
        let mut flash_block_memory = Self::new();
        flash_block_memory
            .save(value)
            .expect("saving a small in-memory flash value should succeed");
        flash_block_memory
    }

    #[must_use]
    pub fn with_raw_bytes(bytes: &[u8]) -> Self {
        let mut flash_block_memory = Self::new();
        flash_block_memory
            .flash_device_memory
            .write_raw_bytes(bytes);
        flash_block_memory
    }

    #[must_use]
    pub fn save_count(&self) -> usize {
        self.save_count
    }
}

#[cfg(test)]
impl Default for FlashBlockMemory {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
impl FlashBlock for FlashBlockMemory {
    type Error = FlashBlockError<Infallible>;

    fn load<T>(&mut self) -> Result<Option<T>, Self::Error>
    where
        T: Serialize + for<'de> Deserialize<'de>,
    {
        match load_block::<FLASH_BLOCK_SIZE, T, _>(
            &mut self.flash_device_memory,
            FLASH_BLOCK_OFFSET,
        ) {
            Ok(value) => Ok(value),
            Err(FlashBlockError::StorageCorrupted | FlashBlockError::FormatError) => Ok(None),
            Err(FlashBlockError::Io(infallible)) => match infallible {},
        }
    }

    fn save<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + for<'de> Deserialize<'de>,
    {
        save_block::<FLASH_BLOCK_SIZE, _, _>(
            &mut self.flash_device_memory,
            FLASH_BLOCK_OFFSET,
            value,
        )?;
        self.save_count += 1;
        Ok(())
    }

    fn clear(&mut self) -> Result<(), Self::Error> {
        clear_block::<FLASH_BLOCK_SIZE, _>(&mut self.flash_device_memory, FLASH_BLOCK_OFFSET)
    }
}

#[cfg(test)]
impl FlashDeviceMemory {
    // TODO Consider consolidating this native desktop flash test double with the
    // test-private `FlashDeviceMemory` in device-envoy-core's flash_block.rs tests.
    fn new() -> Self {
        Self {
            bytes: [FLASH_ERASED_BYTE; FLASH_BLOCK_SIZE],
        }
    }

    fn checked_range(&self, offset: u32, len: usize) -> Range<usize> {
        let start = usize::try_from(offset).expect("flash offset must fit in usize");
        let end = start
            .checked_add(len)
            .expect("flash range must fit in usize");
        assert!(
            end <= FLASH_BLOCK_SIZE,
            "flash range must stay in the block"
        );
        start..end
    }

    fn write_raw_bytes(&mut self, bytes: &[u8]) {
        self.bytes.fill(FLASH_ERASED_BYTE);
        let len = bytes.len().min(FLASH_BLOCK_SIZE);
        self.bytes[..len].copy_from_slice(&bytes[..len]);
    }
}

#[cfg(test)]
impl FlashDevice for FlashDeviceMemory {
    type Error = Infallible;

    fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
        let checked_range = self.checked_range(offset, bytes.len());
        bytes.copy_from_slice(&self.bytes[checked_range]);
        Ok(())
    }

    fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
        let checked_range = self.checked_range(offset, bytes.len());
        self.bytes[checked_range].copy_from_slice(bytes);
        Ok(())
    }

    fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
        let len = usize::try_from(to.saturating_sub(from)).expect("flash erase length fits usize");
        let checked_range = self.checked_range(from, len);
        self.bytes[checked_range].fill(FLASH_ERASED_BYTE);
        Ok(())
    }
}

impl ButtonMemory {
    /// Construct a button test double with no frame scheduling.
    /// See the example on [`ButtonMemory`].
    #[must_use]
    pub fn new() -> Self {
        Self {
            pressed: false,
            pressed_frames: Vec::new(),
            frame_clock: None,
        }
    }

    #[must_use]
    pub(crate) fn with_frame_clock(frame_clock: FrameClockMemory) -> Self {
        Self {
            pressed: false,
            pressed_frames: Vec::new(),
            frame_clock: Some(frame_clock),
        }
    }

    /// Set the button's default pressed state.
    /// See the example on [`ButtonMemory`].
    pub fn set_pressed(&mut self, pressed: bool) {
        self.pressed = pressed;
    }

    /// Override the pressed state for one specific flushed frame index.
    ///
    /// The [`CydMemory` example](CydMemory) demonstrates scheduled state taking
    /// effect after a frame flush.
    pub fn set_pressed_for_frame(&mut self, frame_index: usize, pressed: bool) {
        if let Some(existing_state) = self
            .pressed_frames
            .iter_mut()
            .find(|(existing_frame_index, _pressed_state)| *existing_frame_index == frame_index)
        {
            existing_state.1 = pressed;
            return;
        }
        self.pressed_frames.push((frame_index, pressed));
    }

    fn current_pressed_state(&self) -> bool {
        let Some(frame_clock) = &self.frame_clock else {
            return self.pressed;
        };
        let frame_index = frame_clock.frame_index();
        self.pressed_frames
            .iter()
            .find_map(|(pressed_frame_index, pressed)| {
                (*pressed_frame_index == frame_index).then_some(*pressed)
            })
            .unwrap_or(self.pressed)
    }
}

impl Default for ButtonMemory {
    fn default() -> Self {
        Self::new()
    }
}

impl __ButtonMonitor for ButtonMemory {
    fn is_pressed_raw(&self) -> bool {
        self.current_pressed_state()
    }

    async fn wait_until_pressed_state(&mut self, _pressed: bool) {}
}

impl Button for ButtonMemory {}

fn fill_rectangle_in_framebuffer(
    framebuffer: &mut [u16],
    screen_size: Size,
    rectangle: Rectangle,
    color: u16,
) {
    let clipped_rectangle = rectangle.intersection(&Rectangle::new(Point::zero(), screen_size));
    if clipped_rectangle.size.width == 0 || clipped_rectangle.size.height == 0 {
        return;
    }
    let stride = screen_size.width as usize;
    for position_y in clipped_rectangle.top_left.y
        ..clipped_rectangle.top_left.y + clipped_rectangle.size.height as i32
    {
        for position_x in clipped_rectangle.top_left.x
            ..clipped_rectangle.top_left.x + clipped_rectangle.size.width as i32
        {
            let index = position_y as usize * stride + position_x as usize;
            framebuffer[index] = color;
        }
    }
}

fn fill_contiguous_in_framebuffer<I>(
    framebuffer: &mut [u16],
    screen_size: Size,
    rectangle: Rectangle,
    pixels: I,
) where
    I: IntoIterator<Item = u16>,
{
    if rectangle.size.width == 0 || rectangle.size.height == 0 {
        return;
    }
    let stride = screen_size.width as usize;
    for (pixel_index, pixel) in pixels.into_iter().enumerate() {
        let local_x = pixel_index % rectangle.size.width as usize;
        let local_y = pixel_index / rectangle.size.width as usize;
        if local_y >= rectangle.size.height as usize {
            break;
        }
        let position_x = rectangle.top_left.x + local_x as i32;
        let position_y = rectangle.top_left.y + local_y as i32;
        if position_x < 0
            || position_y < 0
            || position_x >= screen_size.width as i32
            || position_y >= screen_size.height as i32
        {
            continue;
        }
        framebuffer[position_y as usize * stride + position_x as usize] = pixel;
    }
}

fn blit_frame_to_screen(
    framebuffer: &mut [u16],
    screen_size: Size,
    rectangle: Rectangle,
    pixels: &[u16],
) {
    fill_contiguous_in_framebuffer(framebuffer, screen_size, rectangle, pixels.iter().copied());
}

#[cfg(test)]
mod tests {
    use super::{
        ButtonMemory, CydMemory, CydTouchMemory, Error, FlashBlockMemory, MIN_SAMPLES_PER_POINT,
        SAMPLES_DISCARDED_AFTER_DOWN,
    };
    use crate::cyd::touch::driver::{
        CAPTURE_ACK_FRAME_COUNT, MAX_RAW_EVENTS_PER_FRAME, REJECTED_FRAME_COUNT,
        VERIFY_TIMEOUT_FRAMES,
    };
    use crate::cyd::{
        Cyd, CydDisplay, CydTouch,
        backend::{
            CalibrationConfig, Error as CalibrationError, RawTouchEvent, TouchUncalibrated,
            ensure_calibration,
        },
        display::{CydFrame, Orientation},
        touch::{
            RawPoint, TouchEvent,
            calibration::{
                CalibrationCorner, VERIFY_HIT_RADIUS_PIXELS, calibration_corner_center,
                calibration_verify_target_center, distort_demo_screen_to_raw,
            },
        },
    };
    use crate::flash_block::FlashBlock;
    use embedded_graphics::{
        Pixel,
        mono_font::ascii::FONT_9X15_BOLD,
        pixelcolor::{IntoStorage, Rgb565, Rgb888, WebColors},
        prelude::{DrawTarget, Point, Size},
        primitives::Rectangle,
    };
    use futures_executor::block_on;
    use serde::{Deserialize, Serialize};

    #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
    struct DemoValue {
        count: u16,
    }

    fn test_cyd_memory() -> CydMemory {
        CydMemory::new(
            Size::new(320, 240),
            Rgb888::CSS_BLACK,
            Rgb888::CSS_WHITE,
            &FONT_9X15_BOLD,
        )
    }

    #[test]
    fn orientation_is_preserved_by_oriented_memory() {
        for orientation in [
            crate::cyd::display::Orientation::Landscape,
            crate::cyd::display::Orientation::Portrait,
            crate::cyd::display::Orientation::LandscapeInverted,
            crate::cyd::display::Orientation::PortraitInverted,
        ] {
            let memory_cyd = CydMemory::new_with_orientation(
                orientation,
                Rgb888::CSS_BLACK,
                Rgb888::CSS_WHITE,
                &FONT_9X15_BOLD,
            );
            assert_eq!(memory_cyd.orientation(), orientation);
        }
    }

    fn read_next_raw_touch_event(memory_cyd: &CydMemory) -> Result<Option<RawTouchEvent>, Error> {
        let (_display, mut touch) = memory_cyd.parts_uncalibrated();
        touch.read_raw_touch_event()
    }

    fn run_ensure_calibration(
        memory_cyd: &CydMemory,
        memory_flash_block: &mut FlashBlockMemory,
        memory_button: &mut ButtonMemory,
        confirmed_message: Option<&str>,
    ) -> Result<CydTouchMemory, CalibrationError<Error, <FlashBlockMemory as FlashBlock>::Error>>
    {
        let (mut display, touch) = memory_cyd.parts_uncalibrated();
        block_on(ensure_calibration(
            &mut display,
            touch,
            memory_flash_block,
            memory_button,
            confirmed_message,
            memory_cyd.orientation(),
        ))
    }

    #[test]
    fn fresh_frame_starts_cleared_to_background() {
        let memory_cyd = test_cyd_memory();
        let mut display = memory_cyd.display();
        let frame = display.frame_mut(Rectangle::new(Point::new(3, 4), Size::new(2, 2)));
        assert_eq!(frame.pixels, &[Rgb565::CSS_BLACK.into_storage(); 4]);
    }

    #[test]
    fn short_fill_contiguous_iterator_changes_only_supplied_pixels() {
        let memory_cyd = test_cyd_memory();
        let rectangle = Rectangle::new(Point::new(2, 3), Size::new(2, 2));
        {
            let mut display = memory_cyd.display();
            display
                .fill_contiguous(rectangle, [Rgb565::CSS_RED, Rgb565::CSS_GREEN])
                .expect("memory streaming should succeed");
        }

        assert_eq!(memory_cyd.pixel(2, 3), Rgb565::CSS_RED);
        assert_eq!(memory_cyd.pixel(3, 3), Rgb565::CSS_GREEN);
        assert_eq!(memory_cyd.pixel(2, 4), Rgb565::CSS_BLACK);
        assert_eq!(memory_cyd.pixel(3, 4), Rgb565::CSS_BLACK);
    }

    #[test]
    fn overlong_fill_contiguous_iterator_ignores_pixels_beyond_rectangle() {
        let memory_cyd = test_cyd_memory();
        let rectangle = Rectangle::new(Point::new(2, 3), Size::new(2, 2));
        {
            let mut display = memory_cyd.display();
            display
                .fill_contiguous(
                    rectangle,
                    [
                        Rgb565::CSS_RED,
                        Rgb565::CSS_GREEN,
                        Rgb565::CSS_BLUE,
                        Rgb565::CSS_WHITE,
                        Rgb565::CSS_YELLOW,
                    ],
                )
                .expect("memory streaming should succeed");
        }

        assert_eq!(memory_cyd.pixel(2, 3), Rgb565::CSS_RED);
        assert_eq!(memory_cyd.pixel(3, 3), Rgb565::CSS_GREEN);
        assert_eq!(memory_cyd.pixel(2, 4), Rgb565::CSS_BLUE);
        assert_eq!(memory_cyd.pixel(3, 4), Rgb565::CSS_WHITE);
        assert_eq!(memory_cyd.pixel(4, 3), Rgb565::CSS_BLACK);
    }

    #[test]
    fn draw_target_pixel_flushes_to_screen_coordinate() {
        let memory_cyd = test_cyd_memory();
        {
            let mut display = memory_cyd.display();
            let mut frame = display.frame_mut(Rectangle::new(Point::new(10, 20), Size::new(4, 3)));
            frame
                .draw_iter([Pixel(Point::new(11, 21), Rgb565::CSS_RED)])
                .expect("drawing into memory frame should succeed");
            block_on(frame.flush()).expect("flush should succeed");
        }
        assert_eq!(memory_cyd.pixel(11, 21), Rgb565::CSS_RED);
        assert_eq!(
            memory_cyd.last_flush_rectangle(),
            Some(Rectangle::new(Point::new(10, 20), Size::new(4, 3)))
        );
    }

    #[test]
    fn fill_rectangle_clips_to_screen_edges() {
        let memory_cyd = CydMemory::new(
            Size::new(4, 4),
            Rgb888::CSS_BLACK,
            Rgb888::CSS_WHITE,
            &FONT_9X15_BOLD,
        );
        {
            let mut display = memory_cyd.display();
            display
                .fill_rectangle(
                    Rectangle::new(Point::new(-1, -1), Size::new(3, 3)),
                    Rgb565::CSS_GREEN,
                )
                .expect("fill_rectangle should succeed");
            display
                .fill_rectangle(
                    Rectangle::new(Point::new(10, 10), Size::new(2, 2)),
                    Rgb565::CSS_RED,
                )
                .expect("off-screen fill_rectangle should stay a no-op");
        }
        assert_eq!(memory_cyd.pixel(0, 0), Rgb565::CSS_GREEN);
        assert_eq!(memory_cyd.pixel(1, 1), Rgb565::CSS_GREEN);
        assert_eq!(memory_cyd.pixel(3, 3), Rgb565::CSS_BLACK);
    }

    #[test]
    fn raw_touch_frames_drain_then_advance_after_flush() {
        let mut memory_cyd = test_cyd_memory();
        let first_frame = [
            RawTouchEvent::Down { raw_x: 1, raw_y: 2 },
            RawTouchEvent::Up,
        ];
        let second_frame = [RawTouchEvent::Down { raw_x: 3, raw_y: 4 }];
        memory_cyd.script_raw_frames(&[&first_frame, &second_frame]);

        assert_eq!(
            read_next_raw_touch_event(&memory_cyd).expect("read should succeed"),
            Some(RawTouchEvent::Down { raw_x: 1, raw_y: 2 })
        );
        assert_eq!(
            read_next_raw_touch_event(&memory_cyd).expect("read should succeed"),
            Some(RawTouchEvent::Up)
        );
        assert_eq!(
            read_next_raw_touch_event(&memory_cyd).expect("read should succeed"),
            None
        );

        {
            let mut display = memory_cyd.display();
            let mut frame = display.full_frame_mut();
            block_on(frame.flush()).expect("flush should succeed");
        }

        assert_eq!(memory_cyd.flush_count(), 1);
        assert_eq!(
            read_next_raw_touch_event(&memory_cyd).expect("read should succeed"),
            Some(RawTouchEvent::Down { raw_x: 3, raw_y: 4 })
        );
    }

    #[test]
    fn flush_budget_returns_out_of_frames() {
        let mut memory_cyd = test_cyd_memory();
        memory_cyd.set_frame_budget(1);
        {
            let mut display = memory_cyd.display();
            let mut frame = display.full_frame_mut();
            block_on(frame.flush()).expect("first flush should succeed");
        }
        {
            let mut display = memory_cyd.display();
            let mut frame = display.full_frame_mut();
            let error = block_on(frame.flush()).expect_err("second flush should hit frame budget");
            assert_eq!(error, Error::OutOfFrames);
        }
        assert_eq!(memory_cyd.flush_count(), 1);
    }

    #[test]
    fn memory_flash_block_round_trips_and_handles_corruption() {
        let mut memory_flash_block = FlashBlockMemory::new();
        memory_flash_block
            .save(&DemoValue { count: 7 })
            .expect("save should succeed");
        assert_eq!(
            memory_flash_block
                .load::<DemoValue>()
                .expect("load should succeed"),
            Some(DemoValue { count: 7 })
        );

        let mut corrupt_flash_block = FlashBlockMemory::with_raw_bytes(&[1, 2, 3, 4]);
        assert_eq!(
            corrupt_flash_block
                .load::<DemoValue>()
                .expect("corrupt load should degrade to None"),
            None
        );

        memory_flash_block.clear().expect("clear should succeed");
        assert_eq!(
            memory_flash_block
                .load::<DemoValue>()
                .expect("load should succeed"),
            None
        );
    }

    #[test]
    fn ensure_calibration_happy_path_saves_predictable_config() {
        let mut memory_cyd = test_cyd_memory();
        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();
        let raw_points = script_happy_path(&mut memory_cyd);

        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            Some("saved"),
        )
        .expect("happy-path calibration should succeed");

        assert_eq!(memory_flash_block.save_count(), 1);

        let saved_config = memory_flash_block
            .load::<CalibrationConfig>()
            .expect("saved config should deserialize")
            .expect("saved config should exist");

        for (raw_point, calibration_corner) in raw_points.into_iter().zip([
            CalibrationCorner::UpperLeft,
            CalibrationCorner::UpperRight,
            CalibrationCorner::LowerRight,
            CalibrationCorner::LowerLeft,
        ]) {
            let expected_screen_point = calibration_corner_center(calibration_corner);
            let (mapped_x, mapped_y) = saved_config.map_raw_to_screen(raw_point.x, raw_point.y);
            assert!(
                (mapped_x - expected_screen_point.x as f32).abs() <= 1.0,
                "mapped_x={mapped_x} expected_x={}",
                expected_screen_point.x
            );
            assert!(
                (mapped_y - expected_screen_point.y as f32).abs() <= 1.0,
                "mapped_y={mapped_y} expected_y={}",
                expected_screen_point.y
            );
        }
        assert!(memory_cyd.flush_count() > 0);
        // The confirmation message is the only buffered flush per redraw;
        // target/dot geometry streams buffer-free via `draw_items` and
        // doesn't touch `last_flush_rectangle`. See `CALIBRATION_TEXT_RECTANGLE`.
        assert_eq!(
            memory_cyd.last_flush_rectangle(),
            Some(Rectangle::new(Point::new(0, 220), Size::new(320, 20)))
        );
    }

    #[test]
    fn ensure_calibration_uses_preloaded_flash_without_flushing() {
        let mut memory_cyd = test_cyd_memory();
        let saved_config = CalibrationConfig::new(1.0, 0.0, 2.0, 0.0, 1.0, 3.0);
        memory_cyd.push_raw_touch_event(RawTouchEvent::Down { raw_x: 7, raw_y: 9 });
        let mut memory_flash_block = FlashBlockMemory::with_value(&saved_config);
        let mut memory_button = memory_cyd.button_memory();

        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect("preloaded calibration should load");

        assert_eq!(memory_cyd.flush_count(), 0);
        let (_display, mut touch) = memory_cyd.parts_uncalibrated();
        assert_eq!(
            touch
                .read_raw_touch_event()
                .expect("touch read should succeed"),
            Some(RawTouchEvent::Down { raw_x: 7, raw_y: 9 })
        );
    }

    #[test]
    fn preloaded_calibration_preserves_already_oriented_memory_events() {
        for orientation in [
            Orientation::Landscape,
            Orientation::Portrait,
            Orientation::LandscapeInverted,
            Orientation::PortraitInverted,
        ] {
            let mut memory_cyd = CydMemory::new_with_orientation(
                orientation,
                Rgb888::CSS_BLACK,
                Rgb888::CSS_WHITE,
                &FONT_9X15_BOLD,
            );
            let point = Point::new(
                orientation.width() as i32 - 1,
                orientation.height() as i32 - 1,
            );
            memory_cyd.push_touch_event(TouchEvent::Down { point });
            let saved_config = super::identity_calibration_config();
            let mut memory_flash_block = FlashBlockMemory::with_value(&saved_config);
            let mut memory_button = memory_cyd.button_memory();
            let mut touch = run_ensure_calibration(
                &memory_cyd,
                &mut memory_flash_block,
                &mut memory_button,
                None,
            )
            .expect("preloaded calibration should load");

            assert!(matches!(
                touch.try_read(),
                Ok(Some(TouchEvent::Down { point: actual_point }))
                    if actual_point == point
            ));
        }
    }

    #[test]
    fn ensure_calibration_corrupt_flash_reruns_and_overwrites() {
        let mut memory_cyd = test_cyd_memory();
        let mut memory_flash_block = FlashBlockMemory::with_raw_bytes(&[1, 2, 3, 4]);
        let mut memory_button = memory_cyd.button_memory();
        script_happy_path(&mut memory_cyd);

        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect("corrupt flash should fall back to calibration");

        assert_eq!(memory_flash_block.save_count(), 1);
        assert!(
            memory_flash_block
                .load::<CalibrationConfig>()
                .expect("load should succeed")
                .is_some()
        );
    }

    #[test]
    fn ensure_calibration_paces_with_one_flush_per_iteration() {
        let mut memory_cyd = test_cyd_memory();
        memory_cyd.set_frame_budget(3);
        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();

        let error = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect_err("empty input should stop at the frame budget");

        assert!(matches!(
            error,
            CalibrationError::Device(Error::OutOfFrames)
        ));
        assert_eq!(memory_cyd.flush_count(), 3);
    }

    #[test]
    fn ensure_calibration_drains_a_full_tap_in_one_frame() {
        let mut memory_cyd = test_cyd_memory();
        memory_cyd.set_frame_budget(1);
        let upper_left_raw_point = raw_point_for_corner(CalibrationCorner::UpperLeft);
        memory_cyd.script_raw_frames_owned(vec![tap_events(upper_left_raw_point)]);
        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();

        let error = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect_err("single-frame budget should stop after the first drawn frame");

        assert!(matches!(
            error,
            CalibrationError::Device(Error::OutOfFrames)
        ));
        let upper_left_center = calibration_corner_center(CalibrationCorner::UpperLeft);
        let upper_right_center = calibration_corner_center(CalibrationCorner::UpperRight);
        assert_eq!(
            memory_cyd.pixel(upper_left_center.x as usize, upper_left_center.y as usize),
            Rgb565::CSS_WHITE
        );
        assert_eq!(
            memory_cyd.pixel(upper_right_center.x as usize, upper_right_center.y as usize),
            Rgb565::CSS_WHITE
        );
        assert_eq!(memory_cyd.pixel(160, 120), Rgb565::CSS_BLACK);
    }

    #[test]
    fn ensure_calibration_verify_timeout_restarts_and_then_succeeds() {
        let mut memory_cyd = test_cyd_memory();
        let mut frames = happy_path_frames();
        frames.truncate(frames.len() - 1);
        frames.extend((0..verify_timeout_extra_idle_frames()).map(|_| Vec::new()));
        frames.extend((0..rejected_restart_idle_frames()).map(|_| Vec::new()));
        frames.extend(happy_path_frames());
        memory_cyd.script_raw_frames_owned(frames);

        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();

        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect("flow should restart after verify timeout and then save");

        assert_eq!(memory_flash_block.save_count(), 1);
    }

    #[test]
    fn ensure_calibration_dropout_does_not_leak_corner_two_into_corner_three() {
        let mut memory_cyd = test_cyd_memory();
        let upper_left_raw_point = raw_point_for_corner(CalibrationCorner::UpperLeft);
        let upper_right_raw_point = raw_point_for_corner(CalibrationCorner::UpperRight);
        let lower_right_raw_point = raw_point_for_corner(CalibrationCorner::LowerRight);
        let lower_left_raw_point = raw_point_for_corner(CalibrationCorner::LowerLeft);
        let verify_raw_point = raw_point_for_verify_target();
        let mut frames = vec![tap_events(upper_left_raw_point)];
        append_idle_frames(&mut frames, capture_ack_extra_idle_frames());
        frames.push(dropout_tap_events(upper_right_raw_point));
        append_idle_frames(&mut frames, capture_ack_extra_idle_frames());
        frames.push(tap_events(lower_right_raw_point));
        append_idle_frames(&mut frames, capture_ack_extra_idle_frames());
        frames.push(tap_events(lower_left_raw_point));
        frames.push(tap_events(verify_raw_point));
        memory_cyd.script_raw_frames_owned(frames);

        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();
        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect("dropout sequence should still save a calibration");

        let calibration_config = memory_flash_block
            .load::<CalibrationConfig>()
            .unwrap()
            .unwrap();
        assert_maps_near_corner(
            calibration_config,
            lower_right_raw_point,
            CalibrationCorner::LowerRight,
        );
    }

    #[test]
    fn ensure_calibration_lift_off_drift_keeps_captured_point_near_stable_raw_point() {
        let mut memory_cyd = test_cyd_memory();
        let upper_left_raw_point = raw_point_for_corner(CalibrationCorner::UpperLeft);
        let drifted_raw_point = RawPoint {
            x: upper_left_raw_point.x + 400,
            y: upper_left_raw_point.y + 400,
        };
        let upper_right_raw_point = raw_point_for_corner(CalibrationCorner::UpperRight);
        let lower_right_raw_point = raw_point_for_corner(CalibrationCorner::LowerRight);
        let lower_left_raw_point = raw_point_for_corner(CalibrationCorner::LowerLeft);
        let verify_raw_point = raw_point_for_verify_target();
        let mut frames = vec![long_press_with_lift_off_drift_frame(
            upper_left_raw_point,
            drifted_raw_point,
        )];
        append_idle_frames(&mut frames, capture_ack_extra_idle_frames());
        frames.extend(calibration_attempt_frames(&[
            upper_right_raw_point,
            lower_right_raw_point,
            lower_left_raw_point,
            verify_raw_point,
        ]));
        memory_cyd.script_raw_frames_owned(frames);

        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();
        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect("lift-off drift sequence should still save a calibration");

        let calibration_config = memory_flash_block
            .load::<CalibrationConfig>()
            .unwrap()
            .unwrap();
        assert_maps_near_corner(
            calibration_config,
            upper_left_raw_point,
            CalibrationCorner::UpperLeft,
        );
    }

    #[test]
    fn ensure_calibration_rejected_solve_restarts_and_then_saves_honest_script() {
        let mut memory_cyd = test_cyd_memory();
        let upper_left_raw_point = raw_point_for_corner(CalibrationCorner::UpperLeft);
        let lower_right_raw_point = raw_point_for_corner(CalibrationCorner::LowerRight);
        let lower_left_raw_point = raw_point_for_corner(CalibrationCorner::LowerLeft);
        let mut frames = calibration_attempt_frames(&[
            upper_left_raw_point,
            upper_left_raw_point,
            lower_right_raw_point,
            lower_left_raw_point,
            raw_point_for_verify_target(),
        ]);
        append_idle_frames(&mut frames, rejected_restart_idle_frames());
        frames.extend(happy_path_frames());
        memory_cyd.script_raw_frames_owned(frames);

        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();
        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect("rejected solve should restart and then save");

        let calibration_config = memory_flash_block
            .load::<CalibrationConfig>()
            .unwrap()
            .unwrap();
        assert_eq!(memory_flash_block.save_count(), 1);
        assert_maps_near_corner(
            calibration_config,
            raw_point_for_corner(CalibrationCorner::UpperRight),
            CalibrationCorner::UpperRight,
        );
    }

    #[test]
    fn ensure_calibration_verify_miss_restarts_without_saving_candidate() {
        let mut memory_cyd = test_cyd_memory();
        let verify_target_center = calibration_verify_target_center();
        let verify_miss_screen_x =
            verify_target_center.x + VERIFY_HIT_RADIUS_PIXELS.ceil() as i32 + 10;
        let verify_miss_raw_point =
            distort_demo_screen_to_raw(verify_miss_screen_x as f32, verify_target_center.y as f32);
        let mut frames = calibration_attempt_frames(&[
            raw_point_for_corner(CalibrationCorner::UpperLeft),
            raw_point_for_corner(CalibrationCorner::UpperRight),
            raw_point_for_corner(CalibrationCorner::LowerRight),
            raw_point_for_corner(CalibrationCorner::LowerLeft),
            verify_miss_raw_point,
        ]);
        append_idle_frames(&mut frames, rejected_restart_idle_frames());
        frames.extend(happy_path_frames());
        memory_cyd.script_raw_frames_owned(frames);

        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();
        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect("verify miss should restart and then save");

        assert_eq!(memory_flash_block.save_count(), 1);
    }

    #[test]
    fn ensure_calibration_recalibration_button_restarts_mid_flow() {
        let mut memory_cyd = test_cyd_memory();
        let mut frames = vec![tap_events(raw_point_for_corner(
            CalibrationCorner::UpperLeft,
        ))];
        append_idle_frames(&mut frames, 2);
        frames.extend(happy_path_frames());
        memory_cyd.script_raw_frames_owned(frames);

        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();
        memory_button.set_pressed_for_frame(2, true);
        let _touch = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect("button-triggered recalibration should restart and then save");

        let calibration_config = memory_flash_block
            .load::<CalibrationConfig>()
            .unwrap()
            .unwrap();
        assert_eq!(memory_flash_block.save_count(), 1);
        assert_maps_near_corner(
            calibration_config,
            raw_point_for_corner(CalibrationCorner::UpperLeft),
            CalibrationCorner::UpperLeft,
        );
    }

    #[test]
    fn ensure_calibration_drain_cap_flushes_and_preserves_leftovers_during_hold() {
        let mut memory_cyd = test_cyd_memory();
        memory_cyd.set_frame_budget(2);
        let upper_left_raw_point = raw_point_for_corner(CalibrationCorner::UpperLeft);
        let mut oversized_hold_frame = Vec::new();
        oversized_hold_frame.push(RawTouchEvent::Down {
            raw_x: upper_left_raw_point.x,
            raw_y: upper_left_raw_point.y,
        });
        for _raw_event_index in 0..MAX_RAW_EVENTS_PER_FRAME.saturating_sub(1) {
            oversized_hold_frame.push(RawTouchEvent::Move {
                raw_x: upper_left_raw_point.x,
                raw_y: upper_left_raw_point.y,
            });
        }
        oversized_hold_frame.push(RawTouchEvent::Up);
        memory_cyd.script_raw_frames_owned(vec![oversized_hold_frame]);

        let mut memory_flash_block = FlashBlockMemory::new();
        let mut memory_button = memory_cyd.button_memory();
        let error = run_ensure_calibration(
            &memory_cyd,
            &mut memory_flash_block,
            &mut memory_button,
            None,
        )
        .expect_err("oversized hold should stop at the frame budget");

        assert!(matches!(
            error,
            CalibrationError::Device(Error::OutOfFrames)
        ));
        assert_eq!(memory_cyd.flush_count(), 2);
        let upper_left_center = calibration_corner_center(CalibrationCorner::UpperLeft);
        let upper_right_center = calibration_corner_center(CalibrationCorner::UpperRight);
        assert_eq!(
            memory_cyd.pixel(upper_left_center.x as usize, upper_left_center.y as usize),
            Rgb565::CSS_WHITE
        );
        assert_eq!(
            memory_cyd.pixel(upper_right_center.x as usize, upper_right_center.y as usize),
            Rgb565::CSS_WHITE
        );
        assert_eq!(
            read_next_raw_touch_event(&memory_cyd)
                .expect("the oversized frame should be fully drained by the second iteration"),
            None
        );
    }

    fn script_happy_path(memory_cyd: &mut CydMemory) -> [RawPoint; 4] {
        memory_cyd.script_raw_frames_owned(happy_path_frames());
        [
            raw_point_for_corner(CalibrationCorner::UpperLeft),
            raw_point_for_corner(CalibrationCorner::UpperRight),
            raw_point_for_corner(CalibrationCorner::LowerRight),
            raw_point_for_corner(CalibrationCorner::LowerLeft),
        ]
    }

    fn happy_path_frames() -> Vec<Vec<RawTouchEvent>> {
        calibration_attempt_frames(&[
            raw_point_for_corner(CalibrationCorner::UpperLeft),
            raw_point_for_corner(CalibrationCorner::UpperRight),
            raw_point_for_corner(CalibrationCorner::LowerRight),
            raw_point_for_corner(CalibrationCorner::LowerLeft),
            raw_point_for_verify_target(),
        ])
    }

    fn raw_point_for_corner(calibration_corner: CalibrationCorner) -> RawPoint {
        let screen_point = calibration_corner_center(calibration_corner);
        distort_demo_screen_to_raw(screen_point.x as f32, screen_point.y as f32)
    }

    fn tap_events(raw_point: RawPoint) -> Vec<RawTouchEvent> {
        let mut raw_touch_events = Vec::new();
        raw_touch_events.push(RawTouchEvent::Down {
            raw_x: raw_point.x,
            raw_y: raw_point.y,
        });
        for _discarded_sample_index in 0..SAMPLES_DISCARDED_AFTER_DOWN {
            raw_touch_events.push(RawTouchEvent::Move {
                raw_x: raw_point.x,
                raw_y: raw_point.y,
            });
        }
        for _usable_sample_index in 0..MIN_SAMPLES_PER_POINT {
            raw_touch_events.push(RawTouchEvent::Move {
                raw_x: raw_point.x,
                raw_y: raw_point.y,
            });
        }
        raw_touch_events.push(RawTouchEvent::Up);
        raw_touch_events
    }

    fn dropout_tap_events(raw_point: RawPoint) -> Vec<RawTouchEvent> {
        let mut raw_touch_events = tap_events(raw_point);
        raw_touch_events.extend([
            RawTouchEvent::Down {
                raw_x: raw_point.x,
                raw_y: raw_point.y,
            },
            RawTouchEvent::Move {
                raw_x: raw_point.x,
                raw_y: raw_point.y,
            },
            RawTouchEvent::Up,
        ]);
        raw_touch_events
    }

    fn long_press_with_lift_off_drift_frame(
        stable_raw_point: RawPoint,
        drifted_raw_point: RawPoint,
    ) -> Vec<RawTouchEvent> {
        let mut raw_touch_events = Vec::new();
        raw_touch_events.push(RawTouchEvent::Down {
            raw_x: stable_raw_point.x,
            raw_y: stable_raw_point.y,
        });
        for _stable_move_index in 0..2_004 {
            raw_touch_events.push(RawTouchEvent::Move {
                raw_x: stable_raw_point.x,
                raw_y: stable_raw_point.y,
            });
        }
        for _drifted_move_index in 0..3 {
            raw_touch_events.push(RawTouchEvent::Move {
                raw_x: drifted_raw_point.x,
                raw_y: drifted_raw_point.y,
            });
        }
        raw_touch_events.push(RawTouchEvent::Up);
        raw_touch_events
    }

    fn calibration_attempt_frames(raw_points: &[RawPoint]) -> Vec<Vec<RawTouchEvent>> {
        let mut frames = Vec::new();
        for (tap_index, raw_point) in raw_points.iter().copied().enumerate() {
            frames.push(tap_events(raw_point));
            if tap_index + 2 < raw_points.len() {
                append_idle_frames(&mut frames, capture_ack_extra_idle_frames());
            }
        }
        frames
    }

    fn append_idle_frames(frames: &mut Vec<Vec<RawTouchEvent>>, idle_frame_count: usize) {
        frames.extend((0..idle_frame_count).map(|_| Vec::new()));
    }

    fn raw_point_for_verify_target() -> RawPoint {
        let verify_center = calibration_verify_target_center();
        distort_demo_screen_to_raw(verify_center.x as f32, verify_center.y as f32)
    }

    fn assert_maps_near_corner(
        calibration_config: CalibrationConfig,
        raw_point: RawPoint,
        calibration_corner: CalibrationCorner,
    ) {
        let expected_screen_point = calibration_corner_center(calibration_corner);
        let (mapped_x, mapped_y) = calibration_config.map_raw_to_screen(raw_point.x, raw_point.y);
        assert!(
            (mapped_x - expected_screen_point.x as f32).abs() <= 1.0,
            "mapped_x={mapped_x} expected_x={}",
            expected_screen_point.x
        );
        assert!(
            (mapped_y - expected_screen_point.y as f32).abs() <= 1.0,
            "mapped_y={mapped_y} expected_y={}",
            expected_screen_point.y
        );
    }

    const fn capture_ack_extra_idle_frames() -> usize {
        // The tap frame may end with an immediate `None`, but that idle pass only
        // decrements the freshly-entered `ShowCaptured` state before drawing its
        // first acknowledgment screen. Tests still need a full
        // `CAPTURE_ACK_FRAME_COUNT` later idle frames before the next scripted tap
        // is guaranteed to run after the ack window.
        CAPTURE_ACK_FRAME_COUNT
    }

    const fn rejected_restart_idle_frames() -> usize {
        REJECTED_FRAME_COUNT
    }

    const fn verify_timeout_extra_idle_frames() -> usize {
        VERIFY_TIMEOUT_FRAMES.saturating_sub(1)
    }
}