draftwright 0.6.1

Dimensioned engineering drawings from STEP, with SVG, PDF and editable DXF output.
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
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
//! Finished-item footprints for sheet choice; reserved layout bands are never fill.
use crate::layout::{Rect, margin};
use crate::model::{Analysis, Plan};

/// Maintainer's initial target (2026-10-12), as a share of usable paper.
pub const FILL_BAND: [f64; 2] = [0.60, 0.85];
/// Clearance around each drawn item, page mm.
pub const FILL_CLEARANCE: f64 = 1.0;
/// Minimum visible opening across a hole or slot, page mm. Small edge treatments do
/// not set the whole-sheet scale; their sizes are stated by callouts.
pub const MIN_OPENING: f64 = 0.8;
/// The smallest scale the automatic choice offers, whatever the part (1:10).
pub const ABSOLUTE_FLOOR: f64 = 0.1;
pub fn absolute_floor(units: crate::units::Units) -> f64 {
    if units.is_mm() {
        ABSOLUTE_FLOOR
    } else {
        1. / 96.
    }
}

pub fn min_legible_scale(analysis: &Analysis) -> f64 {
    min_legible_scale_in(analysis, crate::units::Units::Mm)
}
pub fn min_legible_scale_in(analysis: &Analysis, units: crate::units::Units) -> f64 {
    let needed =
        min_geometry_scale_in(analysis, units).max(crate::dims::recess_chain_scale(analysis));
    crate::units::scales(units)
        .iter()
        .copied()
        .rev()
        .find(|s| *s >= needed)
        .unwrap_or(needed)
}

/// Geometry floor, before the estimated room for labels inside slot chains.
/// A finished drawing may prove those labels readable with outward arrows.
#[cfg(test)]
pub(crate) fn min_geometry_scale(analysis: &Analysis) -> f64 {
    min_geometry_scale_in(analysis, crate::units::Units::Mm)
}
pub(crate) fn min_geometry_scale_in(analysis: &Analysis, units: crate::units::Units) -> f64 {
    let opening = analysis
        .features
        .iter()
        .filter_map(|f| {
            let key = match f.kind.as_str() {
                "hole" => "diameter",
                "slot" => "width",
                _ => return None,
            };
            f.parameters
                .get(key)?
                .as_f64()
                .filter(|v| v.is_finite() && *v > 0.0)
        })
        .fold(f64::INFINITY, f64::min);
    let longest = (0..3)
        .map(|k| analysis.envelope[1][k] - analysis.envelope[0][k])
        .fold(0.0, f64::max);
    let needed = (MIN_OPENING / opening)
        .max(20.0 / longest.max(1e-12))
        .max(absolute_floor(units));
    crate::units::scales(units)
        .iter()
        .copied()
        .rev()
        .find(|s| *s >= needed)
        .unwrap_or(needed)
}

/// Minimum primary step span: the dimension font's printed capital height, mm.
/// The 3 mm em includes unused font space; a 2.5 mm flange can still exceed its ink.
pub const MIN_STEP_SPAN: f64 = crate::dims::CAP;

fn step_spans<'a>(
    analysis: &'a Analysis,
    plan: &'a Plan,
) -> impl Iterator<Item = (&'a str, f64, f64)> {
    plan.dimensions
        .iter()
        .filter(|d| d.placed.is_some())
        .flat_map(move |d| {
            let scale = plan
                .views
                .iter()
                .find(|v| v.id == d.view)
                .map_or(0.0, |v| v.scale);
            d.measurements.iter().filter_map(move |m| {
                if !matches!(m.parameter.as_str(), "step.length" | "step_position.length") {
                    return None;
                }
                let f = analysis
                    .features
                    .iter()
                    .find(|f| f.id == m.feature && f.kind == "turned_step")?;
                let length =
                    f.parameters.get("hi")?.as_f64()? - f.parameters.get("lo")?.as_f64()?;
                (length.is_finite() && length > 0.0).then_some((m.feature.as_str(), length, scale))
            })
        })
}

/// Primary axial step spans need at least one capital height on paper. A collision-free
/// label alone does not make a compressed profile readable. Small treatments
/// stated by notes (grooves, chamfers and radii) do not set this floor. Baseline
/// stations still owe the physical interval they replace; enlarged detail owners
/// use their own scale, never the parent sheet's.
pub fn illegible_steps(analysis: &Analysis, plan: &Plan) -> usize {
    let mut checked = std::collections::BTreeSet::new();
    step_spans(analysis, plan)
        .filter(|(_, length, scale)| length * scale + 1e-6 < MIN_STEP_SPAN)
        .filter(|(feature, _, _)| checked.insert(*feature))
        .count()
}

/// Existing printed-step minimum, before snapping to a standard sheet scale.
/// Only applicable when every owning view follows the common sheet scale.
pub(crate) fn min_step_scale(analysis: &Analysis, plan: &Plan) -> f64 {
    step_spans(analysis, plan)
        .map(|(_, length, _)| (MIN_STEP_SPAN - 1e-6) / length)
        .fold(0.0, f64::max)
}

fn include(b: &mut Rect, p: [f64; 2]) {
    b[0] = b[0].min(p[0]);
    b[1] = b[1].min(p[1]);
    b[2] = b[2].max(p[0]);
    b[3] = b[3].max(p[1]);
}

fn include_arrow(b: &mut Rect, [tip, tail]: [[f64; 2]; 2]) {
    let normal = [tail[1] - tip[1], tip[0] - tail[0]];
    let k = crate::dims::ARROW_HALF / normal[0].hypot(normal[1]).max(1e-12);
    include(b, tip);
    include(b, [tail[0] + k * normal[0], tail[1] + k * normal[1]]);
    include(b, [tail[0] - k * normal[0], tail[1] - k * normal[1]]);
}

/// Union area of axis-aligned item footprints, without double-counting their intersections.
pub fn union_area(boxes: &[Rect]) -> f64 {
    let mut xs: Vec<f64> = boxes.iter().flat_map(|b| [b[0], b[2]]).collect();
    xs.sort_by(f64::total_cmp);
    xs.dedup();
    xs.windows(2)
        .map(|x| {
            let mut ys: Vec<[f64; 2]> = boxes
                .iter()
                .filter(|b| b[0] < x[1] && b[2] > x[0])
                .map(|b| [b[1], b[3]])
                .collect();
            ys.sort_by(|a, b| a[0].total_cmp(&b[0]));
            let mut end = f64::NEG_INFINITY;
            let mut height = 0.0;
            for y in ys {
                height += (y[1] - y[0].max(end)).max(0.0);
                end = end.max(y[1]);
            }
            (x[1] - x[0]) * height
        })
        .sum()
}

/// Furniture outside the title block: scale, projection symbol and section marks/captions.
/// These use the same resolved paper geometry and font metrics as the renderer.
pub fn furniture_footprints(analysis: &Analysis, plan: &Plan) -> Vec<Rect> {
    furniture_bounds(analysis, &plan.sheet, &plan.views)
}

pub(crate) fn furniture_bounds(
    analysis: &Analysis,
    sheet: &crate::model::PlannedSheet,
    views: &[crate::model::PlannedView],
) -> Vec<Rect> {
    let mut out = Vec::new();
    let text_box = |text: &str, size: f64, at: [f64; 2]| {
        let laid = crate::title_block::lay(text, size);
        [
            at[0] + laid.min[0],
            at[1] + laid.min[1],
            at[0] + laid.max[0],
            at[1] + laid.max[1],
        ]
    };
    let scale = format!("SCALE {}", sheet.scale);
    out.push(text_box(
        &scale,
        crate::title_block::TEXT,
        crate::title_block::scale_note(sheet.title_block, &scale),
    ));
    if let Some(symbol) = &sheet.projection_symbol {
        let mut b = [
            f64::INFINITY,
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::NEG_INFINITY,
        ];
        for c in &symbol.curves {
            let r = c.bbox();
            include(&mut b, [r[0], r[1]]);
            include(&mut b, [r[2], r[3]]);
        }
        if b.iter().all(|x| x.is_finite()) {
            out.push(b);
        }
    }
    for v in views.iter().filter(|v| v.sheet == sheet.number) {
        if let Some(d) = &v.detail {
            out.push(text_box(
                &crate::detail::caption(d),
                crate::section::FONT_SIZE,
                crate::detail::caption_at(v),
            ));
            if let Some(source) = views.iter().find(|s| s.id == d.source_view) {
                let (_, at) = crate::detail::marker(analysis, d, source, views, sheet.page, &[]);
                out.push(text_box(&d.label, crate::section::FONT_SIZE, at));
            }
        }
    }
    for v in views
        .iter()
        .filter(|v| v.sheet == sheet.number && v.cut.is_some())
    {
        // Invariant: The caller selected this view by its cut being Some.
        let cut = v.cut.as_ref().expect("section cut");
        // Invariant: Planned cameras come from the fixed views or checked section/detail cameras, with nonparallel axes.
        let view = haecceity::hlr::View::new(v.direction, v.up).expect("planned view");
        let half = crate::model::extent(analysis, &view).0[1] * v.scale / 2.0;
        out.push(text_box(
            &format!("SECTION {}–{}", cut.label, cut.label),
            crate::section::FONT_SIZE,
            [v.at[0], v.at[1] - half - 7.0],
        ));
        if let Some(m) = views.iter().find(|m| m.id == cut.marked_in) {
            // Invariant: Planned cameras come from the fixed views or checked section/detail cameras, with nonparallel axes.
            let view = haecceity::hlr::View::new(m.direction, m.up).expect("planned view");
            let centre = crate::model::extent(analysis, &view).1;
            let at = |p| {
                let q = view.map(p);
                let q = m.broken.as_ref().map_or(q, |b| b.map(q));
                [
                    m.at[0] + m.scale * (q[0] - centre[0]),
                    m.at[1] + m.scale * (q[1] - centre[1]),
                ]
            };
            let [lo, hi] = analysis.envelope;
            let a = at([lo[0], cut.origin[1], lo[2]]);
            let b = at([hi[0], cut.origin[1], hi[2]]);
            let (ink, letters) = crate::section::cutting_plane(
                a[0].min(b[0]) - crate::section::OVERRUN,
                a[0].max(b[0]) + crate::section::OVERRUN,
                at(cut.origin)[1],
            );
            if let Some(b) = crate::output::items_bbox(&ink) {
                out.push(b);
            }
            out.extend(letters.map(|at| text_box(&cut.label, crate::section::FONT_SIZE, at)));
        }
    }
    out
}

/// Drawn bounds per item, including witnesses and leaders, excluding border and title block.
/// Principal views use the projected part envelope; the isometric uses its measured bounds.
pub fn footprints(analysis: &Analysis, plan: &Plan) -> Vec<Rect> {
    footprints_with_notes(analysis, plan, true, true)
}

fn footprints_with_notes(
    analysis: &Analysis,
    plan: &Plan,
    notes: bool,
    furniture: bool,
) -> Vec<Rect> {
    let mut out = Vec::new();
    for v in &plan.views {
        let b = if v.id == "v:iso" && v.direction == crate::model::VIEWS[3].1 {
            let b = analysis.drawing_iso_bounds();
            [
                v.at[0] + v.scale * b[0],
                v.at[1] + v.scale * b[1],
                v.at[0] + v.scale * b[2],
                v.at[1] + v.scale * b[3],
            ]
        } else {
            let (size, _) = crate::detail::crop_extent(analysis, v);
            [
                v.at[0] - v.scale * size[0] / 2.0,
                v.at[1] - v.scale * size[1] / 2.0,
                v.at[0] + v.scale * size[0] / 2.0,
                v.at[1] + v.scale * size[1] / 2.0,
            ]
        };
        out.push(b);
    }
    // A profile-corner angle is placed only where it is already clear and is dropped otherwise:
    // it never takes part in choosing the paper or scale.
    for p in plan
        .dimensions
        .iter()
        .filter(|d| {
            !d.measurements
                .iter()
                .any(|m| m.parameter == crate::dims::PROFILE_ANGLE)
        })
        .filter_map(|d| d.placed.as_ref())
    {
        let mut b = p.label_box;
        for q in p.lines.iter().flatten() {
            include(&mut b, *q);
        }
        for a in &p.arrows {
            include_arrow(&mut b, *a);
        }
        out.push(b);
    }
    for p in plan.gdt.iter().filter_map(|g| g.placed.as_ref()) {
        let mut b = p.label_box;
        for q in p.lines.iter().chain(&p.strokes).chain(&p.arrows).flatten() {
            include(&mut b, *q);
        }
        for arc in &p.arcs {
            include(&mut b, [arc[0] - arc[2], arc[1] - arc[2]]);
            include(&mut b, [arc[0] + arc[2], arc[1] + arc[2]]);
        }
        for q in p.fills.iter().flatten() {
            include(&mut b, *q);
        }
        for a in &p.arrows {
            include_arrow(&mut b, *a);
        }
        out.push(b);
    }
    if notes {
        out.extend(plan.notes_block.iter().map(|n| n.cells));
    }
    out.extend(
        plan.tables
            .iter()
            .filter_map(|t| t.placed.as_ref().map(|p| p.cells)),
    );
    if let Some(t) = &plan.hole_table {
        out.extend(
            t.blocks
                .iter()
                .filter_map(|t| t.placed.as_ref().map(|p| p.cells)),
        );
    }
    for b in &plan.balloons {
        let mut r = [
            b.at[0] - b.radius,
            b.at[1] - b.radius,
            b.at[0] + b.radius,
            b.at[1] + b.radius,
        ];
        if let Some(label) = b.label_box {
            include(&mut r, [label[0], label[1]]);
            include(&mut r, [label[2], label[3]]);
        }
        for q in b.leader.iter().flatten() {
            include(&mut r, *q);
        }
        out.push(r);
    }
    for p in plan.requirements.iter().filter_map(|r| r.placed.as_ref()) {
        let mut b = p.label_box;
        include(&mut b, [p.glyph[0], p.glyph[1]]);
        include(&mut b, [p.glyph[2], p.glyph[3]]);
        out.push(b);
    }
    if furniture {
        out.extend(furniture_footprints(analysis, plan));
    }
    out
}

/// Footprints that stand against the frame rather than inside the frame gutter: tables, hole
/// tables, the radius table, notes blocks, sheet requirements beside the title block, and page
/// furniture. Each is the same rectangle [`footprints`] reports.
pub(crate) fn framed_footprints(analysis: &Analysis, plan: &Plan) -> Vec<Rect> {
    let mut out: Vec<Rect> = plan
        .tables
        .iter()
        .filter_map(|t| t.placed.as_ref().map(|p| p.cells))
        .chain(
            plan.hole_table
                .iter()
                .chain(&plan.hole_tables)
                .flat_map(|t| {
                    t.blocks
                        .iter()
                        .filter_map(|b| b.placed.as_ref().map(|p| p.cells))
                }),
        )
        .chain(
            plan.radius_table
                .iter()
                .filter_map(|t| t.table.placed.as_ref().map(|p| p.cells)),
        )
        .chain(
            plan.notes_block
                .iter()
                .chain(&plan.radius_notes_block)
                .map(|n| n.cells),
        )
        .collect();
    for p in plan.requirements.iter().filter_map(|r| r.placed.as_ref()) {
        let mut b = p.label_box;
        include(&mut b, [p.glyph[0], p.glyph[1]]);
        include(&mut b, [p.glyph[2], p.glyph[3]]);
        out.push(b);
    }
    out.extend(furniture_footprints(analysis, plan));
    out
}

/// Ink owned by the selected views, without page furniture.
/// Per-view hole schedules count here, for clipping, but not in [`footprints`]: the
/// planner's own fit and fill measures keep their established inputs (and cost).
pub(crate) fn view_ink(analysis: &Analysis, plan: &Plan) -> Vec<Rect> {
    let mut out = footprints_with_notes(analysis, plan, false, false);
    for t in &plan.hole_tables {
        out.extend(
            t.blocks
                .iter()
                .filter_map(|t| t.placed.as_ref().map(|p| p.cells)),
        );
    }
    out.extend(plan.captions.iter().map(|c| c.ink));
    for v in &plan.views {
        out.extend(v.line_work.iter().flat_map(|w| &w.curves).map(|c| c.bbox()));
    }
    out
}

/// Clipping is a feasibility gate, independently of the finding score. Include
/// strokes, arrows, captions and late furniture on their actual carrying page.
pub(crate) fn inside_frames(analysis: &Analysis, plan: &Plan) -> bool {
    std::iter::once(&plan.sheet)
        .chain(&plan.sheets)
        .all(|sheet| {
            let mut local = plan.clone();
            local.sheet = sheet.clone();
            local.views.retain(|v| v.sheet == sheet.number);
            let carries = |id: &str| local.views.iter().any(|v| v.id == id);
            local.dimensions.retain(|d| carries(&d.view));
            local.gdt.retain(|g| carries(&g.view));
            local.balloons.retain(|b| carries(&b.view));
            local.captions.retain(|c| c.sheet == sheet.number);
            local.tables.retain(|t| t.sheet == sheet.number);
            local.hole_table = local.hole_table.filter(|t| t.sheet == sheet.number);
            local.hole_tables.retain(|t| t.sheet == sheet.number);
            if sheet.number > 1 {
                local.notes_block = None;
                local.radius_notes_block = None;
                local.radius_table = None;
                local.requirements.clear();
            }
            // Frame furniture and frame-corner tables sit against the frame; views and
            // annotation ink keep the gutter inside it ([`crate::layout::margin`]).
            let mut framed = furniture_footprints(analysis, &local);
            framed.extend(local.hole_tables.iter().flat_map(|t| {
                t.blocks
                    .iter()
                    .filter_map(|b| b.placed.as_ref().map(|p| p.cells))
            }));
            // Tables stand in frame corners too.
            let tables: Vec<Rect> = local
                .tables
                .iter()
                .filter_map(|t| t.placed.as_ref().map(|p| p.cells))
                .chain(local.hole_table.iter().flat_map(|t| {
                    t.blocks
                        .iter()
                        .filter_map(|b| b.placed.as_ref().map(|p| p.cells))
                }))
                .collect();
            // So do the sheet requirements set beside the title block.
            let requirements: Vec<Rect> = local
                .requirements
                .iter()
                .filter_map(|r| r.placed.as_ref())
                .map(|p| {
                    let mut b = p.label_box;
                    include(&mut b, [p.glyph[0], p.glyph[1]]);
                    include(&mut b, [p.glyph[2], p.glyph[3]]);
                    b
                })
                .collect();
            framed.extend(tables.iter().chain(&requirements).copied());
            let mut ink = footprints_with_notes(analysis, &local, false, false);
            ink.retain(|b| !tables.contains(b) && !requirements.contains(b));
            ink.extend(local.captions.iter().map(|c| c.ink));
            for v in &local.views {
                ink.extend(v.line_work.iter().flat_map(|w| &w.curves).map(|c| c.bbox()));
            }
            // Notes blocks stand in a frame corner, as tables do.
            framed.extend(
                local
                    .notes_block
                    .iter()
                    .chain(&local.radius_notes_block)
                    .map(|n| n.cells),
            );
            framed.extend(
                local
                    .radius_table
                    .iter()
                    .filter_map(|t| t.table.placed.as_ref().map(|p| p.cells)),
            );
            ink.extend(crate::iso_caption::section_text_obstacles(
                analysis,
                sheet,
                &plan.views,
            ));
            // Rendering trims detail markers at the frame. That must not make a
            // clipped automatic candidate appear feasible: test the complete ring,
            // and settle its letter with the renderer's own annotation obstacles.
            let labels: Vec<_> = local
                .dimensions
                .iter()
                .filter_map(|d| d.placed.as_ref().map(|p| p.label_box))
                .chain(
                    local
                        .gdt
                        .iter()
                        .filter_map(|g| g.placed.as_ref().map(|p| p.label_box)),
                )
                .chain(local.balloons.iter().filter_map(|b| b.label_box))
                .collect();
            let mut avoid = labels;
            avoid.extend(
                local
                    .dimensions
                    .iter()
                    .filter_map(|d| d.placed.as_ref())
                    .flat_map(|p| &p.lines)
                    .map(|line| {
                        [
                            line[0][0].min(line[1][0]) - 0.5,
                            line[0][1].min(line[1][1]) - 0.5,
                            line[0][0].max(line[1][0]) + 0.5,
                            line[0][1].max(line[1][1]) + 0.5,
                        ]
                    }),
            );
            for detail in plan.views.iter().filter_map(|v| v.detail.as_ref()) {
                if let Some(source) = plan
                    .views
                    .iter()
                    .find(|v| v.id == detail.source_view && v.sheet == sheet.number)
                {
                    let (circle, at) = crate::detail::marker(
                        analysis,
                        detail,
                        source,
                        &plan.views,
                        sheet.page,
                        &avoid,
                    );
                    ink.push(circle.bbox());
                    let laid = crate::dims::font().text(&detail.label, crate::section::FONT_SIZE);
                    ink.push([
                        at[0] + laid.min[0],
                        at[1] + laid.min[1],
                        at[0] + laid.max[0],
                        at[1] + laid.max[1],
                    ]);
                }
            }
            let on_frame = |b: &Rect| {
                b[0] >= crate::layout::FRAME - 1e-6
                    && b[1] >= crate::layout::FRAME - 1e-6
                    && b[2] <= sheet.page[0] - crate::layout::FRAME + 1e-6
                    && b[3] <= sheet.page[1] - crate::layout::FRAME + 1e-6
            };
            framed.iter().all(on_frame)
                && ink.into_iter().enumerate().all(|(i, b)| {
                    // View outlines keep their whole stroke inside the frame. Thinner ink
                    // (a witness or centre line, a crop edge) may end on the frame line itself:
                    // its stroke stays under the frame's own, so nothing is clipped.
                    let stroke = if i < local.views.len() {
                        crate::output::layer_styles()[0].1.width / 2.0
                    } else {
                        0.0
                    };
                    b[0] >= margin() + stroke - 1e-6
                        && b[1] >= margin() + stroke - 1e-6
                        && b[2] <= sheet.page[0] - margin() - stroke + 1e-6
                        && b[3] <= sheet.page[1] - margin() - stroke + 1e-6
                })
        })
}

/// Usable-area share. Clip at the border and subtract title-block intersections from the union.
pub fn fill(analysis: &Analysis, plan: &Plan) -> f64 {
    fill_boxes(plan, footprints(analysis, plan))
}

/// Source-only notes keep their paper size at every scale. After PMI covers engine
/// dimensions, counting this furniture as diagram fill can favour tiny geometry on
/// smaller paper. Keep the full footprint for fitting and reported fill, but compare
/// the dimensioned drawing itself when choosing between valid PMI/GD&T candidates.
/// Enlargement-only searches keep their established ranking: fixed notes cannot
/// induce a scale reduction there.
pub(crate) fn selection_fill(analysis: &Analysis, plan: &Plan, compaction_possible: bool) -> f64 {
    if compaction_possible
        && !plan.gdt.is_empty()
        && !plan.notes.is_empty()
        && plan.notes.iter().all(|n| n.id.starts_with("pmi:"))
        && crate::dims::pmi_policy::carries(analysis)
    {
        fill_boxes(plan, footprints_with_notes(analysis, plan, false, true))
    } else {
        plan.sheet.fill
    }
}

fn fill_boxes(plan: &Plan, boxes: Vec<Rect>) -> f64 {
    let [w, h] = plan.sheet.page;
    let mut tb = plan.sheet.title_block;
    tb[3] = crate::title_block::top(tb);
    let boxes: Vec<Rect> = boxes
        .into_iter()
        .map(|b| {
            [
                (b[0] - FILL_CLEARANCE).max(margin()),
                (b[1] - FILL_CLEARANCE).max(margin()),
                (b[2] + FILL_CLEARANCE).min(w - margin()),
                (b[3] + FILL_CLEARANCE).min(h - margin()),
            ]
        })
        .filter(|b| b[0] < b[2] && b[1] < b[3])
        .collect();
    let in_title: Vec<Rect> = boxes
        .iter()
        .map(|b| {
            [
                b[0].max(tb[0]),
                b[1].max(tb[1]),
                b[2].min(tb[2]),
                b[3].min(tb[3]),
            ]
        })
        .filter(|b| b[0] < b[2] && b[1] < b[3])
        .collect();
    (union_area(&boxes) - union_area(&in_title))
        / ((w - 2.0 * margin()) * (h - 2.0 * margin()) - (tb[2] - tb[0]) * (tb[3] - tb[1]))
}

/// Bounded measured correction: trim only empty off-paper reservation, then adjust a free row.
/// A failed estimate can leave an orientation view cramped below an otherwise clear row.
/// Lift the entire row together (preserving projection alignment and every dimension), then
/// fit the orientation view against the measured blocks, once. Never move pinned content.
/// Reconcile conservative section bands with settled ink before spilling onto another page.
/// Principal projections and their dimensions stay aligned; free sections may use another gap.
fn correct_sections(analysis: &Analysis, plan: &mut Plan) {
    if !plan.views.iter().any(|v| v.cut.is_some())
        || plan.spec.views.values().any(|v| v.place.is_some())
    {
        return;
    }
    let bounds = footprints(analysis, plan);
    let mut groups = bounds[..plan.views.len()].to_vec();
    for d in &plan.dimensions {
        let Some(p) = &d.placed else { continue };
        let Some(i) = plan.views.iter().position(|v| v.id == d.view) else {
            return;
        };
        include(&mut groups[i], [p.label_box[0], p.label_box[1]]);
        include(&mut groups[i], [p.label_box[2], p.label_box[3]]);
        for q in p.lines.iter().flatten() {
            include(&mut groups[i], *q);
        }
        for arrow in &p.arrows {
            include_arrow(&mut groups[i], *arrow);
        }
    }
    for (i, v) in plan.views.iter().enumerate() {
        for curve in v.line_work.iter().flat_map(|w| &w.curves) {
            let b = curve.bbox();
            include(&mut groups[i], [b[0], b[1]]);
            include(&mut groups[i], [b[2], b[3]]);
        }
        if let Some(detail) = &v.detail {
            let laid = crate::dims::font()
                .text(&crate::detail::caption(detail), crate::section::FONT_SIZE);
            let at = crate::detail::caption_at(v);
            include(&mut groups[i], [at[0] + laid.min[0], at[1] + laid.min[1]]);
            include(&mut groups[i], [at[0] + laid.max[0], at[1] + laid.max[1]]);
            if let Some(j) = plan.views.iter().position(|p| p.id == detail.source_view) {
                let (circle, at) = crate::detail::marker(
                    analysis,
                    detail,
                    &plan.views[j],
                    &plan.views,
                    plan.sheet.page,
                    &[],
                );
                let b = circle.bbox();
                include(&mut groups[j], [b[0], b[1]]);
                include(&mut groups[j], [b[2], b[3]]);
                let laid = crate::dims::font().text(&detail.label, crate::section::FONT_SIZE);
                include(&mut groups[j], [at[0] + laid.min[0], at[1] + laid.min[1]]);
                include(&mut groups[j], [at[0] + laid.max[0], at[1] + laid.max[1]]);
            }
        }
        if let Some(cut) = &v.cut {
            // Invariant: Planned cameras come from the fixed views or checked section/detail cameras, with nonparallel axes.
            let projection = haecceity::hlr::View::new(v.direction, v.up).expect("section view");
            let half = crate::model::extent(analysis, &projection).0[1] * v.scale / 2.;
            let laid = crate::dims::font().text(
                &format!("SECTION {}–{}", cut.label, cut.label),
                crate::section::FONT_SIZE,
            );
            let at = [v.at[0], v.at[1] - half - 7.];
            include(&mut groups[i], [at[0] + laid.min[0], at[1] + laid.min[1]]);
            include(&mut groups[i], [at[0] + laid.max[0], at[1] + laid.max[1]]);
            if let Some(j) = plan.views.iter().position(|w| w.id == cut.marked_in) {
                let parent = &plan.views[j];
                let projection =
                    // Invariant: Planned cameras come from the fixed views or checked section/detail cameras, with nonparallel axes.
                    haecceity::hlr::View::new(parent.direction, parent.up).expect("parent view");
                let (x0, x1, y) = crate::model::cutting_line(analysis, parent, &projection, cut);
                let (ink, letters) = crate::section::cutting_plane(x0, x1, y);
                if let Some(b) = crate::output::items_bbox(&ink) {
                    include(&mut groups[j], [b[0], b[1]]);
                    include(&mut groups[j], [b[2], b[3]]);
                }
                let laid = crate::dims::font().text(&cut.label, crate::section::FONT_SIZE);
                for at in letters {
                    include(&mut groups[j], [at[0] + laid.min[0], at[1] + laid.min[1]]);
                    include(&mut groups[j], [at[0] + laid.max[0], at[1] + laid.max[1]]);
                }
            }
        }
    }

    let [w, h] = plan.sheet.page;
    let drawable = [
        margin() + 2.,
        margin() + 2.,
        w - margin() - 2.,
        h - margin() - 2.,
    ];
    let mut obstacles = vec![plan.sheet.title_block];
    let mut candidate = plan.clone();
    for (i, v) in candidate
        .views
        .iter_mut()
        .enumerate()
        .filter(|(_, v)| v.id != "v:iso")
    {
        let b = groups[i];
        v.area = [b[0] - 1., b[1] - 1., b[2] + 1., b[3] + 1.];
        if v.cut.is_none() {
            obstacles.push(v.area);
        }
    }
    for v in candidate.views.iter_mut().filter(|v| v.cut.is_some()) {
        let b = v.area;
        let size = [b[2] - b[0], b[3] - b[1]];
        let inside = b[0] >= drawable[0]
            && b[1] >= drawable[1]
            && b[2] <= drawable[2]
            && b[3] <= drawable[3];
        if !inside || obstacles.iter().any(|o| crate::sheets::overlap(b, *o)) {
            let r = crate::layout::largest_empty_rect(drawable, &obstacles, size);
            if r[2] - r[0] < size[0] || r[3] - r[1] < size[1] {
                return;
            }
            let delta = [
                (r[0] + r[2] - b[0] - b[2]) / 2.,
                (r[1] + r[3] - b[1] - b[3]) / 2.,
            ];
            v.at = [v.at[0] + delta[0], v.at[1] + delta[1]];
            crate::centrelines::shift(v, delta);
            v.area = [
                b[0] + delta[0],
                b[1] + delta[1],
                b[2] + delta[0],
                b[3] + delta[1],
            ];
            for d in candidate.dimensions.iter_mut().filter(|d| d.view == v.id) {
                if let Some(p) = &mut d.placed {
                    for q in p
                        .lines
                        .iter_mut()
                        .chain(&mut p.arrows)
                        .flatten()
                        .chain(std::iter::once(&mut p.label_at))
                    {
                        q[0] += delta[0];
                        q[1] += delta[1];
                    }
                    for (k, x) in p.label_box.iter_mut().enumerate() {
                        *x += delta[k % 2];
                    }
                }
            }
        }
        v.basis += "; section placed using settled ink and caption bounds";
        obstacles.push(v.area);
    }
    for b in &mut obstacles {
        b[0] -= 2.;
        b[1] -= 2.;
        b[2] += 2.;
        b[3] += 2.;
    }
    if let Some(iso) = candidate.views.iter_mut().find(|v| v.id == "v:iso") {
        let b = analysis.drawing_iso_bounds();
        let size = [b[2] - b[0], b[3] - b[1]];
        if size.iter().any(|s| *s <= 0.) {
            return;
        }
        let r = crate::layout::largest_empty_rect(drawable, &obstacles, size);
        let fit = ((r[2] - r[0]) / size[0]).min((r[3] - r[1]) / size[1]);
        let scale = crate::layout::keep_sheet_scale(
            (0.9 * fit).min(1.3 * plan.sheet.scale_factor),
            plan.sheet.scale_factor,
        );
        if scale <= 0. || obstacles.iter().any(|o| crate::sheets::overlap(r, *o)) {
            return;
        }
        iso.scale = scale;
        iso.at = [
            (r[0] + r[2] - scale * (b[0] + b[2])) / 2.,
            (r[1] + r[3] - scale * (b[1] + b[3])) / 2.,
        ];
        iso.area = r;
        iso.basis = "orientation view fitted around settled projection and section blocks".into();
    }
    if crate::model::drawn_sheets_fit(analysis, &candidate) {
        // Packing moved the section and its centre lines together. Replace
        // their old page-bound findings with checks of the actual final ink.
        candidate
            .problems
            .retain(|p| !p.id.starts_with("p:annotation_off_sheet:ink:"));
        candidate.problems.extend(crate::model::line_work_problems(
            &candidate.sheet,
            &candidate.views,
        ));
        *plan = candidate;
    }
}

pub(crate) fn correct_estimate(analysis: &Analysis, plan: &mut Plan) {
    // A local remedy bypasses measured view refits, including the orientation view.
    // Correcting a label must not unlock the later measured-row/section refit.
    if plan.spec.sheet.keep_layout == Some(true) {
        return;
    }
    // Wider label shelves, or a principal view's generic band at an enlarged scale, can push
    // an unused edge of a reservation past the border (#163: a 21 mm bracket kept 1:1 on an
    // empty A4 because its plan band, not its ink, overran at 2:1). The complete rendered
    // footprints prove whether it is empty paper; never trim an estimate through any model,
    // label, arrow or piece of furniture.
    if plan.problems.iter().any(|p| p.code == "page_fit_uncertain")
        && !crate::placement_intent::has_pins(&plan.spec)
        && plan.gdt.is_empty()
    {
        let [w, h] = plan.sheet.page;
        let inside = |b: &Rect| {
            b[0] >= margin() && b[1] >= margin() && b[2] <= w - margin() && b[3] <= h - margin()
        };
        if footprints(analysis, plan).iter().all(inside) {
            for v in plan.views.iter_mut() {
                let b = [
                    v.area[0].max(margin()),
                    v.area[1].max(margin()),
                    v.area[2].min(w - margin()),
                    v.area[3].min(h - margin()),
                ];
                if b[0] < b[2] && b[1] < b[3] {
                    v.area = b;
                }
            }
        }
    }
    if !plan.problems.iter().any(|p| p.code == "page_fit_uncertain")
        || crate::placement_intent::has_pins(&plan.spec)
        || crate::model::dimension_text_edited(&plan.spec)
        || plan.spec.iso_scale_factor.is_some()
        || plan.spec.views.contains_key("iso")
        || plan.spec.views.contains_key("iso_below")
        || !plan.gdt.is_empty()
        || !plan.balloons.is_empty()
        || plan.hole_table.is_some()
        || !plan.notes.is_empty()
        || !plan.tables.is_empty()
        || plan.requirements.iter().any(|r| r.placed.is_some())
        || plan
            .dimensions
            .iter()
            .any(|d| !matches!(d.kind.as_str(), "linear" | "callout" | "angular"))
    {
        return;
    }
    if plan.views.iter().any(|v| v.cut.is_some()) {
        if !crate::model::drawn_sheets_fit(analysis, plan) {
            correct_sections(analysis, plan);
        }
        return;
    }
    if plan.views.iter().any(|v| v.detail.is_some()) {
        return;
    }
    let Some(iso_index) = plan.views.iter().position(|v| v.id == "v:iso") else {
        return;
    };
    let bounds = footprints(analysis, plan);
    let mut groups: Vec<Rect> = bounds[..plan.views.len()].to_vec();
    // Corner arcs are independent packing obstacles. Expanding their whole
    // carrying view into an arc's empty quadrant needlessly overlaps its neighbour.
    let mut angular = Vec::new();
    for d in plan.dimensions.iter().filter(|d| d.placed.is_some()) {
        if d.kind == "angular" {
            if let Some(b) = crate::dims::ink_box(d) {
                angular.push(b);
            }
            continue;
        }
        let Some(i) = plan.views.iter().position(|v| v.id == d.view) else {
            return;
        };
        // Invariant: The iterator selected only dimensions with placements.
        let p = d.placed.as_ref().expect("placed dimension");
        include(&mut groups[i], [p.label_box[0], p.label_box[1]]);
        include(&mut groups[i], [p.label_box[2], p.label_box[3]]);
        for q in p.lines.iter().chain(&p.arrows).flatten() {
            include(&mut groups[i], *q);
        }
    }
    // The projections share one column reservation, including its unused paper.
    // Keep their area edges aligned so a zero-gap relative pin is a true no-op.
    if plan.dimensions.iter().any(|d| {
        d.measurements
            .iter()
            .any(|m| m.feature.starts_with("f:section_recess:"))
    }) && let (Some(front), Some(plan_view)) = (
        plan.views.iter().position(|v| v.id == "v:front"),
        plan.views.iter().position(|v| v.id == "v:plan"),
    ) {
        let left = groups[front][0].min(groups[plan_view][0]);
        let right = groups[front][2].max(groups[plan_view][2]);
        for i in [front, plan_view] {
            groups[i][0] = left;
            groups[i][2] = right;
        }
        if groups[plan_view][1] - groups[front][3] >= 2.0 {
            let boundary = 0.5 * (groups[front][3] + groups[plan_view][1]);
            groups[front][3] = boundary - 1.0;
            groups[plan_view][1] = boundary + 1.0;
        }
    }
    let top = groups
        .iter()
        .enumerate()
        .filter(|(i, _)| *i != iso_index)
        .map(|(_, b)| b[3])
        .chain(angular.iter().map(|b| b[3]))
        .fold(f64::NEG_INFINITY, f64::max);
    let lift = plan.sheet.page[1] - margin() - 2.0 - top;
    if lift <= 0.0 {
        return;
    }
    let title = plan.sheet.title_block;
    for (i, v) in plan
        .views
        .iter_mut()
        .enumerate()
        .filter(|(i, _)| *i != iso_index)
    {
        v.at[1] += lift;
        crate::centrelines::shift(v, [0.0, lift]);
        let b = groups[i];
        v.area = [b[0] - 1.0, b[1] + lift - 1.0, b[2] + 1.0, b[3] + lift + 1.0];
        // The added one-mm reservation is vacant paper. Where only that pad
        // reaches a title cell, retain all measured ink and trim the empty pad
        // rather than rejecting an otherwise fitting full-size A4 (10247).
        let ink = [b[0], b[1] + lift, b[2], b[3] + lift];
        if crate::sheets::overlap(v.area, title) && !crate::sheets::overlap(ink, title) {
            if ink[1] >= title[3] {
                v.area[1] = v.area[1].max(title[3]);
            } else if ink[2] <= title[0] {
                v.area[2] = v.area[2].min(title[0]);
            } else if ink[0] >= title[2] {
                v.area[0] = v.area[0].max(title[2]);
            } else if ink[3] <= title[1] {
                v.area[3] = v.area[3].min(title[1]);
            }
        }
        v.basis += "; free projection row lifted together using measured annotation bounds";
        groups[i] = v.area;
    }
    for p in plan.dimensions.iter_mut().filter_map(|d| d.placed.as_mut()) {
        for q in p.lines.iter_mut().chain(&mut p.arrows).flatten() {
            q[1] += lift;
        }
        p.label_at[1] += lift;
        p.label_box[1] += lift;
        p.label_box[3] += lift;
    }
    groups.extend(
        angular
            .into_iter()
            .map(|b| [b[0], b[1] + lift, b[2], b[3] + lift]),
    );
    groups.remove(iso_index);
    let mut tb = plan.sheet.title_block;
    tb[3] = tb[3].max(crate::title_block::top(tb) + 4.0);
    groups.push(tb);
    for b in &mut groups {
        b[0] -= 2.0;
        b[1] -= 2.0;
        b[2] += 2.0;
        b[3] += 2.0;
    }
    let b = analysis.drawing_iso_bounds();
    let size = [b[2] - b[0], b[3] - b[1]];
    if size.iter().any(|s| *s <= 0.0) {
        return;
    }
    let [w, h] = plan.sheet.page;
    let rect = crate::layout::largest_empty_rect(
        [margin(), margin(), w - margin(), h - margin()],
        &groups,
        size,
    );
    let fit = ((rect[2] - rect[0]) / size[0]).min((rect[3] - rect[1]) / size[1]);
    let sheet_scale = plan.sheet.scale_factor;
    let scale = crate::layout::keep_sheet_scale((0.9 * fit).min(1.3 * sheet_scale), sheet_scale);
    if scale <= 0.0 {
        return;
    }
    let iso = &mut plan.views[iso_index];
    iso.scale = scale;
    iso.at = [
        (rect[0] + rect[2] - scale * (b[0] + b[2])) / 2.0,
        (rect[1] + rect[3] - scale * (b[1] + b[3])) / 2.0,
    ];
    iso.area = rect;
    iso.basis = format!(
        "the automatic orientation view, fitted once around measured row blocks at {:.4} page mm per model mm{}",
        iso.scale,
        if scale == sheet_scale {
            " (the sheet's scale)"
        } else {
            " (not to scale)"
        }
    );
}

/// Pack settled annotated view blocks without re-routing their witnesses or leaders. The template is built at the same scale on A0; only owned paper geometry moves.
/// Re-place authored note tables around the measured blocks; sheet requirements stay beside the recipient's
/// title block. Authored view relations stay with the existing planner.
pub(crate) fn pack_gdt(analysis: &Analysis, template: &Plan, recipient: &Plan) -> Option<Plan> {
    pack_reserved(analysis, template, recipient, template).or_else(|| {
        // Roomy paper can lengthen automatic leaders. Keep the recipient's settled
        // routes when they pack better, borrowing only the complete note inventory.
        if template.notes.is_empty() || template.notes.iter().any(|n| n.placed.is_none()) {
            return None;
        }
        let mut local = recipient.clone();
        local.notes = template.notes.clone();
        local.notes_block = template.notes_block.clone();
        local.radius_notes_block = template.radius_notes_block.clone();
        local.problems.retain(|p| p.code != "notes_not_placed");
        pack_reserved(analysis, &local, recipient, &local)
    })
}

/// Omission edits reserve the complete inventory, keeping unaffected items fixed.
pub(crate) fn pack_inventory(
    analysis: &Analysis,
    plan: &Plan,
    recipient: &Plan,
    inventory: &[crate::dims::PlannedDimension],
) -> Option<Plan> {
    let mut reservation = plan.clone();
    reservation.dimensions = inventory.to_vec();
    pack_reserved(analysis, plan, recipient, &reservation)
}

fn pack_reserved(
    analysis: &Analysis,
    template: &Plan,
    recipient: &Plan,
    reservation: &Plan,
) -> Option<Plan> {
    pack_reserved_at(analysis, template, recipient, reservation, false).or_else(|| {
        (!template.notes.is_empty())
            .then(|| pack_reserved_at(analysis, template, recipient, reservation, true))
            .flatten()
    })
}

fn pack_reserved_at(
    analysis: &Analysis,
    template: &Plan,
    recipient: &Plan,
    reservation: &Plan,
    top: bool,
) -> Option<Plan> {
    if template.spec.sheet.keep_layout == Some(true)
        || recipient.spec.sheet.keep_layout == Some(true)
        || template.spec.iso_scale_factor.is_some()
        || template.spec.sheet.projection.as_deref() == Some("first")
        || template.hole_table.is_some()
        || !template.balloons.is_empty()
        || (crate::model::historical_layout()
            && (!template.notes.is_empty()
                || template.requirements.iter().any(|r| r.placed.is_some())))
        // Automatic profile/radius notes belong to the established geometry recipe.
        // Moving those changes its annotation corridors; this recovery relocates
        // the authored/PMI ruled notes table that otherwise blocks scale selection.
        || template
            .notes_block
            .iter()
            .chain(&template.radius_notes_block)
            .any(|b| !b.ruled)
        || template.notes.iter().any(|n| n.placed.is_none())
        || !template.tables.is_empty()
        || template.views.iter().any(|v| v.cut.is_some())
        || template.spec.views.values().any(|v| v.place.is_some())
        || crate::placement_intent::has_pins(&template.spec)
        || template.views.iter().map(|v| &v.id).collect::<Vec<_>>()
            != recipient.views.iter().map(|v| &v.id).collect::<Vec<_>>()
    {
        return None;
    }
    let mut p = template.clone();
    p.sheet = recipient.sheet.clone();
    p.requirements = recipient.requirements.clone();
    for requirement in &mut p.requirements {
        if requirement.carrier == "notes"
            && let Some(note) = p.notes.iter().find(|n| n.id == requirement.id)
        {
            requirement.state = note.state.clone();
        }
    }
    let footprints = footprints(analysis, reservation);
    let count = template.views.len();
    let mut groups = footprints[..count].to_vec();
    let owners = reservation
        .dimensions
        .iter()
        .filter(|d| d.placed.is_some())
        .map(|d| d.view.as_str())
        .chain(
            template
                .gdt
                .iter()
                .filter(|g| g.placed.is_some())
                .map(|g| g.view.as_str()),
        );
    for (owner, b) in owners.zip(&footprints[count..]) {
        let i = template.views.iter().position(|v| v.id == owner)?;
        include(&mut groups[i], [b[0], b[1]]);
        include(&mut groups[i], [b[2], b[3]]);
    }
    let mut shifts = vec![[0.0; 2]; count];
    let column: Vec<usize> = template
        .views
        .iter()
        .enumerate()
        .filter(|(_, v)| matches!(v.id.as_str(), "v:front" | "v:plan"))
        .map(|(i, _)| i)
        .collect();
    let left = column
        .iter()
        .map(|i| groups[*i][0])
        .fold(f64::INFINITY, f64::min);
    let right = column
        .iter()
        .map(|i| groups[*i][2])
        .fold(f64::NEG_INFINITY, f64::max);
    // Keep the aligned projection column's reservation aligned too. Relative
    // view pins then describe the same zero-gap relationship as ordinary packing.
    for i in &column {
        groups[*i][0] = left;
        groups[*i][2] = right;
    }
    let root = column
        .iter()
        .copied()
        .find(|i| template.views[*i].id == "v:front")
        .or_else(|| column.first().copied())?;
    let row_bottom = template
        .views
        .iter()
        .enumerate()
        .filter(|(_, v)| matches!(v.id.as_str(), "v:front" | "v:side"))
        .map(|(i, _)| groups[i][1])
        .fold(groups[root][1], f64::min);
    // Packing settled blocks retains the same readable paper to the border as a shelf.
    let common = [margin() + 2.0 - left, margin() + 2.0 - row_bottom];
    for i in &column {
        shifts[*i] = common;
    }
    if let Some(i) = column
        .iter()
        .copied()
        .find(|i| template.views[*i].id == "v:plan")
        && i != root
    {
        // Each measured block already receives 1 mm of padding below.
        shifts[i][1] += groups[root][3] + 2.0 - groups[i][1];
    }
    if let Some(i) = template.views.iter().position(|v| v.id == "v:side") {
        let right = column
            .iter()
            .map(|j| groups[*j][2] + shifts[*j][0])
            .fold(f64::NEG_INFINITY, f64::max);
        shifts[i] = [right + 6.0 - groups[i][0], common[1]];
    }
    let moved = |b: Rect, d: [f64; 2]| {
        [
            b[0] + d[0] - 1.0,
            b[1] + d[1] - 1.0,
            b[2] + d[0] + 1.0,
            b[3] + d[1] + 1.0,
        ]
    };
    let overlap = |a: Rect, b: Rect| a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3];
    let mut boxes: Vec<_> = template
        .views
        .iter()
        .enumerate()
        .filter(|(_, v)| v.id != "v:iso")
        .map(|(i, _)| moved(groups[i], shifts[i]))
        .collect();
    let tb = p.sheet.title_block;
    let mut fixed = vec![tb];
    for r in p.requirements.iter().filter_map(|r| r.placed.as_ref()) {
        let mut b = r.label_box;
        include(&mut b, [r.glyph[0], r.glyph[1]]);
        include(&mut b, [r.glyph[2], r.glyph[3]]);
        fixed.push(b);
    }
    let lift = if top {
        // A tall notes block can fit below a high projection row, beside the title
        // block, even when neither upper corner of a low row can carry it.
        p.sheet.page[1] - margin() - 1.0 - boxes.iter().map(|b| b[3]).fold(0.0, f64::max)
    } else {
        boxes
            .iter()
            .flat_map(|b| {
                fixed
                    .iter()
                    .filter(move |f| overlap(*b, **f))
                    .map(move |f| f[3] + 2.0 - b[1])
            })
            .fold(0.0, f64::max)
    };
    for d in &mut shifts {
        d[1] += lift;
    }
    for b in &mut boxes {
        b[1] += lift;
        b[3] += lift;
    }
    let [w, h] = p.sheet.page;
    if boxes.iter().any(|b| {
        b[0] < margin() - 1e-6
            || b[1] < margin() - 1e-6
            || b[2] > w - margin() + 1e-6
            || b[3] > h - margin() + 1e-6
            || fixed.iter().any(|f| overlap(*b, *f))
    }) {
        return None;
    }
    for (i, a) in boxes.iter().enumerate() {
        if boxes[i + 1..].iter().any(|b| overlap(*a, *b)) {
            return None;
        }
    }
    let delta = |owner: &str| {
        template
            .views
            .iter()
            .position(|v| v.id == owner)
            .map(|i| shifts[i])
    };
    let move_point = |q: &mut [f64; 2], d: [f64; 2]| {
        q[0] += d[0];
        q[1] += d[1];
    };
    let move_box = |b: &mut Rect, d: [f64; 2]| {
        b[0] += d[0];
        b[1] += d[1];
        b[2] += d[0];
        b[3] += d[1];
    };
    for (i, v) in p
        .views
        .iter_mut()
        .enumerate()
        .filter(|(_, v)| v.id != "v:iso")
    {
        move_point(&mut v.at, shifts[i]);
        crate::centrelines::shift(v, shifts[i]);
        v.area = moved(groups[i], shifts[i]);
        v.basis += "; settled annotations and GD&T packed as one measured view block";
    }
    for d in &mut p.dimensions {
        if let Some(q) = &mut d.placed {
            let shift = delta(&d.view)?;
            for pt in q.lines.iter_mut().chain(&mut q.arrows).flatten() {
                move_point(pt, shift);
            }
            move_point(&mut q.label_at, shift);
            move_box(&mut q.label_box, shift);
        }
    }
    for g in &mut p.gdt {
        if let Some(q) = &mut g.placed {
            let shift = delta(&g.view)?;
            if shift != [0., 0.]
                && let Some((_, steps, _)) = &mut q.pose
            {
                steps.push(shift);
            }
            move_point(&mut q.tip, shift);
            move_box(&mut q.label_box, shift);
            for pt in q
                .lines
                .iter_mut()
                .chain(&mut q.arrows)
                .chain(&mut q.strokes)
                .flatten()
            {
                move_point(pt, shift);
            }
            for pt in q.fills.iter_mut().flatten() {
                move_point(pt, shift);
            }
            for arc in &mut q.arcs {
                arc[0] += shift[0];
                arc[1] += shift[1];
            }
            for text in q.letters.iter_mut().chain(&mut q.runs) {
                move_point(&mut text.at, shift);
            }
        }
    }
    boxes.extend(fixed);
    // Notes belong to the sheet, not to a view. Keep their text, rows and provenance,
    // and find their place only after the projection gaps have been squeezed.
    for block in p.notes_block.iter_mut().chain(&mut p.radius_notes_block) {
        let old = block.cells;
        let at = crate::tables::place(
            [old[2] - old[0], old[3] - old[1]],
            &p.sheet,
            &boxes,
            crate::layout::Corner::TopRight,
        )?;
        let shift = [at[0] - old[0], at[1] - old[1]];
        move_box(&mut block.cells, shift);
        move_point(&mut block.title_at, shift);
        for note in &mut p.notes {
            if let Some(q) = &mut note.placed
                && q.cells[0] >= old[0] - 1e-9
                && q.cells[1] >= old[1] - 1e-9
                && q.cells[2] <= old[2] + 1e-9
                && q.cells[3] <= old[3] + 1e-9
            {
                move_box(&mut q.cells, shift);
                for at in &mut q.rows_at {
                    move_point(at, shift);
                }
            }
        }
        boxes.push(block.cells);
    }
    let sheet_scale = p.sheet.scale_factor;
    let has_detail = p.views.iter().any(|v| v.detail.is_some());
    if let Some(iso) = p.views.iter_mut().find(|v| v.id == "v:iso") {
        for b in &mut boxes {
            b[0] -= 2.0;
            b[1] -= 2.0;
            b[2] += 2.0;
            b[3] += 2.0;
        }
        let b = analysis.drawing_iso_bounds();
        let size = [b[2] - b[0], b[3] - b[1]];
        if size.iter().any(|s| *s <= 0.0) {
            return None;
        }
        let rect = crate::layout::largest_empty_rect(
            [margin(), margin(), w - margin(), h - margin()],
            &boxes,
            size,
        );
        let fit = ((rect[2] - rect[0]) / size[0]).min((rect[3] - rect[1]) / size[1]);
        let desired = if has_detail {
            iso.scale.min(sheet_scale)
        } else {
            iso.scale
        };
        let scale = crate::layout::keep_sheet_scale(desired.min(0.9 * fit), sheet_scale);
        if scale <= 0.0 {
            return None;
        }
        iso.scale = scale;
        iso.area = rect;
        iso.at = [
            (rect[0] + rect[2] - scale * (b[0] + b[2])) / 2.0,
            (rect[1] + rect[3] - scale * (b[1] + b[3])) / 2.0,
        ];
        iso.basis = format!(
            "the orientation view, fitted around the measured annotated blocks at {:.4} page mm per model mm{}",
            iso.scale,
            if scale == sheet_scale {
                " (the sheet's scale)"
            } else {
                " (not to scale)"
            }
        );
    }
    // The isometric was fitted again on the recipient sheet. Its scale
    // disclaimer must follow the settled view before grading the packed plan.
    crate::iso_caption::refresh(analysis, &mut p);
    let checked = crate::dims::recheck(analysis, &p);
    let checked_codes: std::collections::BTreeSet<_> = crate::dims::recheck(analysis, template)
        .into_iter()
        .chain(checked.iter().cloned())
        .map(|q| q.code)
        .collect();
    p.problems.retain(|q| !checked_codes.contains(&q.code));
    p.problems.extend(checked);
    p.problems.retain(|q| {
        !matches!(
            q.code.as_str(),
            "title_field_overflow" | "general_tolerance_missing"
        ) && !q.refs.iter().any(|r| r.starts_with("title_block/"))
    });
    p.problems.extend(crate::title_block::problems(
        &p.sheet.title_cells,
        p.sheet.page,
    ));
    p.problems.retain(|q| {
        !matches!(
            q.code.as_str(),
            "unclaimed_geometry" | "feature_not_dimensioned"
        )
    });
    crate::completeness::report(analysis, &mut p);
    p.status = crate::completeness::status(&p.problems);
    p.sheet.fill = fill(analysis, &p);
    Some(p)
}

/// A neighbour may consume more paper only when the dimensioned views enlarge.
pub(crate) fn allowed(smallest: (usize, f64), sheet: usize, scale: f64) -> bool {
    sheet == smallest.0 || (sheet == smallest.0 + 1 && scale > smallest.1)
}

pub(crate) fn rank(a: (f64, f64, f64), b: (f64, f64, f64)) -> std::cmp::Ordering {
    let band = |p: (f64, f64, f64)| (FILL_BAND[0]..=FILL_BAND[1]).contains(&p.2);
    band(b).cmp(&band(a)).then_with(|| {
        if band(a) && band(b) {
            b.0.total_cmp(&a.0).then_with(|| a.1.total_cmp(&b.1))
        } else if crate::nominal::comparison() {
            // This is the unrendered historical circular-route reference, not
            // a live paper choice. Keep its 2026-10-12 recipe so a new paper
            // preference cannot move established callouts to another view.
            b.2.total_cmp(&a.2)
                .then_with(|| b.0.total_cmp(&a.0))
                .then_with(|| a.1.total_cmp(&b.1))
        } else {
            // Maintainer decision, 2026-11-14: below the target band, keep the
            // smaller sheet. Enlargement earns more paper only by reaching the band.
            a.1.total_cmp(&b.1)
                .then_with(|| b.2.total_cmp(&a.2))
                .then_with(|| b.0.total_cmp(&a.0))
        }
    })
}

/// A finished valid, complete pair as the sheet choice sees it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Candidate {
    /// Index into [`crate::layout::PAGES`].
    pub sheet: usize,
    pub scale: f64,
    /// Page width, mm: the paper preference.
    pub width: f64,
    pub fill: f64,
    /// Leaders and witnesses through material beyond the first estimate's.
    pub extra_crossings: usize,
}

/// The maintainer's rule (2026-10-12) over valid, complete candidates only. The smallest fit is
/// the smallest sheet with a valid complete drawing, at its largest such scale; unless the Spec
/// names the sheet, only that pair and its next larger sheet at a larger scale compete, and
/// [`rank`] decides between them by fill. Against a valid first estimate (*seed_clean*), a pair
/// that adds material crossings is set aside (the quality ratchet); it still defines the smallest
/// fit. Returns the smallest fit, and the chosen index, or `None` when every allowed pair adds
/// crossings to the valid first estimate, which is then kept. `None` overall: no candidate.
pub(crate) fn choose(
    candidates: &[Candidate],
    named_sheet: bool,
    seed_clean: bool,
) -> Option<(Option<usize>, (usize, f64))> {
    let smallest = candidates
        .iter()
        .map(|c| (c.sheet, c.scale))
        .min_by(|a, b| a.0.cmp(&b.0).then(b.1.total_cmp(&a.1)))?;
    let key = |c: &Candidate| (c.scale, c.width, c.fill);
    let chosen = candidates
        .iter()
        .enumerate()
        .filter(|(_, c)| {
            named_sheet
                || (c.sheet == smallest.0 && c.scale == smallest.1)
                || (c.sheet == smallest.0 + 1 && allowed(smallest, c.sheet, c.scale))
        })
        .filter(|(_, c)| !seed_clean || c.extra_crossings == 0)
        .min_by(|a, b| rank(key(a.1), key(b.1)))
        .map(|(i, _)| i);
    Some((chosen, smallest))
}

/// Claim unused paper for final annotation bounds, transferring only vacant neighbouring
/// reservation while protecting every view and its ink, the title block and drawing border.
/// The full inventory includes
/// omitted dimensions, so withdrawing one item does not move its neighbours' bands.
pub(crate) fn reserve_annotation_bounds(
    analysis: &Analysis,
    sheet: &crate::model::PlannedSheet,
    views: &mut [crate::model::PlannedView],
    inventory: &[crate::dims::PlannedDimension],
    gdt: &[crate::dims::gdt::PlannedGdt],
) {
    if !inventory.iter().any(|d| {
        d.measurements
            .iter()
            .any(|m| m.feature.starts_with("f:section_recess:"))
    }) {
        return;
    }
    reserve_bounds(analysis, sheet, views, inventory, gdt, None);
}

/// Longer default nominals need their actual paper reservation, including the
/// run-on of a short linear dimension. Reclaim only vacant neighbouring bands;
/// every view, annotation, border and title-block gate remains the same.
pub(crate) fn reserve_nominal_bounds(
    analysis: &Analysis,
    sheet: &crate::model::PlannedSheet,
    views: &mut [crate::model::PlannedView],
    inventory: &[crate::dims::PlannedDimension],
    gdt: &[crate::dims::gdt::PlannedGdt],
) {
    if !crate::nominal::geometry_eligible(analysis) {
        let grown: std::collections::BTreeSet<_> = inventory
            .iter()
            .filter(|d| d.kind == "linear")
            .filter(|d| {
                d.measurements.iter().any(|m| {
                    let number = sheet.units.format(m.value);
                    number
                        .split_once('.')
                        .is_some_and(|(_, fraction)| fraction.len() > 1)
                        && d.label.contains(&number)
                })
            })
            .map(|d| d.id.clone())
            .collect();
        if !grown.is_empty() {
            reserve_bounds(analysis, sheet, views, inventory, gdt, Some(&grown));
        }
        return;
    }
    let grown_views: std::collections::BTreeSet<_> = inventory
        .iter()
        .filter(|d| {
            d.measurements.iter().any(|m| {
                let number = sheet.units.format(m.value);
                number
                    .split_once('.')
                    .is_some_and(|(_, fraction)| fraction.len() > 1)
                    && d.label.contains(&number)
            })
        })
        .map(|d| d.view.clone())
        .collect();
    let grown: std::collections::BTreeSet<_> = inventory
        .iter()
        .filter(|d| grown_views.contains(&d.view))
        .map(|d| d.id.clone())
        .collect();
    if !grown.is_empty() {
        reserve_bounds(analysis, sheet, views, inventory, gdt, Some(&grown));
    }
}

pub(crate) fn reserve_bounds(
    analysis: &Analysis,
    sheet: &crate::model::PlannedSheet,
    views: &mut [crate::model::PlannedView],
    inventory: &[crate::dims::PlannedDimension],
    gdt: &[crate::dims::gdt::PlannedGdt],
    selected: Option<&std::collections::BTreeSet<String>>,
) {
    let mut bounds: Vec<(&str, Rect, bool)> = inventory
        .iter()
        .filter_map(|d| Some((d.view.as_str(), crate::dims::ink_box(d)?, true)))
        .collect();
    let mut protected: Vec<Rect> = views
        .iter()
        .map(|v| {
            let mut b = if v.id == "v:iso" {
                [
                    v.at[0] + v.scale * analysis.drawing_iso_bounds()[0],
                    v.at[1] + v.scale * analysis.drawing_iso_bounds()[1],
                    v.at[0] + v.scale * analysis.drawing_iso_bounds()[2],
                    v.at[1] + v.scale * analysis.drawing_iso_bounds()[3],
                ]
            } else {
                let size = if v.detail.is_some() || v.broken.is_some() {
                    // A crop owns only its enlarged local outline. Reserving the
                    // whole part at the detail scale strands neighbouring bands.
                    crate::detail::crop_extent(analysis, v).0
                } else {
                    let camera =
                        // Invariant: Planned cameras come from the fixed views or checked section/detail cameras, with nonparallel axes.
                        haecceity::hlr::View::new(v.direction, v.up).expect("planned view");
                    crate::model::extent(analysis, &camera).0
                };
                [
                    v.at[0] - v.scale * size[0] / 2.0,
                    v.at[1] - v.scale * size[1] / 2.0,
                    v.at[0] + v.scale * size[0] / 2.0,
                    v.at[1] + v.scale * size[1] / 2.0,
                ]
            };
            for c in v.line_work.iter().flat_map(|w| &w.curves) {
                let r = c.bbox();
                include(&mut b, [r[0], r[1]]);
                include(&mut b, [r[2], r[3]]);
            }
            b
        })
        .collect();
    // Caption paper belongs to the crop too; a neighbouring annotation may
    // reclaim empty detail bands, but never its caption or readable gap.
    for caption in crate::detail::caption_obstacles(views) {
        if let (Some(i), Some(p)) = (
            views.iter().position(|v| v.id == caption.view),
            caption.placed.as_ref(),
        ) {
            include(&mut protected[i], [p.label_box[0], p.label_box[1]]);
            include(&mut protected[i], [p.label_box[2], p.label_box[3]]);
        }
    }
    for (view, b, _) in &bounds {
        if let Some(i) = views.iter().position(|v| v.id == *view) {
            include(&mut protected[i], [b[0], b[1]]);
            include(&mut protected[i], [b[2], b[3]]);
        }
    }
    for g in gdt {
        if let (Some(i), Some(p)) = (views.iter().position(|v| v.id == g.view), g.placed.as_ref()) {
            include(&mut protected[i], [p.label_box[0], p.label_box[1]]);
            include(&mut protected[i], [p.label_box[2], p.label_box[3]]);
            for q in p
                .lines
                .iter()
                .chain(&p.strokes)
                .chain(&p.arrows)
                .flatten()
                .chain(p.fills.iter().flatten())
            {
                include(&mut protected[i], *q);
            }
        }
    }
    // The isometric has reclaimable bands too. Protect its material and the
    // caption's measured ink instead of treating every unused corner as ink.
    let mut caption_ink = inventory.to_vec();
    caption_ink.extend(crate::centrelines::obstacles(views));
    caption_ink.extend(gdt.iter().filter_map(crate::dims::gdt::proxy));
    for caption in crate::iso_caption::plan(analysis, sheet, views, &caption_ink) {
        if let Some(i) = views.iter().position(|v| v.id == caption.view) {
            include(&mut protected[i], [caption.ink[0], caption.ink[1]]);
            include(&mut protected[i], [caption.ink[2], caption.ink[3]]);
        }
    }
    if let Some(ids) = selected {
        bounds = inventory
            .iter()
            .filter(|d| ids.contains(&d.id))
            .filter_map(|d| Some((d.view.as_str(), crate::dims::ink_box(d)?, true)))
            .collect();
    }
    bounds.extend(
        gdt.iter()
            .filter(|g| selected.is_none() && g.kind != "control_frame")
            .filter_map(|g| {
                let p = g.placed.as_ref()?;
                let mut b = p.label_box;
                for q in p
                    .lines
                    .iter()
                    .chain(&p.strokes)
                    .chain(&p.arrows)
                    .flatten()
                    .chain(p.fills.iter().flatten())
                {
                    include(&mut b, *q);
                }
                Some((g.view.as_str(), b, true))
            }),
    );
    let overlap = |a: Rect, b: Rect| {
        a[0] < b[2] - 1e-9 && b[0] < a[2] - 1e-9 && a[1] < b[3] - 1e-9 && b[1] < a[3] - 1e-9
    };
    for (view, b, reclaim) in bounds {
        let Some(i) = views.iter().position(|v| v.id == view) else {
            continue;
        };
        let area = views[i].area;
        let mut candidate = [
            area[0].min(b[0] - 0.5),
            area[1].min(b[1] - 0.5),
            area[2].max(b[2] + 0.5),
            area[3].max(b[3] + 0.5),
        ];
        if b[0] < margin() - 1e-6
            || b[1] < margin() - 1e-6
            || b[2] > sheet.page[0] - margin() + 1e-6
            || b[3] > sheet.page[1] - margin() + 1e-6
            || overlap(candidate, sheet.title_block)
        {
            continue;
        }
        candidate[0] = candidate[0].max(margin());
        candidate[1] = candidate[1].max(margin());
        candidate[2] = candidate[2].min(sheet.page[0] - margin());
        candidate[3] = candidate[3].min(sheet.page[1] - margin());
        let mut areas: Vec<_> = views.iter().map(|v| v.area).collect();
        let mut clear = true;
        for j in 0..views.len() {
            if i == j || !overlap(candidate, areas[j]) {
                continue;
            }
            if !reclaim || (views[j].id == "v:iso" && !crate::nominal::geometry_eligible(analysis))
            {
                clear = false;
                break;
            }
            // Transfer only unused reservation. Every neighbouring view, mark,
            // leader, witness and glyph remains within its original paper.
            let old = areas[j];
            let ink = protected[j];
            let mut choices = Vec::new();
            if ink[2] <= candidate[0] && old[0] < candidate[0] {
                choices.push([old[0], old[1], candidate[0], old[3]]);
            }
            if ink[0] >= candidate[2] && candidate[2] < old[2] {
                choices.push([candidate[2], old[1], old[2], old[3]]);
            }
            if ink[3] <= candidate[1] && old[1] < candidate[1] {
                choices.push([old[0], old[1], old[2], candidate[1]]);
            }
            if ink[1] >= candidate[3] && candidate[3] < old[3] {
                choices.push([old[0], candidate[3], old[2], old[3]]);
            }
            let size = |b: Rect| (b[2] - b[0]) * (b[3] - b[1]);
            if let Some(b) = choices
                .into_iter()
                .max_by(|a, b| size(*a).total_cmp(&size(*b)))
            {
                areas[j] = b;
            } else {
                clear = false;
                break;
            }
        }
        if clear {
            areas[i] = candidate;
            for (v, area) in views.iter_mut().zip(areas) {
                v.area = area;
            }
        }
    }
}

/// Whether a movable explicit pair needs correction for printed linear ink.
/// Used by the live solve and its bounded placement-only comparison.
pub(crate) fn can_settle_explicit_overflow(plan: &Plan) -> bool {
    plan.spec.sheet.size.is_some()
        && plan.spec.sheet.scale.is_some()
        && plan.spec.sheet.keep_layout != Some(true)
        && !crate::model::dimension_text_edited(&plan.spec)
        && !plan.spec.views.values().any(|v| v.place.is_some())
        && !crate::placement_intent::has_pins(&plan.spec)
        && plan.dimensions.iter().any(|d| {
            d.kind == "linear"
                && crate::dims::ink_box(d).is_some_and(|b| {
                    (0..2).any(|k| {
                        b[k] < margin() - 1e-6 || b[k + 2] > plan.sheet.page[k] - margin() + 1e-6
                    })
                })
        })
}

/// Final compose-then-pack pass for settled linear ink (ISSUE-563-b). Use the
/// complete placement inventory so omitting a dimension does not change a pin's
/// frame. Moving a view block transports its already settled routes unchanged.
pub(crate) fn reserve_linear_corridors(
    analysis: &Analysis,
    plan: &mut Plan,
    inventory: &[crate::dims::PlannedDimension],
    automatic_pair: bool,
    radius_reference: Option<&Plan>,
    cache: &crate::dims::footprints::Cache,
) {
    let old: Vec<_> = plan.views.iter().map(|v| (v.at, v.area, v.scale)).collect();
    let compact = (!plan.gdt.is_empty()
        || plan.spec.dimensions.values().any(|d| d.tolerance.is_some())
        || plan.spec.features.values().any(|f| f.fit.is_some()))
        // An unreadable seed keeps its established control-frame bands.
        && (plan.gdt.is_empty() || plan.sheet.scale_factor >= min_legible_scale(analysis))
        && !crate::placement_intent::has_pins(&plan.spec)
        && !crate::model::dimension_text_edited(&plan.spec)
        && !plan.spec.views.values().any(|v| v.place.is_some())
        && (automatic_pair || plan.spec.sheet.size.is_none() || plan.spec.sheet.scale.is_none());
    if compact {
        // Settled control frames and edited labels use their real ink, as pack_gdt does.
        // Estimated empty lanes are not additional physical drafting demands.
        for v in plan.views.iter_mut().filter(|v| v.id != "v:iso") {
            let size = crate::detail::crop_extent(analysis, v).0;
            v.area = [
                v.at[0] - v.scale * size[0] / 2.0,
                v.at[1] - v.scale * size[1] / 2.0,
                v.at[0] + v.scale * size[0] / 2.0,
                v.at[1] + v.scale * size[1] / 2.0,
            ];
        }
        let mut owned = plan.dimensions.clone();
        // A later radius polish restores these settled corridors. Compaction
        // must not discard their paper reservation and then reject the replay
        // merely for leaving its newly shortened annotation band.
        owned.extend(
            crate::placement_intent::held_dimensions(radius_reference, &plan.views)
                .into_iter()
                .filter(|d| {
                    d.measurements.iter().any(|m| {
                        matches!(
                            m.parameter.as_str(),
                            "fillet.radius" | "blend.radius" | "cylindrical_profile.radius"
                        )
                    }) && plan.dimensions.iter().any(|p| {
                        p.id == d.id && p.terms == d.terms && p.measurements == d.measurements
                    }) && radius_reference.is_some_and(|r| {
                        r.views.iter().any(|old| {
                            old.id == d.view
                                && plan.views.iter().any(|now| {
                                    now.id == old.id
                                        && now.scale == old.scale
                                        && now.direction == old.direction
                                        && now.up == old.up
                                })
                        })
                    })
                }),
        );
        owned.extend(plan.gdt.iter().filter_map(crate::dims::gdt::proxy));
        for d in owned.iter().filter(|d| d.placed.is_some()) {
            if let Some(b) = crate::dims::ink_box(d)
                && let Some(v) = plan.views.iter_mut().find(|v| v.id == d.view)
            {
                include(&mut v.area, [b[0], b[1]]);
                include(&mut v.area, [b[2], b[3]]);
            }
        }
    }
    for d in inventory
        .iter()
        .chain(&plan.dimensions)
        .filter(|d| d.kind == "linear")
    {
        let Some(b) = crate::dims::ink_box(d) else {
            continue;
        };
        if let Some(v) = plan.views.iter_mut().find(|v| v.id == d.view) {
            include(&mut v.area, [b[0], b[1]]);
            include(&mut v.area, [b[2], b[3]]);
        }
    }
    if plan
        .views
        .iter()
        .zip(&old)
        .all(|(v, (_, a, _))| v.area == *a)
    {
        return;
    }
    // Placement has already checked this settled ink. Keep its collision
    // identities for replacement instead of repeating the same geometric check
    // before the carrier move. Unplaced-item reasons and the router's own-body
    // material re-entry findings are not replaced by foreign-view collision checks.
    let placed: std::collections::BTreeMap<_, _> = plan
        .dimensions
        .iter()
        .filter(|d| d.placed.is_some())
        .map(|d| (d.id.as_str(), d.view.as_str()))
        .chain(
            plan.gdt
                .iter()
                .filter(|g| g.placed.is_some())
                .map(|g| (g.id.as_str(), g.view.as_str())),
        )
        .collect();
    let previously_checked: std::collections::BTreeSet<_> = plan
        .problems
        .iter()
        .filter(|p| {
            let Some(owner) = p.subjects.first().and_then(|id| placed.get(id.as_str())) else {
                return false;
            };
            match p.code.as_str() {
                "annotation_outside_area"
                | "dimension_text_stray"
                | "annotation_off_sheet"
                | "annotation_over_title_block" => true,
                "annotation_over_view" => p
                    .subjects
                    .get(1)
                    .is_some_and(|id| plan.views.iter().any(|v| v.id == *id)),
                "annotation_line_over_view" => p
                    .subjects
                    .get(1)
                    .is_some_and(|id| id != *owner && plan.views.iter().any(|v| v.id == *id)),
                "dimension_line_shared"
                | "annotation_overlap"
                | "annotation_ink_overlap"
                | "annotation_leader_crossing" => {
                    p.subjects.iter().all(|id| placed.contains_key(id.as_str()))
                }
                "leader_through_feature" | "extension_through_feature" => p.id.contains(":line:"),
                _ => false,
            }
        })
        .map(|p| p.id.clone())
        .collect();
    let mut shifts = vec![[0.0; 2]; plan.views.len()];
    let index = |id: &str| plan.views.iter().position(|v| v.id == id);
    // Dimension pins are relative to their carrier, not absolute paper coordinates.
    // Unlock fixed frames only for actual requested-lane overflow; spare reserved
    // bands must not move an already fitting drawing.
    let explicit_lane = plan.dimensions.iter().any(|d| {
        plan.spec.dimensions.get(&d.id).is_some_and(|entry| {
            !entry.omit && entry.place.as_ref().is_some_and(|p| p.lane.is_some())
        }) && crate::dims::ink_box(d).is_some_and(|b| {
            b[0] < margin() - 1e-6
                || b[1] < margin() - 1e-6
                || b[2] > plan.sheet.page[0] - margin() + 1e-6
                || b[3] > plan.sheet.page[1] - margin() + 1e-6
        })
    });
    // A fixed paper/scale pair still permits its unpinned projection assembly
    // to use vacant paper. In particular, an authored dimension must not freeze
    // a generated peer outside the frame (#331). Only actual printed overflow
    // unlocks this correction; empty estimated bands do not move a fitting pair.
    let settled_overflow = !automatic_pair && can_settle_explicit_overflow(plan);
    let mut free = (explicit_lane
        || settled_overflow
        || (!crate::placement_intent::has_pins(&plan.spec)
            && (automatic_pair
                || plan.spec.sheet.size.is_none()
                || plan.spec.sheet.scale.is_none())))
        && !crate::model::dimension_text_edited(&plan.spec)
        && !plan.spec.views.values().any(|v| v.place.is_some())
        && plan.spec.sheet.keep_layout != Some(true);
    if free {
        let first = plan.spec.sheet.projection.as_deref() == Some("first");
        let column: Vec<usize> = plan
            .views
            .iter()
            .enumerate()
            .filter(|(_, v)| matches!(v.id.as_str(), "v:front" | "v:plan"))
            .map(|(i, _)| i)
            .collect();
        // A finished explicit pair only needs rigid transport. Reopening its
        // estimated gaps would move already clear GD&T toward page furniture.
        if let (Some(front), Some(top)) = (index("v:front"), index("v:plan"))
            && !settled_overflow
        {
            let (below, above) = if first { (top, front) } else { (front, top) };
            let gap = (old[above].1[1] - old[below].1[3]).max(0.0);
            let extra = (plan.views[below].area[3] + gap - plan.views[above].area[1]).max(0.0);
            shifts[top][1] += if first { -extra } else { extra };
        }
        if let Some(side) = index("v:side")
            && !settled_overflow
        {
            let edge = column
                .iter()
                .map(|&i| {
                    if first {
                        plan.views[i].area[0]
                    } else {
                        plan.views[i].area[2]
                    }
                })
                .reduce(|a, b| if first { a.min(b) } else { a.max(b) })
                .unwrap_or(if first {
                    plan.views[side].area[2]
                } else {
                    plan.views[side].area[0]
                });
            let previous = column
                .iter()
                .map(|&i| if first { old[i].1[0] } else { old[i].1[2] })
                .reduce(|a, b| if first { a.min(b) } else { a.max(b) })
                .unwrap_or(edge);
            let gap = if first {
                (previous - old[side].1[2]).max(0.0)
            } else {
                (old[side].1[0] - previous).max(0.0)
            };
            shifts[side][0] = if first {
                (edge - gap - plan.views[side].area[2]).min(0.0)
            } else {
                (edge + gap - plan.views[side].area[0]).max(0.0)
            };
            for (i, _) in plan
                .views
                .iter()
                .enumerate()
                .filter(|(_, v)| v.cut.is_some())
            {
                shifts[i][0] = shifts[side][0];
                // A measured side corridor may reach its section partner. Carry
                // the section beyond the final side edge, preserving the old gap;
                // an actual positive gap also avoids rounded touching rectangles.
                if old[i].1[0] >= old[side].1[0] {
                    let gap = (old[i].1[0] - old[side].1[2]).max(1e-6);
                    shifts[i][0] = shifts[i][0].max(
                        plan.views[side].area[2] + shifts[side][0] + gap - plan.views[i].area[0],
                    );
                }
            }
        }
        // Keep the assembled row inside the drawing area; source annotations and
        // every projection partner travel with it. Page-anchored furniture stays.
        let group: Vec<usize> = plan
            .views
            .iter()
            .enumerate()
            .filter(|(_, v)| v.id != "v:iso")
            .map(|(i, _)| i)
            .collect();
        if settled_overflow && let Some(top) = index("v:plan") {
            // The plan view is free along the projection column. Settle that
            // row first, retaining the front/side row and its unrelated controls.
            // A later whole-assembly correction is needed only if other rows
            // also overflow. All annotation contacts are rechecked below.
            let area = plan.views[top].area;
            let minimum = margin() - area[1];
            let maximum = plan.sheet.page[1] - margin() - area[3];
            if minimum <= maximum {
                shifts[top][1] = 0.0_f64.clamp(minimum, maximum);
            }
        }
        let lower = [0, 1].map(|k| {
            group
                .iter()
                .map(|&i| plan.views[i].area[k] + shifts[i][k])
                .fold(f64::INFINITY, f64::min)
        });
        let lift = [0, 1].map(|k| {
            let minimum = margin() - lower[k];
            if settled_overflow || (compact && !crate::model::annotation_text_edited(&plan.spec)) {
                let upper = group
                    .iter()
                    .map(|&i| plan.views[i].area[k + 2] + shifts[i][k])
                    .fold(f64::NEG_INFINITY, f64::max);
                let maximum = plan.sheet.page[k] - margin() - upper;
                if minimum <= maximum {
                    // The nearest rigid translation preserves projection alignment,
                    // authored sides/lanes and every settled witness/leader route.
                    // Measured bands may need to move down as well as up: the
                    // estimate's centred column can leave the top lane off sheet
                    // even though the complete annotated assembly fits (CTC-01).
                    return 0.0_f64.clamp(minimum, maximum);
                }
            }
            minimum.max(0.0)
        });
        for &i in &group {
            for k in 0..2 {
                shifts[i][k] += lift[k];
            }
        }
        // Borrow vacant paper only when the finished assembly can actually fit.
        // A genuinely oversized fixed pair must retain its established carriers:
        // a partial correction can drive clear lines through neighbouring views.
        if settled_overflow
            && group.iter().any(|&i| {
                (0..2).any(|k| {
                    plan.views[i].area[k] + shifts[i][k] < margin() - 1e-6
                        || plan.views[i].area[k + 2] + shifts[i][k]
                            > plan.sheet.page[k] - margin() + 1e-6
                })
            })
        {
            shifts.fill([0.0; 2]);
            free = false;
        }
        // A whole projection assembly can clear page furniture by a rigid lift.
        // Its settled dimensions and control frames keep their relative positions.
        let title = plan.sheet.title_block;
        let raise = group
            .iter()
            .filter_map(|&i| {
                let a = plan.views[i].area;
                let d = shifts[i];
                (a[0] + d[0] < title[2]
                    && title[0] < a[2] + d[0]
                    && a[1] + d[1] < title[3]
                    && title[1] < a[3] + d[1])
                    .then_some(title[3] + 1.0 - a[1] - d[1])
            })
            .fold(0.0, f64::max);
        if free
            && raise > 0.0
            && group.iter().all(|&i| {
                plan.views[i].area[3] + shifts[i][1] + raise <= plan.sheet.page[1] - margin()
            })
        {
            for &i in &group {
                shifts[i][1] += raise;
            }
        }
    }
    if explicit_lane && shifts.iter().any(|d| *d != [0.0; 2]) {
        plan.sheet.basis = plan.sheet.basis.replace(
            "anchor frames and sheet choice kept fixed for placement pins",
            "sheet choice retained; view carriers translated for the requested lane",
        );
        plan.sheet.basis +=
            "; applied explicit lane reservation by transporting its carrying views";
    }
    for (i, v) in plan.views.iter_mut().enumerate() {
        let delta = shifts[i];
        for (k, offset) in delta.into_iter().enumerate() {
            v.at[k] += offset;
            v.area[k] += offset;
            v.area[k + 2] += offset;
        }
        crate::centrelines::shift(v, delta);
    }
    if plan.spec.views.values().any(|v| v.place.is_some()) {
        // A relative constraint uses the final footprints. Re-resolve its gap,
        // retaining the held annotation carriers, then transport their free peers.
        let template = plan.clone();
        let mut more = Vec::new();
        crate::placement_intent::views(
            &plan.spec,
            &mut plan.views,
            Some(&template),
            &plan.sheet,
            &[],
            &mut more,
        );
        for (i, v) in plan.views.iter_mut().enumerate() {
            if v.id == "v:iso"
                && plan
                    .spec
                    .views
                    .get("iso")
                    .is_some_and(|v| v.place.as_ref().is_some_and(|p| p.pinned))
            {
                v.at = old[i].0;
                v.area = old[i].1;
                v.scale = old[i].2;
            }
            let extra = [
                v.at[0] - template.views[i].at[0],
                v.at[1] - template.views[i].at[1],
            ];
            crate::centrelines::shift(v, extra);
            shifts[i] = [v.at[0] - old[i].0[0], v.at[1] - old[i].0[1]];
        }
        for p in more {
            if !plan.problems.iter().any(|q| q.id == p.id) {
                plan.problems.push(p);
            }
        }
    }
    let deltas: std::collections::BTreeMap<_, _> = plan
        .views
        .iter()
        .enumerate()
        .map(|(i, v)| (v.id.clone(), shifts[i]))
        .collect();
    for d in &mut plan.dimensions {
        let Some(p) = &mut d.placed else {
            continue;
        };
        let delta = deltas.get(&d.view).copied().unwrap_or([0.0; 2]);
        for q in p.lines.iter_mut().chain(&mut p.arrows).flatten() {
            for (k, offset) in delta.into_iter().enumerate() {
                q[k] += offset;
            }
        }
        for (k, offset) in delta.into_iter().enumerate() {
            p.label_at[k] += offset;
            p.label_box[k] += offset;
            p.label_box[k + 2] += offset;
        }
    }
    for g in &mut plan.gdt {
        let delta = deltas.get(&g.view).copied().unwrap_or([0.0; 2]);
        if delta == [0.0; 2] {
            continue;
        }
        if let Some(q) = &mut g.placed {
            if let Some((_, steps, _)) = &mut q.pose {
                steps.push(delta);
            }
            for (k, offset) in delta.into_iter().enumerate() {
                q.tip[k] += offset;
                q.label_box[k] += offset;
                q.label_box[k + 2] += offset;
            }
            for pt in q
                .lines
                .iter_mut()
                .chain(&mut q.arrows)
                .chain(&mut q.strokes)
                .flatten()
            {
                for (k, offset) in delta.into_iter().enumerate() {
                    pt[k] += offset;
                }
            }
            for pt in q.fills.iter_mut().flatten() {
                for (k, offset) in delta.into_iter().enumerate() {
                    pt[k] += offset;
                }
            }
            for arc in &mut q.arcs {
                arc[0] += delta[0];
                arc[1] += delta[1];
            }
            for text in q.letters.iter_mut().chain(&mut q.runs) {
                for (k, offset) in delta.into_iter().enumerate() {
                    text.at[k] += offset;
                }
            }
        }
    }
    // Free isometrics have no measurement ownership. First retain their exact ink
    // and caption if that footprint remains clear; otherwise fit the orientation
    // view once against the composed blocks and the page-anchored furniture.
    if plan.spec.sheet.keep_layout != Some(true)
        && let Some(i) = plan.views.iter().position(|v| v.id == "v:iso")
    {
        let iso = &plan.views[i];
        let mut ink = [
            iso.at[0] + iso.scale * analysis.drawing_iso_bounds()[0],
            iso.at[1] + iso.scale * analysis.drawing_iso_bounds()[1],
            iso.at[0] + iso.scale * analysis.drawing_iso_bounds()[2],
            iso.at[1] + iso.scale * analysis.drawing_iso_bounds()[3],
        ];
        for c in plan.captions.iter().filter(|c| c.view == "v:iso") {
            include(&mut ink, [c.ink[0], c.ink[1]]);
            include(&mut ink, [c.ink[2], c.ink[3]]);
        }
        let overlap = |a: Rect, b: Rect| a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3];
        let mut obstacles: Vec<_> = plan
            .views
            .iter()
            .filter(|v| v.id != "v:iso")
            .map(|v| v.area)
            .collect();
        obstacles.push(plan.sheet.title_block);
        obstacles.extend(
            plan.tables
                .iter()
                .filter_map(|t| t.placed.as_ref().map(|p| p.cells)),
        );
        if let Some(n) = &plan.notes_block {
            obstacles.push(n.cells);
        }
        let iso_pinned = plan
            .spec
            .views
            .get("iso")
            .is_some_and(|v| v.place.as_ref().is_some_and(|p| p.pinned));
        // A held region is part of the pin's canonical frame.
        if !iso_pinned && !obstacles.iter().any(|b| overlap(ink, *b)) {
            plan.views[i].area = ink;
        } else if !iso_pinned
            && free
            && plan.spec.iso_scale_factor.is_none()
            && !plan.spec.views.contains_key("iso")
        {
            let b = analysis.drawing_iso_bounds();
            let size = [b[2] - b[0], b[3] - b[1]];
            if size.iter().all(|v| *v > 0.0) {
                let [w, h] = plan.sheet.page;
                let rect = crate::layout::largest_empty_rect(
                    [margin(), margin(), w - margin(), h - margin()],
                    &obstacles,
                    size,
                );
                let fit = ((rect[2] - rect[0]) / size[0]).min((rect[3] - rect[1]) / size[1]);
                let scale = crate::layout::keep_sheet_scale(
                    plan.views[i].scale.min(0.9 * fit),
                    plan.sheet.scale_factor,
                );
                if scale > 0.0 {
                    let iso = &mut plan.views[i];
                    iso.scale = scale;
                    iso.area = rect;
                    iso.at = [
                        (rect[0] + rect[2] - scale * (b[0] + b[2])) / 2.0,
                        (rect[1] + rect[3] - scale * (b[1] + b[3])) / 2.0,
                    ];
                    iso.basis += "; orientation fitted around measured linear corridors";
                }
            }
        }
    }
    let [w, h] = plan.sheet.page;
    let too_large = plan.views.iter().filter(|v| v.id != "v:iso").any(|v| {
        v.area[0] < margin() - 1e-6
            || v.area[1] < margin() - 1e-6
            || v.area[2] > w - margin() + 1e-6
            || v.area[3] > h - margin() + 1e-6
    });
    if too_large && !plan.problems.iter().any(|p| p.code == "page_fit_uncertain") {
        plan.problems.push(crate::model::Problem {id:"p:page_fit_uncertain:linear_corridors".into(),code:"page_fit_uncertain".into(),severity:"warning".into(),message:"The composed linear corridors do not fit the drawing area; choose a larger sheet or a smaller scale.".into(),subjects:vec!["sheet".into()],..Default::default()});
    }
    let checked = crate::dims::recheck_cached(analysis, plan, cache);
    let ids: std::collections::BTreeSet<_> = checked
        .iter()
        .map(|p| p.id.clone())
        .chain(previously_checked)
        .collect();
    // Material re-entry diagnostics share a code with foreign-view collisions,
    // but have their own identities and must survive a rigid carrier move.
    plan.problems
        .retain(|p| p.code != "annotation_outside_area" && !ids.contains(&p.id));
    plan.problems.extend(checked);
}

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

    #[test]
    fn authored_notes_do_not_unlock_packing_of_automatic_radius_notes() {
        let (_, a) = crate::model::analyse_native(
            &std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/pmi/step/nist_stc_09_asme1_ap242-e4.stp.gz"),
        )
        .unwrap();
        let spec = serde_json::from_value(serde_json::json!({
            "units": "mm",
            "sheet": {"size": "A0", "scale": "1:5"},
            "notes": [{"id": "n:1", "text": "Deburr all machined edges."}]
        }))
        .unwrap();
        let p = crate::model::plan_escalated(&a, &spec).unwrap();
        assert!(p.notes_block.as_ref().unwrap().ruled);
        let radius = p
            .radius_notes_block
            .as_ref()
            .expect("automatic radius/profile notes accompany authored notes");
        assert!(!radius.ruled);
        assert!(p.notes.iter().all(|n| n.placed.is_some()));
        let mut authored_only = p.clone();
        authored_only.radius_notes_block = None;
        authored_only
            .notes
            .retain(|n| !n.id.starts_with("n:f:blend:"));
        assert!(
            pack_gdt(&a, &authored_only, &authored_only).is_some(),
            "the authored table alone is packable"
        );
        assert!(
            pack_gdt(&a, &p, &p).is_none(),
            "the automatic note recipe must stay fixed"
        );
        assert_eq!(p.radius_notes_block.as_ref().unwrap(), radius);
    }

    #[test]
    fn foreign_sheet_details_do_not_reserve_local_furniture() {
        let (_, a) = crate::model::analyse_native(
            &std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/parts/mounting_plate.step"),
        )
        .unwrap();
        let spec = serde_json::from_value(serde_json::json!({"sheet":{"size":"A2","scale":"1:2"},"views":{"detail_c":{"detail":{"around":"f:hole:f6","from":"plan","scale_factor":2}}}})).unwrap();
        let mut p = crate::model::plan(&a, &spec).unwrap();

        for v in &mut p.views {
            v.sheet = 2;
        }
        let with = furniture_bounds(&a, &p.sheet, &p.views);
        p.views.retain(|v| v.detail.is_none());
        assert_eq!(with, furniture_bounds(&a, &p.sheet, &p.views));
    }

    /// #163: an unused edge of a principal view's band past the border is trimmed once every
    /// drawn footprint is proven inside, so the enlarged sheet is judged by its ink.
    #[test]
    fn an_empty_principal_band_past_the_border_is_trimmed_to_the_frame() {
        let (_, a) = crate::model::analyse_native(
            &std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("tests/fixtures/parts/prismatic.step"),
        )
        .unwrap();
        let spec = serde_json::from_value(serde_json::json!({"sheet":{"size":"A3","scale":"1:1"}}))
            .unwrap();
        let mut p = crate::model::plan(&a, &spec).unwrap();
        assert!(p.gdt.is_empty() && crate::model::drawn_sheets_fit(&a, &p));
        // A plan of the shape the automatic search makes: the estimate's doubt, with a
        // principal (uncut) view's reservation running past the top border into empty paper.
        p.spec.sheet.scale = None;
        p.spec.sheet.size = None;
        // An authored orientation view holds the row, as notes or tables do: only the trim
        // may answer the doubt.
        p.spec.views.insert("iso".into(), Default::default());
        p.problems.push(crate::model::Problem {
            code: "page_fit_uncertain".into(),
            severity: "warning".into(),
            ..Default::default()
        });
        // The topmost principal view, so its grown band meets only empty paper.
        let front = (0..p.views.len())
            .filter(|&i| p.views[i].id != "v:iso")
            .max_by(|&i, &j| p.views[i].area[3].total_cmp(&p.views[j].area[3]))
            .unwrap();
        assert!(p.views[front].cut.is_none());
        let top = p.sheet.page[1];
        p.views[front].area[3] = top;
        assert!(!crate::model::drawn_sheets_fit(&a, &p));
        let ink = footprints(&a, &p);
        correct_estimate(&a, &mut p);
        assert!(p.views[front].area[3] <= top - margin() + 1e-9);
        assert!(crate::model::drawn_sheets_fit(&a, &p));
        assert_eq!(ink.len(), footprints(&a, &p).len());
    }

    fn candidate(scale: f64, width: f64, fill: f64) -> (f64, f64, f64) {
        (scale, width, fill)
    }
    fn c(sheet: usize, scale: f64, fill: f64) -> Candidate {
        x(sheet, scale, fill, 0)
    }
    fn x(sheet: usize, scale: f64, fill: f64, extra_crossings: usize) -> Candidate {
        Candidate {
            sheet,
            scale,
            width: crate::layout::PAGES[sheet].1,
            fill,
            extra_crossings,
        }
    }
    #[test]
    fn band_prefers_scale_then_smaller_paper_otherwise_fullest() {
        let best = candidate(2.0, 297.0, 0.60);
        assert!(rank(best, candidate(1.0, 297.0, 0.85)).is_lt());
        assert!(rank(best, candidate(2.0, 420.0, 0.80)).is_lt());
        assert!(rank(best, candidate(5.0, 420.0, 0.90)).is_lt());
        assert!(rank(candidate(1.0, 297.0, 0.59), candidate(2.0, 420.0, 0.40)).is_lt());
    }
    #[test]
    fn neighbour_requires_enlargement_and_two_steps_are_forbidden() {
        assert!(allowed((0, 1.0), 0, 0.5));
        assert!(!allowed((0, 1.0), 1, 1.0));
        assert!(allowed((0, 1.0), 1, 2.0));
        assert!(!allowed((0, 1.0), 2, 5.0));
    }
    /// 10060 as measured: A4 1:1 17.0% and A3 2:1 14.9%, both valid and below the band.
    #[test]
    fn below_the_band_the_fullest_valid_pair_wins_on_less_paper() {
        let set = [c(0, 1.0, 0.170), c(1, 2.0, 0.149)];
        assert_eq!(choose(&set, false, true), Some((Some(0), (0, 1.0))));
    }
    #[test]
    fn historical_route_reference_keeps_its_original_paper_recipe() {
        let small = candidate(1.0, 297.0, 0.30);
        let large = candidate(2.0, 420.0, 0.40);
        assert!(rank(small, large).is_lt());
        // Changing the live paper rule must not relocate the historical
        // reference's circular callouts (FTC-06's boss moved front -> plan).
        assert!(crate::nominal::with_comparison(|| rank(large, small)).is_lt());
    }
    #[test]
    fn historical_route_reference_breaks_equal_fill_ties_by_scale_then_paper() {
        let small = candidate(1.0, 297.0, 0.40);
        let enlarged = candidate(2.0, 420.0, 0.40);
        assert!(rank(small, enlarged).is_lt());
        crate::nominal::with_comparison(|| {
            // The frozen recipe chooses enlargement before saving paper at equal fill.
            assert!(rank(enlarged, small).is_lt());
            assert!(rank(small, enlarged).is_gt());
            assert!(rank(candidate(2.0, 297.0, 0.40), enlarged).is_lt());
        });
    }
    #[test]
    fn only_the_smallest_fits_largest_scale_and_one_enlarged_step_compete() {
        // A4 1:1 fits. A4 1:2, A3 1:1 and every A2 pair are not allowed, however full.
        let set = [
            c(0, 1.0, 0.30),
            c(0, 0.5, 0.31),
            c(1, 1.0, 0.70),
            c(1, 2.0, 0.40),
            c(2, 5.0, 0.75),
        ];
        // 2026-11-14: the maintainer reversed the fullest-below-band rule;
        // A4 at 30% stays ahead of A3 at 40% until the enlargement reaches 60%.
        assert_eq!(choose(&set, false, true), Some((Some(0), (0, 1.0))));
        // In the band, the larger scale wins, then the smaller sheet.
        let set = [c(0, 1.0, 0.65), c(1, 2.0, 0.62)];
        assert_eq!(choose(&set, false, true).unwrap().0, Some(1));
        let set = [c(0, 2.0, 0.65), c(1, 2.0, 0.70)];
        assert_eq!(choose(&set, false, true).unwrap().0, Some(0));
    }
    /// assembly_plate_pin as measured: a valid A3 1:2 adding two crossings still defines the
    /// smallest fit, so A1 is never reached; A2 1:1, its allowed enlargement, is chosen.
    /// spool_fits: every allowed pair adds crossings, so the valid first estimate is kept.
    #[test]
    fn a_material_veto_never_moves_the_smallest_fit() {
        let set = [
            x(1, 0.5, 0.194, 2),
            x(2, 1.0, 0.245, 0),
            x(2, 0.5, 0.096, 1),
            x(3, 2.0, 0.251, 0),
        ];
        assert_eq!(choose(&set, false, true), Some((Some(1), (1, 0.5))));
        // An invalid first estimate's crossing count vetoes nothing.
        // 2026-11-14: without a material veto, smaller below-band paper wins.
        assert_eq!(choose(&set, false, false), Some((Some(0), (1, 0.5))));
        let spool = [
            x(0, 0.2, 0.226, 4),
            x(1, 0.5, 0.311, 2),
            x(2, 1.0, 0.475, 0),
        ];
        assert_eq!(choose(&spool, false, true), Some((None, (0, 0.2))));
        // 2026-11-14: an invalid seed permits the smallest fit, not the fuller enlargement.
        assert_eq!(choose(&spool, false, false), Some((Some(0), (0, 0.2))));
    }
    #[test]
    fn a_named_sheet_chooses_its_scale_by_fill() {
        let set = [c(2, 1.0, 0.30), c(2, 0.5, 0.12)];
        assert_eq!(choose(&set, true, true).unwrap().0, Some(0));
        assert_eq!(choose(&[], true, true), None);
    }
}