BREP_app 0.2.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
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
//! The BOM's COLUMN CONFIGURATION — the catalogue of known fields, the
//! settings-textarea format, and the translation between that text and the
//! generic [`crate::column_tree`] widget's `ColumnSpec` / `ColumnLayout`.
//!
//! This is the BOM-shaped half deliberately kept OUT of the widget. The widget
//! knows "a column of kind K"; this module knows that a BOM column is either a
//! PART field or an OCCURRENCE field, which of them are built in, and how the
//! user writes that down.
//!
//! # The settings text
//!
//! One column per line, in display order. A leading `*` means SHOWN:
//!
//! ```text
//! part.Mass
//! *part.Part_Number
//! *occurrence.Notes
//! *occurrence.Item_Number
//! ```
//!
//! * `part.` — stored on the PART, shared by every occurrence of it.
//! * `occurrence.` — stored on ONE placement.
//! * A name the catalogue does not know is a user-added CUSTOM field, not an
//!   error: it becomes a text column and is stored like any other.
//! * `#` starts a comment. Blank lines are ignored.
//! * A MALFORMED line (no `.`, an unknown prefix, an empty field name) costs
//!   that ONE column and nothing else: it is skipped, the text is left exactly
//!   as typed, and the panel lists `line N: …` under the textarea. A typo must
//!   never cost the user the rest of their configuration.
//! * A duplicate `prefix.Name` keeps the FIRST and reports the rest — two rules
//!   for one column would otherwise be decided by whichever the loop saw last.
//!
//! # The freeze marker
//!
//! A line that is exactly `-` FREEZES everything above it: those columns stay
//! put while the rest scroll horizontally, as in a spreadsheet.
//!
//! ```text
//! *part.Part_Number
//! -
//! *part.Description
//! ```
//!
//! * The STRUCTURAL columns — Item, the visibility toggle, the status badges —
//!   have no lines here and NEVER scroll. They are the row's identity and its
//!   state; scrolling them away leaves a table of values with nothing saying
//!   which part each line is about. So the frozen band is those three plus
//!   whatever the marker names, and a configuration with no marker at all still
//!   holds them still.
//! * A marker below every column would freeze the lot, leaving nothing to
//!   scroll it against; the widget reads that as "frozen: none" so no column
//!   can be stranded off the right edge.
//! * The FIRST marker decides. A second one is reported like any other
//!   unusable line — and, unlike a comment, it is DROPPED rather than
//!   preserved: preserved lines are re-emitted ABOVE the column block, where a
//!   stray `-` would come back as "freeze nothing" on the next write-back.
//!
//! Reordering or hiding a column by dragging its heading WRITES BACK here, so
//! the text and the table can never disagree. Comment and malformed lines
//! survive that round trip (they are re-emitted above the column block), so an
//! automated rewrite can never eat something the user typed.

use crate::column_tree::{CellKind, ColumnLayout, ColumnSpec};
use std::collections::HashSet;

/// The user-facing prefix for a field stored on the PART.
pub const PART_PREFIX: &str = "part";

/// The user-facing prefix for a field stored on ONE occurrence.
pub const OCCURRENCE_PREFIX: &str = "occurrence";

/// The always-present structural column: the tree itself (part name +
/// occurrence id). Not a stored attribute, so it is not written in the
/// settings text — but it IS an ordinary column to the widget, so the user can
/// still resize, reorder, and even hide it (the tree then draws in whatever
/// column comes first).
pub const ITEM_KEY: &str = "item";

/// The other structural column: the per-row ACTION MENU trigger. Also not a
/// stored attribute, so also not written in the settings text.
pub const ACTIONS_KEY: &str = "actions";

/// The per-row visibility toggle — structural, like [`ITEM_KEY`]: it shows the
/// scene's truth for the row's member solids and is never configured away,
/// because a component list you cannot blank out of the viewport is a
/// regression against the Structure panel this replaced.
pub const VISIBLE_KEY: &str = "visible";

/// The per-row status badges (fixed / outdated / worst constraint status).
/// Structural for the same reason, and one column rather than three because
/// they are all "what is true of this instance right now", read at a glance.
pub const FLAGS_KEY: &str = "flags";

/// The freeze marker: a settings line that is exactly this holds every column
/// above it fixed while the rest scroll.
pub const FREEZE_MARKER: &str = "-";

/// `occurrence.Quantity` is DERIVED, never stored: in the packed view it is
/// how many occurrences the row rolls up, in the unpacked view it is 1. It is
/// the one column the brief exempts from "all columns are editable".
pub const QUANTITY_KEY: &str = "occurrence.Quantity";

/// Which store a BOM column's value lives in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
    /// On the part's own document (`partAttributes`) — shared by every
    /// occurrence of the part.
    Part,
    /// On the placing ACOMP's `inputParams.bom` — one placement's own.
    Occurrence,
}

impl Scope {
    pub fn prefix(self) -> &'static str {
        match self {
            Scope::Part => PART_PREFIX,
            Scope::Occurrence => OCCURRENCE_PREFIX,
        }
    }
}

/// One configured BOM column.
#[derive(Debug, Clone, PartialEq)]
pub struct BomColumn {
    pub scope: Scope,
    /// The field name as written in the settings text (`Part_Number`) — also
    /// the attribute key in the stored document.
    pub field: String,
    /// Shown in the table (a leading `*` in the settings text).
    pub shown: bool,
}

impl BomColumn {
    /// The widget column key — the settings text's own `prefix.Field`, so a
    /// hit key, a layout entry and a config line all read the same.
    pub fn key(&self) -> String {
        format!("{}.{}", self.scope.prefix(), self.field)
    }

    /// The heading: the field name with underscores opened out.
    pub fn label(&self) -> String {
        self.field.replace('_', " ")
    }

    /// The editor kind — from the catalogue when the field is built in, plain
    /// text for a user-added one.
    pub fn kind(&self) -> CellKind {
        if self.key() == QUANTITY_KEY {
            return CellKind::ReadOnly;
        }
        catalogue()
            .iter()
            .find(|entry| entry.scope == self.scope && entry.field == self.field)
            .map(|entry| entry.kind.clone())
            .unwrap_or(CellKind::Text)
    }
}

/// A built-in field: its scope, name and editor kind.
pub struct CatalogueEntry {
    pub scope: Scope,
    pub field: &'static str,
    pub kind: CellKind,
}

/// The built-in BOM fields. Part fields describe the PART, occurrence fields
/// describe ONE PLACEMENT — the owner's split, and the reason they persist in
/// two different documents.
pub fn catalogue() -> Vec<CatalogueEntry> {
    let choice = |options: &[&str]| CellKind::Choice {
        options: options.iter().map(|option| option.to_string()).collect(),
    };
    let part = |field, kind| CatalogueEntry {
        scope: Scope::Part,
        field,
        kind,
    };
    let occurrence = |field, kind| CatalogueEntry {
        scope: Scope::Occurrence,
        field,
        kind,
    };
    vec![
        // --- Part ---------------------------------------------------------
        part("Part_Number", CellKind::Text),
        part("Revision", CellKind::Text),
        part("Description", CellKind::Text),
        part(
            "Part_Type",
            choice(&["Manufactured", "Purchased", "Assembly", "Phantom", "Reference"]),
        ),
        part("Make_Buy", choice(&["Make", "Buy"])),
        part(
            "Unit_of_Measure",
            choice(&["EA", "MM", "M", "IN", "FT", "KG", "G", "LB", "L", "ML"]),
        ),
        part("Material", CellKind::Text),
        part("Finish", CellKind::Text),
        part("Mass", CellKind::Numeric { step: 0.01 }),
        part("Manufacturer", CellKind::Text),
        part("Manufacturer_Part_Number", CellKind::Text),
        part("Supplier", CellKind::Text),
        part("Supplier_Part_Number", CellKind::Text),
        part(
            "Lifecycle_State",
            choice(&["In Work", "In Review", "Released", "Obsolete"]),
        ),
        // --- Occurrence ---------------------------------------------------
        // Item / Find numbers are TEXT, not numeric: real BOMs use `1.2.3`
        // and `010`, and a numeric editor would eat both.
        occurrence("Item_Number", CellKind::Text),
        // Derived — see `QUANTITY_KEY`.
        occurrence("Quantity", CellKind::ReadOnly),
        occurrence("Reference_Designator", CellKind::Text),
        occurrence("Find_Number", CellKind::Text),
        occurrence("Effectivity", CellKind::Text),
        occurrence("Occurrence_Name", CellKind::Text),
        occurrence("Position", CellKind::Text),
        occurrence("Notes", CellKind::Text),
        occurrence(
            "BOM_Structure",
            choice(&["Normal", "Phantom", "Reference", "Inseparable"]),
        ),
        occurrence("Alternate_Substitute", CellKind::Text),
    ]
}

/// The shipped configuration: every built-in field, in a sensible BOM reading
/// order, with the ones a parts list is actually read for starred. Everything
/// else is one `*` away.
pub fn default_text() -> String {
    let shown: HashSet<&str> = [
        "occurrence.Item_Number",
        "occurrence.Quantity",
        "part.Part_Number",
        "part.Revision",
        "part.Description",
        "part.Material",
        "occurrence.Reference_Designator",
        "occurrence.Notes",
    ]
    .into_iter()
    .collect();
    // Reading order: what identifies the line, then what the part IS, then the
    // sourcing tail.
    let order = [
        "occurrence.Item_Number",
        "occurrence.Quantity",
        "part.Part_Number",
        "part.Revision",
        "part.Description",
        "part.Part_Type",
        "part.Make_Buy",
        "part.Unit_of_Measure",
        "part.Material",
        "part.Finish",
        "part.Mass",
        "part.Lifecycle_State",
        "occurrence.Reference_Designator",
        "occurrence.Find_Number",
        "occurrence.Occurrence_Name",
        "occurrence.Position",
        "occurrence.Effectivity",
        "occurrence.BOM_Structure",
        "occurrence.Alternate_Substitute",
        "occurrence.Notes",
        "part.Manufacturer",
        "part.Manufacturer_Part_Number",
        "part.Supplier",
        "part.Supplier_Part_Number",
    ];
    let mut out = String::from(
        "# One BOM column per line, in display order. A leading * shows it.\n\
         # part.<Field> is stored on the part; occurrence.<Field> on one placement.\n\
         # A name not listed here is a custom text field, not an error.\n\
         # A line that is just - freezes the columns above it; the rest scroll.\n",
    );
    for key in order {
        if shown.contains(key) {
            out.push('*');
        }
        out.push_str(key);
        out.push('\n');
    }
    out
}

/// The configuration text actually in force: the stored setting, or the
/// shipped default when it is empty. EMPTY is the persisted "never configured"
/// state (see `RenderSettings::bom_columns`), so a later change to the shipped
/// default still reaches every user who never overrode it — and a document
/// that was never configured persists byte-for-byte as before.
pub fn effective_text(stored: &str) -> String {
    if stored.trim().is_empty() {
        default_text()
    } else {
        stored.to_string()
    }
}

/// The result of reading the settings text.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct ParsedColumns {
    /// The configured columns, in the text's order.
    pub columns: Vec<BomColumn>,
    /// Lines the parser could not use, as `line N: why` — shown under the
    /// textarea. The text itself is never rewritten by parsing.
    pub problems: Vec<String>,
    /// Comment and malformed lines, verbatim, so a write-back can re-emit them
    /// instead of eating them.
    pub preserved: Vec<String>,
    /// How many configured columns stood ABOVE the `-` freeze marker; `None`
    /// when the text has no marker at all (nothing frozen).
    pub frozen: Option<usize>,
}

/// Read the settings text. Never fails: an unusable line costs that one column
/// and is reported.
pub fn parse(text: &str) -> ParsedColumns {
    let mut out = ParsedColumns::default();
    let mut seen: HashSet<String> = HashSet::new();
    for (index, raw) in text.lines().enumerate() {
        let number = index + 1;
        let line = raw.trim();
        if line.is_empty() {
            continue;
        }
        if line.starts_with('#') {
            out.preserved.push(line.to_string());
            continue;
        }
        if line == FREEZE_MARKER {
            // The FIRST marker decides. A second is reported and dropped — a
            // preserved one would be re-emitted above the column block on the
            // next write-back and would then read as "freeze nothing".
            if out.frozen.is_some() {
                out.problems.push(format!(
                    "line {number}: a second '{FREEZE_MARKER}' freeze marker — the first one decides"
                ));
            } else {
                out.frozen = Some(out.columns.len());
            }
            continue;
        }
        let (shown, rest) = match line.strip_prefix('*') {
            Some(rest) => (true, rest.trim()),
            None => (false, line),
        };
        let Some((prefix, field)) = rest.split_once('.') else {
            out.problems.push(format!(
                "line {number}: '{rest}' has no '.' — write {PART_PREFIX}.Field or {OCCURRENCE_PREFIX}.Field"
            ));
            out.preserved.push(raw.trim_end().to_string());
            continue;
        };
        let scope = match prefix.trim() {
            PART_PREFIX => Scope::Part,
            OCCURRENCE_PREFIX => Scope::Occurrence,
            other => {
                out.problems.push(format!(
                    "line {number}: unknown prefix '{other}' — only '{PART_PREFIX}.' and '{OCCURRENCE_PREFIX}.' exist"
                ));
                out.preserved.push(raw.trim_end().to_string());
                continue;
            }
        };
        let field = field.trim();
        if field.is_empty() {
            out.problems
                .push(format!("line {number}: '{rest}' names no field"));
            out.preserved.push(raw.trim_end().to_string());
            continue;
        }
        let column = BomColumn {
            scope,
            field: field.to_string(),
            shown,
        };
        let key = column.key();
        if !seen.insert(key.clone()) {
            out.problems
                .push(format!("line {number}: '{key}' is already configured above"));
            continue;
        }
        out.columns.push(column);
    }
    out
}

/// Write a column list back out as settings text, re-emitting the preserved
/// (comment / malformed) lines above it so an automated rewrite — a header
/// drag, a hide — can never eat something the user typed. `frozen` re-emits the
/// `-` marker after that many columns, so dragging a column across the freeze
/// boundary writes itself down like any other reorder.
pub fn serialize(columns: &[BomColumn], preserved: &[String], frozen: Option<usize>) -> String {
    let mut out = String::new();
    for line in preserved {
        out.push_str(line);
        out.push('\n');
    }
    for (index, column) in columns.iter().enumerate() {
        if frozen == Some(index) {
            out.push_str(FREEZE_MARKER);
            out.push('\n');
        }
        if column.shown {
            out.push('*');
        }
        out.push_str(&column.key());
        out.push('\n');
    }
    // A marker BELOW every column (everything frozen) is legitimate and must
    // survive the round trip.
    if frozen.is_some_and(|at| at >= columns.len()) {
        out.push_str(FREEZE_MARKER);
        out.push('\n');
    }
    out
}

/// The widget's column SPECS for a parsed configuration: the structural tree
/// column first, then every configured column (hidden ones included — the
/// widget's own hide list decides what is drawn, so a hidden column is still
/// offered in the right-click checklist).
pub fn column_specs(parsed: &ParsedColumns) -> Vec<ColumnSpec> {
    let mut specs = vec![
        ColumnSpec::new(ITEM_KEY, "Item", CellKind::ReadOnly).width(190.0),
        ColumnSpec::new(VISIBLE_KEY, "", CellKind::Toggle).width(26.0),
        ColumnSpec::new(FLAGS_KEY, "", CellKind::Badges).width(52.0),
    ];
    for column in &parsed.columns {
        let width = match column.kind() {
            CellKind::ReadOnly => 60.0,
            CellKind::Numeric { .. } => 70.0,
            _ => 120.0,
        };
        specs.push(ColumnSpec::new(column.key(), column.label(), column.kind()).width(width));
    }
    specs.push(
        ColumnSpec::new(
            ACTIONS_KEY,
            "",
            // The MENU trigger, not one action: the ellipsis says "there is a
            // list behind this", which a pencil did not.
            CellKind::Actions {
                label: "\u{22EF}".to_string(),
            },
        )
        .width(34.0),
    );
    specs
}

/// The widget LAYOUT for a parsed configuration: the text's order, and its
/// unstarred columns hidden. Widths and sort are the caller's — they are
/// session state, not configuration, so they are deliberately not written into
/// the user's text.
pub fn layout_from(parsed: &ParsedColumns, keep: &ColumnLayout) -> ColumnLayout {
    let mut order = vec![
        ITEM_KEY.to_string(),
        VISIBLE_KEY.to_string(),
        FLAGS_KEY.to_string(),
    ];
    let mut hidden = HashSet::new();
    for column in &parsed.columns {
        let key = column.key();
        if !column.shown {
            hidden.insert(key.clone());
        }
        order.push(key);
    }
    order.push(ACTIONS_KEY.to_string());
    ColumnLayout {
        order,
        hidden,
        widths: keep.widths.clone(),
        sort: keep.sort.clone(),
        // +1 for the structural Item column, which leads the order and is
        // always inside the frozen band when there is a marker at all.
        frozen: parsed.frozen.map_or(STRUCTURAL_LEADING, |above| above + STRUCTURAL_LEADING),
    }
}

/// The freeze marker's place in the settings text for a layout the USER changed
/// by dragging: how many CONFIGURED columns fall inside the frozen band (the
/// structural Item / Actions columns have no line of their own). `None` when
/// nothing is frozen, so a document that never froze anything keeps a text with
/// no marker in it.
/// The structural columns that always lead the arrangement: Item, the
/// visibility toggle and the status badges. They have no lines in the settings
/// text, so every conversion between "columns the user typed" and "columns the
/// widget arranges" has to step over exactly this many.
pub const STRUCTURAL_LEADING: usize = 3;

pub fn frozen_from_layout(layout: &ColumnLayout) -> Option<usize> {
    // The structural columns freeze IMPLICITLY — they are not configurable and
    // have no lines — so a band holding only them is spelled by no marker at
    // all. Emitting one here would invent a `-` in the user's text on the first
    // resize of a table nobody had frozen anything in.
    if layout.frozen <= STRUCTURAL_LEADING {
        return None;
    }
    Some(
        layout
            .order
            .iter()
            .take(layout.frozen)
            .filter(|key| {
                !matches!(
                    key.as_str(),
                    ITEM_KEY | VISIBLE_KEY | FLAGS_KEY | ACTIONS_KEY
                )
            })
            .count(),
    )
}

/// Fold a layout the USER changed by dragging back into a column list, so it
/// can be serialized into the settings text. The structural columns have no
/// lines of their own, so they are skipped; a column the layout somehow does
/// not name keeps its configured place at the end.
pub fn columns_from_layout(parsed: &ParsedColumns, layout: &ColumnLayout) -> Vec<BomColumn> {
    let mut out: Vec<BomColumn> = Vec::new();
    for key in &layout.order {
        if matches!(
            key.as_str(),
            ITEM_KEY | VISIBLE_KEY | FLAGS_KEY | ACTIONS_KEY
        ) {
            continue;
        }
        if let Some(column) = parsed.columns.iter().find(|column| &column.key() == key) {
            out.push(BomColumn {
                shown: !layout.hidden.contains(key),
                ..column.clone()
            });
        }
    }
    for column in &parsed.columns {
        if !out.iter().any(|kept| kept.key() == column.key()) {
            out.push(BomColumn {
                shown: !layout.hidden.contains(&column.key()),
                ..column.clone()
            });
        }
    }
    out
}

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

    #[test]
    fn a_star_shows_and_a_bare_line_hides() {
        let parsed = parse("part.Mass\n*part.Part_Number\n*occurrence.Notes\n");
        assert!(parsed.problems.is_empty(), "{:?}", parsed.problems);
        assert_eq!(
            parsed.columns,
            vec![
                BomColumn { scope: Scope::Part, field: "Mass".into(), shown: false },
                BomColumn { scope: Scope::Part, field: "Part_Number".into(), shown: true },
                BomColumn { scope: Scope::Occurrence, field: "Notes".into(), shown: true },
            ]
        );
        // Order is the TEXT's order, and the layout hides the unstarred one.
        let layout = layout_from(&parsed, &ColumnLayout::default());
        assert_eq!(
            layout.order,
            vec![
                "item",
                VISIBLE_KEY,
                FLAGS_KEY,
                "part.Mass",
                "part.Part_Number",
                "occurrence.Notes",
                "actions"
            ]
        );
        assert!(layout.hidden.contains("part.Mass"));
        assert!(!layout.hidden.contains("part.Part_Number"));
    }

    /// Blank lines and `#` comments are not columns and not complaints.
    #[test]
    fn blank_lines_and_comments_are_neither_columns_nor_problems() {
        let parsed = parse("# the BOM\n\n  \n*part.Revision\n");
        assert_eq!(parsed.columns.len(), 1);
        assert!(parsed.problems.is_empty());
        assert_eq!(parsed.preserved, vec!["# the BOM"]);
    }

    /// A MALFORMED line costs ONE column, names its line number, and leaves
    /// every other line working — a typo must not cost the configuration.
    #[test]
    fn a_malformed_line_costs_one_column_and_says_which() {
        let parsed = parse("*part.Part_Number\nnonsense\n*widget.Colour\n*part.\n*part.Mass\n");
        assert_eq!(
            parsed
                .columns
                .iter()
                .map(BomColumn::key)
                .collect::<Vec<_>>(),
            vec!["part.Part_Number", "part.Mass"],
            "the good lines are untouched"
        );
        assert_eq!(parsed.problems.len(), 3, "{:?}", parsed.problems);
        assert!(parsed.problems[0].starts_with("line 2:"), "{:?}", parsed.problems);
        assert!(parsed.problems[0].contains("no '.'"));
        assert!(parsed.problems[1].starts_with("line 3:"));
        assert!(parsed.problems[1].contains("unknown prefix 'widget'"));
        assert!(parsed.problems[2].starts_with("line 4:"));
        assert!(parsed.problems[2].contains("names no field"));
        // ...and the bad lines are kept, so a write-back cannot eat them.
        assert_eq!(parsed.preserved, vec!["nonsense", "*widget.Colour", "*part."]);
    }

    /// A duplicate keeps the FIRST rule and reports the rest, rather than
    /// letting whichever line the loop saw last silently win.
    #[test]
    fn a_duplicate_keeps_the_first_and_reports_the_rest() {
        let parsed = parse("*part.Mass\npart.Mass\n");
        assert_eq!(parsed.columns.len(), 1);
        assert!(parsed.columns[0].shown, "the FIRST rule stands");
        assert_eq!(parsed.problems.len(), 1);
        assert!(parsed.problems[0].contains("already configured above"));
    }

    /// An unknown field name is a user-added CUSTOM column — a text field,
    /// stored like any other, not an error.
    #[test]
    fn an_unknown_field_is_a_custom_text_column_not_an_error() {
        let parsed = parse("*occurrence.Torque_Spec\n*part.Cure_Time\n");
        assert!(parsed.problems.is_empty(), "{:?}", parsed.problems);
        assert_eq!(parsed.columns[0].kind(), CellKind::Text);
        assert_eq!(parsed.columns[1].kind(), CellKind::Text);
        assert_eq!(parsed.columns[0].label(), "Torque Spec", "underscores open out");
    }

    /// The catalogue's kinds reach the columns: a dropdown is a dropdown, mass
    /// is numeric, and Quantity is READ-ONLY because it is derived.
    #[test]
    fn catalogue_kinds_reach_the_columns_and_quantity_is_read_only() {
        let parsed = parse("*part.Make_Buy\n*part.Mass\n*occurrence.Quantity\n*part.Description\n");
        assert_eq!(
            parsed.columns[0].kind(),
            CellKind::Choice { options: vec!["Make".into(), "Buy".into()] }
        );
        assert_eq!(parsed.columns[1].kind(), CellKind::Numeric { step: 0.01 });
        assert_eq!(
            parsed.columns[2].kind(),
            CellKind::ReadOnly,
            "quantity is derived from the occurrence count, never typed"
        );
        assert_eq!(parsed.columns[3].kind(), CellKind::Text);
    }

    /// The shipped default parses clean, offers every built-in field exactly
    /// once, and shows a readable subset rather than all 24 at once.
    #[test]
    fn the_default_text_parses_clean_and_covers_the_catalogue() {
        let parsed = parse(&default_text());
        assert!(parsed.problems.is_empty(), "{:?}", parsed.problems);
        let keys: HashSet<String> = parsed.columns.iter().map(BomColumn::key).collect();
        assert_eq!(keys.len(), parsed.columns.len(), "no duplicates");
        for entry in catalogue() {
            let key = format!("{}.{}", entry.scope.prefix(), entry.field);
            assert!(keys.contains(&key), "{key} is offered");
        }
        assert_eq!(catalogue().len(), 24, "14 part + 10 occurrence fields");
        let shown = parsed.columns.iter().filter(|column| column.shown).count();
        assert!(
            (4..=12).contains(&shown),
            "a readable default, not all 24: {shown}"
        );
    }

    /// A header drag / hide round-trips through the text — the table and the
    /// configuration can never disagree — and comment + malformed lines
    /// survive it.
    #[test]
    fn a_layout_change_round_trips_through_the_text_keeping_stray_lines() {
        let text = "# mine\n*part.Part_Number\npart.Mass\nnonsense\n*occurrence.Notes\n";
        let parsed = parse(text);
        let mut layout = layout_from(&parsed, &ColumnLayout::default());
        // The user drags Notes to the front and un-hides Mass.
        layout.order = vec![
            "item".into(),
            VISIBLE_KEY.into(),
            FLAGS_KEY.into(),
            "occurrence.Notes".into(),
            "part.Mass".into(),
            "part.Part_Number".into(),
            "actions".into(),
        ];
        layout.hidden.remove("part.Mass");

        let rewritten = serialize(
            &columns_from_layout(&parsed, &layout),
            &parsed.preserved,
            frozen_from_layout(&layout),
        );
        assert_eq!(
            rewritten,
            "# mine\nnonsense\n*occurrence.Notes\n*part.Mass\n*part.Part_Number\n"
        );
        // Re-reading it reproduces the layout — the round trip is closed.
        let again = parse(&rewritten);
        let relaid = layout_from(&again, &ColumnLayout::default());
        assert_eq!(relaid.order, layout.order);
        assert!(relaid.hidden.is_empty(), "everything is shown now");
    }

    /// Widths and sort are SESSION state, not configuration: a re-read of the
    /// text keeps them rather than resetting the table under the user.
    #[test]
    fn widths_and_sort_survive_a_re_read_of_the_text() {
        let parsed = parse("*part.Mass\n");
        let mut keep = ColumnLayout::default();
        keep.widths.insert("part.Mass".into(), 240.0);
        keep.sort = Some(("part.Mass".into(), true));
        let layout = layout_from(&parsed, &keep);
        assert_eq!(layout.widths["part.Mass"], 240.0);
        assert_eq!(layout.sort, Some(("part.Mass".into(), true)));
    }

    /// The two structural columns are real columns to the widget (so they
    /// resize and reorder like any other) but have no line in the text — a
    /// rewrite must not invent `part.item` lines for them.
    #[test]
    fn the_structural_columns_are_never_written_to_the_text() {
        let parsed = parse("*part.Mass\n");
        let specs = column_specs(&parsed);
        assert_eq!(specs[0].key, ITEM_KEY, "the tree column leads");
        assert_eq!(specs[1].key, VISIBLE_KEY, "then the visibility toggle");
        assert_eq!(specs[2].key, FLAGS_KEY, "then the status badges");
        assert_eq!(specs[4].key, ACTIONS_KEY, "the action column trails");
        assert_eq!(specs.len(), STRUCTURAL_LEADING + 2);
        assert!(
            matches!(specs[4].kind, CellKind::Actions { .. }),
            "the action column hosts the row MENU trigger, which the widget \
             opens and the panel acts on"
        );
        let layout = layout_from(&parsed, &ColumnLayout::default());
        assert_eq!(
            layout.order,
            vec![ITEM_KEY, VISIBLE_KEY, FLAGS_KEY, "part.Mass", ACTIONS_KEY]
        );
        let text = serialize(
            &columns_from_layout(&parsed, &layout),
            &parsed.preserved,
            frozen_from_layout(&layout),
        );
        assert_eq!(text, "*part.Mass\n", "no lines for the structural columns");
    }

    /// The `-` marker freezes what is above it. The structural Item column
    /// rides inside the frozen band (a freeze without the column that names
    /// the row is never what is meant), so the widget's count is one more than
    /// the text's, and the whole thing round-trips through a write-back.
    #[test]
    fn the_dash_marker_freezes_the_columns_above_it_and_round_trips() {
        let text = "*part.Part_Number\n-\n*part.Description\n*occurrence.Notes\n";
        let parsed = parse(&text);
        assert_eq!(parsed.frozen, Some(1), "one configured column above the dash");
        assert!(parsed.problems.is_empty(), "{:?}", parsed.problems);
        assert!(
            !parsed.preserved.iter().any(|line| line == FREEZE_MARKER),
            "the marker is not a preserved line — it would be re-emitted above \
             the columns and would then read as 'freeze nothing'"
        );
        let layout = layout_from(&parsed, &ColumnLayout::default());
        assert_eq!(
            layout.frozen,
            STRUCTURAL_LEADING + 1,
            "the structural columns + Part Number"
        );
        assert_eq!(frozen_from_layout(&layout), Some(1), "back to text terms");
        assert_eq!(
            serialize(
                &columns_from_layout(&parsed, &layout),
                &parsed.preserved,
                frozen_from_layout(&layout)
            ),
            text,
            "the marker survives a write-back in its own place"
        );
    }

    /// No marker is the state every configuration written before freezing
    /// existed is in: nothing frozen.
    #[test]
    fn no_dash_still_holds_the_structural_columns_still() {
        let parsed = parse("*part.Mass\n*part.Finish\n");
        assert_eq!(parsed.frozen, None, "the TEXT names no frozen column");
        let layout = layout_from(&parsed, &ColumnLayout::default());
        assert_eq!(
            layout.frozen, STRUCTURAL_LEADING,
            "but Item / visibility / badges never scroll: they are the row's \
             identity, and scrolling them away leaves values with nothing \
             saying which part each line is about"
        );
        assert_eq!(
            frozen_from_layout(&layout),
            None,
            "the implicit freeze is NOT a marker — round-tripping it would \
             invent a `-` in the user's text"
        );
        assert_eq!(
            serialize(
                &columns_from_layout(&parsed, &layout),
                &parsed.preserved,
                frozen_from_layout(&layout)
            ),
            "*part.Mass\n*part.Finish\n",
            "and no marker is invented"
        );
    }

    /// A dash above everything, a dash below everything, and a SECOND dash:
    /// the first two are legitimate configurations, the third costs that one
    /// line and nothing else.
    #[test]
    fn dash_edges_and_a_second_dash() {
        let top = parse("-\n*part.Mass\n");
        assert_eq!(top.frozen, Some(0), "nothing above it but the Item column");
        assert_eq!(
            layout_from(&top, &ColumnLayout::default()).frozen,
            STRUCTURAL_LEADING
        );

        let bottom = parse("*part.Mass\n-\n");
        assert_eq!(bottom.frozen, Some(1), "every column is above it");
        let layout = layout_from(&bottom, &ColumnLayout::default());
        assert_eq!(layout.frozen, STRUCTURAL_LEADING + 1);
        assert_eq!(
            serialize(
                &columns_from_layout(&bottom, &layout),
                &bottom.preserved,
                frozen_from_layout(&layout)
            ),
            "*part.Mass\n-\n",
            "a trailing marker survives"
        );

        let twice = parse("*part.Mass\n-\n*part.Finish\n-\n*part.Revision\n");
        assert_eq!(twice.frozen, Some(1), "the FIRST marker decides");
        assert_eq!(twice.problems.len(), 1, "{:?}", twice.problems);
        assert!(twice.problems[0].starts_with("line 4:"), "{:?}", twice.problems);
        assert_eq!(twice.columns.len(), 3, "and it costs no column");
    }
}