retex-engine 1.3.0

The TeX typesetting engine for retex
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
//! Shipping pages out (*TeX: The Program* ยง592โ€“ยง640, LuaTeX's PDF
//! backend positions).
//!
//! `ship_out` prints the `[n]` progress report, walks the box exactly as
//! TeX's `hlist_out`/`vlist_out` do (including the cumulative glue
//! rounding and leaders, ยง619โ€“ยง637), executes `\openout`/`\write`/
//! `\closeout` whatsits, and hands glyphs, rules and literals either to a
//! [`Backend`] in page coordinates (`\outputmode>0`) or to the
//! [`crate::dvi`] writer in DVI coordinates (`\outputmode=0`).

use crate::Engine;
use crate::fonts::PacketCommand;
use crate::glue::Glue;
use crate::nodes::{NodeData, NodeRef, RUNNING, Whatsit, glue_sub, id};
use crate::primitives_gen::{assign_dimen as dp, assign_int as ip};

/// A destination for shipped pages (the PDF writer). Coordinates are in
/// scaled points from the lower-left corner of the page, y upwards.
pub trait Backend {
    /// Starts a page of the given size.
    fn begin_page(&mut self, engine: &Engine, width: i32, height: i32);
    /// Draws character `chr` of font `font` with its origin at (x, y).
    fn glyph(&mut self, engine: &Engine, font: u32, chr: u32, x: i32, y: i32);
    /// Draws a glyph expanded horizontally by `ef` millionths of its width
    /// (font expansion; `ef` is never 0).
    fn glyph_expanded(&mut self, engine: &Engine, font: u32, chr: u32, x: i32, y: i32, ef: i32) {
        let _ = ef;
        self.glyph(engine, font, chr, x, y);
    }
    /// Draws a filled rule with its lower-left corner at (x, y).
    fn rule(&mut self, x: i32, y: i32, width: i32, height: i32);
    /// Emits a literal (`\pdfextension literal`) at (x, y).
    fn literal(&mut self, mode: u8, data: &[u8], x: i32, y: i32);
    /// Emits text written by `pdf.print` at (x, y): a literal without
    /// the newline after it (observed).
    fn print(&mut self, mode: u8, data: &[u8], x: i32, y: i32) {
        self.literal(mode, data, x, y);
    }
    /// Finishes the page.
    fn end_page(&mut self, engine: &Engine);
    /// Finishes the document.
    fn finish(&mut self, engine: &mut Engine) -> Option<Finished>;

    /// `\pdfextension save` at (x, y).
    fn save(&mut self, x: i32, y: i32) {
        self.literal(0, b"q", x, y);
    }

    /// `\pdfextension restore` at (x, y).
    fn restore(&mut self, x: i32, y: i32) {
        self.literal(0, b"Q", x, y);
    }

    /// `\pdfextension setmatrix` at (x, y).
    fn set_matrix(&mut self, x: i32, y: i32, matrix: &[u8]) {
        let mut d = matrix.to_vec();
        d.extend_from_slice(b" 0 0 cm");
        self.literal(0, &d, x, y);
    }

    /// Before the process forks for a preamble snapshot: writes out what
    /// is buffered (see [`resume`](Self::resume)).
    fn suspend(&mut self) -> std::io::Result<()> {
        Ok(())
    }

    /// Whether a pass can resume from the snapshot taken at
    /// [`suspend`](Self::suspend): the output file is still there, at least
    /// as long as then (a failed build may have removed it).
    fn resumable(&self) -> bool {
        true
    }

    /// A fingerprint of the state that decides what the backend writes
    /// from now on (see [`crate::fingerprint`]): not what it wrote.
    fn fingerprint(&mut self) -> u64 {
        0
    }

    /// For `--watch` (see `docs/design/incremental-rebuilds.md`): what the
    /// output holds so far, flushed to the file, as an encoded
    /// `retex_pdf::Prefix`; `None` if there is no output file.
    fn prefix(&mut self) -> Option<Vec<u8>> {
        None
    }

    /// The output file, and where it was first opened (it keeps that name
    /// once the run is over).
    fn output_file(&self) -> Option<(std::path::PathBuf, std::path::PathBuf)> {
        None
    }

    /// Gives the output file the second name `to`, under which it goes on
    /// (its first name may then be given to another file).
    fn divert(&mut self, _to: &std::path::Path) -> std::io::Result<()> {
        Err(std::io::Error::other("not supported"))
    }

    /// Goes on in file `to` with another run's `prefix` (see
    /// [`prefix`](Self::prefix)), read from that run's file `from`,
    /// followed by `saved` from `cut` on: this backend's output up to the
    /// end (taken from its file before the other run changed it), the two
    /// runs being in the same state at that point.
    fn splice(
        &mut self,
        _prefix: &[u8],
        _from: &std::path::Path,
        _saved: &[u8],
        _cut: u64,
        _to: &std::path::Path,
    ) -> std::io::Result<()> {
        Err(std::io::Error::other("not supported"))
    }

    /// In a process resumed from a preamble snapshot: reopens the output
    /// file opened before the snapshot, cut back to its length then (the
    /// forked processes share the file's position otherwise).
    fn resume(&mut self) -> std::io::Result<()> {
        Ok(())
    }

    /// Gives up the output file: with `remove`, it is deleted (after a
    /// fatal error), otherwise left empty (no pages), as LuaTeX does.
    fn abandon(&mut self, _remove: bool) {}

    /// Prepares for writing an object whose text is still to be made
    /// (allocates the object stream it will go into, as LuaTeX does).
    fn begin_object(&mut self, _engine: &Engine) {}

    /// The object number of the page begun last.
    fn current_page_object(&self) -> Option<i32> {
        None
    }

    /// Writes the page's contents and dictionary: the page attributes and
    /// resources of `items` are final, and whether there are annotations.
    fn close_page_contents(&mut self, _engine: &Engine, _items: &crate::pdfext::PageItems) {}

    /// Hands over the page's annotations, links, destinations and
    /// referenced objects, just before [`end_page`](Self::end_page).
    fn page_items(&mut self, _engine: &Engine, _items: &crate::pdfext::PageItems) {}

    /// Starts writing box resource `index` (natural size `size` = width,
    /// height, depth) as a form XObject; drawing goes into the form until
    /// [`end_box_form`](Self::end_box_form).
    fn begin_box_form(
        &mut self,
        _engine: &Engine,
        _index: u32,
        _size: (i32, i32, i32),
        _attr: &[u8],
        _resources: &[u8],
    ) {
    }

    /// Finishes the box resource being written (its content stream).
    fn end_box_form(&mut self, _engine: &Engine) {}

    /// Writes the resources of the box resource finished last, after the
    /// forms it uses.
    fn close_box_form_resources(&mut self, _engine: &Engine) {}

    /// Writes the resources of the page ended last, after the forms it
    /// uses.
    fn close_page_resources(&mut self, _engine: &Engine) {}

    /// Draws box resource `index` with its lower-left corner at (x, y),
    /// scaled to `width` ร— `height` (height + depth).
    fn box_form(
        &mut self,
        _engine: &Engine,
        _index: u32,
        _x: i32,
        _y: i32,
        _width: i32,
        _height: i32,
    ) {
    }

    /// Writes image resource `index` (its object number) now (`\immediate`).
    fn write_image(&mut self, _engine: &Engine, _index: u32) {}

    /// Draws image resource `index` with its lower-left corner at (x, y),
    /// `width` wide and `height` (height + depth) tall.
    fn image(
        &mut self,
        _engine: &Engine,
        _index: u32,
        _x: i32,
        _y: i32,
        _width: i32,
        _height: i32,
    ) {
    }

    /// The images written (when the pages and forms using them were
    /// closed) since the last call, if the backend writes them that way;
    /// `None` to have them announced at the end of the page using them.
    fn written_images(&mut self) -> Option<Vec<u32>> {
        None
    }

    /// Writes an object created with `\pdfextension obj`.
    fn write_object(&mut self, _engine: &Engine, _obj: &crate::pdfext::PdfObject) {}
}

/// What the backend reports when the document is finished.
#[derive(Clone, Debug, Default)]
pub struct Finished {
    /// The output file name as printed in "Output written on โ€ฆ".
    pub file: String,
    /// Its size in bytes.
    pub size: u64,
    /// Files embedded, as printed: `<font file>`, `{encoding file}`
    /// (LuaTeX order).
    pub embedded: Vec<String>,
    /// Objects written into object streams, and the number of streams.
    pub objstm: (u32, u32),
}

/// The width of the replacement nodes before `q` (from `head`).
fn items_before_width(e: &Engine, head: NodeRef, q: NodeRef) -> i32 {
    let mut w = 0;
    let mut r = head;
    while !r.is_null() && r != q {
        w += e.replace_item_width(r);
        r = e.nodes.next(r);
    }
    w
}

/// The glue-rounding state of a box being shipped (`cur_g`, `cur_glue`).
#[derive(Clone)]
struct GlueState {
    cur_g: i32,
    cur_glue: f64,
    order: u8,
    sign: u8,
    set: f64,
}

impl GlueState {
    /// TeX's glue computation for one glue node: returns its width.
    fn advance(&mut self, g: &Glue) -> i32 {
        let mut w = g.width - self.cur_g;
        if self.sign != 0 {
            let applies = if self.sign == 1 {
                g.stretch_order == self.order
            } else {
                g.shrink_order == self.order
            };
            if applies {
                if self.sign == 1 {
                    self.cur_glue += f64::from(g.stretch);
                } else {
                    self.cur_glue -= f64::from(g.shrink);
                }
                let t = (self.set * self.cur_glue).clamp(-1_000_000_000.0, 1_000_000_000.0);
                self.cur_g = t.round() as i32;
            }
        }
        w += self.cur_g;
        w
    }
}

impl Engine {
    /// Calls the page-number callback `name` if one is registered; whether
    /// it was.
    fn page_number_callback(&mut self, name: &str) -> bool {
        let Some(lua) = self.lua.clone() else {
            return false;
        };
        if !lua.has_callback(name) {
            return false;
        }
        if let Err(e) = lua.call_simple(self, name) {
            self.lua_error(&e);
        }
        true
    }

    /// Ships box `p` out (`ship_out`).
    pub fn ship_out(&mut self, p: NodeRef) {
        self.work_begin(crate::profile::Work::Shipout);
        self.ship_out_inner(p);
        self.work_end();
    }

    fn ship_out_inner(&mut self, p: NodeRef) {
        self.pdf.page_annots.clear();
        let tracing = self.eqtb.int(ip::TRACINGOUTPUT) > 0;
        if tracing {
            self.printer.print_nl("");
            self.printer.print_ln();
            self.printer.print_str("Completed box being shipped out");
        }
        // The `start_page_number` callback replaces ` [` and the page
        // numbers, `stop_page_number` the closing `]` (observed).
        if !self.page_number_callback("start_page_number") {
            if self.printer.term_offset > self.printer.max_print_line.saturating_sub(9) {
                self.printer.print_ln();
            } else if self.printer.term_offset > 0 || self.printer.file_offset > 0 {
                self.printer.print_char(' ' as u32);
            }
            self.printer.print_char('[' as u32);
            let mut j = 9;
            while j > 0 && self.eqtb.count[j].val == 0 {
                j -= 1;
            }
            for k in 0..=j {
                self.printer.print_int(self.eqtb.count[k].val.into());
                if k < j {
                    self.printer.print_char('.' as u32);
                }
            }
        }
        self.printer.update_terminal();
        if p.is_null() {
            // `tex.shipout` of a void box (observed).
            self.luatex_warning(
                "backend",
                "pagedir differs from bodydir, the output may be placed wrongly on the page",
            );
            let msg = "no vlist or hlist in (xform) shipout";
            if self.eqtb.int(ip::OUTPUTMODE) > 0 {
                self.pdf_fatal(msg);
            }
            self.luatex_fatal("pdf backend", msg);
        }
        if tracing {
            if !self.page_number_callback("stop_page_number") {
                self.printer.print_char(']' as u32);
            }
            self.begin_diagnostic();
            self.show_box(p);
            self.end_diagnostic(true);
        }
        self.ship_box(p);
        if !tracing && !self.page_number_callback("stop_page_number") {
            self.printer.print_char(']' as u32);
        }
        self.dead_cycles = 0;
        self.printer.update_terminal();
        self.nodes.flush_list(p);
    }

    /// Ships the contents of box `p`.
    fn ship_box(&mut self, p: NodeRef) {
        let Some(b) = self.nodes.box_data(p).cloned() else {
            return;
        };
        let pdf = self.eqtb.int(ip::OUTPUTMODE) > 0;
        // Page size and origin.
        let h_origin = self.eqtb.dimen(crate::backend::H_ORIGIN);
        let v_origin = self.eqtb.dimen(crate::backend::V_ORIGIN);
        let h_off = self.eqtb.dimen(dp::HOFFSET);
        let v_off = self.eqtb.dimen(dp::VOFFSET);
        let mut width = self.eqtb.dimen(dp::PAGEWIDTH);
        let mut height = self.eqtb.dimen(dp::PAGEHEIGHT);
        // Observed: without \pagewidth (\pageheight), the page is the box
        // plus 1in and the offset on each side, whatever the origin.
        const ONE_INCH: i32 = 4_736_286;
        if width <= 0 {
            width = b.width + 2 * (ONE_INCH + h_off);
        }
        if height <= 0 {
            height = b.height + b.depth + 2 * (ONE_INCH + v_off);
        }
        let mut backend = if pdf { self.backend.take() } else { None };
        let forms_depth = self.pending_forms.len();
        self.pending_forms.push(Vec::new());
        if let Some(be) = backend.as_mut() {
            self.pdf.page = Default::default();
            be.begin_page(self, width, height);
            if let Some(n) = be.current_page_object() {
                let page = self.total_pages as i32 + 1;
                self.pdf.page_refs.insert(page, n);
                self.pdf.kinds.insert(n, crate::pdfext::ObjKind::Page);
            }
            // Observed: written at the page box's reference point.
            let (x, y) = (h_origin + h_off, height - (v_origin + v_off + b.height));
            for (mode, lit) in self.page_colorstack_literals() {
                be.literal(mode, &lit, x, y);
            }
        }
        let dvi = if pdf {
            None
        } else {
            let mut d = std::mem::take(&mut self.dvi);
            d.begin_page(self, (b.width, b.height, b.depth), (h_off, v_off));
            Some(d)
        };
        let sync = self.synctex_recording();
        if sync {
            self.synctex_begin_page((h_origin + h_off, v_origin + v_off));
        }
        let mut walker = Walker {
            backend,
            dvi,
            h_origin: h_origin + h_off,
            v_origin: v_origin + v_off,
            page_height: height,
            dvi_h: h_off,
            dvi_v: v_off,
            cur_s: -1,
            doing_leaders: false,
            page: true,
            sync,
        };
        // Observed: a right-to-left hbox shipped out as the page has its
        // right edge at the origin.
        let cur_h = if self.nodes.id(p) == id::HLIST && b.dir == 1 {
            -b.width
        } else {
            0
        };
        let cur_v = b.height;
        if self.nodes.id(p) == id::VLIST {
            self.vlist_out(&mut walker, p, cur_h, cur_v);
        } else {
            self.hlist_out(&mut walker, p, cur_h, cur_v);
        }
        if let Some(mut be) = walker.backend.take() {
            self.flush_pending_objects(be.as_mut());
            self.collect_page_texts();
            let items = std::mem::take(&mut self.pdf.page);
            be.close_page_contents(self, &items);
            self.pdf.page = items;
            self.resolve_link_actions();
            let items = std::mem::take(&mut self.pdf.page);
            be.page_items(self, &items);
            // Observed order: the page's own objects, the forms it uses,
            // its resources.
            be.end_page(self);
            let mut be = self.write_pending_forms(be);
            be.close_page_resources(self);
            self.flush_pending_objects(be.as_mut());
            self.backend = Some(be);
            let page_images = std::mem::take(&mut self.pdf.page_images);
            let written = self.backend.as_mut().and_then(|b| b.written_images());
            for n in written.unwrap_or(page_images) {
                self.print_image_name(n);
            }
        }
        self.pending_forms.truncate(forms_depth);
        if let Some(mut d) = walker.dvi.take() {
            d.end_page();
            self.dvi = d;
        }
        if sync {
            self.synctex_end_page();
        }
        self.total_pages += 1;
        if let Some(f) = self.progress_hook {
            f(self);
        }
        if let Some(f) = self.page_hook {
            f(self);
        }
    }

    /// Finishes the PDF file and nothing else, quietly: for `--watch`,
    /// in a process that writes a PDF spliced from two runs (see
    /// [`Backend::splice`]). Returns whether it was written.
    pub fn finish_pdf_only(&mut self) -> bool {
        let Some(mut be) = self.backend.take() else {
            return false;
        };
        self.pdf_finish_document();
        self.flush_pending_objects(be.as_mut());
        let done = be.finish(self).is_some();
        self.backend = Some(be);
        done
    }

    /// Writes the objects queued while the backend was busy.
    fn flush_pending_objects(&mut self, be: &mut dyn Backend) {
        for obj in std::mem::take(&mut self.pdf.pending) {
            be.write_object(self, &obj);
        }
    }

    /// Prints LuaTeX's note about reading font map file `name`
    /// (`{/path/pdftex.map}`), when it exists.
    pub(crate) fn print_map_file_note(&mut self, name: &str) {
        let path = self
            .kpse
            .as_ref()
            .and_then(|k| k.borrow_mut().find_file(name, retex_kpath::FileFormat::Map));
        if let Some(path) = path {
            // Printed like a C string (log lines up to 80 characters).
            let mut text = b"{".to_vec();
            text.extend_from_slice(path.to_string_lossy().as_bytes());
            text.push(b'}');
            self.printer.print_lua_bytes(&text);
        }
    }

    /// Outputs a glyph with its reference point at TeX position (`h`,
    /// `v`).
    fn out_glyph(&mut self, w: &mut Walker, font: u32, chr: u32, h: i32, v: i32, ef: i32) {
        self.out_glyph_at_depth(w, font, chr, h, v, ef, 0);
    }

    /// [`out_glyph`](Self::out_glyph) inside `depth` virtual characters.
    #[allow(clippy::too_many_arguments)]
    fn out_glyph_at_depth(
        &mut self,
        w: &mut Walker,
        font: u32,
        chr: u32,
        h: i32,
        v: i32,
        ef: i32,
        depth: u32,
    ) {
        if let Some(vf) = &self.font(font).vf
            && vf.packets.contains_key(&chr)
        {
            if depth < 8 {
                let mut st = PacketState {
                    h,
                    v,
                    font: 0,
                    stack: Vec::new(),
                    ef,
                    depth,
                    vf: vf.clone(),
                    vfont: font,
                    chr,
                };
                let vf = vf.clone();
                for c in &vf.packets[&chr] {
                    self.packet_command(w, &mut st, c);
                }
            }
            return;
        }
        if !self.pdf.map_note_done
            && w.backend.is_some()
            && self.font(font).chars.contains_key(&chr)
        {
            // Observed: LuaTeX reads the map file when the first character
            // is output (not a virtual one, nor one missing from its font,
            // in \nullfont, say).
            self.pdf.map_note_done = true;
            self.print_map_file_note("pdftex.map");
        }
        let (x, y) = w.pos(h, v);
        // Observed: a character missing from its font is not output.
        if let Some(be) = w.backend.as_deref_mut()
            && self.font(font).chars.contains_key(&chr)
        {
            if ef == 0 {
                be.glyph(self, font, chr, x, y);
            } else {
                be.glyph_expanded(self, font, chr, x, y, ef);
            }
        }
        if let Some(d) = w.dvi.as_mut()
            && self.font(font).chars.contains_key(&chr)
        {
            let wd = crate::expansion::expanded_width(self.font_char_dimen(font, chr, 0), ef);
            d.glyph(self, font, chr, w.dvi_h + h, w.dvi_v + v, wd);
        }
    }

    /// Runs one command of a virtual character's packet: characters of
    /// the local fonts and rules are output at the positions the packet
    /// moves to (in DVI as in PDF, LuaTeX writes the local fonts'
    /// characters, not the virtual one).
    fn packet_command(&mut self, w: &mut Walker, st: &mut PacketState, c: &PacketCommand) {
        match c {
            PacketCommand::Font(i) => st.font = st.vf.fonts.get(*i).copied().unwrap_or(0),
            PacketCommand::FontId(f) => st.font = *f,
            PacketCommand::Char(c) => {
                // The first local font until one is selected.
                if st.font == 0 {
                    st.font = st.vf.fonts.first().copied().unwrap_or(0);
                }
                let f = st.font;
                if f != 0 && self.font(f).chars.contains_key(c) {
                    self.out_glyph_at_depth(w, f, *c, st.h, st.v, st.ef, st.depth + 1);
                    st.h = st.h.wrapping_add(crate::expansion::expanded_width(
                        self.font_char_dimen(f, *c, 0),
                        st.ef,
                    ));
                }
            }
            PacketCommand::Rule { height, width } => {
                if *height > 0 && *width > 0 {
                    Self::out_rule(w, st.h, st.v, *width, *height);
                }
                st.h = st.h.wrapping_add(*width);
            }
            PacketCommand::Right(x) => st.h = st.h.wrapping_add(*x),
            PacketCommand::Down(y) => st.v = st.v.wrapping_add(*y),
            PacketCommand::Push => st.stack.push((st.h, st.v)),
            PacketCommand::Pop => {
                if let Some((h, v)) = st.stack.pop() {
                    (st.h, st.v) = (h, v);
                }
            }
            PacketCommand::Special(data) => self.out_special(w, st.h, st.v, data),
            PacketCommand::Pdf(mode, data) => {
                let (x, y) = w.pos(st.h, st.v);
                if let Some(be) = w.backend.as_deref_mut() {
                    be.literal(*mode, data, x, y);
                }
            }
            PacketCommand::Lua(r) => self.packet_lua(w, st, *r),
            // Observed: only a box is output, with its reference point at
            // the current point (its shift is ignored), and the position
            // stays.
            PacketCommand::Node(p) => {
                if matches!(self.nodes.id(*p), id::HLIST | id::VLIST) {
                    self.out_box(w, *p, st.h, st.v);
                }
            }
        }
    }

    /// Runs the `lua` command of a packet, kept under reference `r`.
    /// While it runs, the `vf` library draws into the packet (from its
    /// current state, which it leaves for the commands after) and
    /// `pdf.getpos` gives the packet's current point.
    fn packet_lua(&mut self, w: &mut Walker, st: &mut PacketState, r: i32) {
        let Some(host) = self.lua.clone() else {
            return;
        };
        let walker = std::mem::take(w);
        let saved_pos = self.pdf.pos;
        self.pdf.pos = walker.pos(st.h, st.v);
        let args = crate::ReferenceArgs::Glyph(st.vfont, st.chr);
        self.vf_frames.push(VfFrame {
            walker,
            state: st.clone(),
        });
        let result = host.call_reference(self, r, args);
        if let Some(frame) = self.vf_frames.pop() {
            *w = frame.walker;
            // Observed: the font `vf.fontid` selects is not kept for the
            // commands after.
            let font = st.font;
            *st = frame.state;
            st.font = font;
        }
        self.pdf.pos = saved_pos;
        if let Err(e) = result {
            self.lua_error(&e);
        }
    }

    /// Runs `cmd` in the packet whose `lua` command is running (the `vf`
    /// library); false outside one.
    pub fn vf_command(&mut self, cmd: &PacketCommand) -> bool {
        let Some(mut frame) = self.vf_frames.pop() else {
            return false;
        };
        // Observed: `vf.char` outputs nothing until the packet's commands
        // or `vf.fontid` selected a font (no first local font by
        // default).
        if matches!(cmd, PacketCommand::Char(_)) && frame.state.font == 0 {
            self.vf_frames.push(frame);
            return true;
        }
        self.packet_command(&mut frame.walker, &mut frame.state, cmd);
        self.pdf.pos = frame.walker.pos(frame.state.h, frame.state.v);
        self.vf_frames.push(frame);
        true
    }

    /// A dimension given to the `vf` library (`vf.right(x)`) in the
    /// packet whose `lua` command is running: observed, `x` is a
    /// fix_word scaled by the size of the virtual font, as dimensions in
    /// VF files are, and one beyond 16 times the size is a fatal error.
    /// `None` outside a packet.
    pub fn vf_scaled(&mut self, x: i64) -> Option<i32> {
        let f = self.vf_frames.last()?.state.vfont;
        if !(-(1 << 24)..1 << 24).contains(&x) {
            self.pdf_fatal_in("vf", "vf scaling");
        }
        let size = self.font(f).size;
        Some(retex_font::tfm::FixScaler::new(size).scale(x as i32))
    }

    /// Outputs a rule with its lower left corner at TeX position (`h`,
    /// `v`).
    fn out_rule(w: &mut Walker, h: i32, v: i32, width: i32, height: i32) {
        let (x, y) = w.pos(h, v);
        if let Some(be) = w.backend.as_deref_mut() {
            be.rule(x, y, width, height);
        }
        if let Some(d) = w.dvi.as_mut() {
            d.rule(w.dvi_h + h, w.dvi_v + v, width, height);
        }
    }

    /// Draws box resource `index` with its lower-left corner at (`h`, `v`).
    /// A form not written yet is written after the page or form being
    /// written (observed object numbering of LuaTeX).
    fn out_box_resource(
        &mut self,
        w: &mut Walker,
        index: i32,
        h: i32,
        v: i32,
        width: i32,
        height: i32,
    ) {
        let n = index as u32;
        let (x, y) = w.pos(h, v);
        let Some(mut be) = w.backend.take() else {
            return;
        };
        if self
            .box_resource_slot(n)
            .is_some_and(|i| !self.box_resources[i].written)
        {
            match self.pending_forms.last_mut() {
                Some(p) => {
                    if !p.contains(&n) {
                        p.push(n);
                    }
                }
                None => be = self.write_box_resource(be, n),
            }
        }
        be.box_form(self, n, x, y, width, height);
        w.backend = Some(be);
    }

    /// Writes box resource `n` as a form: ships its box into the form with
    /// the box's reference point at (0, depth), then the forms it uses that
    /// are not written yet, then its resources.
    pub fn write_box_resource(&mut self, be: Box<dyn Backend>, n: u32) -> Box<dyn Backend> {
        let Some(slot) = self.box_resource_slot(n) else {
            return be;
        };
        let r = self.box_resources[slot].clone();
        if r.written {
            return be;
        }
        // Observed: a form is shipped out like a page, so with
        // \tracingoutput positive the line is shown (but neither the
        // page number nor the box).
        if self.eqtb.int(ip::TRACINGOUTPUT) > 0 {
            self.printer.print_nl("");
            self.printer.print_ln();
            self.printer.print_str("Completed box being shipped out");
        }
        let mut be = be;
        let (bw, bh, bd) = r.size;
        self.pending_forms.push(Vec::new());
        self.form_objects.push(Vec::new());
        be.begin_box_form(self, n, (bw, bh, bd), &r.attr, &r.resources);
        let sync = self.synctex_recording();
        if sync {
            self.synctex_begin_form(bh + bd);
        }
        let mut walker = Walker {
            backend: Some(be),
            dvi: None,
            h_origin: 0,
            v_origin: 0,
            page_height: bh + bd,
            dvi_h: 0,
            dvi_v: 0,
            cur_s: -1,
            doing_leaders: false,
            page: false,
            sync,
        };
        if self.nodes.id(r.list) == id::VLIST {
            self.vlist_out(&mut walker, r.list, 0, bh);
        } else {
            self.hlist_out(&mut walker, r.list, 0, bh);
        }
        let mut be = walker.backend.take().expect("the walker keeps the backend");
        be.end_box_form(self);
        self.box_resources[slot].written = true;
        for obj in self.form_objects.pop().unwrap_or_default() {
            be.write_object(self, &obj);
        }
        be = self.write_pending_forms(be);
        // Observed: the forms this one uses are written inside its sheet.
        if sync {
            self.synctex_end_form();
        }
        be.close_box_form_resources(self);
        // Observed: an image is announced when it is written, after the
        // first form or page using it.
        for n in be.written_images().unwrap_or_default() {
            self.print_image_name(n);
        }
        be
    }

    /// Writes the forms used by the page or form just finished that are
    /// not written yet.
    fn write_pending_forms(&mut self, mut be: Box<dyn Backend>) -> Box<dyn Backend> {
        for n in self.pending_forms.pop().unwrap_or_default() {
            be = self.write_box_resource(be, n);
        }
        be
    }

    /// Draws image `index` with its lower-left corner at (`h`, `v`).
    fn out_image(&mut self, w: &mut Walker, index: i32, h: i32, v: i32, width: i32, height: i32) {
        let (x, y) = w.pos(h, v);
        if let Some(be) = w.backend.as_deref_mut() {
            be.image(self, index as u32, x, y, width, height);
            if self.mark_image_written(index as u32) {
                self.pdf.page_images.push(index as u32);
            }
        }
    }

    /// Outputs box `p` (`hlist_out` or `vlist_out`) with its reference
    /// point at (`h`, `v`).
    fn out_box(&mut self, w: &mut Walker, p: NodeRef, h: i32, v: i32) {
        // A box that contains itself (made by Lua code) is not followed
        // forever (LuaTeX crashes).
        if w.cur_s >= crate::nodes::MAX_NESTING as i32 {
            return;
        }
        if self.nodes.id(p) == id::VLIST {
            self.vlist_out(w, p, h, v);
        } else {
            self.hlist_out(w, p, h, v);
        }
    }

    /// Enters a box: `cur_s` goes up and nested boxes get a DVI `push`.
    fn enter_box(w: &mut Walker) {
        w.cur_s += 1;
        if let Some(d) = w.dvi.as_mut() {
            if w.cur_s > 0 {
                d.push(w.cur_s);
            } else {
                d.note_depth(w.cur_s);
            }
        }
    }

    /// Leaves a box (`dvi_pop`).
    fn leave_box(w: &mut Walker) {
        if w.cur_s > 0
            && let Some(d) = w.dvi.as_mut()
        {
            d.pop();
        }
        w.cur_s -= 1;
    }

    /// Outputs an hlist box (`hlist_out`); (`cur_h`, `cur_v`) is the box's
    /// reference point in TeX coordinates (v downwards).
    fn hlist_out(&mut self, w: &mut Walker, this_box: NodeRef, mut cur_h: i32, cur_v: i32) {
        let Some(b) = self.nodes.box_data(this_box).cloned() else {
            return;
        };
        let mut gs = GlueState {
            cur_g: 0,
            cur_glue: 0.0,
            order: b.glue_order,
            sign: b.glue_sign,
            set: b.glue_set,
        };
        Self::enter_box(w);
        let base_line = cur_v;
        let left_edge = cur_h;
        let ctx = crate::pdfship::BoxCtx {
            left: left_edge,
            base: base_line,
            width: b.width,
            height: b.height,
            depth: b.depth,
        };
        if !w.doing_leaders {
            self.ship_continue_links(w, &ctx);
        }
        if w.sync {
            let f = self.sync_of(this_box);
            self.synctex
                .box_open(true, f, cur_h, cur_v, [b.width, b.height, b.depth]);
        }
        // Right-to-left boxes and direction nodes: where each node goes
        // (the nodes are still output in list order).
        let places = self.rtl_places(b.head, b.dir == 1, &gs);
        let mut i = 0;
        let mut p = b.head;
        while !p.is_null() {
            let next = self.nodes.next(p);
            // (Nodes a `\latelua` function inserted have no place.)
            let rtl = match places.as_ref().and_then(|pl| pl.get(i)) {
                Some(&(x, rtl)) => {
                    cur_h = left_edge + x;
                    i += 1;
                    rtl
                }
                None => false,
            };
            if w.sync {
                self.sync_hlist_node(p, cur_h, base_line);
            }
            let n = self.nodes.get(p);
            let n_id = n.id;
            match &n.data {
                NodeData::Glyph(g) => {
                    let (font, chr, xo, yo, ef) =
                        (g.font, g.chr, g.xoffset, g.yoffset, g.expansion_factor);
                    if self.fonts.char_metrics(font, chr).is_none() {
                        self.shipout_lost_char(font, chr);
                    }
                    // In right-to-left text the offset goes leftwards.
                    let x = if rtl { cur_h - xo } else { cur_h + xo };
                    self.out_glyph(w, font, chr, x, base_line - yo, ef);
                    cur_h +=
                        crate::expansion::expanded_width(self.font_char_dimen(font, chr, 0), ef);
                }
                NodeData::Box(inner) => {
                    let (iw, shift, head) = (inner.width, inner.shift, inner.head);
                    if !head.is_null() {
                        self.out_box(w, p, cur_h, base_line + shift);
                    } else if w.sync {
                        let size = [iw, inner.height, inner.depth];
                        let f = self.sync_of(p);
                        self.synctex
                            .void_box(n_id == id::HLIST, f, cur_h, base_line, size);
                    }
                    cur_h += iw;
                }
                NodeData::Rule {
                    width,
                    depth,
                    height,
                    index,
                    ..
                } => {
                    let (wd, ht, dpt, idx) = (*width, *height, *depth, *index);
                    if n.subtype == crate::image::IMAGE_RULE {
                        self.out_image(w, idx, cur_h, base_line + dpt, wd, ht + dpt);
                    } else if n.subtype == crate::image::BOX_RESOURCE_RULE {
                        self.out_box_resource(w, idx, cur_h, base_line + dpt, wd, ht + dpt);
                    } else {
                        Self::hlist_rule(w, cur_h, base_line, wd, ht, dpt, &b);
                    }
                    cur_h += wd;
                    if w.sync {
                        let f = self.sync_of(p);
                        self.synctex.rule(f, cur_h, base_line, [wd, ht, dpt]);
                    }
                }
                NodeData::Glue { spec, leader } => {
                    let (spec, leader, sub) = (*spec, *leader, n.subtype);
                    let wd = gs.advance(&spec);
                    let box_leaders = sub >= glue_sub::A_LEADERS
                        && !leader.is_null()
                        && self.nodes.id(leader) != id::RULE;
                    if sub >= glue_sub::A_LEADERS && !leader.is_null() {
                        self.hlist_leaders(w, leader, sub, cur_h, left_edge, base_line, wd, &b);
                    }
                    cur_h += wd;
                    if w.sync && !box_leaders {
                        let f = self.sync_of(p);
                        self.synctex.glue(f, cur_h, base_line);
                    }
                }
                NodeData::Kern {
                    kern,
                    expansion_factor,
                } => {
                    let wd = kern + expansion_factor;
                    if w.sync {
                        // Observed: the width recorded is the kern's,
                        // without font expansion.
                        let f = self.sync_of(p);
                        self.synctex.kern(f, *kern);
                    }
                    cur_h += wd;
                }
                NodeData::Math { surround, glue } => {
                    let g = *glue;
                    if w.sync {
                        let f = self.sync_of(p);
                        self.synctex.math(f, cur_h, base_line);
                    }
                    cur_h += surround;
                    if g != Glue::ZERO {
                        cur_h += gs.advance(&g);
                    }
                }
                NodeData::MarginKern { width, .. } => cur_h += width,
                NodeData::Whatsit(_) => {
                    self.out_what(w, p, cur_h, base_line, &ctx);
                    // A `\latelua` function can insert nodes after it.
                    p = self.nodes.next(p);
                    continue;
                }
                NodeData::Disc { replace, .. } => {
                    let replace = *replace;
                    // A discretionary that was not broken shows its
                    // replacement text (from its right end in
                    // right-to-left text, as other nodes there).
                    let mut items = Vec::new();
                    let mut q = replace;
                    while !q.is_null() {
                        items.push(q);
                        q = self.nodes.next(q);
                    }
                    let start = cur_h;
                    let total: i32 = items.iter().map(|&q| self.replace_item_width(q)).sum();
                    for q in items {
                        if rtl {
                            // Placed at its left edge, from the right end.
                            cur_h = start + total
                                - items_before_width(self, replace, q)
                                - self.replace_item_width(q);
                        }
                        match &self.nodes.get(q).data {
                            NodeData::Glyph(g) => {
                                let (font, chr, ef) = (g.font, g.chr, g.expansion_factor);
                                self.out_glyph(w, font, chr, cur_h, base_line, ef);
                                if w.sync {
                                    self.synctex.glyph();
                                }
                                cur_h += crate::expansion::expanded_width(
                                    self.font_char_dimen(font, chr, 0),
                                    ef,
                                );
                            }
                            NodeData::Kern {
                                kern,
                                expansion_factor,
                            } => {
                                let wd = kern + expansion_factor;
                                if w.sync {
                                    self.synctex.end_run(cur_h, base_line);
                                    let f = self.sync_of(q);
                                    self.synctex.kern(f, *kern);
                                }
                                cur_h += wd;
                            }
                            // Boxes and rules, as in the list (crop's
                            // `\discretionary{}{}{\hbox{---}}`).
                            NodeData::Box(inner) => {
                                let (iw, shift, head) = (inner.width, inner.shift, inner.head);
                                if !head.is_null() {
                                    self.out_box(w, q, cur_h, base_line + shift);
                                }
                                cur_h += iw;
                            }
                            NodeData::Rule {
                                width,
                                depth,
                                height,
                                ..
                            } => {
                                let (wd, ht, dpt) = (*width, *height, *depth);
                                Self::hlist_rule(w, cur_h, base_line, wd, ht, dpt, &b);
                                cur_h += wd;
                            }
                            _ => {}
                        }
                    }
                }
                _ => {}
            }
            p = next;
        }
        if places.is_some() {
            cur_h = left_edge + b.width;
        }
        if !w.doing_leaders {
            self.ship_end_box_links(w, &ctx);
        }
        if w.sync {
            self.synctex.end_run(cur_h, base_line);
            let f = self.sync_of(this_box);
            self.synctex.box_close(true, f, cur_h, base_line);
        }
        Self::leave_box(w);
    }

    /// The width a node of an unbroken discretionary's replacement adds.
    fn replace_item_width(&self, q: NodeRef) -> i32 {
        match &self.nodes.get(q).data {
            NodeData::Glyph(g) => crate::expansion::expanded_width(
                self.font_char_dimen(g.font, g.chr, 0),
                g.expansion_factor,
            ),
            NodeData::Kern {
                kern,
                expansion_factor,
            } => kern + expansion_factor,
            NodeData::Box(b) => b.width,
            NodeData::Rule { width, .. } => *width,
            _ => 0,
        }
    }

    /// The horizontal room each node of an hlist takes when output, in
    /// list order (glue as set, with TeX's rounding in that order).
    fn hlist_widths(&self, head: NodeRef, gs: &GlueState) -> Vec<i32> {
        let mut gs = gs.clone();
        let mut out = Vec::new();
        let mut p = head;
        while !p.is_null() {
            let n = self.nodes.get(p);
            let w = match &n.data {
                NodeData::Glyph(g) => crate::expansion::expanded_width(
                    self.font_char_dimen(g.font, g.chr, 0),
                    g.expansion_factor,
                ),
                NodeData::Box(inner) => inner.width,
                NodeData::Rule { width, .. } => *width,
                NodeData::Glue { spec, .. } => gs.advance(spec),
                NodeData::Kern {
                    kern,
                    expansion_factor,
                } => kern + expansion_factor,
                NodeData::Math { surround, glue } => {
                    surround
                        + if *glue != Glue::ZERO {
                            gs.advance(glue)
                        } else {
                            0
                        }
                }
                NodeData::MarginKern { width, .. } => *width,
                NodeData::Disc { replace, .. } => {
                    let mut q = *replace;
                    let mut w = 0;
                    while !q.is_null() {
                        w += self.replace_item_width(q);
                        q = self.nodes.next(q);
                    }
                    w
                }
                _ => 0,
            };
            out.push(w);
            p = n.next;
        }
        out
    }

    /// Where the nodes of an hlist go, in list order: (left edge from the
    /// box's left edge, whether in right-to-left text), or `None` for a
    /// left-to-right box without direction nodes. As LuaTeX (observed in
    /// its PDF output): direction nodes delimit segments; a left-to-right
    /// segment places its nodes from its left end rightwards, a
    /// right-to-left one (a `TRT` box, or text after `\begindir TRT`) from
    /// its right end leftwards, both in list order, a nested segment
    /// taking the room of its width.
    fn rtl_places(&self, head: NodeRef, box_rtl: bool, gs: &GlueState) -> Option<Vec<(i32, bool)>> {
        let mut has_dirs = false;
        let mut p = head;
        while !p.is_null() {
            if self.nodes.id(p) == id::DIR {
                has_dirs = true;
                break;
            }
            p = self.nodes.next(p);
        }
        if !box_rtl && !has_dirs {
            return None;
        }
        let widths = self.hlist_widths(head, gs);
        enum Item {
            Node(usize),
            Seg(bool, Vec<Item>),
        }
        let mut stack: Vec<(bool, Vec<Item>)> = vec![(box_rtl, Vec::new())];
        let close = |stack: &mut Vec<(bool, Vec<Item>)>| {
            let (rtl, items) = stack.pop().expect("open segment");
            stack
                .last_mut()
                .expect("outer segment")
                .1
                .push(Item::Seg(rtl, items));
        };
        let mut p = head;
        let mut k = 0;
        while !p.is_null() {
            if let NodeData::Dir { dir, .. } = self.nodes.data(p) {
                let begin = self.nodes.subtype(p) != crate::dirs::dir_sub::END;
                if !begin && stack.len() > 1 {
                    // The direction node belongs to the segment it ends.
                    stack.last_mut().expect("segment").1.push(Item::Node(k));
                    close(&mut stack);
                } else if begin {
                    stack.push((*dir == 1, vec![Item::Node(k)]));
                } else {
                    stack.last_mut().expect("segment").1.push(Item::Node(k));
                }
            } else {
                stack.last_mut().expect("segment").1.push(Item::Node(k));
            }
            k += 1;
            p = self.nodes.next(p);
        }
        while stack.len() > 1 {
            close(&mut stack);
        }
        fn width(items: &[Item], widths: &[i32]) -> i32 {
            items
                .iter()
                .map(|it| match it {
                    Item::Node(i) => widths[*i],
                    Item::Seg(_, sub) => width(sub, widths),
                })
                .sum()
        }
        fn place(rtl: bool, items: &[Item], left: i32, widths: &[i32], out: &mut [(i32, bool)]) {
            let mut x = if rtl {
                left + width(items, widths)
            } else {
                left
            };
            for it in items {
                match it {
                    Item::Node(i) => {
                        if rtl {
                            x -= widths[*i];
                            out[*i] = (x, true);
                        } else {
                            out[*i] = (x, false);
                            x += widths[*i];
                        }
                    }
                    Item::Seg(r, sub) => {
                        let w = width(sub, widths);
                        if rtl {
                            x -= w;
                            place(*r, sub, x, widths, out);
                        } else {
                            place(*r, sub, x, widths, out);
                            x += w;
                        }
                    }
                }
            }
        }
        let (rtl, items) = stack.pop().expect("box segment");
        let mut out = vec![(0, false); widths.len()];
        place(rtl, &items, 0, &widths, &mut out);
        Some(out)
    }

    /// SyncTeX before node `p` of an hlist: a glyph continues a run of
    /// glyphs, the nodes that do not end one leave it, others end it.
    #[inline]
    fn sync_hlist_node(&mut self, p: NodeRef, cur_h: i32, base_line: i32) {
        match self.nodes.id(p) {
            id::GLYPH => self.synctex.glyph(),
            id::MARK | id::INS | id::ADJUST | id::BOUNDARY | id::LOCAL_PAR => {}
            _ => self.synctex.end_run(cur_h, base_line),
        }
    }

    /// A rule in an hlist whose left end is at `cur_h` (TeX's `fin_rule`
    /// in ยง624); running dimensions come from the enclosing box.
    fn hlist_rule(
        w: &mut Walker,
        cur_h: i32,
        base_line: i32,
        wd: i32,
        ht: i32,
        dpt: i32,
        this_box: &crate::nodes::BoxData,
    ) {
        let ht = if ht == RUNNING { this_box.height } else { ht };
        let dpt = if dpt == RUNNING { this_box.depth } else { dpt };
        let total = ht + dpt;
        if total > 0 && wd > 0 {
            Self::out_rule(w, cur_h, base_line + dpt, wd, total);
        }
    }

    /// Outputs a vlist box (`vlist_out`).
    fn vlist_out(&mut self, w: &mut Walker, this_box: NodeRef, cur_h: i32, cur_v: i32) {
        let Some(b) = self.nodes.box_data(this_box).cloned() else {
            return;
        };
        let mut gs = GlueState {
            cur_g: 0,
            cur_glue: 0.0,
            order: b.glue_order,
            sign: b.glue_sign,
            set: b.glue_set,
        };
        Self::enter_box(w);
        let left_edge = cur_h;
        let ctx = crate::pdfship::BoxCtx {
            left: left_edge,
            base: cur_v,
            width: b.width,
            height: b.height,
            depth: b.depth,
        };
        let mut cur_v = cur_v - b.height;
        let top_edge = cur_v;
        if w.sync {
            let f = self.sync_of(this_box);
            self.synctex
                .box_open(false, f, cur_h, cur_v, [b.width, b.height, b.depth]);
        }
        let mut p = b.head;
        while !p.is_null() {
            let next = self.nodes.next(p);
            let n = self.nodes.get(p);
            match &n.data {
                NodeData::Box(inner) => {
                    let (ih, idp, shift, head) =
                        (inner.height, inner.depth, inner.shift, inner.head);
                    if head.is_null() {
                        cur_v += ih + idp;
                        if w.sync {
                            let size = [inner.width, ih, idp];
                            let hlist = n.id == id::HLIST;
                            let f = self.sync_of(p);
                            self.synctex.void_box(hlist, f, left_edge, cur_v, size);
                        }
                    } else {
                        cur_v += ih;
                        self.out_box(w, p, left_edge + shift, cur_v);
                        cur_v += idp;
                    }
                }
                NodeData::Rule {
                    width,
                    depth,
                    height,
                    index,
                    ..
                } => {
                    let wd = if *width == RUNNING { b.width } else { *width };
                    let total = height + depth;
                    let idx = *index;
                    cur_v += total;
                    if n.subtype == crate::image::IMAGE_RULE {
                        self.out_image(w, idx, left_edge, cur_v, wd, total);
                    } else if n.subtype == crate::image::BOX_RESOURCE_RULE {
                        self.out_box_resource(w, idx, left_edge, cur_v, wd, total);
                    } else if total > 0 && wd > 0 {
                        Self::out_rule(w, left_edge, cur_v, wd, total);
                    }
                }
                NodeData::Glue { spec, leader } => {
                    let (spec, leader, sub) = (*spec, *leader, n.subtype);
                    let ht = gs.advance(&spec);
                    if sub >= glue_sub::A_LEADERS && !leader.is_null() {
                        cur_v =
                            self.vlist_leaders(w, leader, sub, cur_v, left_edge, top_edge, ht, &b);
                    } else {
                        cur_v += ht;
                    }
                }
                NodeData::Kern { kern, .. } => cur_v += kern,
                NodeData::Whatsit(_) => {
                    self.out_what(w, p, left_edge, cur_v, &ctx);
                    // A `\latelua` function can insert nodes after it.
                    p = self.nodes.next(p);
                    continue;
                }
                _ => {}
            }
            p = next;
        }
        if w.sync {
            let f = self.sync_of(this_box);
            self.synctex.box_close(false, f, left_edge, cur_v);
        }
        Self::leave_box(w);
    }

    /// Where leaders of the given kind start and how much space follows
    /// each copy (ยง626, ยง635): returns (start, gap) for a space of size
    /// `size` at `cur` filled with boxes of size `step`.
    fn leader_start(sub: u16, cur: i32, edge0: i32, size: i32, step: i32) -> (i32, i32) {
        if sub == glue_sub::C_LEADERS || sub == glue_sub::X_LEADERS {
            let lq = size / step;
            let lr = size % step;
            if sub == glue_sub::C_LEADERS {
                (cur + lr / 2, 0)
            } else {
                let lx = lr / (lq + 1);
                (cur + (lr - (lq - 1) * lx) / 2, lx)
            }
        } else {
            let mut c = edge0 + step * ((cur - edge0) / step);
            if c < cur {
                c += step;
            }
            (c, 0)
        }
    }

    /// Leaders in an hlist (ยง625โ€“ยง628) filling `wd` from `cur_h`.
    #[allow(clippy::too_many_arguments)]
    fn hlist_leaders(
        &mut self,
        w: &mut Walker,
        leader: NodeRef,
        sub: u16,
        cur_h: i32,
        left_edge: i32,
        base_line: i32,
        wd: i32,
        this_box: &crate::nodes::BoxData,
    ) {
        let lb = match &self.nodes.get(leader).data {
            NodeData::Rule { height, depth, .. } => {
                let (ht, dpt) = (*height, *depth);
                Self::hlist_rule(w, cur_h, base_line, wd, ht, dpt, this_box);
                return;
            }
            NodeData::Box(lb) => lb.clone(),
            _ => return,
        };
        let leader_wd = lb.width;
        if leader_wd <= 0 || wd <= 0 {
            return;
        }
        let rule_wd = wd + 10; // compensates for floating-point rounding
        let edge = cur_h + rule_wd;
        let (mut h, lx) = Self::leader_start(sub, cur_h, left_edge, rule_wd, leader_wd);
        // The box is output even if it is empty, which counts towards the
        // DVI stack depth (ยง628).
        while h + leader_wd <= edge {
            let outer = w.doing_leaders;
            w.doing_leaders = true;
            self.out_box(w, leader, h, base_line + lb.shift);
            w.doing_leaders = outer;
            h += leader_wd + lx;
        }
    }

    /// Leaders in a vlist (ยง634โ€“ยง637) filling `ht` below `cur_v`; returns
    /// the new `cur_v`.
    #[allow(clippy::too_many_arguments)]
    fn vlist_leaders(
        &mut self,
        w: &mut Walker,
        leader: NodeRef,
        sub: u16,
        cur_v: i32,
        left_edge: i32,
        top_edge: i32,
        ht: i32,
        this_box: &crate::nodes::BoxData,
    ) -> i32 {
        let lb = match &self.nodes.get(leader).data {
            NodeData::Rule { width, .. } => {
                let wd = if *width == RUNNING {
                    this_box.width
                } else {
                    *width
                };
                if ht > 0 && wd > 0 {
                    Self::out_rule(w, left_edge, cur_v + ht, wd, ht);
                }
                return cur_v + ht;
            }
            NodeData::Box(lb) => lb.clone(),
            _ => return cur_v + ht,
        };
        let leader_ht = lb.height + lb.depth;
        if leader_ht <= 0 || ht <= 0 {
            return cur_v + ht;
        }
        let rule_ht = ht + 10; // compensates for floating-point rounding
        let edge = cur_v + rule_ht;
        let (mut v, lx) = Self::leader_start(sub, cur_v, top_edge, rule_ht, leader_ht);
        while v + leader_ht <= edge {
            let outer = w.doing_leaders;
            w.doing_leaders = true;
            self.out_box(w, leader, left_edge + lb.shift, v + lb.height);
            w.doing_leaders = outer;
            v += leader_ht + lx;
        }
        edge - 10
    }

    /// Executes a whatsit at TeX position (`h`, `v`) (`out_what`).
    fn out_what(
        &mut self,
        w: &mut Walker,
        p: NodeRef,
        h: i32,
        v: i32,
        ctx: &crate::pdfship::BoxCtx,
    ) {
        let NodeData::Whatsit(wh) = &self.nodes.get(p).data else {
            return;
        };
        let (x, y) = w.pos(h, v);
        match (**wh).clone() {
            Whatsit::Open { stream, name } if !w.doing_leaders => {
                self.open_write_stream(stream as i32, &name)
            }
            Whatsit::Write { stream, data } if !w.doing_leaders => self.write_out(stream, &data),
            Whatsit::Close { stream } if !w.doing_leaders => self.close_write_stream(stream as i32),
            Whatsit::Special { data } => self.out_special(w, h, v, &data),
            Whatsit::PdfLiteral { mode, data, .. } => {
                let bytes = match data {
                    crate::nodes::LateData::Bytes(b)
                    | crate::nodes::LateData::Lua { data: b, .. } => b,
                    crate::nodes::LateData::Function { .. } => Vec::new(),
                    crate::nodes::LateData::Tokens(t) => {
                        let toks = self.expand_late_tokens(&t);
                        self.print_to_string(|e| e.show_token_list(&toks, 0, toks.len(), i64::MAX))
                    }
                };
                if let Some(be) = w.backend.as_deref_mut() {
                    be.literal(mode, &bytes, x, y);
                }
            }
            Whatsit::LateLua { data, .. } => {
                let code = match data {
                    crate::nodes::LateData::Bytes(b)
                    | crate::nodes::LateData::Lua { data: b, .. } => Ok(b),
                    crate::nodes::LateData::Tokens(t) => {
                        let toks = self.expand_late_tokens(&t);
                        Ok(self.lua_code(&toks))
                    }
                    crate::nodes::LateData::Function { reference } => Err(reference),
                };
                // `pdf.getpos`, `pdf.print` and `pdf.registerannot` work on
                // this context while the code runs.
                self.pdf.pos = (x, y);
                let outer = self.pdf.late.replace(Default::default());
                match code {
                    Ok(code) => self.run_lua(&code),
                    // Observed: a function is called with the whatsit;
                    // the nodes it inserts after it are output next.
                    Err(r) => {
                        if let Some(host) = self.lua.clone()
                            && let Err(e) =
                                host.call_reference(self, r, crate::ReferenceArgs::Node(p))
                        {
                            self.lua_error(&e);
                        }
                    }
                }
                let ctx = std::mem::replace(&mut self.pdf.late, outer).unwrap_or_default();
                if let Some(be) = w.backend.as_deref_mut() {
                    for (mode, text) in &ctx.prints {
                        be.print(*mode, text, x, y);
                    }
                }
                self.pdf
                    .page
                    .annots
                    .extend(ctx.annots.into_iter().map(|a| (a, None)));
            }
            Whatsit::PdfRefobj { objnum } if !w.doing_leaders => self.ship_refobj(w, objnum),
            Whatsit::PdfAnnot { dims, objnum, data } if !w.doing_leaders => {
                self.ship_annot(w, ctx, h, v, dims, objnum, &data)
            }
            Whatsit::PdfStartLink {
                dims,
                objnum,
                attr,
                action,
            } if !w.doing_leaders => {
                self.ship_start_link(w, ctx, h, v, dims, objnum, &attr, &action)
            }
            Whatsit::PdfEndLink if !w.doing_leaders => self.ship_end_link(w, h, v),
            Whatsit::PdfDest {
                id,
                view,
                structure,
            } if !w.doing_leaders => self.ship_dest(w, ctx, h, v, &id, &view, structure),
            Whatsit::SavePos => {
                self.last_x_pos = x;
                self.last_y_pos = y;
            }
            Whatsit::PdfSave => {
                if let Some(be) = w.backend.as_deref_mut() {
                    be.save(x, y);
                }
            }
            Whatsit::PdfRestore => {
                if let Some(be) = w.backend.as_deref_mut() {
                    be.restore(x, y);
                }
            }
            Whatsit::PdfSetmatrix { data } => {
                if let Some(be) = w.backend.as_deref_mut() {
                    be.set_matrix(x, y, &data);
                }
            }
            Whatsit::PdfColorstack { stack, cmd, data } => {
                let out = self.colorstack_op(stack, cmd, data);
                if let (Some((mode, lit)), Some(be)) = (out, w.backend.as_deref_mut()) {
                    be.literal(mode, &lit, x, y);
                }
            }
            _ => {}
        }
    }

    /// Outputs a `\special` at TeX position (`h`, `v`).
    fn out_special(&mut self, w: &mut Walker, h: i32, v: i32, data: &[u8]) {
        let (x, y) = w.pos(h, v);
        if let Some(d) = w.dvi.as_mut() {
            d.special(w.dvi_h + h, w.dvi_v + v, data);
        } else if let Some(be) = w.backend.as_deref_mut() {
            // Observed in PDF mode: `pdf:` specials (any case) are
            // literals, with an optional mode keyword; every other
            // special is dropped with a warning.
            if data.len() >= 4 && data[..4].eq_ignore_ascii_case(b"pdf:") {
                let rest = &data[4..];
                let (mode, text) = [
                    (&b"direct:"[..], 2),
                    (b"page:", 1),
                    (b"raw:", 3),
                    (b"text:", 4),
                    (b"origin:", 0),
                ]
                .iter()
                .find_map(|(k, m)| rest.strip_prefix(*k).map(|t| (*m, t)))
                .unwrap_or((crate::pdfext::literal_mode::ORIGIN, rest));
                be.literal(mode, text, x, y);
            } else {
                self.printer.print_nl("Non-PDF special ignored!");
            }
        }
    }

    /// Applies a colour-stack command; returns the literal to emit.
    fn colorstack_op(&mut self, stack: i32, cmd: u8, data: Vec<u8>) -> Option<(u8, Vec<u8>)> {
        use crate::pdfext::colorstack_cmd as c;
        self.pdf_ensure_colorstacks();
        let def = self.pdf.colorstacks.get(stack.max(0) as usize).cloned()?;
        let st = self
            .colorstack_values
            .entry(stack)
            .or_insert_with(|| vec![def.init.clone()]);
        match cmd {
            c::SET => {
                if let Some(top) = st.last_mut() {
                    *top = data;
                } else {
                    st.push(data);
                }
            }
            c::PUSH => st.push(data),
            c::POP => {
                if st.len() > 1 {
                    st.pop();
                }
            }
            _ => {}
        }
        let lit = st.last().cloned().unwrap_or_default();
        Some((def.mode, lit))
    }

    /// Expands a late token list (as `\write` does) and returns the
    /// expanded tokens.
    fn expand_late_tokens(&mut self, list: &crate::token::TokenList) -> Vec<crate::token::Token> {
        use crate::token::Token;
        use std::rc::Rc;
        self.ins_list(Rc::from(vec![
            Token::RIGHT_BRACE,
            Token::cs(self.cs.end_write),
        ]));
        self.begin_token_list(list.clone(), crate::input::TokKind::WriteText);
        self.ins_list(Rc::from(vec![Token::LEFT_BRACE]));
        let toks = self.scan_toks(false, true);
        self.get_token();
        toks
    }

    /// Finishes the output file at the end of the run and reports it.
    pub fn finish_backend(&mut self) {
        if let Some(f) = self.final_hook {
            f(self);
        }
        if self.dvi.pages() > 0 {
            self.finish_dvi();
        } else if self.pdf.output_opened && self.eqtb.int(ip::OUTPUTMODE) <= 0 {
            // LuaTeX opened the DVI file for `pdf.obj` and leaves it empty.
            let _ = std::fs::write(self.output_path("dvi"), b"");
        }
        let Some(mut be) = self.backend.take() else {
            return;
        };
        if self.pdf.fatal || self.total_pages == 0 {
            be.abandon(self.pdf.fatal);
            self.backend = Some(be);
            return;
        }
        if self.eqtb.int(ip::DRAFTMODE) > 0 && self.eqtb.int(ip::OUTPUTMODE) > 0 {
            // `-draftmode`: the document is typeset but no PDF is written
            // (the backend wrote to a scratch file, removed here). LuaTeX
            // prints this warning; unlike LuaTeX, which empties an
            // existing PDF file, retex leaves it as it is.
            be.abandon(true);
            self.backend = Some(be);
            self.printer
                .print_nl("warning  (pdf backend): draftmode enabled, not changing output pdf");
            self.printer.print_ln();
            return;
        }
        if self.total_pages > 0 {
            self.pdf_finish_document();
            self.flush_pending_objects(be.as_mut());
        }
        if self.total_pages > 0
            && let Some(fin) = be.finish(self)
        {
            // Observed: printed one after the other like C strings (log
            // lines up to 80 characters), right after what came before.
            for f in &fin.embedded {
                self.printer.print_lua_bytes(f.as_bytes());
            }
            self.pdf.objstm_stats = fin.objstm;
            self.print_output_written(&fin.file, self.total_pages, fin.size);
        }
        self.backend = Some(be);
    }

    /// The path of output file `<jobname>.<ext>` (in `-output-directory`).
    pub(crate) fn output_path(&self, ext: &str) -> std::path::PathBuf {
        let job =
            String::from_utf8_lossy(self.job_name.as_deref().unwrap_or(b"texput")).into_owned();
        let name = format!("{job}.{ext}");
        match &self.files.output_dir {
            Some(d) => d.join(&name),
            None => std::path::PathBuf::from(&name),
        }
    }

    /// Writes the postamble and the DVI file `<jobname>.dvi` (ยง642).
    fn finish_dvi(&mut self) {
        let mut dvi = std::mem::take(&mut self.dvi);
        let pages = dvi.pages();
        let data = dvi.finish(self);
        let path = self.output_path("dvi");
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        if std::fs::write(&path, &data).is_err() {
            self.printer.print_nl("! I can't write on file `");
            self.printer.print_bytes(name.as_bytes());
            self.printer.print_str("'.");
            return;
        }
        self.print_output_written(&name, pages, data.len() as u64);
    }

    /// Prints `Output written on NAME (N pages, B bytes).`.
    fn print_output_written(&mut self, name: &str, pages: u32, size: u64) {
        self.output_written = Some((name.to_owned(), pages, size));
        self.printer.print_nl("Output written on ");
        self.printer.print_bytes(name.as_bytes());
        self.printer.print_str(" (");
        self.printer.print_int(i64::from(pages));
        self.printer
            .print_str(if pages == 1 { " page" } else { " pages" });
        self.printer.print_str(", ");
        self.printer.print_int(size as i64);
        self.printer.print_str(" bytes).");
    }
}

/// The state of a page being shipped: the outputs and the coordinate
/// systems they use.
#[derive(Default)]
pub(crate) struct Walker {
    /// The PDF backend (PDF mode).
    backend: Option<Box<dyn Backend>>,
    /// The DVI writer (DVI mode).
    dvi: Option<crate::dvi::DviWriter>,
    h_origin: i32,
    v_origin: i32,
    page_height: i32,
    /// The DVI position of TeX's origin (`\hoffset`, `\voffset`).
    dvi_h: i32,
    dvi_v: i32,
    /// Box nesting depth (`cur_s`): -1 outside the page box.
    pub(crate) cur_s: i32,
    /// Whether a leader box is being output (`doing_leaders`).
    doing_leaders: bool,
    /// Whether this is a page (not a box resource): annotations, links
    /// and destinations belong to pages.
    pub(crate) page: bool,
    /// Whether SyncTeX records this sheet.
    sync: bool,
}

impl Walker {
    /// Page coordinates (from the lower left, y up) of TeX point
    /// (`h`, `v`) measured from the origin, v downwards.
    pub(crate) fn pos(&self, h: i32, v: i32) -> (i32, i32) {
        (self.h_origin + h, self.page_height - (self.v_origin + v))
    }
}

/// The state of a virtual character's packet being run.
#[derive(Clone)]
pub(crate) struct PacketState {
    /// The current point.
    h: i32,
    v: i32,
    /// The current font.
    font: u32,
    /// The points saved by `push`.
    stack: Vec<(i32, i32)>,
    /// The expansion factor of the virtual character.
    ef: i32,
    /// How deeply virtual characters are nested.
    depth: u32,
    /// The virtual font, its id and the character.
    vf: std::rc::Rc<crate::fonts::VirtualFont>,
    vfont: u32,
    chr: u32,
}

/// A packet whose `lua` command is running, with the output it draws
/// into.
pub(crate) struct VfFrame {
    walker: Walker,
    state: PacketState,
}