draftwright 0.6.0-alpha.2

Automated technical drawings from STEP B-rep: a Rust port of draftwright.
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
//! Final, bounded route repair against the complete printed inventory (#147).
//! Geometry producers remain in `leaders`; datum triangles never move here.
use std::collections::{BTreeMap, BTreeSet};

use super::{Placed, PlannedDimension, gdt, interior, leaders, placement};
use crate::model::{Analysis, Plan, Problem, Spec};

/// Counts every crossing kind independently, plus every other problem code.
/// Trading a leader/leader crossing for a leader through text is never an improvement.
fn counts(problems: &[Problem]) -> BTreeMap<String, usize> {
    let mut out = BTreeMap::new();
    for p in problems {
        *out.entry(p.code.clone()).or_default() += 1;
        for kind in &p.crossing_kinds {
            *out.entry(format!("crossing:{kind}")).or_default() += 1;
        }
    }
    out
}

fn route_issue(code: &str) -> bool {
    matches!(
        code,
        "annotation_leader_crossing"
            | "annotation_ink_overlap"
            | "annotation_overlap"
            | "annotation_over_view"
            | "annotation_line_over_view"
            | "annotation_leader_long"
    )
}

fn improves(before: &[Problem], after: &[Problem]) -> bool {
    improves_with_contacts(before, after, false)
}

fn improves_with_contacts(before: &[Problem], after: &[Problem], contacts: bool) -> bool {
    let a = counts(before);
    let b = counts(after);
    let defects = |counts: &BTreeMap<String, usize>| {
        counts
            .iter()
            .filter(|(code, _)| {
                route_issue(code)
                    || code.as_str() == "label_crowded"
                    || (contacts
                        && matches!(
                            code.as_str(),
                            "leader_along_centreline"
                                | "annotation_outside_area"
                                | "leader_through_feature"
                                | "leader_centerline_overlap"
                        ))
            })
            .map(|(_, n)| n)
            .sum::<usize>()
    };
    b.iter().all(|(k, n)| *n <= a.get(k).copied().unwrap_or(0)) && defects(&b) < defects(&a)
}

fn no_regression(before: &[Problem], after: &[Problem]) -> bool {
    let (a, b) = (counts(before), counts(after));
    b.iter().all(|(k, n)| *n <= a.get(k).copied().unwrap_or(0))
}

type Extensions = Vec<(usize, [[f64; 2]; 2])>;
fn extension_sets(plan: &Plan) -> BTreeMap<u32, Extensions> {
    let mut out: BTreeMap<u32, Extensions> = BTreeMap::new();
    for (i, d) in plan.dimensions.iter().enumerate() {
        if let Some(p) = &d.placed
            && p.arrows.len() == 2
            && p.lines.len() >= 3
        {
            let page = plan
                .views
                .iter()
                .find(|v| v.id == d.view)
                .map_or(1, |v| v.sheet);
            out.entry(page)
                .or_default()
                .extend(p.lines[..2].iter().map(|e| (i, *e)));
        }
    }
    out
}

/// The complete ring/tag and shaft of a schedule balloon are fixed annotation ink.
pub(super) fn balloon_obstacle(b: &crate::hole_table::Balloon) -> PlannedDimension {
    let [x, y] = b.at;
    let r = b.radius;
    let ring = [x - r, y - r, x + r, y + r];
    let label = b.label_box.unwrap_or_else(|| {
        let ink = super::label_ink(std::slice::from_ref(&b.tag), super::font());
        let w = 0.5 * (ink.max[0] - ink.min[0]);
        let h = 0.5 * (ink.max[1] - ink.min[1]);
        [x - w, y - h, x + w, y + h]
    });
    let box_ = [
        label[0].min(ring[0]),
        label[1].min(ring[1]),
        label[2].max(ring[2]),
        label[3].max(ring[3]),
    ];
    let mut lines = Vec::new();
    if r > 0.0 {
        let corners = [
            [x - r, y - r],
            [x + r, y - r],
            [x + r, y + r],
            [x - r, y + r],
        ];
        lines.extend((0..4).map(|i| [corners[i], corners[(i + 1) % 4]]));
    }
    let mut arrows = Vec::new();
    if let Some([tip, end]) = b.leader {
        lines.push([tip, end]);
        arrows.push(placement::arrow(tip, end));
    }
    PlannedDimension {
        callout_offset: None,
        id: b.id.clone(),
        kind: "ink".into(),
        view: b.view.clone(),
        value: 0.0,
        label: b.tag.clone(),
        terms: vec![b.tag.clone()],
        measurements: Vec::new(),
        default: true,
        from_spec: Vec::new(),
        basis: "balloon".into(),
        state: b.state.clone(),
        region: None,
        reference: false,
        determined_by: Vec::new(),
        placed: Some(Placed {
            label_box: box_,
            label_at: b.at,
            rotation: 0.0,
            lines,
            arrows,
        }),
    }
}

pub(super) fn furniture(plan: &Plan) -> Vec<PlannedDimension> {
    let mut fixed = crate::centrelines::obstacles(&plan.views);
    fixed.extend(plan.tables.iter().filter_map(crate::tables::proxy));
    fixed.extend(
        plan.hole_table
            .iter()
            .chain(&plan.hole_tables)
            .flat_map(|t| &t.blocks)
            .filter_map(crate::tables::proxy),
    );
    fixed.extend(plan.balloons.iter().map(balloon_obstacle));
    for block in [&plan.notes_block, &plan.radius_notes_block]
        .into_iter()
        .flatten()
    {
        fixed.push(crate::notes::proxy(block));
    }
    if let Some(table) = &plan.radius_table {
        fixed.extend(crate::tables::proxy(&table.table));
    }
    fixed.extend(plan.requirements.iter().filter_map(gdt::finish_proxy));
    fixed.extend(plan.captions.iter().map(crate::iso_caption::proxy));
    // Triangles stay fixed; all-around marks travel with their frame's bend.
    // Reserve both independently of the frame's label box.
    for g in &plan.gdt {
        if let Some(p) = &g.placed {
            let mut shapes: Vec<_> = p
                .fills
                .iter()
                .enumerate()
                .map(|(i, fill)| (format!("{}:triangle:{i}", g.id), fill.clone()))
                .collect();
            let count = g
                .modifiers
                .iter()
                .map(|m| if m == "all_over" { 2 } else { 1 })
                .sum();
            for (i, arc) in p.arcs.iter().rev().take(count).enumerate() {
                let [x, y, r, _, _] = *arc;
                shapes.push((
                    format!("{}:modifier:{i}", g.id),
                    vec![
                        [x - r, y - r],
                        [x + r, y - r],
                        [x + r, y + r],
                        [x - r, y + r],
                    ],
                ));
            }
            for (id, fill) in shapes {
                let mut d = gdt::proxy(g).expect("a placed glyph has a proxy");
                d.id = id;
                d.kind = "ink".into();
                let b = fill.iter().fold(
                    [
                        f64::INFINITY,
                        f64::INFINITY,
                        f64::NEG_INFINITY,
                        f64::NEG_INFINITY,
                    ],
                    |b, p| {
                        [
                            b[0].min(p[0]),
                            b[1].min(p[1]),
                            b[2].max(p[0]),
                            b[3].max(p[1]),
                        ]
                    },
                );
                let p = d.placed.as_mut().expect("the proxy retains its placement");
                p.label_box = b;
                p.lines = (0..fill.len())
                    .map(|i| [fill[i], fill[(i + 1) % fill.len()]])
                    .collect();
                p.arrows.clear();
                fixed.push(d);
            }
        }
    }
    fixed
}

/// Generic callout routes leave a text gap and centre on the full reservation.
/// A frame instead meets its actual rule, below any count above the box. Do this
/// before checking the candidate, so collisions see exactly the printed route.
fn meet_frame(g: &gdt::PlannedGdt, next: &mut Placed) -> bool {
    let Some(p) = g.placed.as_ref().filter(|_| g.kind == "control_frame") else {
        return true;
    };
    if p.frame_strokes == 0 || p.strokes.is_empty() || next.lines.is_empty() {
        return false;
    }
    let bounds = p.strokes.iter().take(p.frame_strokes).flatten().fold(
        [
            f64::INFINITY,
            f64::INFINITY,
            f64::NEG_INFINITY,
            f64::NEG_INFINITY,
        ],
        |b, q| {
            [
                b[0].min(q[0]),
                b[1].min(q[1]),
                b[2].max(q[0]),
                b[3].max(q[1]),
            ]
        },
    );
    let dx = next.label_box[0] - p.label_box[0];
    let dy = next.label_box[1] - p.label_box[1];
    let y = 0.5 * (bounds[1] + bounds[3]) + dy;
    let last = next.lines.len() - 1;
    let shelf = &mut next.lines[last];
    let x = if shelf[1][0] >= shelf[0][0] {
        bounds[0]
    } else {
        bounds[2]
    } + dx;
    shelf[1] = [x, y];
    if last > 0 {
        shelf[0][1] = y;
        let bend = shelf[0];
        next.lines[last - 1][1] = bend;
    }
    if last <= 1 {
        let shaft = next.lines[0];
        if (shaft[1][0] - shaft[0][0]).hypot(shaft[1][1] - shaft[0][1]) + 1e-9 < super::ARROW {
            return false;
        }
        for arrow in &mut next.arrows {
            if arrow[0] == shaft[0] {
                *arrow = placement::arrow(shaft[0], shaft[1]);
            }
        }
    }
    true
}

fn rehang(g: &mut gdt::PlannedGdt, next: &Placed) {
    let p = g.placed.as_mut().expect("placed glyph");
    let delta = [
        next.label_box[0] - p.label_box[0],
        next.label_box[1] - p.label_box[1],
    ];
    let shift = |q: &mut [f64; 2]| {
        q[0] += delta[0];
        q[1] += delta[1];
    };
    // The glyph and text move as one rigid object: compartment widths and text size stay.
    for line in &mut p.strokes {
        for q in line {
            shift(q);
        }
    }
    for arc in &mut p.arcs {
        arc[0] += delta[0];
        arc[1] += delta[1];
    }
    for text in p.letters.iter_mut().chain(&mut p.runs) {
        shift(&mut text.at);
    }
    if g.kind != "datum_feature" {
        let old_elbow = p.lines.first().map(|s| s[1]);
        let new_elbow = next.lines.first().map(|s| s[1]);
        // All-around/all-over rings belong at the bend, rather than on the frame.
        if let (Some(a), Some(b)) = (old_elbow, new_elbow) {
            let count = g
                .modifiers
                .iter()
                .map(|m| if m == "all_over" { 2 } else { 1 })
                .sum::<usize>();
            for arc in p.arcs.iter_mut().rev().take(count) {
                arc[0] += b[0] - a[0] - delta[0];
                arc[1] += b[1] - a[1] - delta[1];
            }
        }
        p.tip = next.lines[0][0];
    }
    p.lines.clone_from(&next.lines);
    p.arrows.clone_from(&next.arrows);
    p.label_box = next.label_box;
}

/// Feature callouts over blank face (maintainer 2026-10-25: more labels over the interior). Each
/// automatic feature callout drawn outside its view takes the best interior route the
/// settled-route sweep offers, when its whole label is on proven blank face, its leader is no
/// longer and none of its findings grows, code by code. Linear dimensions stay outside.
///
/// *natural* is the same request finished without the Spec's omissions. When it shares this
/// drawing's paper and view positions, its moves are copied for the items both draw and no other
/// item moves, so omitting one item moves no other.
pub(crate) fn prefer_interior(
    analysis: &Analysis,
    spec: &Spec,
    plan: &mut Plan,
    natural: Option<&Plan>,
) {
    if crate::nominal::comparison() {
        return;
    }
    let cache = super::footprints::Cache::default();
    if let Some(n) = natural.filter(|n| {
        n.sheet.size == plan.sheet.size
            && n.sheet.scale == plan.sheet.scale
            && n.views.len() == plan.views.len()
            && n.views
                .iter()
                .zip(&plan.views)
                .all(|(a, b)| a.id == b.id && a.at == b.at)
    }) {
        let mut all = plan.dimensions.clone();
        all.extend(plan.gdt.iter().filter_map(gdt::proxy));
        let mut changed = BTreeSet::new();
        let mut rechecked_codes = BTreeSet::new();
        for i in 0..plan.dimensions.len() {
            let d = &plan.dimensions[i];
            let Some(q) = n.dimensions.iter().find(|q| {
                q.id == d.id
                    && q.region == Some(super::CandidateRegion::Interior)
                    && q.basis.contains(interior::BASIS)
            }) else {
                continue;
            };
            if d.kind != "callout"
                || d.region == Some(super::CandidateRegion::Interior)
                || d.placed == q.placed
                || spec
                    .dimensions
                    .get(&d.id)
                    .is_some_and(|s| s.place.is_some())
            {
                continue;
            }
            let Some(sheet) = plan.views.iter().find(|v| v.id == d.view).and_then(|v| {
                std::iter::once(&plan.sheet)
                    .chain(&plan.sheets)
                    .find(|s| s.number == v.sheet)
            }) else {
                continue;
            };
            rechecked_codes.extend(
                placement::collisions_for(analysis, &all, sheet, &plan.views, &cache, &d.id)
                    .into_iter()
                    .map(|p| p.code),
            );
            all[i].placed.clone_from(&q.placed);
            all[i].region = q.region;
            let d = &mut plan.dimensions[i];
            d.placed.clone_from(&q.placed);
            d.region = q.region;
            d.basis.clone_from(&q.basis);
            if let Some(t) = n.callout_tips.get(&d.id) {
                plan.callout_tips.insert(d.id.clone(), t.clone());
            }
            changed.insert(d.id.clone());
        }
        refresh(analysis, plan, &all, &cache, &changed, &rechecked_codes);
        return;
    }
    let proofs = interior::callout_proofs(analysis, &plan.views);
    let mut wants = super::wants(analysis).0;
    let frames: BTreeMap<_, _> = plan
        .views
        .iter()
        .filter_map(|v| {
            let name = v.id.strip_prefix("v:")?;
            super::NAMES
                .contains(&name)
                .then(|| (name, placement::Frame::new(analysis, v)))
        })
        .collect();
    super::detail_routes(analysis, &mut wants, &plan.views);
    super::route(&mut wants, &frames, analysis);
    let fixed = furniture(plan);
    let mut all = plan.dimensions.clone();
    all.extend(plan.gdt.iter().filter_map(gdt::proxy));
    let mut changed = BTreeSet::new();
    let mut rechecked_codes = BTreeSet::new();
    let length = |p: &Placed| {
        p.lines
            .iter()
            .map(|[a, b]| (b[0] - a[0]).hypot(b[1] - a[1]))
            .sum::<f64>()
    };
    // Repeat until nothing moves, so finishing a finished drawing changes nothing: a callout
    // moved inside can free the room another one needs.
    for _ in 0..4 {
        let moved = changed.len();
        for i in 0..plan.dimensions.len() {
            let d = &all[i];
            let Some(old) = d.placed.clone() else {
                continue;
            };
            if d.kind != "callout"
                || d.region == Some(super::CandidateRegion::Interior)
                || spec
                    .dimensions
                    .get(&d.id)
                    .is_some_and(|s| s.place.is_some())
            {
                continue;
            }
            let Some(view) = plan.views.iter().find(|v| v.id == d.view) else {
                continue;
            };
            let (Some(frame), Some(proof)) = (
                frames.get(view.id.trim_start_matches("v:")),
                proofs.get(&view.id),
            ) else {
                continue;
            };
            if placement::boxes_overlap(old.label_box, frame.outline()) {
                continue;
            }
            let Some(sheet) = std::iter::once(&plan.sheet)
                .chain(&plan.sheets)
                .find(|s| s.number == view.sheet)
            else {
                continue;
            };
            let Some(want) = wants.iter().find(|w| w.id == d.id) else {
                continue;
            };
            let peers: Vec<_> = all
                .iter()
                .enumerate()
                .filter(|(j, q)| {
                    *j != i
                        && plan
                            .views
                            .iter()
                            .find(|v| v.id == q.view)
                            .is_none_or(|v| v.sheet == sheet.number)
                })
                .map(|(_, q)| q.clone())
                .chain(fixed.iter().cloned())
                .collect();
            let candidates = leaders::settled_routes(
                analysis,
                sheet,
                &plan.views,
                d,
                Some(want),
                &peers,
                Some(proof.as_ref()),
            );
            let id = d.id.clone();
            let found = placement::collisions_for(analysis, &all, sheet, &plan.views, &cache, &id);
            let before = counts(&found);
            for next in candidates.into_iter().take(40) {
                if !placement::boxes_overlap(next.label_box, frame.outline())
                    || !proof.annotation_clear(view, &next, true)
                    || length(&next) > length(&old) + 1e-6
                {
                    continue;
                }
                all[i].placed = Some(next.clone());
                let after = counts(&placement::collisions_for(
                    analysis,
                    &all,
                    sheet,
                    &plan.views,
                    &cache,
                    &id,
                ));
                if after
                    .iter()
                    .all(|(code, n)| before.get(code).is_some_and(|m| n <= m))
                {
                    rechecked_codes.extend(found.iter().map(|p| p.code.clone()));
                    changed.insert(id.clone());
                    let d = &mut plan.dimensions[i];
                    d.placed = Some(next.clone());
                    d.region = Some(super::CandidateRegion::Interior);
                    if !d.basis.contains(interior::BASIS) {
                        d.basis += interior::BASIS;
                    }
                    all[i].region = d.region;
                    plan.callout_tips.insert(
                        id.clone(),
                        (
                            d.view.clone(),
                            [
                                next.lines[0][0][0] - view.at[0],
                                next.lines[0][0][1] - view.at[1],
                            ],
                        ),
                    );
                    break;
                }
                all[i].placed = Some(old.clone());
            }
        }
        if changed.len() == moved {
            break;
        }
    }
    refresh(analysis, plan, &all, &cache, &changed, &rechecked_codes);
}

/// A moved callout's collision findings, measured again where it now stands.
pub(super) fn refresh(
    analysis: &Analysis,
    plan: &mut Plan,
    all: &[PlannedDimension],
    cache: &super::footprints::Cache,
    changed: &BTreeSet<String>,
    rechecked_codes: &BTreeSet<String>,
) {
    if changed.is_empty() {
        return;
    }
    let checked: Vec<_> = std::iter::once(&plan.sheet)
        .chain(&plan.sheets)
        .flat_map(|s| placement::collisions_cached(analysis, all, s, &plan.views, cache))
        .collect();
    plan.problems.retain(|p| {
        !p.subjects.iter().any(|s| changed.contains(s)) || !rechecked_codes.contains(&p.code)
    });
    plan.problems.extend(checked.into_iter().filter(|p| {
        p.subjects.iter().any(|s| changed.contains(s)) && rechecked_codes.contains(&p.code)
    }));
    plan.sheet.fill = crate::sheet_fit::fill(analysis, plan);
    plan.status = crate::completeness::status(&plan.problems);
}

/// Final text clearance is inspected on the same filled arrowheads and
/// labels as the reported contacts, after local opening dimensions are added.
fn crowding(
    analysis: &Analysis,
    plan: &Plan,
    all: &[PlannedDimension],
    dimension_count: usize,
    id: &str,
    fixed_strokes: bool,
) -> Vec<Problem> {
    let mut candidate = plan.clone();
    candidate.dimensions = all[..dimension_count].to_vec();
    super::contacts::report(analysis, &mut candidate);
    if fixed_strokes {
        candidate
            .problems
            .extend(super::contacts::fixed_stroke_contacts(&candidate));
    }
    candidate
        .problems
        .into_iter()
        .filter(|p| {
            matches!(
                p.code.as_str(),
                "label_crowded"
                    | "leader_across_view"
                    | "leader_to_hidden_edge"
                    | "leader_along_centreline"
                    | "leader_centerline_overlap"
            ) && p.subjects.iter().any(|s| s == id)
        })
        .collect()
}

pub(crate) fn finish(analysis: &Analysis, spec: &Spec, plan: &mut Plan) {
    finish_with(analysis, spec, plan, false, None);
}

/// Repair independent frames after their neighbours have attached as units.
/// Size labels and attached hole frames remain fixed together.
pub(crate) fn finish_frames(analysis: &Analysis, spec: &Spec, plan: &mut Plan) {
    finish_with(analysis, spec, plan, true, None);
}

// Transport a proven native callout corridor between identical projection owners.
// Attachment and elbow follow model scale; text, shoulder and arrow length stay in paper mm.
fn reference_route(
    d: &PlannedDimension,
    view: &crate::model::PlannedView,
    reference: &Plan,
) -> Option<Placed> {
    let old = reference
        .dimensions
        .iter()
        .find(|q| q.id == d.id && q.view == d.view && q.terms == d.terms)?;
    let old_view = reference.views.iter().find(|v| {
        v.id == d.view
            && v.direction == view.direction
            && v.up == view.up
            && v.cut == view.cut
            && v.detail == view.detail
    })?;
    let p = old.placed.as_ref()?;
    let shaft = *p.lines.first()?;
    let map = |q: [f64; 2]| {
        [0, 1].map(|k| view.at[k] + (q[k] - old_view.at[k]) * view.scale / old_view.scale)
    };
    let tip = map(shaft[0]);
    let elbow = map(shaft[1]);
    let delta = [0, 1].map(|k| elbow[k] - shaft[1][k]);
    let mut next = p.clone();
    for q in next.lines.iter_mut().skip(1).flatten() {
        crate::placement_intent::move_point(q, delta);
    }
    next.lines[0] = [tip, elbow];
    next.arrows = p
        .arrows
        .iter()
        .map(|[a, b]| [map(*a), [0, 1].map(|k| tip[k] + b[k] - a[k])])
        .collect();
    crate::placement_intent::move_point(&mut next.label_at, delta);
    crate::placement_intent::move_box(&mut next.label_box, delta);
    Some(next)
}

/// Repair only contacts newly introduced by a paper/scale candidate. Existing
/// contacts in the displaced drawing keep the established routing policy.
pub(crate) fn finish_new_contacts(
    analysis: &Analysis,
    spec: &Spec,
    plan: &mut Plan,
    ids: &BTreeSet<String>,
    reference: &Plan,
) {
    finish_with(analysis, spec, plan, false, Some((ids, reference)));
}

fn finish_with(
    analysis: &Analysis,
    spec: &Spec,
    plan: &mut Plan,
    only_frames: bool,
    new_contacts: Option<(&BTreeSet<String>, &Plan)>,
) {
    let pmi_retry = placement::pmi_witness_retry(analysis);
    let openings = plan.dimensions.iter().any(|d| {
        d.measurements
            .iter()
            .any(|m| m.feature.starts_with("f:rectangular_through_notch:"))
    });
    let repair_issue = |code: &str| {
        route_issue(code)
            || (openings && code == "label_crowded")
            || (new_contacts.is_some()
                && matches!(
                    code,
                    "leader_along_centreline"
                        | "annotation_outside_area"
                        | "leader_through_feature"
                        | "leader_centerline_overlap"
                ))
    };
    // Added lanes must not leave an otherwise unreported leader alongside
    // an extension. Use the placer's existing one-mm contact predicate.
    let extension_sets = if openings || pmi_retry || new_contacts.is_some() {
        extension_sets(plan)
    } else {
        BTreeMap::new()
    };
    // Attached marks move with their authored unit. Before attachment, PMI
    // callouts may retry their changed witness corridors; the ordinary hole
    // attachment pass then proves a place for each frame beside the new label.
    let coupled: BTreeSet<_> = if (openings || pmi_retry)
        && !plan.gdt.is_empty()
        && (!pmi_retry || plan.gdt.iter().any(super::hole_marks::attached))
    {
        super::hole_marks::attachments(analysis, plan)
            .into_iter()
            .filter(|(id, _)| {
                !pmi_retry
                    || plan
                        .gdt
                        .iter()
                        .any(|g| &g.id == id && super::hole_marks::attached(g))
            })
            .filter_map(|(_, callout)| callout)
            .collect()
    } else {
        BTreeSet::new()
    };
    let extension_bad: BTreeSet<_> = plan
        .dimensions
        .iter()
        .filter(|d| {
            d.kind == "callout"
                && !coupled.contains(&d.id)
                && (pmi_retry || !d.measurements.iter().any(|m| m.feature.starts_with("pmi:")))
        })
        .filter_map(|d| {
            let p = d.placed.as_ref()?;
            let page = plan.views.iter().find(|v| v.id == d.view)?.sheet;
            let extensions = extension_sets.get(&page)?;
            (leaders::extension_contacts(extensions, &p.lines, p.label_box).0 > 0)
                .then(|| d.id.clone())
        })
        .collect();
    let initial_contacts = if openings || new_contacts.is_some() {
        let mut found = super::contacts::contacts(plan);
        if new_contacts.is_some() {
            found.extend(super::contacts::fixed_stroke_contacts(plan));
        }
        found
    } else {
        Vec::new()
    };
    if crate::nominal::comparison()
        || crate::planning::lookup::<bool>(analysis, "canonical-circular-recipes", &[])
            .unwrap_or(false)
        || (!plan
            .problems
            .iter()
            .chain(&initial_contacts)
            .any(|p| repair_issue(&p.code))
            && extension_bad.is_empty())
    {
        return;
    }
    let mut affected_ids: BTreeSet<_> = plan
        .problems
        .iter()
        .chain(&initial_contacts)
        .filter(|p| repair_issue(&p.code))
        .flat_map(|p| p.subjects.iter().cloned())
        .collect();
    affected_ids.extend(extension_bad.iter().cloned());
    if let Some((ids, _)) = new_contacts {
        affected_ids.retain(|id| ids.contains(id));
    }
    if only_frames
        && !plan.gdt.iter().any(|g| {
            g.placed.is_some()
                && affected_ids.contains(&g.id)
                && (!super::hole_marks::attached(g) || g.side == "leader")
        })
    {
        return;
    }
    if !plan
        .dimensions
        .iter()
        .any(|d| d.kind == "callout" && d.placed.is_some() && affected_ids.contains(&d.id))
        && !plan.gdt.iter().any(|g| {
            g.kind != "surface_finish" && g.placed.is_some() && affected_ids.contains(&g.id)
        })
    {
        return;
    }
    let cache = super::footprints::Cache::default();
    let proofs = interior::proofs(analysis, &plan.views);
    let exterior = if plan.gdt.iter().any(|g| g.kind == "datum_feature") {
        interior::exterior_proofs(analysis, &plan.views)
    } else {
        BTreeMap::new()
    };
    let mut wants = super::wants(analysis).0;
    let frames = plan
        .views
        .iter()
        .filter_map(|v| {
            let name = super::NAMES
                .iter()
                .chain(crate::detail::NAMES.iter())
                .copied()
                .find(|name| v.id.strip_prefix("v:") == Some(*name))?;
            Some((name, placement::Frame::new(analysis, v)))
        })
        .collect();
    super::detail_routes(analysis, &mut wants, &plan.views);
    super::route(&mut wants, &frames, analysis);
    let mut fixed = furniture(plan);
    let mut all = plan.dimensions.clone();
    all.extend(plan.gdt.iter().filter_map(gdt::proxy));
    let dimension_count = plan.dimensions.len();
    let mut changed = BTreeSet::new();
    let mut rechecked_codes = BTreeSet::new();
    // Settle the established straight-normal/frame/callout inventory first.
    // Bends may then improve datums against those fixed routes, without taking
    // a corridor a later frame needed to escape a worse initial arrangement.
    for bends in [false, true] {
        if bends && !plan.gdt.iter().any(|g| g.kind == "datum_feature") {
            continue;
        }
        for _ in 0..2 {
            let mut moved = false;
            for i in 0..all.len() {
                let d = &all[i];
                if (bends && !d.id.starts_with("pmi:datum."))
                    || (only_frames
                        && (i < dimension_count
                            || plan.gdt.iter().find(|g| g.id == d.id).is_some_and(|g| {
                                super::hole_marks::attached(g) && g.side != "leader"
                            })))
                    || !affected_ids.contains(&d.id)
                    || d.kind != "callout"
                    || d.placed.is_none()
                    || spec
                        .dimensions
                        .get(&d.id)
                        .is_some_and(|s| s.place.is_some())
                    || spec
                        .annotations
                        .get(&d.id)
                        .is_some_and(|s| s.place.is_some())
                {
                    continue;
                }
                let Some(view) = plan.views.iter().find(|v| v.id == d.view) else {
                    continue;
                };
                let Some(sheet) = std::iter::once(&plan.sheet)
                    .chain(&plan.sheets)
                    .find(|s| s.number == view.sheet)
                else {
                    continue;
                };
                let mut before =
                    placement::collisions_for(analysis, &all, sheet, &plan.views, &cache, &d.id);
                if (openings || new_contacts.is_some()) && i < dimension_count {
                    before.extend(crowding(
                        analysis,
                        plan,
                        &all,
                        dimension_count,
                        &d.id,
                        new_contacts.is_some(),
                    ));
                }
                let extension_retry =
                    only_frames || new_contacts.is_some() || extension_bad.contains(&d.id);
                let extension_budget = |p: &Placed| {
                    if !extension_retry {
                        return (0, 0);
                    }
                    extension_sets.get(&sheet.number).map_or((0, 0), |e| {
                        leaders::extension_contacts(e, &p.lines, p.label_box)
                    })
                };
                let before_extension = extension_budget(d.placed.as_ref().expect("placed callout"));
                if !before.iter().any(|p| repair_issue(&p.code)) && before_extension.0 == 0 {
                    continue;
                }
                let glyph = plan.gdt.iter().find(|g| g.id == d.id).cloned();
                let want = wants.iter().find(|w| w.id == d.id);
                if glyph.is_none() && want.is_none() {
                    continue;
                }
                // Finishes have a prescribed outward normal, independent of leadered labels.
                if glyph.as_ref().is_some_and(|g| g.kind == "surface_finish") {
                    continue;
                }
                let triangle_prefix = format!("{}:triangle:", d.id);
                let modifier_prefix = format!("{}:modifier:", d.id);
                let peers: Vec<_> = all
                    .iter()
                    .enumerate()
                    .filter(|(j, q)| {
                        *j != i
                            && plan
                                .views
                                .iter()
                                .find(|v| v.id == q.view)
                                .is_none_or(|v| v.sheet == sheet.number)
                    })
                    .map(|(_, q)| q.clone())
                    .chain(
                        fixed
                            .iter()
                            .filter(|q| {
                                !q.id.starts_with(&triangle_prefix)
                                    && !q.id.starts_with(&modifier_prefix)
                            })
                            .cloned(),
                    )
                    .collect();
                // A reduced drawing can have settled on the wrong hemisphere of
                // a hole. Seed the bounded sweep from the displaced drawing's proven
                // attachment as well, rather than examining only its bad nearby tips.
                let inherited_route = new_contacts.and_then(|(_, reference)| {
                    before
                        .iter()
                        .any(|p| p.code == "leader_through_feature")
                        .then(|| reference_route(d, view, reference))
                        .flatten()
                });
                let mut seeded = d.clone();
                if let Some(route) = &inherited_route {
                    seeded.placed = Some(route.clone());
                }
                let mut candidates = if glyph.as_ref().is_some_and(|g| g.kind == "datum_feature") {
                    gdt::normal_routes(glyph.as_ref().expect("datum"), bends)
                } else {
                    leaders::settled_routes(
                        analysis,
                        sheet,
                        &plan.views,
                        &seeded,
                        want,
                        &peers,
                        proofs.get(&view.id).map(|p| p.as_ref()),
                    )
                };
                if before_extension.0 > 0 {
                    candidates.sort_by_cached_key(&extension_budget);
                }
                if let Some(route) = inherited_route {
                    candidates.insert(0, route);
                }
                let id = d.id.clone();
                let old = d.placed.clone();
                let mut grown_area = None;
                let limit = if glyph.as_ref().is_some_and(|g| g.kind == "datum_feature") {
                    candidates.len()
                } else {
                    40
                };
                for mut next in candidates.into_iter().take(limit) {
                    if let Some(g) = &glyph
                        && !meet_frame(g, &mut next)
                    {
                        continue;
                    }
                    // The all-around/all-over marks travel with the bend. Reserve
                    // their actual extent as well as the proxy's shaft and frame.
                    if let Some(g) = glyph.as_ref().filter(|g| !g.modifiers.is_empty()) {
                        let ring = if g.modifiers.iter().any(|m| m == "all_over") {
                            1.7 * 0.42 * super::TEXT
                        } else {
                            0.42 * super::TEXT
                        } + 0.5;
                        let bend = next.lines[0][1];
                        let b = [
                            bend[0] - ring,
                            bend[1] - ring,
                            bend[0] + ring,
                            bend[1] + ring,
                        ];
                        let ring_clear = proofs.get(&view.id).map_or_else(
                            || {
                                frames
                                    .get(view.id.trim_start_matches("v:"))
                                    .is_none_or(|f| !placement::boxes_overlap(b, f.outline()))
                            },
                            |p| p.blank(view, b) || p.exterior_clear(view, b, &[], &[]),
                        );
                        if !ring_clear
                            || peers.iter().filter_map(|d| d.placed.as_ref()).any(|p| {
                                placement::boxes_overlap(b, p.label_box)
                                    || p.lines
                                        .iter()
                                        .chain(&p.arrows)
                                        .any(|s| leaders::touches_box(*s, b))
                            })
                            || (proofs
                                .get(&view.id)
                                .is_some_and(|p| p.blank(view, next.label_box))
                                && !proofs[&view.id].blank(view, b))
                        {
                            continue;
                        }
                    }
                    // Full sheet furniture is fixed even when collision reporting only
                    // enumerates dimensions and PMI. Keep the existing 1 mm text gap.
                    let pad = [
                        next.label_box[0] - 1.,
                        next.label_box[1] - 1.,
                        next.label_box[2] + 1.,
                        next.label_box[3] + 1.,
                    ];
                    // A bent datum must not trade a crossing for a shaft that
                    // reads as touching another letter box on the finished drawing.
                    let shaft_gap = if glyph.as_ref().is_some_and(|g| g.kind == "datum_feature") {
                        super::contacts::TEXT_CLEAR
                    } else {
                        0.0
                    };
                    if peers.iter().filter_map(|q| q.placed.as_ref()).any(|q| {
                        let text = [
                            q.label_box[0] - shaft_gap,
                            q.label_box[1] - shaft_gap,
                            q.label_box[2] + shaft_gap,
                            q.label_box[3] + shaft_gap,
                        ];
                        placement::boxes_overlap(pad, q.label_box)
                            || q.lines
                                .iter()
                                .chain(&q.arrows)
                                .any(|s| placement::crosses(*s, pad))
                            || next.lines.iter().any(|s| placement::crosses(*s, text))
                    }) {
                        continue;
                    }

                    all[i].placed = Some(next.clone());
                    // A free source callout can need a little more of its view's
                    // annotation band after witness lanes move. Reuse the hole
                    // attachment proof: grow only into vacant drawable paper.
                    let area = if ((pmi_retry && extension_retry) || new_contacts.is_some())
                        && i < dimension_count
                    {
                        super::ink_box(&all[i]).and_then(|ink| {
                            super::hole_marks::grown(view, ink, sheet, &plan.views, &peers)
                        })
                    } else {
                        None
                    };
                    let trial_views = area.map(|area| {
                        let mut views = plan.views.clone();
                        views.iter_mut().find(|v| v.id == view.id).unwrap().area = area;
                        views
                    });
                    let mut after = placement::collisions_for(
                        analysis,
                        &all,
                        sheet,
                        trial_views.as_deref().unwrap_or(&plan.views),
                        &cache,
                        &id,
                    );
                    if (openings || new_contacts.is_some()) && i < dimension_count {
                        after.extend(crowding(
                            analysis,
                            plan,
                            &all,
                            dimension_count,
                            &id,
                            new_contacts.is_some(),
                        ));
                    }
                    let next_extension = extension_budget(&next);
                    if next_extension.0 <= before_extension.0
                        && next_extension.1 <= before_extension.1
                        && ((if new_contacts.is_some() {
                            improves_with_contacts(&before, &after, true)
                        } else {
                            improves(&before, &after)
                        }) || (next_extension.0 < before_extension.0
                            && no_regression(&before, &after)))
                    {
                        rechecked_codes.extend(before.iter().chain(&after).map(|p| p.code.clone()));
                        if i < dimension_count {
                            let d = &mut plan.dimensions[i];
                            let inside = proofs
                                .get(&view.id)
                                .is_some_and(|p| p.annotation_clear(view, &next, true));
                            d.region = inside.then_some(super::CandidateRegion::Interior);
                            if inside {
                                if !d.basis.contains(interior::BASIS) {
                                    d.basis += interior::BASIS;
                                }
                            } else {
                                d.basis = d.basis.replace(interior::BASIS, "");
                            }
                            d.placed = Some(next.clone());
                            plan.callout_tips.insert(
                                id.clone(),
                                (
                                    d.view.clone(),
                                    [
                                        next.lines[0][0][0] - view.at[0],
                                        next.lines[0][0][1] - view.at[1],
                                    ],
                                ),
                            );
                        } else if let Some(g) = plan.gdt.iter_mut().find(|g| g.id == id) {
                            rehang(g, &next);
                            let inside = proofs
                                .get(&view.id)
                                .is_some_and(|p| p.blank(view, next.label_box))
                                || (g.kind == "datum_feature"
                                    && exterior
                                        .get(&view.id)
                                        .is_some_and(|p| p.exterior_annotation_clear(view, &next)));
                            let inside =
                                inside
                                    && frames.get(view.id.trim_start_matches("v:")).is_some_and(
                                        |f| placement::boxes_overlap(next.label_box, f.outline()),
                                    );
                            if inside {
                                if !g.basis.contains(interior::BASIS) {
                                    g.basis += interior::BASIS;
                                }
                            } else {
                                g.basis = g.basis.replace(interior::BASIS, "");
                            }
                            if g.kind != "datum_feature"
                                && !inside
                                && let Some(frame) = frames.get(view.id.trim_start_matches("v:"))
                            {
                                let o = frame.outline();
                                let b = next.label_box;
                                g.side = if b[2] <= o[0] {
                                    "left"
                                } else if b[0] >= o[2] {
                                    "right"
                                } else if b[1] >= o[3] {
                                    "above"
                                } else {
                                    "below"
                                }
                                .into();
                            }
                        }
                        if glyph.as_ref().is_some_and(|g| !g.modifiers.is_empty()) {
                            fixed = furniture(plan);
                        }
                        changed.insert(id.clone());
                        grown_area = area.map(|area| (view.id.clone(), area));
                        moved = true;
                        break;
                    }
                    all[i].placed.clone_from(&old);
                }
                if let Some((id, area)) = grown_area {
                    plan.views.iter_mut().find(|v| v.id == id).unwrap().area = area;
                }
            }
            if !moved {
                break;
            }
        }
    }
    if changed.is_empty() {
        return;
    }
    let checked: Vec<_> = std::iter::once(&plan.sheet)
        .chain(&plan.sheets)
        .flat_map(|s| placement::collisions_cached(analysis, &all, s, &plan.views, &cache))
        .collect();
    // Replace only findings involving changed ink; untouched diagnostics retain their identity.
    plan.problems.retain(|p| {
        !p.subjects.iter().any(|s| changed.contains(s))
            || !(rechecked_codes.contains(&p.code)
                || matches!(
                    p.code.as_str(),
                    "annotation_leader_long" | "annotation_line_over_view"
                ))
    });
    plan.problems.extend(
        checked
            .into_iter()
            .filter(|p| p.subjects.iter().any(|s| changed.contains(s))),
    );
    plan.sheet.fill = crate::sheet_fit::fill(analysis, plan);
    plan.status = crate::completeness::status(&plan.problems);
}

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

    fn crossing(kinds: &[&str]) -> Problem {
        Problem {
            code: "annotation_leader_crossing".into(),
            crossing_kinds: kinds.iter().map(|s| (*s).into()).collect(),
            ..Default::default()
        }
    }

    #[test]
    fn a_route_must_improve_crossings_without_trading_kinds_or_text() {
        let before = vec![crossing(&["leader"]), crossing(&["extension_line"])];
        assert!(improves(&before, &[crossing(&["extension_line"])]));
        assert!(!improves(&before, &[crossing(&["arrow"])]));
        assert!(improves(
            &[Problem {
                code: "annotation_ink_overlap".into(),
                ..Default::default()
            }],
            &[]
        ));
        assert!(
            !improves(&before, &before),
            "ties retain the existing exterior route"
        );
        assert!(!improves(
            &before,
            &[Problem {
                code: "annotation_ink_overlap".into(),
                ..Default::default()
            }]
        ));
    }

    #[test]
    fn repaired_frame_routes_meet_both_rules_below_the_count() {
        let g: gdt::PlannedGdt = serde_json::from_value(serde_json::json!({
            "id":"frame", "kind":"control_frame", "view":"v:front", "cells":["position","0.1"],
            "side":"right", "source":"test", "faces":[], "label":"position 0.1",
            "default":true, "basis":"test", "state":{"kind":"shown"},
            "placed":{
                "tip":[-10.,0.], "label_box":[0.,0.,20.,10.5], "lines":[], "arrows":[],
                "strokes":[[[0.,0.],[20.,0.]],[[20.,0.],[20.,5.]],[[20.,5.],[0.,5.]],[[0.,5.],[0.,0.]]],
                "frame_strokes":4, "arcs":[], "fills":[], "letters":[], "runs":[]
            }
        })).unwrap();
        for (tip, bend, text_end, edge) in [
            ([30., 40.], [35., 55.25], [39., 55.25], 40.),
            ([70., 40.], [65., 55.25], [61., 55.25], 60.),
        ] {
            let mut next = Placed {
                lines: vec![[tip, bend], [bend, text_end]],
                arrows: vec![placement::arrow(tip, bend)],
                label_box: [40., 50., 60., 60.5],
                label_at: [40., 50.],
                rotation: 0.,
            };
            assert!(meet_frame(&g, &mut next));
            assert_eq!(next.lines[1][1], [edge, 52.5]);
            assert_eq!(next.lines[0][1], next.lines[1][0]);
            assert_eq!(next.lines[1][0][1], next.lines[1][1][1]);
            assert_eq!(next.arrows, [placement::arrow(tip, next.lines[0][1])]);
            assert_eq!(next.label_box, [40., 50., 60., 60.5]);
        }
        let mut short = Placed {
            lines: vec![[[35., 52.], [35., 55.25]], [[35., 55.25], [39., 55.25]]],
            arrows: vec![placement::arrow([35., 52.], [35., 55.25])],
            label_box: [40., 50., 60., 60.5],
            label_at: [40., 50.],
            rotation: 0.,
        };
        assert!(
            !meet_frame(&g, &mut short),
            "the adjusted shaft must carry its whole arrow"
        );
    }

    #[test]
    fn a_final_frame_cannot_cross_a_schedule_balloon_label() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/parts/mounting_plate.step");
        let a = crate::model::analyse_native(&path).unwrap().1;
        let mut plan = crate::model::plan(&a, &Spec::default()).unwrap();
        plan.balloons.push(crate::hole_table::Balloon {
            label_box_before: None,
            id: "schedule/tag/B8".into(),
            tag: "B8".into(),
            view: "v:plan".into(),
            features: Vec::new(),
            certifying: true,
            interior: false,
            at: [140., 170.],
            radius: 0.,
            label_box: Some([138., 168.5, 142., 171.5]),
            leader: None,
            state: crate::items::State::Shown,
        });
        let fixed = furniture(&plan);
        let label = fixed
            .iter()
            .find(|d| d.id == "schedule/tag/B8")
            .expect("the printed balloon is a final obstacle")
            .placed
            .as_ref()
            .unwrap();
        let frame = Placed {
            lines: vec![[[120., 170.], [160., 170.]]],
            arrows: Vec::new(),
            label_box: [160., 167., 180., 173.],
            label_at: [160., 167.],
            rotation: 0.,
        };
        assert!(
            !placement::annotations_clear(&frame, label),
            "the frame shaft crosses tag B8"
        );
    }

    #[test]
    fn a_proven_interior_gdt_flag_preserves_the_complete_glyph_and_text() {
        let mut g: gdt::PlannedGdt = serde_json::from_value(serde_json::json!({
            "id":"pmi:test", "kind":"control_frame", "view":"v:plan", "side":"right",
            "source":"test", "faces":[0], "cells":["A"], "label":"A", "default":true,
            "basis":"test", "state":{"kind":"shown"}, "placed": {
                "tip":[-10.,3.], "lines":[[[-10.,3.],[-2.,3.]],[[-2.,3.],[0.,3.]]],
                "arrows":[[[-10.,3.],[-7.3,3.]]], "label_box":[0.,0.,8.,6.],
                "strokes":[[[0.,0.],[8.,0.]],[[8.,0.],[8.,6.]],[[8.,6.],[0.,6.]],[[0.,6.],[0.,0.]]],
                "arcs":[], "fills":[], "letters":[{"text":"A","at":[4.,3.],"size":3.}],
                "runs":[{"text":"A","at":[4.,3.],"size":3.}] }
        }))
        .unwrap();
        let old = crate::model::render_item(crate::model::AnnotationItem::Gdt(&g));
        assert!(!old.drawn[0].interior);
        g.basis += interior::BASIS;
        let new = crate::model::render_item(crate::model::AnnotationItem::Gdt(&g));
        assert!(new.drawn[0].interior);
        assert_eq!(new.drawn[0].ink, old.drawn[0].ink);
        assert_eq!(new.drawn[0].label, old.drawn[0].label);
        assert_eq!(new.text.len(), old.text.len());
        assert!(new.text.iter().all(|t| t.size == 3.0));
    }
}