draftwright 0.2.15

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
//! The approved #309 inventory. Only existing Spec fields belong in this table.
//! Keep reporting outside the layout solve: bases must not change automatic geometry.
use crate::model::{Invalid, Plan, Problem};
use std::cell::{Cell, RefCell};
use std::sync::Arc;

#[derive(Clone, Copy)]
enum Family {
    Part,
    Views,
    Sheet,
    Dimensions,
    Attachment,
    Wording,
    Furniture,
    Linework,
    Requirements,
}

// Decision family -> fields that change it -> current exceptions. Missing capabilities
// are reported honestly, not advertised as fields that the Spec cannot yet accept.
const OVERRIDES: [(&str, &str, &str); 9] = [
    (
        "part and orientation",
        "part",
        "Frame changes require reanalysis (#309)",
    ),
    (
        "view selection",
        "views/sections; views/<view> keys [omit, half_section, detail, break]",
        "Named and explicit sections use front-facing planes; cameras and half-section side unavailable (#309)",
    ),
    (
        "paper and arrangement",
        "sheet keys [size, scale, preferred_max_size, preferred_max_sheets, view_gutter, dimension_spacing, projection]; sheets; views/<view> keys [sheet, place]; iso_scale_factor",
        "Captions state actual scale; caption placement unavailable (#309)",
    ),
    (
        "dimension selection, origins and local presentation",
        "dimensions/<dimension> keys [omit, between, along, view, place, text, style, presentation]; dimension_source; origin; dimension_schemes; precision; faces/<face>/profile_corners",
        "Displaced linear place fields report placement_displaced; keep measured values; force-show, named supports and wrap width unavailable (#309)",
    ),
    (
        "recognition, grouping and attachment",
        "feature_declarations; features/<feature> keys [reclassify, suppress, split, pattern]; annotations/<annotation>/place",
        "Unrelated GD&T moves report gdt_position_changed; named support overrides unavailable (#309)",
    ),
    (
        "wording and precision",
        "precision; features/<feature>/callouts/style; sheet/callouts/style; annotations/<annotation>/text",
        "Keep measured values; wrap width unavailable (#309)",
    ),
    (
        "tables, tags, notes and furniture",
        "hole_table; sheet keys [table_columns, title]; notes; tables; annotations/<annotation> keys [omit, text, place]",
        "Automatic tag order and block placement unavailable (#309)",
    ),
    (
        "linework, symbols and inspection rings",
        "sheet keys [hidden, centre_marks, centre_lines, uncited_datums, balloons]; views/<view> keys [hidden, centre_marks, centre_lines, thread_depiction, knurl_depiction]; features/<feature> keys [modelled_thread, spring]; annotations/<annotation>/omit; balloons",
        "Pens/fonts/hatching unavailable; sections omit hidden ink (#309)",
    ),
    (
        "requirements and checker conclusions",
        "",
        "No presentation override: PMI owns requirements; lint independently checks the drawing",
    ),
];

#[derive(Clone, Copy)]
enum Target<'a> {
    Document,
    View(&'a str),
    Dimension(&'a str),
    Feature(&'a str),
    Annotation(&'a str),
}

fn add(basis: &mut String, family: Family, target: Target<'_>) {
    let (_, fields, exception) = OVERRIDES[family as usize];
    let fields = fields
        .split("; ")
        .filter_map(|field| {
            let mut field = field.to_string();
            for (placeholder, value) in [
                (
                    "<view>",
                    match target {
                        Target::View(id) => Some(id),
                        _ if matches!(family, Family::Sheet) => Some("<view>"),
                        _ => None,
                    },
                ),
                (
                    "<dimension>",
                    match target {
                        Target::Dimension(id) => Some(id),
                        _ => None,
                    },
                ),
                (
                    "<annotation>",
                    match target {
                        Target::Annotation(id) => Some(id),
                        _ => None,
                    },
                ),
                (
                    "<feature>",
                    Some(match target {
                        Target::Feature(id) => id,
                        _ => "<feature>",
                    }),
                ),
            ] {
                if field.contains(placeholder) {
                    field = field.replace(placeholder, &crate::items::key(value?));
                }
            }
            (!field.is_empty()).then_some(field)
        })
        .collect::<Vec<_>>()
        .join("; ");
    let guidance = if fields.is_empty() {
        format!("; {exception}")
    } else {
        format!("; Spec: {fields}; {exception}")
    };
    if !basis.contains(&guidance) {
        // Preserve dependency tails and routing proofs across late recovery.
        let at = ["; dependencies: ", crate::dims::interior::BASIS]
            .iter()
            .filter_map(|suffix| basis.find(suffix))
            .min()
            .unwrap_or(basis.len());
        basis.insert_str(at, &guidance);
    }
}

thread_local! {
    static DEPTH: Cell<usize> = const { Cell::new(0) };
    static PLACEMENT_REFERENCE: RefCell<Option<Arc<Plan>>> = const { RefCell::new(None) };
    static REFERENCE_ONLY: Cell<bool> = const { Cell::new(false) };
}
struct Boundary;
impl Drop for Boundary {
    fn drop(&mut self) {
        DEPTH.set(DEPTH.get() - 1);
        if DEPTH.get() == 0 {
            PLACEMENT_REFERENCE.set(None);
            REFERENCE_ONLY.set(false);
        }
    }
}
/// Nested canonical and recovery plans keep their original bases during the solve.
pub(crate) fn boundary(
    analysis: &crate::model::Analysis,
    spec: &crate::model::Spec,
    run: impl FnOnce() -> Result<Plan, Invalid>,
) -> Result<Plan, Invalid> {
    let outer = DEPTH.get() == 0;
    DEPTH.set(DEPTH.get() + 1);
    let _guard = Boundary;
    if outer {
        let reference = (!crate::placement_intent::has_pins(spec))
            .then(|| prepare_placement_reference(analysis, spec, None))
            .flatten()
            .map(Arc::new);
        PLACEMENT_REFERENCE.set(reference);
    }
    let mut plan = run()?;
    if outer {
        let anchor = plan.placement_anchor.take();
        if crate::placement_intent::has_pins(&plan.spec) {
            PLACEMENT_REFERENCE.set(
                prepare_placement_reference(analysis, &plan.spec, anchor.as_deref()).map(Arc::new),
            );
        }
        crate::model::refresh_line_work_problems(&mut plan);
        report(analysis, &mut plan);
        crate::hole_table::labels::finish(analysis, &mut plan);
    }
    Ok(plan)
}

/// The placement counterfactual keeps every other authored requirement. It is
/// shared by GD&T's incumbent trial and the final public displacement report.
pub(crate) fn placement_reference(spec: &crate::model::Spec) -> Option<Arc<Plan>> {
    if !spec.dimensions.values().any(|d| d.place.is_some()) {
        return None;
    }
    PLACEMENT_REFERENCE.with_borrow(Clone::clone)
}

/// Reference drawings need geometry, not another canonical label-anchor replay
/// or repair offers. These metadata passes cannot change the reference ink.
pub(crate) fn reference_only() -> bool {
    REFERENCE_ONLY.get()
}

/// Whether free places or authored pin positions differ from neutral anchors.
pub(crate) fn has_placement_change(spec: &crate::model::Spec) -> bool {
    let pinned = spec.dimensions.values().any(|d| {
        d.place
            .as_ref()
            .is_some_and(|p| p.pinned && !crate::placement_intent::automatic_pin(p))
    });
    spec.dimensions.values().any(|d| {
        d.place.as_ref().is_some_and(|p| {
            if pinned {
                p.pinned && !crate::placement_intent::automatic_pin(p)
            } else {
                !p.pinned && *p != Default::default()
            }
        })
    })
}

/// Preserve unrelated entries, including explicit empty directives. Only an
/// entry made empty by withdrawing its actual placement can disappear.
fn placement_counterfactual(spec: &crate::model::Spec) -> Option<crate::model::Spec> {
    if !has_placement_change(spec) {
        return None;
    }
    let pinned = spec.dimensions.values().any(|d| {
        d.place
            .as_ref()
            .is_some_and(|p| p.pinned && !crate::placement_intent::automatic_pin(p))
    });
    let mut base = spec.clone();
    base.dimensions.retain(|_, d| {
        let Some(p) = &d.place else { return true };
        if pinned && p.pinned {
            let neutral = crate::placement_intent::Place {
                view: p.view.clone(),
                pinned: true,
                ..Default::default()
            };
            d.place = Some(neutral);
        } else if !pinned && !p.pinned && *p != Default::default() {
            d.place = None;
            return *d != Default::default();
        }
        true
    });
    Some(base)
}

fn prepare_placement_reference(
    analysis: &crate::model::Analysis,
    spec: &crate::model::Spec,
    anchor: Option<&Plan>,
) -> Option<Plan> {
    let base = placement_counterfactual(spec)?;
    let effective = crate::spec_gdt::effective(analysis, spec).ok()?;
    if !matches!(&effective.pmi, Some(crate::pmi::Reading::Read(r)) if r.records.iter().any(|r| matches!(r.category, crate::pmi::Category::Datum | crate::pmi::Category::GeometricTolerance)))
    {
        return None;
    }
    struct Restore(bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            REFERENCE_ONLY.set(self.0);
        }
    }
    let _restore = Restore(REFERENCE_ONLY.replace(true));
    // Free placement comparisons use one primitive single-sheet solve, never
    // allocator/recovery search. Pins retain the live finished anchor and need
    // the same fixed-frame finishing path; reusing it avoids a canonical replay.
    let anchored = crate::placement_intent::has_pins(spec);
    let run = || {
        if anchored {
            crate::model::plan_recovered(analysis, &base)
        } else {
            crate::model::plan(analysis, &base)
        }
    };
    let mut reference = if let Some(anchor) = anchor {
        crate::planning::with_pin_reference(anchor.clone(), run)
    } else {
        run()
    }
    .ok()?;
    if !anchored {
        // Compare the same finished paper geometry. A primitive reference has
        // not composed its measured linear corridors; an explicit pair's new
        // row correction must apply here too, without allocator/fix searches.
        if crate::sheet_fit::can_settle_explicit_overflow(&reference) {
            let inventory = reference.dimensions.clone();
            crate::sheet_fit::reserve_linear_corridors(
                analysis,
                &mut reference,
                &inventory,
                false,
                None,
                &crate::dims::footprints::Cache::default(),
            );
        }
        crate::iso_caption::refresh(analysis, &mut reference);
        crate::view_gutters::apply(analysis, &mut reference);
        crate::iso_caption::refresh(analysis, &mut reference);
    }
    Some(reference)
}

fn report_gdt_moves(plan: &mut Plan) {
    plan.problems.retain(|p| p.code != "gdt_position_changed");
    for g in &mut plan.gdt {
        if !g
            .basis
            .contains("; automatic position displaced by dimension placement")
        {
            continue;
        }
        g.basis = g.basis.replace(
            "; automatic position displaced by dimension placement; see gdt_position_changed",
            "",
        );
    }
    if !plan.spec.dimensions.values().any(|d| d.place.is_some()) {
        return;
    }
    let Some(before) = placement_reference(&plan.spec) else {
        return;
    };
    // An automatically selected different paper is not a controlled local
    // placement comparison. Do not publish a causal claim from that drawing.
    if before.sheet.size != plan.sheet.size || before.sheet.scale != plan.sheet.scale {
        return;
    }
    // Count Spec changes, including requests without drawn ink. A single
    // changed placement explains the move even when packing acts indirectly.
    let changed: std::collections::BTreeSet<_> = before
        .spec
        .dimensions
        .keys()
        .chain(plan.spec.dimensions.keys())
        .filter(|id| {
            before
                .spec
                .dimensions
                .get(*id)
                .and_then(|d| d.place.as_ref())
                != plan.spec.dimensions.get(*id).and_then(|d| d.place.as_ref())
        })
        .map(String::as_str)
        .collect();
    for g in &mut plan.gdt {
        if plan
            .spec
            .annotations
            .get(&g.id)
            .is_some_and(|a| a.place.is_some())
        {
            continue;
        }
        let Some(old) = before
            .gdt
            .iter()
            .find(|old| old.id == g.id)
            .and_then(|g| g.placed.as_ref())
        else {
            continue;
        };
        let Some(now) = g.placed.as_ref() else {
            continue;
        };
        // 0.01 paper mm is below a plotted stroke; packing's 0.00001 mm
        // clearance epsilon is not a user-visible movement.
        if old
            .label_box
            .iter()
            .zip(now.label_box)
            .all(|(a, b)| (a - b).abs() <= 0.01)
        {
            continue;
        }
        // Prefer direct ink evidence when several placements changed. With
        // just one change, the placement-only comparison identifies the cause.
        let mut causes: Vec<_> = plan
            .dimensions
            .iter()
            .filter(|d| {
                changed.contains(d.id.as_str())
                    && d.view == g.view
                    && crate::dims::ink_in_box(d, old.label_box)
                    && !before
                        .dimensions
                        .iter()
                        .find(|b| b.id == d.id)
                        .is_some_and(|b| {
                            b.view == g.view && crate::dims::ink_in_box(b, old.label_box)
                        })
            })
            .map(|d| d.id.as_str())
            .collect();
        if causes.is_empty() && changed.len() == 1 {
            causes.extend(changed.iter().copied());
        }
        let cause = if causes.is_empty() {
            "while the requested dimension placements were laid out".into()
        } else {
            format!(
                "to make room for the requested place of {}",
                causes
                    .iter()
                    .map(|id| {
                        plan.dimensions
                            .iter()
                            .chain(&before.dimensions)
                            .find(|d| d.id == *id)
                            .map(|d| crate::wording::item(&d.id, &d.kind, &d.label))
                            .unwrap_or_else(|| format!("dimension {id}"))
                    })
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        };
        let paths: Vec<_> = causes
            .iter()
            .map(|id| format!("dimensions/{}/place", crate::items::key(id)))
            .collect();
        let named = crate::wording::item(&g.id, &g.kind, &g.label);
        g.basis +=
            "; automatic position displaced by dimension placement; see gdt_position_changed";
        plan.problems.push(Problem {
            id: format!("p:gdt_position_changed:{}", g.id),
            code: "gdt_position_changed".into(),
            severity: "warning".into(),
            message: format!(
                "{} moved from its automatic position {cause}.",
                crate::wording::capital(&named)
            ),
            subjects: std::iter::once(g.id.clone())
                .chain(causes.iter().map(|id| (*id).to_string()))
                .collect(),
            refs: paths.clone(),
            ..Default::default()
        });
    }
}

fn report_placements(analysis: &crate::model::Analysis, plan: &mut Plan) {
    let displaced = crate::dims::with_compact(
        plan.sheet.dimension_spacing == crate::model::DimensionSpacing::Compact,
        || crate::dims::displaced_linear_fields(analysis, plan),
    );
    // Refresh our findings once at the public boundary. Replayed plans may
    // already carry reports, but no stale displacement should survive a fix.
    plan.problems.retain(|p| p.code != "placement_displaced");
    for d in &mut plan.dimensions {
        if !d.basis.contains("place intent:") {
            continue;
        }
        const APPLIED: &str =
            "; applied linear place intent: requested side, lane and along fields retained";
        const END: &str = "; final layout uses the recorded ink position";
        d.basis = d.basis.replace(APPLIED, "");
        if let Some(start) = d.basis.find("; displaced place intent:")
            && let Some(end) = d.basis[start..].find(END)
        {
            d.basis.replace_range(start..start + end + END.len(), "");
        }
    }
    for d in &mut plan.dimensions {
        if d.kind == "linear"
            && d.placed.is_some()
            && plan
                .spec
                .dimensions
                .get(&d.id)
                .and_then(|d| d.place.as_ref())
                .is_some_and(|p| p.side.is_some() || p.lane.is_some() || p.along.is_some())
            && !displaced.iter().any(|(id, _)| *id == d.id)
            && !d.basis.contains("; applied linear place intent")
        {
            d.basis +=
                "; applied linear place intent: requested side, lane and along fields retained";
        }
    }
    for (id, fields) in displaced {
        let d = plan.dimensions.iter_mut().find(|d| d.id == id).unwrap();
        let named = crate::wording::item(&d.id, &d.kind, &d.label);
        d.basis = d
            .basis
            .replace("the spec places it in", "the spec requests it in");
        d.basis += &format!(
            "; displaced place intent: {}; final layout uses the recorded ink position",
            fields.join(", ")
        );
        let path = format!("dimensions/{}/place", crate::items::key(&id));
        let causes: Vec<_> = plan
            .dimensions
            .iter()
            .filter(|d| {
                d.id != id
                    && plan
                        .spec
                        .dimensions
                        .get(&d.id)
                        .and_then(|d| d.place.as_ref())
                        .is_some_and(|p| p.pinned)
            })
            .map(|d| crate::wording::item(&d.id, &d.kind, &d.label))
            .collect();
        let cause = if causes.is_empty() {
            "the final collision and sheet-boundary layout".into()
        } else {
            format!("the final layout around pinned {}", causes.join(", "))
        };
        plan.problems.push(Problem {
            id: format!("p:placement_displaced:{id}"), code: "placement_displaced".into(), severity: "warning".into(),
            message: format!("The requested place of {named} was displaced in {} by {cause}. The drawing is retained at its recorded position; adjust the placement or release the conflicting constraint.", fields.join(", ")),
            subjects: vec![id], refs: vec![path], ..Default::default()
        });
    }
    plan.status = crate::completeness::status(&plan.problems);
}

fn report(analysis: &crate::model::Analysis, plan: &mut Plan) {
    report_gdt_moves(plan);
    report_placements(analysis, plan);
    crate::broken::check_anchors(plan);
    add(&mut plan.sheet.basis, Family::Part, Target::Document);
    if let Some(part) = &plan.spec.part
        && !plan.sheet.basis.contains("; applied part:")
    {
        plan.sheet.basis += &format!(
            "; applied part: {part:?}; selected geometry is part {:?}",
            plan.binding.part_index
        );
    }
    for sheet in std::iter::once(&mut plan.sheet).chain(&mut plan.sheets) {
        add(&mut sheet.basis, Family::Sheet, Target::Document);
        add(&mut sheet.basis, Family::Furniture, Target::Document);
        add(&mut sheet.basis, Family::Wording, Target::Document);
        add(&mut sheet.basis, Family::Attachment, Target::Document);
    }
    for v in &mut plan.views {
        let id = v.id.trim_start_matches("v:");
        add(&mut v.basis, Family::Views, Target::View(id));
        add(&mut v.basis, Family::Linework, Target::View(id));
        if let Some(b) = &v.broken
            && !v.basis.contains(&format!("; applied {}:", b.source))
        {
            v.basis += &format!(
                "; applied {}: uniform projected interval {:?}, retained gap {} paper mm; displaced full-length depiction; axis/remove/gap/aligned override automatic break choices",
                b.source, b.remove, b.paper_gap
            );
        }
    }
    for d in &mut plan.dimensions {
        add(&mut d.basis, Family::Dimensions, Target::Dimension(&d.id));
    }
    for d in &mut plan.omitted {
        add(&mut d.basis, Family::Dimensions, Target::Dimension(&d.id));
    }
    for c in &mut plan.recognition_corrections {
        add(&mut c.basis, Family::Attachment, Target::Feature(&c.id));
    }
    for g in &mut plan.gdt {
        let target = if g.kind == "label" {
            Target::Annotation(&g.id)
        } else {
            Target::Document
        };
        add(&mut g.basis, Family::Attachment, target);
        if matches!(target, Target::Annotation(_)) {
            add(&mut g.basis, Family::Wording, target);
            add(&mut g.basis, Family::Linework, target);
        }
        add(&mut g.basis, Family::Requirements, Target::Document);
    }
    for r in &mut plan.requirements {
        add(&mut r.basis, Family::Requirements, Target::Document);
    }
    for n in &mut plan.notes {
        let target = if n.default {
            Target::Annotation(&n.id)
        } else {
            Target::Document
        };
        add(&mut n.basis, Family::Furniture, target);
    }
    for t in &mut plan.tables {
        add(&mut t.basis, Family::Furniture, Target::Document);
    }
    if let Some(t) = &mut plan.radius_table {
        add(&mut t.table.basis, Family::Furniture, Target::Document);
    }
    for t in plan.hole_table.iter_mut().chain(&mut plan.hole_tables) {
        add(&mut t.basis, Family::Furniture, Target::Document);
        for block in &mut t.blocks {
            add(&mut block.basis, Family::Furniture, Target::Document);
        }
    }
    for ring in &mut plan.inspection_balloons {
        add(&mut ring.basis, Family::Linework, Target::Document);
        add(&mut ring.basis, Family::Requirements, Target::Document);
    }
    for c in &mut plan.captions {
        add(&mut c.basis, Family::Sheet, Target::View("iso"));
    }
    for (name, entry) in &plan.spec.views {
        if entry.broken.is_some()
            && !plan
                .views
                .iter()
                .any(|v| v.id == format!("v:{name}") && v.broken.is_some())
        {
            crate::broken::not_applied(
                &mut plan.problems,
                name,
                &format!("views/{name}/break"),
                "the carrying view is omitted or displaced",
            );
        }
    }
    for (id, entry) in &plan.spec.dimensions {
        if entry.presentation.is_some()
            && !plan.dimensions.iter().any(|d| {
                &d.id == id && d.placed.is_some() && d.from_spec.iter().any(|f| f == "presentation")
            })
        {
            let problem_id = format!("p:dimension_edit_unapplied:presentation/{id}");
            if plan.problems.iter().any(|p| p.id == problem_id) {
                continue;
            }
            plan.problems.push(Problem {
                id: problem_id, code: "dimension_edit_unapplied".into(), severity: "warning".into(), subjects: vec![id.clone()],
                message: format!("dimensions/{}/presentation was not applied: it needs a separately drawn cylindrical-mouth pocket depth callout; the request is retained.", crate::items::key(id)),
                ..Default::default()
            });
            plan.status = crate::completeness::status(&plan.problems);
        }
    }
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    #[test]
    fn empty_placement_needs_no_comparison() {
        let spec = serde_json::from_value(serde_json::json!({
            "dimensions":{"empty":{},"no-op":{"place":{}},"bare":{"place":{"view":"plan","pinned":true}}}
        }))
        .unwrap();
        assert!(super::placement_counterfactual(&spec).is_none());
    }

    #[test]
    fn comparison_preserves_every_unrelated_directive() {
        let mut value = serde_json::json!({"sheet":{"size":"A4","scale":"1:1"}, "dimensions":{
            "pin":{"place":{"view":"plan","pinned":true,"offset":[14,12]}},
            "peer":{"place":{"view":"plan","side":"above","along":0.25}},
            "empty":{},"no-op":{"place":{}}
        }});
        let spec: crate::model::Spec = serde_json::from_value(value.clone()).unwrap();
        let mut expected = value.clone();
        expected["dimensions"]["pin"]["place"]
            .as_object_mut()
            .unwrap()
            .remove("offset");
        assert_eq!(
            super::placement_counterfactual(&spec).unwrap(),
            serde_json::from_value(expected).unwrap()
        );

        let mut bare = value.clone();
        bare["dimensions"]["pin"]["place"]
            .as_object_mut()
            .unwrap()
            .remove("offset");
        let spec = serde_json::from_value(bare.clone()).unwrap();
        bare["dimensions"].as_object_mut().unwrap().remove("peer");
        assert_eq!(
            super::placement_counterfactual(&spec).unwrap(),
            serde_json::from_value(bare).unwrap()
        );

        value["dimensions"]["pin"]["place"]["pinned"] = serde_json::json!(false);
        let spec = serde_json::from_value(value.clone()).unwrap();
        // Withdraw the two free placements, retaining both unrelated empty
        // directives and the rest of the document byte-for-byte in its fields.
        value["dimensions"].as_object_mut().unwrap().remove("pin");
        value["dimensions"].as_object_mut().unwrap().remove("peer");
        assert_eq!(
            super::placement_counterfactual(&spec).unwrap(),
            serde_json::from_value(value).unwrap()
        );
    }

    #[test]
    fn final_ink_recheck_keeps_real_overflow_and_unrelated_findings() {
        use crate::{model, output::Curve};
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/parts/prismatic.step");
        let (_, a) = model::analyse(&path).unwrap();
        let mut p = model::plan(&a, &model::Spec::default()).unwrap();
        for id in ["ink:stale", "d:other"] {
            p.problems.push(model::Problem {
                id: format!("p:annotation_off_sheet:{id}"),
                code: "annotation_off_sheet".into(),
                severity: "error".into(),
                ..Default::default()
            });
        }
        p.views[0].line_work.push(crate::centrelines::LineWork {
            id: "ink:actual".into(),
            kind: "cross".into(),
            curves: vec![Curve::Line([-1., 20.], [20., 20.])],
            centre: None,
            radial: false,
            global_axis: false,
            overrun: 0.,
        });
        model::refresh_line_work_problems(&mut p);
        assert!(!p.problems.iter().any(|q| q.id.ends_with("ink:stale")));
        assert!(p.problems.iter().any(|q| q.id.ends_with("ink:actual")));
        assert!(p.problems.iter().any(|q| q.id.ends_with("d:other")));
        p.views[0].line_work.last_mut().unwrap().curves = vec![Curve::Line([20., 20.], [30., 20.])];
        model::refresh_line_work_problems(&mut p);
        assert!(!p.problems.iter().any(|q| q.id.ends_with("ink:actual")));
        assert!(p.problems.iter().any(|q| q.id.ends_with("d:other")));
        p.spec.sheet.frame_gutter = Some(15.);
        model::refresh_line_work_problems(&mut p);
        assert!(
            p.problems.iter().any(|q| q.id.ends_with("ink:actual")),
            "20 mm is outside the requested 25 mm drawable inset"
        );
    }
}