mossaic 0.8.1

Draw pixel art in your GitHub contribution graph — a terminal chart, an editor, and a planner that says what today owes
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
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
//! Write text into a GitHub contribution graph by dating commits.
//!
//! ```sh
//! cargo run --bin mossaic-art -- VYNCINT --year 2027                    # preview only
//! cargo run --bin mossaic-art -- VYNCINT --year 2027 --snapshot art.json
//! cargo run --bin mossaic-art -- VYNCINT --year 2027 --repo ../art --write
//! ```
//!
//! Nothing is ever pushed. `--write` makes local commits in a directory you
//! name; pushing is a separate command it prints for you to run.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use chrono::{Datelike, Local, NaiveDate};
use mossaic::art::{self, Grid};
use mossaic::cli::{Args, YEARS};
use mossaic::primer::{Appearance, Palette, Season};
use mossaic::{github, graphics, plan, plural, png, primer, templates, thousands, Colour};

const HELP: &str = r#"mossaic-art — draw on a GitHub contribution graph by dating commits

usage:
  mossaic-art TEXT [options]        write words through a 5x5 font
  mossaic-art --template NAME       draw a picture from the catalogue
  mossaic-art --matrix FILE         draw a picture of your own
  mossaic-art --draw                draw one by hand, in an editor

examples:
  mossaic-art --draw                                 a blank year, by hand
  mossaic-art --list-templates                       the pictures on offer
  mossaic-art --template dragon --year 2027          a picture across next year
  mossaic-art VYNCINT --year 2027                    what it looks like, and costs
  mossaic-art VYNCINT --year 2027 --save             remember it
  mossaic-art --track                                am I on pace?
  mossaic-art --backfill --repo ../art --write       commit what the plan is short

WHAT TO DRAW
  TEXT                letters, digits, punctuation and shapes: `I :heart: RUST`.
                      Drawn Mon-Fri through a 5x5 font; --font lists every glyph
  --template NAME     a picture from the catalogue
  --list-templates    list the templates, with a thumbnail of each, and exit
  --matrix FILE       (--file) a .art file: 7 rows of the shades 0-4, or of the
                      blocks ░ ▒ ▓ █ with a space for 0. `#` starts a comment
  --image FILE        a PNG, shrunk to fit the year and quantised to five shades.
                      A dark pixel is a busy day, the way ink reads on paper
  --invert            with --image, bright pixels become the busy days instead
  --dither            with --image, spread the rounding error into neighbouring
                      days (Floyd-Steinberg), so a gradient reads as one
  --draw              open the editor: arrows or hjkl to move, 0-4 to paint a
                      shade, space to cycle one, the mouse to paint, u to undo,
                      s to save. With --template or --matrix it opens that picture
  --output FILE       (-o) where --draw saves (default: the picture's name)

  A picture is seven rows by up to 53 columns, any of GitHub's five shades per
  day, using the whole week and the whole year. Text uses Mon-Fri and one shade.

WHERE IT GOES
  --year YEAR         which year's calendar (default: this one)
  --start-week N      left edge, in weeks (default: centred)
  --commits N         commits for the brightest day; darker shades are priced
                      against it (default 4)
  --top ROW           first calendar row, 0 = Sunday (default 1, so Mon-Fri).
                      Text only; a picture uses all seven rows
  --background LEVEL  (--bg) draw the background as a shade 0-3 rather than
                      leaving it empty, so the whole year stays green. Text
                      only. Keep it two levels clear of the letters, or the
                      two greens are too close to tell apart

TRACKING
  --track [USER]      how far along, what today owes, and whether the picture can
                      still be drawn at all. Reads --merge if given, otherwise
                      asks gh for USER (default: whoever gh is)
  --today DATE        what counts as today, as YYYY-MM-DD (default: the clock),
                      so a report is repeatable and a future day can be asked
  --merge PATH        a saved calendar to draw on top of, so the preview accounts
                      for contributions already there
  --plan PATH         where the plan lives (default: mossaic-plan.json)
  --save              write the plan, so later runs need no flags at all

MAKING THE COMMITS
  --repo DIR          the repository --write commits into (local only)
  --write             actually create the commits
  --backfill          commit only what each past day is still short of the plan,
                      never adding to a day that is already bright, and leaving
                      days still to come alone. Needs --repo, and --write to commit
  --name NAME         commit author name (default: git config)
  --email ADDRESS     commit author email (default: git config)

OUTPUT
  --snapshot PATH     write a calendar file for `mossaic --file PATH`
  --login NAME        the name that snapshot carries (default: preview)
  --format F          text (default), json or markdown — what --track prints.
                      The GitHub Action reads json and markdown
  --color WHEN        (--colour) auto (default), always or never. auto means
                      colour when stdout is a terminal and NO_COLOR is unset
  --no-color          (--no-colour) the same as --color never
  --font              print every glyph the font has, and exit
  --png PATH          with --font, write the glyph sheet to a PNG instead

  -V, --version       print the version
  -h, --help          show this help

Save the plan once and later runs need no flags at all:

  mossaic-art VYNCINT --year 2027 --start-week 6 --save
  mossaic-art --track          # reads mossaic-plan.json

Pictures, templates and the .art format: docs/ART.md
  https://github.com/vyncint/mossaic/blob/main/docs/ART.md

also installed:
  mossaic          the chart itself
  mossaic-glyphs   what this terminal makes of the fallback cells"#;

fn main() {
    // Before anything prints: a reader that closes early is not a crash.
    mossaic::quiet_broken_pipe();
    let Some(options) = parse_args() else {
        return;
    };

    // The CLI has already bounded the year, so this only fails for a caller
    // that reached past it.
    let grid = Grid::new(options.year).unwrap_or_else(|| {
        fail(&format!(
            "{} is not a year a calendar can hold",
            options.year
        ))
    });
    // A picture takes a path of its own, before a single line of the text
    // machinery runs. That is what makes "no regressions for text" a property
    // of the control flow rather than a claim about the diff.
    if let Some((name, canvas)) = options.canvas.clone() {
        if options.draw {
            run_editor(&options, &grid, &name, canvas);
        } else {
            run_canvas(&options, &grid, &name, &canvas);
        }
        return;
    }
    if options.draw {
        fail("--draw draws a picture; it has nothing to do with TEXT");
    }

    let columns = art::bitmap(&options.text).unwrap_or_else(|error| fail(&error));

    // The letters are always the brightest shade; --background picks what they
    // are drawn *on*. Rejected here rather than rendered, because a background
    // at or above the letters is not faint art, it is a blank graph.
    let shades = art::Shades {
        ink: 4,
        field: options.background,
    };
    shades.check().unwrap_or_else(|error| fail(&error));

    // Loaded before placing, because the background's price is quoted against
    // the year's busiest day and --merge can raise it. Only a run that draws
    // needs it: tracking and backfilling read the calendar themselves, and
    // loading it here as well would parse the file twice and say anything it
    // has to say about it twice.
    let existing = match (&options.merge, options.track || options.backfill) {
        (Some(path), false) => load(path, &grid),
        _ => BTreeMap::new(),
    };
    let peak = existing
        .values()
        .copied()
        .max()
        .unwrap_or(0)
        .max(options.commits)
        .max(shades.min_peak());
    let ink = art::Ink {
        lit: options.commits,
        field: shades.commits(peak).field,
    };

    // What the shades actually come out as, which is not always what was asked
    // for: a busy year can push the letters below level 4, and a --commits too
    // small to outrun the background makes the whole thing invisible.
    let drawn = art::Shades {
        ink: art::level(ink.lit, peak),
        field: art::level(ink.field, peak),
    };
    // Only for a run that would draw *a flat count*. `--commits` is what a
    // plain `--write` puts on a lit day; neither tracking nor backfilling uses
    // it — both work out what a day needs from the year's real peak. Refusing
    // `--track --merge --background` over a busy year told the user their plan
    // was impossible when the only thing wrong was a flag that run does not
    // use, and `--backfill` ignores it for exactly the same reason.
    if !options.track && !options.backfill && shades.field > 0 && drawn.field >= drawn.ink {
        fail(&format!(
            "--commits {} puts the letters at level {} and the background at level {}, \
             so the letters would not show.\n  \
             In this year a letter day needs at least {} commits to sit above a \
             level-{} background.",
            options.commits,
            drawn.ink,
            drawn.field,
            thousands(art::commits_to_reach(shades.field + 1, peak)),
            shades.field,
        ));
    }

    let placed = art::place(&columns, &grid, options.top, options.start_week, ink)
        .unwrap_or_else(|error| fail(&error));
    if placed.skipped > 0 {
        eprintln!(
            "note: {} lit {} fell outside {} and {} dropped — the first and \
             last calendar columns are partial weeks, so {} of {} columns hold a \
             whole letter",
            placed.skipped,
            plural(placed.skipped, "pixel", "pixels"),
            grid.year,
            plural(placed.skipped, "was", "were"),
            grid.usable_weeks(),
            grid.weeks
        );
    }

    // Resolved, not as typed: a centred text keeps the column it was centred on,
    // which is the whole point of writing the plan down.
    if options.save {
        let spec = plan::Spec {
            text: options.text.to_uppercase(),
            year: options.year,
            start_week: placed.start_week,
            top: options.top,
            commits: options.commits,
            background: options.background,
            user: options.tracking.clone(),
            art: None,
        };
        spec.save(&options.plan_path)
            .unwrap_or_else(|error| fail(&error));
        // stderr, not stdout. Under `--format json` or `--format markdown`
        // stdout is a *document*: this was its first line, so
        // `--track --save --format json | jq .` handed a parser two lines of
        // prose and still exited 0, with an empty stderr — no signal
        // anywhere. Every other note a track run makes already goes here;
        // this was the single `println!` that could run ahead of the
        // document. It bit only on the run that writes the plan, so it read
        // as a flake on first use.
        eprintln!(
            "saved {} — from now on:\n  mossaic-art --track\n",
            options.plan_path.display()
        );
    }

    if options.track {
        track_progress(&options, &grid, &columns, &placed, shades);
        return;
    }
    if options.backfill {
        backfill(&options, &grid, &columns, &placed, shades);
        return;
    }

    let mut combined = existing.clone();
    for (day, count) in &placed.all() {
        // Saturating: the peak the whole costing model rests on is computed from
        // this map, and a `--merge` calendar is a file. Wrapping here reported a
        // peak of 8 for a year whose busiest day held four billion, and then
        // quoted a price to match it.
        let total = combined.entry(*day).or_insert(0);
        *total = total.saturating_add(*count);
    }

    let peak = combined.values().copied().max().unwrap_or(1);
    let art_level = art::level(options.commits, peak);
    let total = placed.total();
    println!(
        "{}  ·  {}  ·  {} of {} columns  ·  {} {}  ·  {} {}\n",
        options.text.to_uppercase(),
        grid.year,
        columns.len(),
        grid.weeks,
        placed.lit.len(),
        plural(placed.lit.len(), "day", "days"),
        thousands(total),
        plural(total, "commit", "commits"),
    );

    let palette = options
        .colour
        .enabled()
        .then(|| Palette::new(Appearance::Dark, Season::Default, true));
    println!(
        "{}\n",
        art::preview(&art::shading(&placed, shades), &grid, palette.as_ref())
    );

    // What the reader will actually be able to tell apart. Only interesting
    // once there are two shades to compare; against an empty graph the answer
    // is always "obviously".
    if shades.field > 0 {
        let (legibility, delta) = drawn.worst();
        println!(
            "background level {} under letters at level {}  ·  {} background {}, \
             {} each  ·  ΔE {delta:.0} at worst, {legibility}",
            drawn.field,
            drawn.ink,
            thousands(placed.field.len() as u32),
            plural(placed.field.len(), "day", "days"),
            ink.field,
        );
        match legibility {
            primer::Legibility::Faint => println!(
                "  -> {} and {} are neighbouring shades. On some themes they are all \
                 but the same colour;\n     leave two levels between them — \
                 --background {} is the safe one against level {}.",
                drawn.field,
                drawn.ink,
                drawn.ink.saturating_sub(2),
                drawn.ink
            ),
            primer::Legibility::Readable => println!(
                "  -> readable, but not at a glance on a small graph. \
                 --background {} reads more clearly.",
                drawn.ink.saturating_sub(3)
            ),
            primer::Legibility::Clear => {}
        }
        println!();
    }

    if !existing.is_empty() {
        // Shading is relative to the year's peak, so say plainly whether the
        // letters will actually stand out from what is already there.
        let rivals = existing
            .iter()
            .filter(|(day, count)| {
                !placed.lit.contains_key(*day) && art::level(**count, peak) >= art_level
            })
            .count();
        println!(
            "drawing over {} {} already active (busiest {})",
            existing.len(),
            plural(existing.len(), "day", "days"),
            existing.values().copied().max().unwrap_or(0)
        );
        println!(
            "peak after merge {peak}  ·  letters land at level {art_level}/4  ·  \
             {rivals} existing {} as bright or brighter",
            plural(rivals, "day", "days")
        );
        if art_level < 4 {
            let days: Vec<NaiveDate> = placed.lit.keys().copied().collect();
            if let Some(need) = art::commits_for_level(&days, &existing, 4) {
                println!(
                    "  -> for the brightest level, use --commits {need} ({} commits)",
                    thousands(need.saturating_mul(placed.lit.len() as u32))
                );
            }
        }
        if rivals > 6 {
            println!("  -> the letters will be competing with a lot of real activity");
        }
    }

    if let Some(path) = &options.snapshot {
        let body = art::snapshot(&combined, &grid, &options.login);
        std::fs::write(path, body)
            .unwrap_or_else(|error| fail(&format!("could not write {path:?}: {error}")));
        println!(
            "\nwrote {} — see it in the real renderer with:",
            path.display()
        );
        println!("  mossaic --file {}", path.display());
    }

    match (&options.repo, options.write) {
        (Some(repo), true) => {
            let (name, email) = art::identity();
            let name = options.name.unwrap_or(name);
            let email = options.email.unwrap_or(email);
            println!(
                "\ncommitting {} commits into {} as {name} <{email}>",
                thousands(total),
                repo.display()
            );
            let label = format!("art: {}", options.text.to_uppercase());
            let made = art::write_commits(&placed.all(), repo, &label, &name, &email)
                .unwrap_or_else(|error| fail(&error));
            println!(
                "made {} commits — nothing has been pushed.\n\n\
                 To publish, create an empty repo on GitHub and:\n\n  \
                 cd {}\n  git remote add origin git@github.com:<you>/<repo>.git\n  \
                 git push -u origin main\n\n\
                 To count towards the graph these must be on the default branch of a \
                 repo you own (not a fork), authored with an email registered to your \
                 GitHub account.",
                thousands(made as u32),
                repo.display()
            );
        }
        (Some(_), false) => println!("\n(add --write to create the commits; this was a dry run)"),
        (None, true) => fail("--write needs --repo DIR"),
        (None, false) => {}
    }
}

/// `--draw`: the editor, from opening the terminal to putting it back.
///
/// The loop is deliberately thin. Everything that decides anything lives in
/// [`mossaic::draw::Editor`], which holds no terminal — so the interesting
/// claims about this feature are checked by unit tests rather than by reading
/// a screen through a pseudo-terminal and hoping.
fn run_editor(options: &Options, grid: &Grid, name: &str, canvas: art::Canvas) {
    use ratatui::crossterm::event::{
        self, DisableMouseCapture, EnableMouseCapture, Event, KeyEventKind, KeyModifiers,
    };
    use ratatui::crossterm::execute;
    use ratatui::crossterm::terminal::{BeginSynchronizedUpdate, EndSynchronizedUpdate};

    let output = options.output.clone().unwrap_or_else(|| {
        // The picture's own name, lowercased and dashed, so a template opened
        // and saved lands somewhere predictable rather than on top of itself.
        let stem: String = name
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() {
                    c.to_ascii_lowercase()
                } else {
                    '-'
                }
            })
            .collect();
        PathBuf::from(format!("{}.art", stem.trim_matches('-')))
    });

    let start = options
        .start_week
        .unwrap_or_else(|| canvas.centred(grid).min(grid.weeks.saturating_sub(1)));
    let mut editor = mossaic::draw::Editor::new(canvas, *grid, start, output, options.commits);
    if editor.canvas.meta().name.is_none() {
        let mut meta = editor.canvas.meta().clone();
        meta.name = Some(name.to_string());
        editor.canvas.set_meta(meta);
    }

    let mut terminal = ratatui::try_init()
        .unwrap_or_else(|error| fail(&format!("--draw needs an interactive terminal ({error})")));
    // The editor takes the alternate screen and enables mouse reporting, and
    // until 0.7.0 had neither a panic hook nor a signal handler — so both of
    // the exits nobody writes code for left the terminal borrowed.
    mossaic::restore::guard_terminal();
    let mut out = std::io::stdout();
    let _ = execute!(out, EnableMouseCapture);
    let palette = mossaic::draw::palette();

    let outcome = (|| -> std::io::Result<()> {
        loop {
            let mut body = ratatui::layout::Rect::default();
            // Bracketed, like the chart's own loop: a terminal that understands
            // DEC 2026 then shows a whole frame rather than one caught halfway
            // through being painted. It is also what lets a test wait for a
            // *complete* frame instead of reading a torn one.
            execute!(out, BeginSynchronizedUpdate)?;
            terminal.draw(|frame| {
                mossaic::draw::render(frame, &editor, &palette);
                // The same rectangle the grid was drawn in, so a click lands on
                // the cell it was aimed at.
                let area = frame.area();
                body = ratatui::layout::Rect {
                    x: area.x,
                    y: area.y + 1,
                    width: area.width,
                    height: (mossaic::art::CANVAS_ROWS as u16) + 2,
                };
            })?;
            execute!(out, EndSynchronizedUpdate)?;
            let origin = mossaic::draw::grid_origin(body);

            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                    match editor.on_key(key.code, ctrl) {
                        mossaic::draw::Outcome::Quit => break,
                        mossaic::draw::Outcome::Save => {
                            if let Err(error) = editor.save() {
                                editor.status = error;
                            }
                        }
                        mossaic::draw::Outcome::Idle => {}
                    }
                }
                Event::Mouse(mouse) => editor.on_mouse(mouse, origin),
                _ => {}
            }
        }
        Ok(())
    })();

    let _ = execute!(out, DisableMouseCapture);
    let restored = ratatui::try_restore();
    if let Some(error) = [outcome.err(), restored.err()].into_iter().flatten().next() {
        fail(&format!("{error}"));
    }

    // Said after the terminal is back, so it is readable rather than painted
    // over by the alternate screen going away.
    if editor.dirty {
        eprintln!(
            "not saved — press s in the editor, or run it again and save to {}",
            editor.output.display()
        );
    } else if editor.output.exists() {
        println!("{}", editor.output.display());
        println!(
            "\ndraw it on a year:\n  mossaic-art --matrix {} --year {}",
            editor.output.display(),
            grid.year
        );
    }
}

/// `--list-templates`: the catalogue, with where each one came from.
fn show_templates(colour: bool) {
    let catalogue = templates::catalogue();
    // Read before the early return: a directory holding only broken files
    // used to print "no templates installed", which is the least helpful
    // true sentence available.
    let skipped = templates::skipped();
    if catalogue.is_empty() && skipped.is_empty() {
        println!("no templates installed");
        return;
    }
    let palette = colour.then(|| Palette::new(Appearance::Dark, Season::Default, true));
    let width = catalogue
        .iter()
        .map(|template| template.name.len())
        .max()
        .unwrap_or(0);

    println!(
        "{} {}:\n",
        catalogue.len(),
        plural(catalogue.len(), "template", "templates")
    );
    for template in &catalogue {
        let author = template
            .author()
            .map(|who| format!("  by {who}"))
            .unwrap_or_default();
        println!(
            "  {:<width$}  {}{author}",
            template.name,
            template.title(),
            width = width
        );
        if let Some(description) = template.description() {
            println!("  {:<width$}  {description}", "", width = width);
        }
        println!(
            "  {:<width$}  {} columns, {}\n",
            "",
            template.canvas.width(),
            template.origin,
            width = width
        );
        // A thumbnail, because a name and a sentence are not a picture and the
        // whole point of choosing one is what it looks like.
        for row in 0..art::CANVAS_ROWS {
            let mut line = String::from("    ");
            for week in 0..template.canvas.width() {
                let level = template.canvas.at(week, row);
                let block = art::SHADE_CHARS[usize::from(level).min(4)].1;
                match (&palette, level) {
                    (Some(palette), level) if level > 0 => {
                        let rgb = palette.levels[usize::from(level).min(4)];
                        line.push_str(&format!(
                            "\x1b[38;2;{};{};{}m{block}\x1b[0m",
                            rgb.0, rgb.1, rgb.2
                        ));
                    }
                    _ => line.push(block),
                }
            }
            println!("{line}");
        }
        println!();
    }
    // What was skipped, and why. `templates::read_dir`'s own doc comment
    // already called this command "the command you would reach for to find
    // out which one is broken" — and it named nothing, counted nothing and
    // wrote no byte to stderr. #57's walkthrough puts a first-time
    // contributor on exactly this path: `cp your-name.art templates/ &&
    // mossaic-art --list-templates`.
    if !skipped.is_empty() {
        println!(
            "{} {} skipped:",
            skipped.len(),
            plural(skipped.len(), "file was", "files were")
        );
        for broken in &skipped {
            println!("  {}: {}", broken.file, broken.why);
        }
        println!();
    }
    if let Some(first) = catalogue.first() {
        println!("draw one:  mossaic-art --template {}", first.name);
    }
}

/// Everything a run that draws a **picture** does, from preview to commits.
///
/// Deliberately a path of its own rather than a widening of the text one. The
/// two share the plan, the pricing and every report format that a machine
/// reads; what they do not share is language. A canvas has no letters and no
/// background, so a report that says "letters at level 4, background at level
/// 1" would be describing something that is not there.
fn run_canvas(options: &Options, grid: &Grid, name: &str, canvas: &art::Canvas) {
    let start = options.start_week.unwrap_or_else(|| canvas.centred(grid));
    if start >= grid.weeks {
        fail(&format!(
            "--start-week {start} is past the {} columns {} has",
            grid.weeks, grid.year
        ));
    }
    let (levels, skipped) = canvas.place(grid, start);
    if levels.is_empty() {
        fail(&format!(
            "nothing of the picture lands inside {} from week {start}",
            grid.year
        ));
    }
    if skipped > 0 {
        eprintln!(
            "note: {skipped} {} of the picture fell outside {} — the first and \
             last calendar columns are partial weeks, so a full-width picture \
             overhangs them. Try --start-week, or a narrower picture.",
            plural(skipped, "shade", "shades"),
            grid.year
        );
    }

    // Resolved, exactly as a text plan is: the picture is stored inline, so a
    // template edited next month cannot re-target a plan drawn from it today.
    if options.save {
        let spec = plan::Spec {
            text: name.to_string(),
            year: options.year,
            start_week: start,
            top: 0,
            commits: options.commits,
            background: 0,
            user: options.tracking.clone(),
            art: Some(canvas.to_art()),
        };
        spec.save(&options.plan_path)
            .unwrap_or_else(|error| fail(&error));
        // stderr, not stdout. Under `--format json` or `--format markdown`
        // stdout is a *document*: this was its first line, so
        // `--track --save --format json | jq .` handed a parser two lines of
        // prose and still exited 0, with an empty stderr — no signal
        // anywhere. Every other note a track run makes already goes here;
        // this was the single `println!` that could run ahead of the
        // document. It bit only on the run that writes the plan, so it read
        // as a flake on first use.
        eprintln!(
            "saved {} — from now on:\n  mossaic-art --track\n",
            options.plan_path.display()
        );
    }

    if options.track {
        track_canvas(options, grid, name, canvas, &levels, start);
        return;
    }

    let existing = match &options.merge {
        Some(path) => load(path, grid),
        None => BTreeMap::new(),
    };
    // `--commits` prices the *brightest* day, and every darker level is priced
    // against it by the same formula GitHub shades with. At the default of 4
    // that is 1, 2, 3, 4 commits for levels 1 to 4 — the smallest year in which
    // all five shades are distinct.
    let peak = existing
        .values()
        .copied()
        .max()
        .unwrap_or(0)
        .max(options.commits)
        .max(canvas.min_peak());
    let commits: BTreeMap<NaiveDate, u32> = levels
        .iter()
        .filter(|(_, level)| **level > 0)
        .map(|(date, level)| (*date, art::commits_to_reach(*level, peak)))
        .collect();
    let total = commits
        .values()
        .fold(0u32, |sum, count| sum.saturating_add(*count));

    if options.backfill {
        backfill_canvas(options, grid, &levels);
        return;
    }

    // The days the *calendar* holds, not the cells the canvas has. A
    // full-width picture is 7 x 53 = 371 cells against a year of 365, and the
    // table used to count all of them — disagreeing with the header directly
    // above it and with what `--write` makes, after a note that had just said
    // cells were dropped.
    let histogram = art::levels_histogram(&levels);
    println!(
        "{name}  ·  {}  ·  {} of {} columns  ·  {} {}  ·  {} {}\n",
        grid.year,
        canvas.width(),
        grid.weeks,
        commits.len(),
        plural(commits.len(), "day", "days"),
        thousands(total),
        plural(total, "commit", "commits"),
    );

    let palette = options
        .colour
        .enabled()
        .then(|| Palette::new(Appearance::Dark, Season::Default, true));
    println!("{}\n", art::preview(&levels, grid, palette.as_ref()));

    println!("  level  days   commits each");
    for level in (1..=4u8).rev() {
        if histogram[usize::from(level)] == 0 {
            continue;
        }
        println!(
            "  {level:>5}  {:>4}   {}",
            histogram[usize::from(level)],
            thousands(art::commits_to_reach(level, peak)),
        );
    }
    println!("  {:>5}  {:>4}   must stay dark", 0, histogram[0]);

    // Whether a reader will see a picture or a smudge. The pair measured is the
    // darkest and brightest the drawing actually uses: if those two are faint,
    // everything between them is worse.
    // Asked about the shades that land inside the year. A picture whose only
    // ink falls in the partial weeks drew nothing and still reported
    // `shades 0 4 · ΔE 70, clear`: the one check this project tells you to
    // read twice, passing on a drawing that does not exist. `closest_pair_of`
    // returns `None` for a single shade, so such a run now prints no verdict
    // at all rather than a flattering one.
    if let Some((low, high, legibility, delta)) = art::Canvas::closest_pair_of(&histogram) {
        let used: Vec<String> = art::Canvas::palette_of(&histogram)
            .iter()
            .map(u8::to_string)
            .collect();
        println!(
            "\n  shades {}  ·  closest pair {low} and {high}  ·  ΔE {delta:.0}, {legibility}",
            used.join(" ")
        );
        if legibility != primer::Legibility::Clear {
            println!(
                "  -> levels {low} and {high} are all but the same colour on some themes, so \
                 whatever\n     they separate will read as one shade for part of your \
                 audience. Leaving two\n     levels between the shades you need told apart is \
                 what fixes it."
            );
        }
    }
    println!();

    if let Some(path) = &options.snapshot {
        let mut combined = existing.clone();
        for (day, count) in &commits {
            let total = combined.entry(*day).or_insert(0);
            *total = total.saturating_add(*count);
        }
        let body = art::snapshot(&combined, grid, &options.login);
        std::fs::write(path, body)
            .unwrap_or_else(|error| fail(&format!("could not write {path:?}: {error}")));
        println!(
            "wrote {} — see it in the real renderer with:",
            path.display()
        );
        println!("  mossaic --file {}\n", path.display());
    }

    match (&options.repo, options.write) {
        (Some(repo), true) => {
            let (default_name, default_email) = art::identity();
            let who = options.name.clone().unwrap_or(default_name);
            let email = options.email.clone().unwrap_or(default_email);
            println!(
                "committing {} commits into {} as {who} <{email}>",
                thousands(total),
                repo.display()
            );
            let label = format!("art: {name}");
            let made = art::write_commits(&commits, repo, &label, &who, &email)
                .unwrap_or_else(|error| fail(&error));
            println!(
                "made {} commits — nothing has been pushed.\n\n\
                 To publish, create an empty repo on GitHub and:\n\n  \
                 cd {}\n  git remote add origin git@github.com:<you>/<repo>.git\n  \
                 git push -u origin main",
                thousands(made as u32),
                repo.display()
            );
        }
        (Some(_), false) => println!("(add --write to create the commits; this was a dry run)"),
        (None, true) => fail("--write needs --repo DIR"),
        (None, false) => {}
    }
}

/// `--track` for a picture: how far along it is, and what today owes.
fn track_canvas(
    options: &Options,
    grid: &Grid,
    name: &str,
    canvas: &art::Canvas,
    levels: &BTreeMap<NaiveDate, u8>,
    start: usize,
) {
    let colour = options.colour.enabled();
    let palette = colour.then(|| Palette::new(Appearance::Dark, Season::Default, true));
    let (who, actual) = observed(options, grid);
    let plan = plan::Plan::from_levels(name, grid, levels, start, canvas.width(), &actual);
    let today = options.now();

    // Every machine-read format is generic over the plan already, so a picture
    // reports through exactly the same code a text plan does. Only the human
    // one below needed writing, because only it uses words like "letters".
    if options.format != Format::Text {
        let year_total = actual
            .values()
            .fold(0u32, |sum, count| sum.saturating_add(*count));
        // The sweep, on the path that publishes. A picture used to pass
        // `None` here on the reasoning that it "is usually the full width of
        // the year, so there is no column to move it to" — true of the four
        // shipped templates and wrong about every picture narrower than the
        // year, which is the shape docs/ART.md asks contributors to draw.
        // The overhang it was guarding against is now measured by
        // `best_start_week_of` rather than assumed here, so a full-width
        // template still gets exactly `None` — for the reason, not by
        // refusing to look.
        let suggestion = plan::best_start_week_of(canvas, grid, &actual, today);
        let report = plan::Report::of(&plan, &who, year_total, today, suggestion);
        match options.format {
            Format::Json => println!(
                "{}",
                serde_json::to_string_pretty(&report)
                    .unwrap_or_else(|error| fail(&format!("could not encode the report: {error}")))
            ),
            Format::Markdown => println!("{}", report.markdown()),
            Format::Text => unreachable!("handled above"),
        }
        return;
    }

    // The placement, for the same reason the text path prints it below its
    // own header: tracking with a different `--start-week` compares against
    // a different plan and reports nonsense confidently. The text path had
    // "the plan N of M columns from week W"; the picture path had nothing,
    // and a picture is what the shipped consumer tracks.
    println!(
        "{name} · {} · week {}, {} {} — tracking {who}\n",
        grid.year,
        plan.start_week,
        plan.columns,
        plural(plan.columns, "column", "columns")
    );
    println!("{}\n", art::preview(levels, grid, palette.as_ref()));

    let (owing_days, owing_commits) = plan.owing();
    let drawn = plan.bright();
    let wanted = plan.letters().count();
    match plan.verdict() {
        plan::Verdict::Done => println!("  Drawn. Every day is the shade the picture asks for."),
        plan::Verdict::Reachable => println!(
            "  On track — {drawn} of {wanted} shaded {} right, \
             {owing_days} to go.",
            plural(wanted, "day is", "days are")
        ),
        plan::Verdict::Holed { holes } => {
            println!(
                "  Cannot be drawn cleanly — {holes} {} brighter than the \
                 picture wants,\n  and nothing takes a contribution away.",
                plural(holes, "day is", "days are")
            );
            // `holed` is the one verdict a reader cannot act on by
            // contributing more, so it is the one that most owes them a next
            // move. The letters path has said this since it had a sweep; the
            // picture path printed the diagnosis and stopped.
            match plan::best_start_week_of(canvas, grid, &actual, today) {
                Some((week, 0)) => println!("  --start-week {week} draws it cleanly."),
                Some((week, left)) if left < holes => println!(
                    "  --start-week {week} would leave {left} {} instead of {holes}.",
                    plural(left, "hole", "holes")
                ),
                _ => println!(
                    "  Every placement in {} runs into the same problem; an emptier\n  \
                     year is the way out.",
                    grid.year
                ),
            }
        }
    }

    println!("\n  level  days   done   owing   each");
    let histogram = canvas.histogram();
    for level in (1..=4u8).rev() {
        if histogram[usize::from(level)] == 0 {
            continue;
        }
        let at_level: Vec<&plan::Day> = plan
            .days
            .iter()
            .filter(|day| levels.get(&day.date).copied() == Some(level))
            .collect();
        let done = at_level.iter().filter(|day| day.done()).count();
        let short: u32 = at_level
            .iter()
            .fold(0u32, |sum, day| sum.saturating_add(day.short()));
        let each = at_level.first().map(|day| day.need).unwrap_or(0);
        println!(
            "  {level:>5}  {:>4}   {done:>4}   {:>5}   {}",
            at_level.len(),
            thousands(short),
            thousands(each),
        );
    }
    let dark: Vec<&plan::Day> = plan
        .days
        .iter()
        .filter(|day| day.want == plan::Want::Hole)
        .collect();
    println!(
        "  {:>5}  {:>4}   {:>4}   {:>5}   must stay dark",
        0,
        dark.len(),
        dark.iter().filter(|day| day.done()).count(),
        "-",
    );

    println!(
        "\n  still owing  {} {} · {} {}",
        thousands(owing_days as u32),
        plural(owing_days, "day", "days"),
        thousands(owing_commits),
        plural(owing_commits, "contribution", "contributions")
    );

    // What a day is owed turns on `want`, not on whether `need` is zero. Both
    // a day the picture wants dark and a day the picture does not cover have a
    // need of zero, and the advice for them is opposite: one must be left
    // alone or the drawing is damaged, the other is free. Reading the number
    // instead of the intent told people to stay dark on days that were none of
    // the plan's business — every day after the picture ends, for one.
    let describe = |day: &plan::Day| match day.want {
        plan::Want::Around => "outside the picture — nothing owed".to_string(),
        plan::Want::Hole => "must stay dark".to_string(),
        plan::Want::Lit if day.short() > 0 => format!(
            "{} of {} there, {} to go",
            thousands(day.have),
            thousands(day.need),
            thousands(day.short())
        ),
        plan::Want::Lit if day.over() > 0 => format!(
            "{} is past {}, which is a hole",
            thousands(day.have),
            thousands(day.ceiling.unwrap_or(0))
        ),
        plan::Want::Lit => "already the right shade".to_string(),
    };
    if plan.holds(today) {
        println!(
            "  today        {}",
            match plan.on(today) {
                Some(day) => describe(day),
                // No entry at all: outside the picture and with nothing on it,
                // which `from_levels` does not bother recording.
                None => "outside the picture — nothing owed".to_string(),
            }
        );
        if let Some(next) = today.succ_opt().filter(|next| plan.holds(*next)) {
            println!(
                "  tomorrow     {}",
                match plan.on(next) {
                    Some(day) => describe(day),
                    None => "outside the picture — nothing owed".to_string(),
                }
            );
        }
    }

    let holes = plan.holes();
    if !holes.is_empty() {
        println!(
            "\n  {} {} already too bright:",
            holes.len(),
            plural(holes.len(), "day", "days")
        );
        for day in holes.iter().take(8) {
            println!(
                "    {}  has {}, wants at most {}",
                day.date,
                thousands(day.have),
                thousands(day.ceiling.unwrap_or(0))
            );
        }
        if holes.len() > 8 {
            println!("    ... and {} more", holes.len() - 8);
        }
    }
    println!();
}

/// `--backfill` for a picture: commit what each day already past still owes.
fn backfill_canvas(options: &Options, grid: &Grid, levels: &BTreeMap<NaiveDate, u8>) {
    let (_, actual) = observed(options, grid);
    let plan = plan::Plan::from_levels("picture", grid, levels, 0, 0, &actual);
    let today = options.now();
    let owed: BTreeMap<NaiveDate, u32> = plan
        .days
        .iter()
        .filter(|day| day.date <= today && day.short() > 0)
        .map(|day| (day.date, day.short()))
        .collect();
    let total = owed
        .values()
        .fold(0u32, |sum, count| sum.saturating_add(*count));

    if owed.is_empty() {
        println!("nothing to catch up on — every day up to {today} is already right.");
        return;
    }
    println!(
        "{} {} short up to {today}, {} contributions in total",
        owed.len(),
        plural(owed.len(), "day is", "days are"),
        thousands(total)
    );
    match (&options.repo, options.write) {
        (Some(repo), true) => {
            let (default_name, default_email) = art::identity();
            let who = options.name.clone().unwrap_or(default_name);
            let email = options.email.clone().unwrap_or(default_email);
            let made = art::write_commits(&owed, repo, "art: catch up", &who, &email)
                .unwrap_or_else(|error| fail(&error));
            println!(
                "made {} commits — nothing has been pushed.",
                thousands(made as u32)
            );
        }
        (Some(_), false) => println!("(add --write to create them; this was a dry run)"),
        (None, true) => fail("--write needs --repo DIR"),
        (None, false) => println!("(--repo DIR --write would create them)"),
    }
}

/// The year as it actually stands: a saved response if one was given, otherwise
/// whatever `gh` reports. Shared by `--track` and `--backfill`, which ask the
/// same question of the same year and must never get different answers.
fn observed(options: &Options, grid: &Grid) -> (String, BTreeMap<NaiveDate, u32>) {
    match &options.merge {
        Some(path) => (path.display().to_string(), load(path, grid)),
        None => {
            // Cleaned where it enters, which is the rule the calendar already
            // follows: a login can arrive from a plan file, a plan file is a
            // file someone may have sent you, and every path below this prints
            // it — a header, an error, the report's `source`. A terminal
            // executes what it is written.
            let who = options
                .tracking
                .clone()
                .or_else(github::whoami)
                .map(|who| mossaic::printable(&who))
                .unwrap_or_else(|| {
                    fail("could not tell whose contributions to track — pass `--track USER`, or run `gh auth login`")
                });
            // Named, because whose year this is can come from a saved plan
            // rather than from the command line, and "gh was not found" gives no
            // hint about which login it was going to ask for.
            let calendar = github::fetch(&who, grid.year, options.now()).unwrap_or_else(|error| {
                fail(&format!(
                    "could not read {who}'s {} contributions: {error}",
                    grid.year
                ))
            });
            (who, plan::contributions(&calendar))
        }
    }
}

/// Commit what the plan is short, and nothing else.
///
/// A plain `--write` puts the same count on every lit day, which over an active
/// year is both wasteful and self-defeating: adding to the busiest day raises
/// the year's peak, and the peak is what every letter day is measured against.
/// A shortfall cannot do that. `need` is at most the peak already — the
/// brightest shade is three quarters of it — so topping a day up to `need`
/// never exceeds the busiest day and never moves the target. One pass, with no
/// fixed point to chase.
fn backfill(
    options: &Options,
    grid: &Grid,
    columns: &[[bool; art::GLYPH_ROWS]],
    placed: &art::Placed,
    shades: art::Shades,
) {
    let repo = options.repo.clone().unwrap_or_else(|| {
        fail("--backfill needs --repo DIR — the directory to make the commits in")
    });
    let (who, actual) = observed(options, grid);
    let plan = plan::Plan::build(
        &options.text,
        grid,
        placed,
        columns.len(),
        options.top,
        &actual,
        shades,
    );

    // Days already past, and only those. A day at or past what it needs
    // contributes nothing here, and neither does one whose job is to stay dark —
    // `short()` is zero for both.
    //
    // The date bound is the point of the mode. Back-dating is the only way to
    // reach a day that has gone by; a day still to come needs no help, and
    // whether GitHub even counts a future-dated commit is unverified (see
    // docs/ART.md). Writing the whole year would also mean pre-filling a
    // background onto days that have not happened.
    let today = options.now();
    let owed: BTreeMap<NaiveDate, u32> = plan
        .days
        .iter()
        .filter(|day| day.date < today && day.short() > 0)
        .map(|day| (day.date, day.short()))
        .collect();
    let total = owed.values().fold(0u32, |sum, n| sum.saturating_add(*n));
    let ahead = plan
        .days
        .iter()
        .filter(|day| day.date >= today && day.short() > 0)
        .count();

    println!(
        "{}  ·  {}  ·  backfilling against {who}\n",
        plan.text, plan.year
    );
    let (letter_days, letter_commits) = plan.owing();
    println!(
        "  letters     {letter_days} {} short, {} commits",
        plural(letter_days, "day", "days"),
        thousands(letter_commits)
    );
    if shades.field > 0 {
        let (field_days, field_commits) = plan.field_owing();
        println!(
            "  background  {field_days} {} short, {} commits",
            plural(field_days, "day", "days"),
            thousands(field_commits)
        );
    }
    println!(
        "  a day gets  what it is short of {}, never a flat count",
        thousands(plan.need)
    );
    // Only when there is something past to reach: before the year starts, "days
    // before 2026-08-19" for a 2027 plan names a date the plan has never heard
    // of, and the line below says the useful thing anyway.
    if !owed.is_empty() {
        println!("  reaching    days before {today}, which are the ones only back-dating reaches");
        if ahead > 0 {
            println!(
                "              {ahead} {} from {today} on {} short too, and left alone — \
                 contribute on those as they come",
                plural(ahead, "day", "days"),
                plural(ahead, "is", "are")
            );
        }
    }
    // An irreversible write is the worst place to leave this unsaid: the letters
    // can be finished and still read with holes in them, and no number of
    // commits changes that.
    if let plan::Verdict::Holed { holes } = plan.verdict() {
        println!(
            // "are" — 0.6.3's plural pass dropped the verb here, so the
            // sentence read "61 days inside the letters already lit".
            "\n  warning: {} cannot be drawn cleanly in {}{holes} {} inside the\n  \
             letters {} already lit, and nothing takes those away. Backfilling will\n  \
             brighten the letters, and the text will still read with holes in it.\n  \
             `mossaic-art --track` sweeps --start-week for a placement with fewer.",
            plan.text,
            plan.year,
            plural(holes, "day", "days"),
            plural(holes, "is", "are")
        );
    }

    if owed.is_empty() {
        match ahead {
            0 => println!("\nnothing to backfill — every day the plan wants is already there."),
            _ => {
                println!("\nnothing to backfill — every day the plan is short of is still to come.")
            }
        }
        return;
    }
    println!(
        "\n  {} {} across {} {}, earliest {}, latest {}",
        thousands(total),
        plural(total, "commit", "commits"),
        owed.len(),
        plural(owed.len(), "day", "days"),
        owed.keys().next().expect("not empty"),
        owed.keys().next_back().expect("not empty"),
    );

    if !options.write {
        println!("\n(add --write to create them; this was a dry run)");
        return;
    }

    let (name, email) = art::identity();
    let name = options.name.clone().unwrap_or(name);
    let email = options.email.clone().unwrap_or(email);
    println!(
        "\ncommitting {} commits into {} as {name} <{email}>",
        thousands(total),
        repo.display()
    );
    let label = format!("art: {}", plan.text);
    let made = art::write_commits(&owed, &repo, &label, &name, &email)
        .unwrap_or_else(|error| fail(&error));
    println!(
        "made {} commits — nothing has been pushed.\n\n\
         To publish, from {}:\n\n  \
         git push -u origin main\n\n\
         To count towards the graph these must be on the default branch of a repo \
         you own (not a fork), authored with an email registered to your GitHub \
         account. Run --track again afterwards: GitHub takes a few minutes to \
         recount.",
        thousands(made as u32),
        repo.display()
    );
}

/// How far along the plan is, what today owes, and whether the text can still
/// be drawn at all.
fn track_progress(
    options: &Options,
    grid: &Grid,
    columns: &[[bool; art::GLYPH_ROWS]],
    placed: &art::Placed,
    shades: art::Shades,
) {
    let colour = options.colour.enabled();
    let palette = colour.then(|| Palette::new(Appearance::Dark, Season::Default, true));
    let paint = |text: &str, colour: Option<mossaic::primer::Rgb>| match (colour, &palette) {
        (Some(colour), Some(_)) => format!(
            "\x1b[38;2;{};{};{}m{text}\x1b[0m",
            colour.0, colour.1, colour.2
        ),
        _ => text.to_string(),
    };
    let shade = |level: usize| palette.as_ref().map(|palette| palette.levels[level]);
    let danger = || palette.as_ref().map(|palette| palette.danger);

    let (who, actual) = observed(options, grid);

    let plan = plan::Plan::build(
        &options.text,
        grid,
        placed,
        columns.len(),
        options.top,
        &actual,
        shades,
    );
    // A day inside the letters only spoils them if it is brighter than the
    // background they would otherwise be — with no background, that is any
    // contribution at all.
    let hideable = plan.field_ceiling.unwrap_or(0);

    // Resolved once, and said out loud only when the plan's year has already
    // ended: `under_way` and not `holds` together mean today is past the last
    // day of it. There the today, tomorrow and next-seven-days lines are simply
    // absent with nothing to explain them, which reads like a fault.
    //
    // Deliberately silent for a year that has *not started*, which is the other
    // way to fall outside it. That is the first example in the help, the README
    // and docs/ART.md, and the report already answers it in full — "2027 has not
    // started. The first letter day is Mon Feb 8." A note there told people
    // their own year was wrong.
    let today = options.now();
    if plan.under_way(today) && !plan.holds(today) {
        eprintln!(
            "note: {today} is after {}, so this report has no today or tomorrow in \
             it — those lines cover the plan's own year.",
            plan.year
        );
    }

    // json and markdown are for machines and for messages; both carry every
    // number the text report prints, so a notification never has to be parsed
    // out of a screen.
    if options.format != Format::Text {
        let suggestion = plan::best_start_week(
            grid,
            columns.len(),
            options.top,
            columns,
            &actual,
            hideable,
            today,
        );
        let year_total = actual
            .values()
            .fold(0u32, |sum, count| sum.saturating_add(*count));
        let report = plan::Report::of(&plan, &who, year_total, today, suggestion);
        match options.format {
            Format::Json => println!(
                "{}",
                serde_json::to_string_pretty(&report).expect("a tree of numbers and strings")
            ),
            Format::Markdown => print!("{}", report.markdown()),
            Format::Text => unreachable!("handled below"),
        }
        return;
    }
    let (owing_days, owing_commits) = plan.owing();
    let holes = plan.holes();
    let total = actual
        .values()
        .fold(0u32, |sum, count| sum.saturating_add(*count));

    // The placement is part of the plan, and it lives in the command line —
    // tracking with a different --start-week than the text was drawn with
    // compares against a different plan entirely. Printing which one is on
    // screen makes that visible rather than baffling.
    println!(
        "{}  ·  {}  ·  week {}, {} {}  ·  tracking {who}\n",
        plan.text,
        plan.year,
        plan.start_week,
        plan.columns,
        plural(plan.columns, "column", "columns")
    );
    println!(
        "  the plan    {} of {} columns from week {}, on rows {}-{}",
        plan.columns,
        grid.weeks,
        plan.start_week,
        options.top,
        options.top + art::GLYPH_ROWS - 1
    );
    println!(
        "  the year    {} contributions{}",
        thousands(total),
        match plan.peak_day {
            Some(date) if plan.peak > 0 => format!(
                "  ·  busiest {} ({})",
                date.format("%b %-d"),
                thousands(plan.peak)
            ),
            _ => String::new(),
        }
    );
    println!(
        "              a letter day has to reach {} to match it",
        thousands(plan.need)
    );
    if shades.field > 0 {
        let (legibility, delta) = shades.worst();
        println!(
            "  the shades  letters at level {}, background at level {}  ·  \
             ΔE {delta:.0} at worst, {legibility}",
            shades.ink, shades.field
        );
        println!(
            "              a background day has to reach {}{}",
            thousands(plan.field_need),
            match plan.field_ceiling {
                Some(most) => format!(" and stay under {}", thousands(most + 1)),
                None => String::new(),
            }
        );
    }
    println!();

    let bright = plan.bright();
    let letters = plan.letters().count();
    const BAR: usize = 28;
    let filled = (bright * BAR).checked_div(letters).unwrap_or(0);
    let bar = format!("{}{}", "".repeat(filled), "".repeat(BAR - filled));
    println!(
        "  letters     {}  {} of {} bright",
        paint(&bar, shade(4)),
        bright,
        letters
    );
    if owing_days > 0 {
        println!(
            "  owing       {owing_days} {} short, {} contributions between them",
            plural(owing_days, "day", "days"),
            thousands(owing_commits)
        );
    }
    // The background gets its own bar rather than being folded into the
    // letters': three hundred easy days would drown out seven hard ones, and
    // the letters are the point.
    let field_days = plan.field().count();
    if field_days > 0 {
        let done = plan.field_bright();
        let filled = (done * BAR).checked_div(field_days).unwrap_or(0);
        let bar = format!("{}{}", "".repeat(filled), "".repeat(BAR - filled));
        println!(
            "  background  {}  {} of {} at level {}",
            paint(&bar, shade(usize::from(shades.field))),
            done,
            field_days,
            shades.field
        );
        let (field_owing_days, field_owing_commits) = plan.field_owing();
        if field_owing_days > 0 {
            println!(
                "  owing       {field_owing_days} background {} short, {} contributions",
                plural(field_owing_days, "day", "days"),
                thousands(field_owing_commits)
            );
        }
    }
    if !holes.is_empty() {
        println!(
            "  holes       {}",
            paint(
                &format!(
                    "{} {} lit inside the letters and cannot be unlit",
                    holes.len(),
                    plural(holes.len(), "day is", "days are")
                ),
                danger()
            )
        );
    }
    if plan.around() > 0 {
        println!(
            "  around      {} {} outside the text with contributions",
            plan.around(),
            plural(plan.around(), "day", "days")
        );
    }

    println!("\n{}\n", plan::preview(&plan, grid, palette.as_ref()));

    match plan.verdict() {
        plan::Verdict::Done => {
            println!("  {}", paint(&format!("{} is drawn.", plan.text), shade(4)))
        }
        plan::Verdict::Reachable => println!(
            "  {} can still be drawn cleanly — {}.",
            plan.text,
            match plan.field_owing().1 {
                0 => format!("{} contributions to go", thousands(owing_commits)),
                owed => format!(
                    "{} for the letters, {} for the field",
                    thousands(owing_commits),
                    thousands(owed)
                ),
            }
        ),
        plan::Verdict::Holed { holes } => {
            println!(
                "  {}",
                paint(
                    &format!("{} cannot be drawn cleanly in {}.", plan.text, plan.year),
                    danger()
                )
            );
            println!(
                "    {holes} {} inside the letters already have contributions, and\n    \
                 nothing takes those away — the text would read with holes in it.",
                plural(holes, "day", "days")
            );
            match plan::best_start_week(
                grid,
                columns.len(),
                options.top,
                columns,
                &actual,
                hideable,
                today,
            ) {
                Some((week, left)) if left < holes => {
                    println!("    --start-week {week} would leave {left} instead of {holes}.")
                }
                _ => println!(
                    "    Every placement in {} runs into the same problem; an emptier\n    \
                     year is the way out.",
                    plan.year
                ),
            }
        }
    }

    // What to do next, which is the question this is really for.
    if !plan.under_way(today) {
        let first = plan
            .letters()
            .map(|day| day.date)
            .next()
            .unwrap_or(grid.first);
        println!(
            "\n  {} has not started. The first letter day is {} {}.",
            plan.year,
            plan::weekday(first),
            first.format("%b %-d")
        );
        return;
    }
    println!();
    for (label, date) in [
        ("today", today),
        ("tomorrow", today.succ_opt().unwrap_or(today)),
    ] {
        if !grid.holds(date) {
            continue;
        }
        let line = match plan.on(date) {
            Some(day) if day.want == plan::Want::Lit && day.short() > 0 => format!(
                "a letter day — {} needed, {} there, {} to go",
                thousands(day.need),
                thousands(day.have),
                thousands(day.short())
            ),
            Some(day) if day.want == plan::Want::Lit => {
                "a letter day — already bright enough".to_string()
            }
            // Over its ceiling, and nothing undoes it. Which loss it is
            // depends on where the day sits: inside the letters it is a hole,
            // and calling that "too many for level 0" when no background was
            // asked for describes a shade that does not exist.
            Some(day) if day.over() > 0 && day.want == plan::Want::Hole => {
                format!(
                    "inside the letters and already lit ({}) — a permanent hole",
                    thousands(day.have)
                )
            }
            Some(day) if day.over() > 0 => format!(
                "background — {} contributions, {} too many for level {}",
                thousands(day.have),
                thousands(day.over()),
                shades.field
            ),
            Some(day) if day.need > 0 && day.short() > 0 => format!(
                "background — {} needed, {} there, {} to go{}",
                thousands(day.need),
                thousands(day.have),
                thousands(day.short()),
                match day.ceiling {
                    Some(most) => format!(" (and no more than {})", thousands(most)),
                    None => String::new(),
                }
            ),
            Some(day) if day.need > 0 => "background — already the right shade".to_string(),
            // Inside the letters with nothing asked of it. Committing here is
            // the one mistake that cannot be worked off afterwards, so saying
            // so before the day arrives is the whole point of reading this.
            Some(day) if day.want == plan::Want::Hole => {
                "inside the letters — keep it dark, or it becomes a permanent hole".to_string()
            }
            Some(day) if day.have > 0 => "not part of the text, and already lit".to_string(),
            _ => "not part of the text — anything committed on it shows".to_string(),
        };
        println!(
            "  {label:<11} {} {}  ·  {line}",
            plan::weekday(date),
            date.format("%b %-d")
        );
    }

    let upcoming = plan.schedule(today, 7);
    if upcoming
        .iter()
        .any(|day| day.want != plan::Want::Around || day.need > 0)
    {
        println!("\n  the next seven days");
        for day in upcoming {
            let what = match day.want {
                plan::Want::Lit if day.short() > 0 => {
                    format!("letter  {} to go", thousands(day.short()))
                }
                plan::Want::Lit => "letter  done".to_string(),
                // Already past its ceiling, before the advice arrives. Telling
                // someone to keep a day dark that is already lit is worse than
                // saying nothing: inside the letters it is a hole and permanent,
                // and outside it is a field day that has run too bright.
                plan::Want::Hole if day.over() > 0 => "hole".to_string(),
                _ if day.over() > 0 => "too bright".to_string(),
                _ if day.short() > 0 => {
                    format!("field   {} to go", thousands(day.short()))
                }
                _ if day.need > 0 => "field   done".to_string(),
                // Nothing to do, which is not the same as nothing to say: this
                // is a day inside the letters that has to stay empty.
                plan::Want::Hole => "keep dark".to_string(),
                _ => "".to_string(),
            };
            println!(
                "    {} {}   {what}",
                plan::weekday(day.date),
                day.date.format("%b %-d")
            );
        }
    }

    let (past, past_commits) = plan.overdue(today);
    let (future, future_commits) = plan.ahead(today);
    if past == 0 && future == 0 {
        return;
    }
    println!("\n  the rest of the year");
    println!(
        "    {future} letter {} still to come, {} contributions",
        plural(future, "day", "days"),
        thousands(future_commits)
    );
    if past > 0 {
        // The command has to be the one that does what the sentence above it
        // says. A plain `--write` would put a flat `--commits` on every lit day,
        // including the ones already bright — and with the text typed out it
        // would not even read the plan, so the placement could differ from the
        // one just reported on.
        println!(
            "    {past} letter {} already past, {} contributions — only back-dated\n    \
             commits reach those:\n\n      mossaic-art {}--backfill --repo ../art --write\n",
            plural(past, "day", "days"),
            thousands(past_commits),
            match options.plan_loaded {
                true => String::new(),
                // No saved plan, so the placement has to be spelled out or the
                // command would draw a differently-placed text.
                false => format!(
                    "{} --year {} --start-week {} --top {} {}",
                    plan.text,
                    plan.year,
                    plan.start_week,
                    options.top,
                    match shades.field {
                        0 => String::new(),
                        level => format!("--background {level} "),
                    }
                ),
            }
        );
        if !options.plan_loaded {
            println!(
                "    (or `--save` the plan once, and it is just \
                 `mossaic-art --backfill …`)"
            );
        }
    }
}

/// Every glyph, side by side — what a contributed one actually looks like next
/// to its neighbours, which is the thing a table of quoted strings cannot show.
fn show_font(colour: bool) {
    const PER_ROW: usize = 8;
    let palette = Palette::new(Appearance::Dark, Season::Default, true);
    let paint = |cell: &str, lit: bool| {
        if !colour {
            return if lit {
                cell.to_string()
            } else {
                "  ".to_string()
            };
        }
        let shade = palette.levels[if lit { 4 } else { 0 }];
        format!(
            "\x1b[38;2;{};{};{}m{cell}\x1b[0m",
            shade.0, shade.1, shade.2
        )
    };

    let characters: Vec<char> = art::alphabet().collect();
    println!(
        "{} glyphs, {}x{} each — write any of them with mossaic-art TEXT\n",
        characters.len(),
        art::GLYPH_COLS,
        art::GLYPH_ROWS
    );
    for chunk in characters.chunks(PER_ROW) {
        let labels: Vec<String> = chunk
            .iter()
            .map(|character| format!("{:<12}", art::label(*character)))
            .collect();
        println!("  {}", labels.join("").trim_end());
        for row in 0..art::GLYPH_ROWS {
            let mut line = String::from("  ");
            for character in chunk {
                let glyph = art::glyph(*character).expect("from the font itself");
                for lit in glyph[row].chars() {
                    line.push_str(&paint("██", lit == '#'));
                }
                line.push_str("  ");
            }
            println!("{line}");
        }
        println!();
    }
}

/// Every glyph the font has, drawn as contribution cells and written to a PNG.
///
/// The font view above is for a terminal; this is for everywhere else. A
/// README cannot show block sextants — too few systems have a font for them —
/// and it cannot show the symbols either, since half of them are
/// ambiguous-width. An image of the real rasteriser's output has neither
/// problem, and it is what the glyphs will actually look like on a graph.
fn write_font_sheet(path: &Path) {
    /// Glyphs to a row. Thirteen is what makes the sheet about twice as wide
    /// as it is tall, which is the shape a README column wants.
    const PER_ROW: usize = 13;
    /// Bright glyphs on a light-green field, which is how the art at the top
    /// of the README is drawn — and the arrangement that keeps every day of a
    /// year green rather than leaving 300 of them dark.
    const INK: u8 = 4;
    const FIELD: u8 = 1;

    // Space draws nothing, so a blank block in the middle of the sheet would
    // read as a mistake rather than as a glyph.
    let characters: Vec<char> = art::alphabet().filter(|c| !c.is_whitespace()).collect();
    /// Field between glyphs, and around them. One cell was not enough: with
    /// the gutter the same shade as the field, neighbouring glyphs had no
    /// boundary and a row of letters read as one long smear.
    const GAP: usize = 2;
    let rows = characters.len().div_ceil(PER_ROW);
    let width = PER_ROW * (art::GLYPH_COLS + GAP) + GAP;
    let height = rows * (art::GLYPH_ROWS + GAP) + GAP;

    // The field first, so the gaps between glyphs are the field rather than
    // holes in it, then each glyph's lit days over the top.
    let mut levels: Vec<Vec<Option<u8>>> = vec![vec![Some(FIELD); height]; width];
    for (index, character) in characters.iter().enumerate() {
        let glyph = art::glyph(*character).expect("from the font itself");
        let left = GAP + (index % PER_ROW) * (art::GLYPH_COLS + GAP);
        let top = GAP + (index / PER_ROW) * (art::GLYPH_ROWS + GAP);
        for (row, line) in glyph.iter().enumerate() {
            for (column, lit) in line.chars().enumerate() {
                if lit == '#' {
                    levels[left + column][top + row] = Some(INK);
                }
            }
        }
    }

    let palette = Palette::new(Appearance::Dark, Season::Default, true);
    let image = graphics::sheet(&levels, &palette, (9, 19));
    png::write(path, &image, palette.canvas)
        .unwrap_or_else(|error| fail(&format!("could not write {}: {error}", path.display())));
    println!(
        "wrote {}{}x{} px, {} glyphs",
        path.display(),
        image.width,
        image.height,
        characters.len()
    );
}

/// Existing contributions from a saved `gh api graphql` response.
fn load(path: &Path, grid: &Grid) -> BTreeMap<NaiveDate, u32> {
    // `from_file` names the path itself now, so re-prefixing would print it
    // twice — and it used to quote the path where every other path message
    // in these tools does not.
    let calendar =
        github::from_file(&path.to_string_lossy(), None).unwrap_or_else(|error| fail(&error));
    let kept: BTreeMap<NaiveDate, u32> = calendar
        .days()
        .filter(|day| day.count > 0 && grid.holds(day.date))
        .map(|day| (day.date, day.count))
        .collect();
    // A calendar for another year filters down to nothing, and everything
    // downstream is then correct about an empty year: 9,527 contributions read
    // as none, and an impossible plan reads as trivially reachable. `--year` is
    // the flag most likely to be typed as a one-off over a saved plan, so the
    // mismatch is easy to reach and silent when it happens.
    if kept.is_empty() && calendar.days().any(|day| day.count > 0) {
        eprintln!(
            "note: {} holds no contributions in {} — it covers {}. Tracking \
             against an empty year.",
            path.display(),
            grid.year,
            calendar.year
        );
    }
    kept
}

/// What `--track` prints.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Format {
    Text,
    Json,
    Markdown,
}

impl Options {
    /// What "today" means for this run: `--today` when it was given, otherwise
    /// the clock.
    ///
    /// An input rather than an ambient fact, which is what makes a report
    /// reproducible — and what lets a plan be asked about a day that has not
    /// arrived yet.
    fn now(&self) -> NaiveDate {
        self.today.unwrap_or_else(|| Local::now().date_naive())
    }
}

struct Options {
    format: Format,
    track: bool,
    tracking: Option<String>,
    /// Commit each day's shortfall rather than a flat count.
    backfill: bool,
    /// What "today" means. `None` reads the clock.
    today: Option<NaiveDate>,
    /// Whether the plan was read from a file, which decides how the advice at
    /// the end of `--track` spells the command it suggests.
    plan_loaded: bool,
    text: String,
    year: i32,
    commits: u32,
    /// The level the background sits at. Zero leaves it empty.
    background: u8,
    top: usize,
    start_week: Option<usize>,
    /// Where the plan is read from and written to.
    plan_path: PathBuf,
    /// Write the plan after resolving it.
    save: bool,
    merge: Option<PathBuf>,
    snapshot: Option<PathBuf>,
    repo: Option<PathBuf>,
    write: bool,
    login: String,
    name: Option<String>,
    email: Option<String>,
    colour: Colour,
    /// The picture being drawn, and what to call it, for a run that draws a
    /// canvas rather than text.
    ///
    /// Beside `text` rather than replacing it, so that every path that reads
    /// `text` is exactly the code it was: a canvas run branches away at the
    /// top of `main` and never reaches them.
    canvas: Option<(String, art::Canvas)>,
    /// Where `--draw` writes the picture it made.
    output: Option<PathBuf>,
    /// Open the editor instead of drawing straight to the terminal.
    draw: bool,
}

fn parse_args() -> Option<Options> {
    let mut options = Options {
        format: Format::Text,
        track: false,
        tracking: None,
        backfill: false,
        today: None,
        plan_loaded: false,
        text: String::new(),
        plan_path: PathBuf::from(plan::DEFAULT_SPEC),
        save: false,
        year: Local::now().year(),
        commits: 4,
        background: 0,
        top: 1,
        start_week: None,
        merge: None,
        snapshot: None,
        repo: None,
        write: false,
        login: "preview".to_string(),
        name: None,
        email: None,
        colour: Colour::default(),
        canvas: None,
        output: None,
        draw: false,
    };

    let mut template: Option<String> = None;
    let mut matrix: Option<PathBuf> = None;
    let mut picture: Option<PathBuf> = None;
    let mut image_options = mossaic::image::Options::default();
    let mut list_templates = false;
    let mut font = false;
    let mut png_path: Option<PathBuf> = None;
    let mut track = false;
    let mut tracking: Option<String> = None;
    let mut args = Args::from_env("mossaic-art");

    while let Some(arg) = args.next_arg() {
        // Past a bare `--`, every argument is the text — checked before the
        // flag names, or `-- --year` would still match the `--year` arm and
        // `--` would mean "only the next one", which is nobody's convention.
        if args.past_end_of_options() {
            if options.text.is_empty() {
                options.text = art::canonical(&arg).unwrap_or_else(|error| fail(&error));
            } else {
                // The trap `--` sets for a first-time user: it means
                // *everything* after it, as it does in `ls` and `git`, so
                // options have to come first. Say that rather than leaving
                // them to work it out.
                fail(&format!(
                    "unexpected argument {arg:?} — everything after -- is the text, \
                     so put the options before it"
                ));
            }
            continue;
        }
        match arg.as_str() {
            "-h" | "--help" => {
                println!("{HELP}");
                return None;
            }
            "-V" | "--version" => {
                println!("mossaic-art {}", env!("CARGO_PKG_VERSION"));
                return None;
            }
            "-y" | "--year" => options.year = args.year("--year"),
            // Every one of these is bounded where it is read, so the cast that
            // follows cannot misrepresent it. `--commits -1` used to come out
            // as four billion, and `--start-week -1` as `usize::MAX`, where
            // building a date from it panicked.
            "--commits" => {
                // A million a day is far past any real need — the brightest
                // shade is three quarters of the year's peak — and it keeps a
                // whole year of them inside a u32.
                options.commits = args.number_in("--commits", "count", 1..=1_000_000) as u32;
            }
            "--background" | "--bg" => {
                // Bounded here so the error names the flag; `Shades::check`
                // then decides whether the pair can draw anything.
                options.background = args.number_in("--background", "level", 0..=4) as u8;
            }
            "--top" => {
                let rows = (art::WEEKDAYS - art::GLYPH_ROWS) as i64;
                options.top = args.number_in("--top", "row", 0..=rows) as usize;
            }
            "--start-week" => {
                // A loose bound here, because the tight one depends on the year
                // and the text: `place` knows both and refuses what will not
                // fit, naming the last column that would.
                options.start_week =
                    Some(args.number_in("--start-week", "column", 0..=60) as usize);
            }
            "--backfill" => options.backfill = true,
            "--today" => {
                let raw = args.value("--today");
                let date = NaiveDate::parse_from_str(&raw, "%Y-%m-%d").unwrap_or_else(|_| {
                    fail(&format!("--today wants a date as YYYY-MM-DD, not {raw:?}"))
                });
                if !YEARS.contains(&date.year()) {
                    fail(&format!(
                        "--today {raw} is outside the years these tools work in, \
                         {} to {}",
                        YEARS.start(),
                        YEARS.end()
                    ));
                }
                options.today = Some(date);
            }
            "--merge" => options.merge = Some(args.value("--merge").into()),
            "--snapshot" => options.snapshot = Some(args.value("--snapshot").into()),
            "--repo" => options.repo = Some(args.value("--repo").into()),
            "--write" => options.write = true,
            "--login" => options.login = args.value("--login"),
            "--name" => options.name = Some(args.value("--name")),
            "--email" => options.email = Some(args.value("--email")),
            "--color" | "--colour" => {
                let raw = args.value("--color");
                options.colour = Colour::parse(&raw).unwrap_or_else(|| {
                    fail(&format!("--color wants auto, always or never, not {raw:?}"))
                });
            }
            "--no-colour" | "--no-color" => options.colour = Colour::Never,
            "--format" => {
                options.format = match args.value("--format").as_str() {
                    "text" => Format::Text,
                    "json" => Format::Json,
                    "markdown" | "md" => Format::Markdown,
                    other => fail(&format!(
                        "unknown format {other:?} — text, json or markdown"
                    )),
                }
            }
            "--plan" => options.plan_path = args.value("--plan").into(),
            "--save" => options.save = true,
            "--template" => template = Some(args.value("--template")),
            "--image" => picture = Some(args.value("--image").into()),
            "--invert" => image_options.invert = true,
            "--dither" => image_options.dither = true,
            "--matrix" | "--file" => matrix = Some(args.value("--matrix").into()),
            "--list-templates" => list_templates = true,
            "--output" | "-o" => options.output = Some(args.value("--output").into()),
            "--draw" => options.draw = true,
            "--font" => font = true,
            "--png" => png_path = Some(PathBuf::from(args.value("--png"))),
            "--track" => {
                track = true;
                // An optional user follows, if the next argument is not a flag.
                if args.peek_value() {
                    tracking = args.next_arg();
                }
            }
            // `is_positional` rather than a bare `starts_with('-')`: after a
            // bare `--`, an argument that looks like a flag is text. The
            // hyphen is a glyph the font draws and three documents list, and
            // it could not be typed in the position they put it in.
            other if !args.is_positional(other) => {
                let hint = if options.text.is_empty() {
                    " — if that is the text, write it after --"
                } else {
                    " — try --help"
                };
                fail(&format!("unknown option {other:?}{hint}"))
            }
            other if options.text.is_empty() => {
                // Expanded here rather than at every use: the plan is saved
                // uppercased and read back by the tracker, and `:star:` has to
                // survive both. A character does.
                options.text = art::canonical(other).unwrap_or_else(|error| fail(&error));
            }
            other => fail(&format!("unexpected argument {other:?}")),
        }
    }

    // The same rule, for the three flags that named a companion and were
    // then ignored without it. #26 settled the principle in the maintainer's
    // own words — "They are side effects and inputs the user explicitly
    // asked for … Either honour them or refuse the combination" — and
    // enumerated `--snapshot`, `--write` and `--file`, all three of which
    // are refused above. These were missed.
    //
    // Refusing rather than honouring, deliberately: honouring `--png` would
    // mean deciding what a PNG of a preview, a template list, a tracking
    // report and a backfill each *are*, and `--snapshot` plus
    // `mossaic --file --png` already covers the one people want. Refusing
    // keeps that door open.
    //
    // The cost of the silence was the shape a script cannot see:
    // `mossaic-art --template dragon --png preview.png` in a workflow printed
    // a cheerful report, exited 0 and produced nothing, so the next step read
    // a file that was not there — or, in a job that regenerates art,
    // republished the previous run's stale PNG.
    for (flag, ignored, needs, what) in [
        (
            "--png",
            png_path.is_some() && !font,
            "--font",
            "writes the glyph sheet",
        ),
        (
            "-o",
            options.output.is_some() && !options.draw,
            "--draw",
            "names the file the editor saves to",
        ),
        (
            "--format",
            args.was_typed("--format") && !track,
            "--track",
            "chooses how the tracking report is written",
        ),
    ] {
        if ignored {
            fail(&format!("{flag} {what} — it needs {needs}"));
        }
    }

    if list_templates {
        show_templates(options.colour.enabled());
        return None;
    }

    // One picture, from one place. Two sources on one command line would mean
    // guessing which was meant, and the guess would be silent.
    let sources = [
        ("--template", template.is_some()),
        ("--matrix", matrix.is_some()),
        ("--image", picture.is_some()),
        ("a TEXT argument", !options.text.is_empty()),
    ];
    let given: Vec<&str> = sources
        .iter()
        .filter(|(_, present)| *present)
        .map(|(name, _)| *name)
        .collect();
    if given.len() > 1 {
        fail(&format!(
            "{} both draw the picture — pick one",
            given.join(" and ")
        ));
    }

    // A picture uses the whole week and carries its own shades, so neither of
    // these means anything to one. Refused rather than ignored, and only when
    // actually typed: `--top` has a default, and failing on a default nobody
    // chose would make every picture command need a flag to unset it.
    if template.is_some() || matrix.is_some() || picture.is_some() {
        for (flag, why) in [
            (
                "top",
                "chooses which rows the letters sit on; a picture uses the whole week",
            ),
            (
                "background",
                "shades the field behind the letters; a picture names its own shade for every day",
            ),
            (
                "bg",
                "shades the field behind the letters; a picture names its own shade for every day",
            ),
        ] {
            if args.was_typed(flag) {
                fail(&format!("--{flag} {why}"));
            }
        }
    }

    if let Some(name) = &template {
        let found = templates::find(name).unwrap_or_else(|error| fail(&error));
        options.canvas = Some((found.title().to_string(), found.canvas));
    }
    // Said plainly rather than ignored: both change what a picture looks like,
    // so a run where they do nothing is a run that drew something other than
    // what was asked for.
    for (flag, given) in [
        ("--invert", image_options.invert),
        ("--dither", image_options.dither),
    ] {
        if given && picture.is_none() {
            fail(&format!(
                "{flag} describes how to read an image — it needs --image"
            ));
        }
    }
    if let Some(path) = &picture {
        let canvas = mossaic::image::load(path, image_options).unwrap_or_else(|error| fail(&error));
        let name = canvas
            .meta()
            .name
            .clone()
            .unwrap_or_else(|| "picture".to_string());
        options.canvas = Some((name, canvas));
    }
    if let Some(path) = &matrix {
        let body = std::fs::read_to_string(path)
            .unwrap_or_else(|error| fail(&format!("could not read {}: {error}", path.display())));
        let canvas = art::Canvas::parse(&body)
            .unwrap_or_else(|error| fail(&format!("{}: {error}", path.display())));
        let name = canvas.meta().name.clone().unwrap_or_else(|| {
            path.file_stem()
                .and_then(|stem| stem.to_str())
                .unwrap_or("picture")
                .to_string()
        });
        options.canvas = Some((name, canvas));
    }

    // After the loop, so that flags on either side of it are all in hand.
    if font {
        match &png_path {
            Some(path) => write_font_sheet(path),
            None => show_font(options.colour.enabled()),
        }
        return None;
    }
    // A saved plan fills in whatever was not typed. Typed flags always win, so
    // `--year 2028` against a saved 2027 plan is a one-off, not a surprise.
    // Set before the plan is read, so that the `is_none` check below sees a
    // user typed on this command line. Assigning them afterwards is what threw
    // the saved one away: `tracking` is `None` for a bare `--track`, so a plan
    // that named a user was loaded and then overwritten with nothing.
    options.track = track;
    options.tracking = tracking;
    // The editor is a source of its own: `--draw` with nothing else starts on a
    // blank year rather than complaining there is nothing to draw.
    if options.draw && options.canvas.is_none() && options.text.is_empty() {
        let blank = art::Canvas::blank(art::CANVAS_COLS).expect("53 is a canvas width");
        options.canvas = Some(("untitled".to_string(), blank));
    }

    match (
        options.text.is_empty() && options.canvas.is_none(),
        options.plan_path.exists(),
    ) {
        (true, true) => {
            let spec = plan::Spec::load(&options.plan_path).unwrap_or_else(|error| fail(&error));
            options.plan_loaded = true;
            options.text = spec.text;
            if !args.was_typed("year") {
                options.year = spec.year;
            }
            if !args.was_typed("top") {
                options.top = spec.top;
            }
            if !args.was_typed("commits") {
                options.commits = spec.commits;
            }
            if !args.was_typed("background") && !args.was_typed("bg") {
                options.background = spec.background;
            }
            if !args.was_typed("start-week") {
                options.start_week = Some(spec.start_week);
            }
            if options.tracking.is_none() {
                options.tracking = spec.user;
            }
            // A saved picture is the picture. `text` is then its name rather
            // than something to run through the font, so the two are swapped
            // over here and the text path is never entered.
            if let Some(canvas) = spec.art.as_deref() {
                let canvas = art::Canvas::parse(canvas).unwrap_or_else(|error| {
                    fail(&format!("{}: {error}", options.plan_path.display()))
                });
                options.canvas = Some((options.text.clone(), canvas));
                options.text = String::new();
            }
        }
        (true, false) => fail(&format!(
            "nothing to draw.\n\n  \
             mossaic-art VYNCINT --year 2027        draw something\n  \
             mossaic-art --template dragon          draw a picture instead\n  \
             mossaic-art VYNCINT --year 2027 --save remember it, then just \
             `mossaic-art --track`\n\n\
             (no plan at {})",
            options.plan_path.display()
        )),
        _ => {}
    }
    // One reports and the other writes; running both from one command line
    // would mean guessing which was meant.
    if options.track && options.backfill {
        fail("--track reports on the plan and --backfill commits to it — pick one");
    }
    // Tracking writes nothing, so a flag asking it to was doing nothing at all —
    // silently, which is worse than refusing. Distinct from `--commits`, a tuning
    // parameter tracking genuinely has no use for; these ask for a side effect.
    if options.track {
        for (flag, asked) in [
            ("--snapshot", options.snapshot.is_some()),
            ("--write", options.write),
            ("--repo", options.repo.is_some()),
        ] {
            if asked {
                fail(&format!(
                    "--track reports on the plan and writes nothing, so {flag} would \
                     do nothing. Drop one of them."
                ));
            }
        }
    }
    Some(options)
}

fn fail(message: &str) -> ! {
    eprintln!("mossaic-art: {message}");
    std::process::exit(2)
}