indicatrix-editor 0.7.2

GUI-free faceting-design editor logic shared by the desktop editor and the wasm web app: the EditorSession (design, undo/redo with caller-supplied coalescing timestamps, selection, dirty tracking), tier/preform/material form parsing, plain-struct view models, the cutting sheet, Retarget, the guided walkthrough and the solve policy. No GUI toolkit, no threads, no clock, no filesystem.
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
//! Parses the tier-edit form's text/enum fields into a
//! [`indicatrix_cut_core::ConstraintTier`]/[`TierTarget`].
//!
//! Including the shorthand index-entry notations (colon-separated arithmetic sequences
//! and the orbit "xN" fold-count suffix).

use super::number_expr::{NameValues, eval_number};
use indicatrix::geometry::meet_solver::MeetConstraint;
use indicatrix_cut_core::{ConstraintTier, TierTarget};

/// Parses just the angle text an inline tier-list cell commits (`inline_set_angle`).
///
/// The same validation [`parse_tier_form`]'s own angle field applies (must parse as a
/// finite `f64`), pulled out so the inline cell doesn't need a whole tier form's worth of
/// other fields just to validate one number.
///
/// # Errors
///
/// A message when `angle` is not a finite number, or its magnitude exceeds 90
/// degrees. The text may be arithmetic over constants (`41 + 0.5`); see
/// [`eval_number`].
pub fn parse_angle_only(angle: &str) -> Result<f64, String> {
    parse_angle_only_with_names(angle, None)
}

/// [`parse_angle_only`], where the text may also name tiers through `names` (`P1 - 2`
/// with the angle magnitude of the tier called `P1`).
///
/// # Errors
///
/// As [`parse_angle_only`]; a name `names` does not know is reported as "there is no
/// tier called 'X'".
pub fn parse_angle_only_with_names(
    angle: &str,
    names: Option<NameValues<'_>>,
) -> Result<f64, String> {
    let angle_deg = eval_number(angle, names).map_err(|error| error.message("Angle", angle))?;
    if !angle_deg.is_finite() {
        return Err("Angle must be a finite number.".to_string());
    }
    reject_angle_over_90(angle_deg)?;
    Ok(angle_deg)
}

/// Parses `token` as the colon-separated arithmetic sequence shorthand
/// `start:step:stop` (e.g. `"0:12:96"`) for the Indices field -- generates every
/// `start + k*step` strictly before `stop` (exclusive, the same half-open
/// convention every other "count up to N" in
/// this codebase uses), wrapped modulo `gear_teeth_abs` so a sequence that
/// runs past the gear's own tooth count still lands on real positions
/// instead of failing outright. Each generated value still goes through the
/// caller's own finite/range/duplicate checks, so a wrap that lands out of
/// range or repeats an earlier value is still caught and reported.
///
/// Returns `None` when `token` does not split into exactly three colon-
/// separated parts or any of them fails to parse as a plain `f64` (or `step`
/// is exactly zero, which would loop forever) -- the caller then falls
/// through to treating `token` as an ordinary single index, which reports
/// its own "not a number" error the normal way.
fn parse_colon_sequence(token: &str, gear_teeth_abs_f64: f64) -> Option<Vec<f64>> {
    let parts: Vec<&str> = token.split(':').collect();
    let [start, step, stop] = parts.as_slice() else {
        return None;
    };
    let start: f64 = start.trim().parse().ok()?;
    let step: f64 = step.trim().parse().ok()?;
    let stop: f64 = stop.trim().parse().ok()?;
    if step == 0.0 || !(start.is_finite() && step.is_finite() && stop.is_finite()) {
        return None;
    }
    let mut values = Vec::new();
    let mut current = start;
    // Bounded rather than a `while` run to `stop`: a pathological step (say
    // `1e-9`) must still terminate rather than hang the UI thread. No real
    // index gear has anywhere near this many teeth, so the bound is never
    // reached by a legitimate sequence.
    for _ in 0..10_000 {
        if (step > 0.0 && current >= stop) || (step < 0.0 && current <= stop) {
            break;
        }
        values.push(if gear_teeth_abs_f64 > 0.0 {
            current.rem_euclid(gear_teeth_abs_f64)
        } else {
            current
        });
        current += step;
    }
    Some(values)
}

/// Parses `suffix` as the "xN" fold-count half of the "N xM" orbit shorthand
/// (e.g. `"12 x8"`) -- the same `x`-prefixed notation the ORBIT column already
/// displays for a complete family (see `docs/manual/03-loading-and-tier-list.md`'s
/// "Orbits" section: `orbit x8`).
/// Returns the fold count when `suffix` is exactly `x`/`X` followed by one or
/// more digits naming a positive count, `None` otherwise -- the caller then
/// treats the two tokens as two ordinary (and, for the second, almost
/// certainly invalid) indices, which still reports a normal "not a number"
/// error rather than silently doing nothing.
fn parse_orbit_suffix(suffix: &str) -> Option<u32> {
    let digits = suffix.strip_prefix(['x', 'X'])?;
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    digits.parse::<u32>().ok().filter(|&n| n > 0)
}

/// Expands `base` into `fold_count` evenly spaced index-wheel positions --
/// `base + k * (gear_teeth_abs / fold_count)` for `k` in `0..fold_count`, wrapped
/// modulo `gear_teeth_abs`. The other half of [`parse_orbit_suffix`]'s "12 x8"
/// shorthand. A `fold_count` that does not
/// evenly divide the gear still produces values (landing on fractional
/// teeth) rather than being rejected here -- the caller's own non-integral-
/// index warning is what flags that, exactly as it would for a hand-typed
/// fractional index.
fn expand_orbit_shorthand(base: f64, fold_count: u32, gear_teeth_abs_f64: f64) -> Vec<f64> {
    if gear_teeth_abs_f64 <= 0.0 {
        return vec![base];
    }
    let step = gear_teeth_abs_f64 / f64::from(fold_count);
    (0..fold_count)
        .map(|k| f64::mul_add(f64::from(k), step, base).rem_euclid(gear_teeth_abs_f64))
        .collect()
}

/// Folds an index onto the ring `0..gear_teeth_abs_f64`, so the gear's own tooth count
/// (96 on a 96-tooth gear) and `0` name the same position.
///
/// A gear of zero teeth (nonsensical, but not this function's business to reject)
/// leaves the value as it is.
fn wheel_position(value: f64, gear_teeth_abs_f64: f64) -> f64 {
    if gear_teeth_abs_f64 > 0.0 {
        value.rem_euclid(gear_teeth_abs_f64)
    } else {
        value
    }
}

/// A magnitude beyond 90 degrees is never a real facet. Every angle in this app
/// is measured from the girdle plane or is the girdle itself (`0.0`), so nothing
/// legitimately authored ever exceeds a right angle either side. Left unchecked,
/// a mistyped extra digit (e.g. `410` for `41.0`) can sail through the inline
/// cell and tier form and only surface later as "Degenerate: only N vertex(es)",
/// with no hint the angle was the mistake.
fn reject_angle_over_90(angle_deg: f64) -> Result<(), String> {
    if angle_deg.abs() > 90.0 {
        // The message reads the magnitude (`-91` and `91` both read `91.00`): the side of the
        // girdle is the block's, not a sign.
        return Err(format!(
            "Angle {:.2}\u{b0} exceeds 90\u{b0} -- angles are measured from the girdle \
             plane, so no crown or pavilion facet can be steeper than that.",
            angle_deg.abs()
        ));
    }
    Ok(())
}

/// [`parse_tier_form`]'s bundled input.
///
/// The tier-edit form's five text/enum fields
/// (`angle`/`constraint_kind`/`constraint_text`/`name`/`indices`), the design's own
/// `gear_teeth_abs` needed to validate `indices` against it, and the two carry-through
/// values (`imported_meet`/`original_notes`) an existing row keeps across a save (see
/// [`parse_tier_form`]'s own doc comment for both).
///
/// Bundled into its own struct purely to keep [`parse_tier_form`] under clippy's
/// argument-count lint -- every one of these eight fields is still required, none
/// dropped.
pub struct TierFormFields<'a> {
    /// The angle text field; must parse as a finite `f64`.
    pub angle: &'a str,
    /// `EditorTierItem`'s three-way constraint-kind encoding -- see
    /// [`parse_tier_form`]'s own doc comment for the `0`/`1`/`2` mapping.
    pub constraint_kind: i32,
    /// The constraint text field, meaning depending on `constraint_kind`.
    pub constraint_text: &'a str,
    /// The tier's name field.
    pub name: &'a str,
    /// The comma/space/semicolon-separated index list text field.
    pub indices: &'a str,
    /// The design's own index-wheel tooth count, used to validate `indices`.
    pub gear_teeth_abs: u32,
    /// The tier's current `imported_meet`, threaded straight through unchanged.
    pub imported_meet: Option<MeetConstraint>,
    /// The tier's current `original_notes`, threaded straight through unchanged.
    pub original_notes: Option<String>,
    /// Every OTHER tier's own name token (`ConstraintTier::names()`, i.e. already
    /// split on `/` -- see that method's own doc comment for the multi-name join
    /// convention), gathered by the caller with the tier being saved itself
    /// excluded. Checked case-insensitively against this form's own name so two
    /// tiers can never silently share a name --
    /// `MeetNameResolver::name_match` (`indicatrix::geometry::meet_solver::names`)
    /// binds a `MeetNamed` reference to the FIRST tier bearing a given name, so an
    /// undetected collision does not error, it just silently redirects some OTHER
    /// tier's constraint to the wrong facet.
    ///
    /// This form validates only the tier being saved. The other direction -- other
    /// tiers whose `MeetNamed` lists name the tier being RENAMED -- is handled when
    /// the save becomes an edit: `crate::tier_save::tier_save_edit` rewrites those lists
    /// in the same batch, and `crate::tier_save::unnaming_blocked_message` refuses to
    /// leave a met tier unnamed.
    pub other_tier_names: Vec<String>,
}

/// Parses a tier form's index field into validated index-wheel positions.
///
/// Accepts a comma/space/semicolon separated list whose tokens may each be a plain
/// number, a `start:step:stop` arithmetic sequence, or a `base xN` orbit shorthand
/// (see [`parse_colon_sequence`] and [`expand_orbit_shorthand`]
/// for each form's own rules). Every produced value is checked for finiteness, for
/// being on the design's own gear (`0` up to and including `gear_teeth_abs`), and for
/// not repeating.
///
/// The index wheel is a ring: `gear_teeth_abs` (96 on a 96-tooth gear) is the same
/// position as `0`. A typed `96` is therefore valid, and is kept exactly as typed (never
/// rewritten to `0`, so a `.asc` file that carries `96` round-trips), while the duplicate
/// check compares ring positions, so `0, 96` is reported as a repeat.
///
/// # Errors
///
/// A message naming the offending token, ready to show the cutter. A value produced
/// by a shorthand names the shorthand it came from as well as the value itself, so
/// a range or duplicate error is traceable back to what was actually typed. A value
/// off the gear reports the valid range ("Indices run from 0 to 96 on this gear.").
///
/// `pub(super)` (rather than private to this module) so
/// `callbacks::tier_actions::setup_generate_step_series_callback` can parse its own
/// shared indices field with the exact same free-text convention
/// [`parse_tier_form`]'s own indices field uses, instead of a second, divergent
/// parser.
pub fn parse_index_list(indices: &str, gear_teeth_abs: u32) -> Result<Vec<f64>, String> {
    let gear_teeth_abs_f64 = f64::from(gear_teeth_abs);
    let mut parsed_indices: Vec<f64> = Vec::new();
    let push_index =
        |value: f64, label: &str, parsed_indices: &mut Vec<f64>| -> Result<(), String> {
            if !value.is_finite() {
                return Err(format!("Index '{label}' must be a finite number."));
            }
            if value < 0.0 || value > gear_teeth_abs_f64 {
                return Err(format!(
                    "Index '{label}' is off the gear. \
                     Indices run from 0 to {gear_teeth_abs} on this gear."
                ));
            }
            let position = wheel_position(value, gear_teeth_abs_f64);
            if parsed_indices.iter().any(|&earlier| {
                (wheel_position(earlier, gear_teeth_abs_f64) - position).abs() < 1e-9
            }) {
                return Err(format!("Index '{label}' is listed more than once."));
            }
            parsed_indices.push(value);
            Ok(())
        };

    let raw_tokens: Vec<&str> = indices
        .split([',', ' ', ';'])
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect();
    let mut i = 0;
    while i < raw_tokens.len() {
        let token = raw_tokens[i];
        // "0:12:96" -- a colon-separated arithmetic sequence.
        if let Some(values) = parse_colon_sequence(token, gear_teeth_abs_f64) {
            for value in values {
                push_index(
                    value,
                    &format!("{value} (from '{token}')"),
                    &mut parsed_indices,
                )?;
            }
            i += 1;
            continue;
        }
        // "12 x8" -- a base index followed by an "xN" fold-count token.
        if let Ok(base) = token.parse::<f64>()
            && let Some(next) = raw_tokens.get(i + 1)
            && let Some(fold_count) = parse_orbit_suffix(next)
        {
            let shorthand = format!("{token} {next}");
            for value in expand_orbit_shorthand(base, fold_count, gear_teeth_abs_f64) {
                push_index(
                    value,
                    &format!("{value} (from '{shorthand}')"),
                    &mut parsed_indices,
                )?;
            }
            i += 2;
            continue;
        }
        let value: f64 = token
            .parse()
            .map_err(|_| format!("Index '{token}' is not a number."))?;
        push_index(value, token, &mut parsed_indices)?;
        i += 1;
    }
    Ok(parsed_indices)
}

/// Parses the tier-edit form's five text/enum fields into a [`ConstraintTier`].
///
/// Pure
/// and unit tested directly (see this module's tests) rather than only exercised
/// through the Slint callback -- every validation an editor's numeric text field
/// needs (not a number, not finite) surfaces as a plain `Err` message shown via a
/// toast, never a panic on bad user input.
///
/// There is deliberately no `mast` field -- see `indicatrix_cut_core::design`'s
/// module docs: a mast is [`indicatrix_cut_core::Design::solve`]'s output, never
/// authored state. The form does not offer a text field for it at all.
/// `constraint_kind` is `EditorTierItem`'s own three-way encoding (`app.slint`'s
/// `editor_save_tier` callback), the inverse of `super::state`'s
/// `constraint_kind_and_text`:
/// - `0` -- [`MeetConstraint::MeetExisting`] (`constraint_text` ignored).
/// - `1` -- [`MeetConstraint::MeetNamed`], `constraint_text` a comma-separated name
///   list.
/// - `2` -- [`MeetConstraint::ScaleReference`], `constraint_text` a single real
///   number (the authored dimension itself).
/// - `3`/`4`/`5` -- an authored `TierTarget` ("cut to
///   depth"/"girdle thickness"/"table width" -- see [`parse_tier_target`], this
///   function's cutter-facing counterpart). The returned
///   [`ConstraintTier::constraint`] is a `ScaleReference(0.0)` PLACEHOLDER for
///   these three kinds -- `indicatrix_cut_core::design::targets`'s module docs
///   document that `Design::resolved_meet_tier_inputs` always overwrites it
///   with the real resolved mast before solving, so this function itself never
///   needs (and cannot, without a `Design` to bisect against) compute the real
///   value. The caller (`callbacks::tier_actions::setup_save_tier_callback`)
///   calls [`parse_tier_target`] separately, with the same `constraint_kind`/
///   `constraint_text`, to get the actual `TierTarget` for its own
///   `Edit::SetTierTarget`.
/// - anything else -- rejected as an `Err`, never silently coerced to a default
///   constraint kind.
///
/// Indices split on comma/space/semicolon, matching
/// `indicatrix_vault::local::reconstruct_asc_schedule`'s own splitting convention for
/// the same kind of field, so a value copied from that reconstruction's indices
/// column round-trips straight back in. Two shorthand forms are recognized before
/// that plain split-and-parse: `"start:step:stop"` (a colon-separated arithmetic
/// sequence, exclusive of `stop`, see [`parse_colon_sequence`]) and `"base xN"`
/// (a base index followed by an `xN` fold count, expanded the same
/// way the ORBIT column's own `orbit x8` label already describes a complete family,
/// see [`parse_orbit_suffix`]/[`expand_orbit_shorthand`]); either form's generated
/// values are wrapped modulo the gear and fed through the exact same per-value
/// validation below as a hand-typed index. Each parsed value is then validated
/// against `gear_teeth_abs` (the design's own index-wheel tooth count, from
/// [`indicatrix_cut_core::design::tier::ScheduleMeta::gear_teeth_abs`]): it must be
/// finite, within `0.0..=gear_teeth_abs as f64` (an index the gear physically has no
/// tooth for is never silently accepted; the closing value is the same position as `0`
/// on the ring and is kept as typed), and not a repeat of an earlier value in the
/// same list (a duplicate names the same facet occurrence twice, which is never a
/// meaningful tier; `0` and `gear_teeth_abs` count as the same position). The first entry that fails any of these is reported by its own
/// text, matching every other field's own "name the offending value" convention here.
/// A non-integral value (from either a hand-typed fraction or a fold count that does
/// not evenly divide the gear) is still ACCEPTED here -- warning about it without
/// rejecting it is the caller's job (`callbacks::tier_actions::setup_save_tier_callback`),
/// since it is real GemCad-file behavior (`indicatrix_formats::asc`'s own module docs
/// measure roughly 0.2% of real index tokens as fractional), not necessarily a mistake.
///
/// `imported_meet` is threaded straight through to the built [`ConstraintTier`]
/// unchanged -- this function never inspects or clears it. The caller
/// (`super::callbacks::setup_save_tier_callback`) passes the CURRENT tier's own
/// `imported_meet` when editing an existing row (`index >= 0`) so that tweaking,
/// say, just this tier's name does not silently discard the file's stated meet
/// instruction, and `None` when adding a brand-new tier (`index < 0`), which
/// has no import history to preserve at all. The one-click "Adopt" action
/// (`super::callbacks::setup_adopt_meet_callback`) is the only thing that ever
/// actually CONSULTS this field to build a new constraint from it.
///
/// # Errors
///
/// A message naming the offending field: an angle that is not a finite number or
/// exceeds 90 degrees, a name another tier already holds, an invalid index list
/// (see [`parse_index_list`]), an empty "meet named" list, a scale reference that
/// is not a finite number, or an unknown constraint kind.
pub fn parse_tier_form(form: TierFormFields<'_>) -> Result<ConstraintTier, String> {
    let TierFormFields {
        angle,
        constraint_kind,
        constraint_text,
        name,
        indices,
        gear_teeth_abs,
        imported_meet,
        original_notes,
        other_tier_names,
    } = form;
    let angle_deg = parse_angle_only(angle)?;

    let name = name.trim();
    // Reject a name (or, for a `/`-joined multi-name tier, any ONE of its names)
    // another tier already holds -- see `TierFormFields::other_tier_names`'s own
    // doc comment for why an undetected collision is worse than merely confusing.
    for token in name.split('/').map(str::trim).filter(|s| !s.is_empty()) {
        if let Some(existing) = other_tier_names
            .iter()
            .find(|other| other.eq_ignore_ascii_case(token))
        {
            return Err(format!(
                "Another tier is already named '{existing}' -- facet names must be unique so \
                 meet constraints resolve to the right tier."
            ));
        }
    }

    let parsed_indices = parse_index_list(indices, gear_teeth_abs)?;

    let constraint = match constraint_kind {
        0 => MeetConstraint::MeetExisting,
        1 => {
            let names: Vec<String> = constraint_text
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect();
            if names.is_empty() {
                return Err("\"Meet named\" needs at least one facet name.".to_string());
            }
            MeetConstraint::MeetNamed(names)
        }
        2 => {
            let value = eval_number(constraint_text, None)
                .map_err(|error| error.message("Scale reference", constraint_text))?;
            if !value.is_finite() {
                return Err("Scale reference must be a finite number.".to_string());
            }
            MeetConstraint::ScaleReference(value)
        }
        // 3-5: an authored `TierTarget` ("cut to depth"/"girdle thickness"/
        // "table width") -- see this function's own doc comment and
        // `parse_tier_target` below. The tier's own `constraint` is a
        // `ScaleReference` placeholder that `Design::resolved_meet_tier_inputs`
        // always overwrites before solving; the real millimetre value is
        // validated and returned separately, by `parse_tier_target`, since this
        // function only ever returns a `ConstraintTier`.
        3..=5 => MeetConstraint::ScaleReference(0.0),
        other => return Err(format!("Unknown constraint kind {other}.")),
    };

    Ok(ConstraintTier {
        angle_deg,
        name: name.to_string(),
        indices: parsed_indices,
        constraint,
        imported_meet,
        original_notes,
        detached: Vec::new(),
    })
}

/// [`parse_tier_form`] for a form whose angle field may hold a RELATION: text starting
/// with `=` (`=C1-4`, `= (P1 + P3) / 2`) drives the tier's angle from other tiers
/// instead of fixing it.
///
/// Returns the tier and the relation text exactly as typed after the `=` (trimmed;
/// the caller turns it into a relation with `EditorSession::set_tier_relation`, which
/// reads the tier names against the design). The tier carries `placeholder_angle_deg`
/// -- the tier's current angle when editing, any valid angle for a new tier -- because
/// the relation, not this form, decides the real angle once it is applied. An angle
/// field that does not start with `=` behaves exactly as [`parse_tier_form`] and
/// returns no relation text.
///
/// # Errors
///
/// As [`parse_tier_form`]; an angle field that is only `=` is an "Angle ..." error.
pub fn parse_tier_form_with_relation(
    form: TierFormFields<'_>,
    placeholder_angle_deg: f64,
) -> Result<(ConstraintTier, Option<String>), String> {
    let Some(relation) = form.angle.trim().strip_prefix('=') else {
        return parse_tier_form(form).map(|tier| (tier, None));
    };
    let relation = relation.trim().to_owned();
    if relation.is_empty() {
        return Err(
            "Angle relation is empty -- type a calculation after '=', for example =C1-4."
                .to_string(),
        );
    }
    let placeholder = placeholder_angle_deg.to_string();
    let tier = parse_tier_form(TierFormFields {
        angle: &placeholder,
        ..form
    })?;
    Ok((tier, Some(relation)))
}

/// Parses the tier form's Meets combo into a [`TierTarget`] when `constraint_kind` names
/// one of the three target kinds.
///
/// `3` [`TierTarget::DepthMm`], `4` [`TierTarget::GirdleThicknessMm`], `5`
/// [`TierTarget::TableWidthMm`] -- the counterpart to [`parse_tier_form`]'s own
/// `0`/`1`/`2` handling for a plain [`MeetConstraint`].
///
/// `constraint_text` is the SAME single numeric field
/// [`parse_tier_form`] reads for kind `2` (`ScaleReference`); here it is
/// always a millimetre figure, matching the unit every [`TierTarget`] variant
/// itself declares.
///
/// `Ok(None)` for every other kind (`0`/`1`/`2`, or anything
/// [`parse_tier_form`] would itself reject) -- "no target," not an error, so a
/// plain meet/scale-reference save that never authored a target is a no-op
/// through `callbacks::tier_actions::setup_save_tier_callback`'s own
/// target-clearing logic, which calls this unconditionally alongside
/// [`parse_tier_form`].
///
/// # Errors
///
/// The same "name the offending value" wording [`parse_tier_form`]'s own
/// `ScaleReference` arm uses, prefixed with the target's own cutter-facing
/// label ("Depth"/"Girdle thickness"/"Table width") instead of "Scale
/// reference" -- `callbacks::tier_actions::tier_form_error_field` recognizes
/// all three prefixes and classifies them the same `"constraint"` field a
/// bad Meets value always has. A non-finite or non-positive value is
/// rejected the same way a non-positive preform dimension is
/// ([`super::preform_and_new_design::parse_preform_form`]): a depth, girdle
/// thickness, or table width of zero or less is never a real target.
pub fn parse_tier_target(
    constraint_kind: i32,
    constraint_text: &str,
) -> Result<Option<TierTarget>, String> {
    let (label, build): (&str, fn(f64) -> TierTarget) = match constraint_kind {
        3 => ("Depth", TierTarget::DepthMm as fn(f64) -> TierTarget),
        4 => (
            "Girdle thickness",
            TierTarget::GirdleThicknessMm as fn(f64) -> TierTarget,
        ),
        5 => (
            "Table width",
            TierTarget::TableWidthMm as fn(f64) -> TierTarget,
        ),
        _ => return Ok(None),
    };
    let text = constraint_text.trim();
    let value = eval_number(text, None).map_err(|error| error.message(label, text))?;
    if !value.is_finite() {
        return Err(format!("{label} must be a finite number."));
    }
    if value <= 0.0 {
        return Err(format!("{label} must be a positive number."));
    }
    Ok(Some(build(value)))
}

/// Classifies a [`parse_tier_form`] (or `Edit`-apply) error message by tier-form field.
///
/// The answer is `"angle"`, `"name"`, `"indices"` or `"constraint"` (and, for the concave
/// form, `"tool"`, `"theta"`, `"x"`, `"y"`, `"z"`, `"diameter"` or `"tool_angle"`), or `""` for a
/// general/unclassified error -- what a UI reads to put a red border on the SPECIFIC
/// offending control, not only on the shared message under the whole form.
///
/// Matched on the exact wording this module's own error branches build (it reads the
/// rendered text rather than a structured variant, since [`parse_tier_form`] returns a
/// plain `String`); a message this does not recognize classifies as `""`, the same
/// "general" bucket an apply-time (post-parse) failure falls into.
///
/// Moved from the desktop's `tier_actions::tier_form`.
#[must_use]
pub fn tier_form_error_field(message: &str) -> &'static str {
    // The concave form's messages name their field up front (`"theta: ..."`, see
    // `loading::concave_form`); none of the flat form's messages has that lowercase
    // `field:` shape, so this cannot shadow them.
    if let Some(field) = concave_form_error_field(message) {
        return field;
    }
    if message.starts_with("Angle") {
        "angle"
    } else if message.starts_with("Another tier is already named") {
        "name"
    } else if message.starts_with("Index '") {
        "indices"
    } else if message.starts_with("\"Meet named\"")
        || message.starts_with("Scale reference")
        || message.starts_with("No facet named")
        || message.starts_with("Unknown constraint kind")
        // `parse_tier_target`'s own three target labels -- same "constraint" bucket
        // as `Scale reference`'s wording, since these are all failures of the same
        // Meets-combo numeric field.
        || message.starts_with("Depth")
        || message.starts_with("Girdle thickness")
        || message.starts_with("Table width")
    {
        "constraint"
    } else {
        ""
    }
}

/// The field a concave form message names by prefix, or `None` for any other message.
///
/// `"tool angle:"` is listed before `"tool:"`; the answers are `"name"`, `"angle"`,
/// `"indices"`, `"tool"`, `"theta"`, `"x"`, `"y"`, `"z"`, `"diameter"` and `"tool_angle"`.
fn concave_form_error_field(message: &str) -> Option<&'static str> {
    const PREFIXES: [(&str, &str); 10] = [
        ("tool angle:", "tool_angle"),
        ("tool:", "tool"),
        ("name:", "name"),
        ("angle:", "angle"),
        ("indices:", "indices"),
        ("theta:", "theta"),
        ("x:", "x"),
        ("y:", "y"),
        ("z:", "z"),
        ("diameter:", "diameter"),
    ];
    PREFIXES
        .iter()
        .find(|(prefix, _)| message.starts_with(prefix))
        .map(|&(_, field)| field)
}

/// The warning shown for a non-integral index-wheel position, which is accepted anyway.
///
/// [`parse_tier_form`] deliberately ACCEPTS such a position (real
/// `.asc` files carry a small but real fraction of these) rather than rejecting it,
/// since a hand-typed fraction is sometimes exactly what was meant. Without this
/// warning a cutter gets no signal at all when it was NOT meant -- a stray extra digit
/// ("12.5" for "12") would only ever surface later as an obscure solver oddity. A
/// caller shows it after a successful parse, so a save is never blocked by this, only
/// flagged. `1e-3` matches `indicatrix_cut_core`'s own `orbit::model::INDEX_TOLERANCE`
/// order of magnitude for "close enough to call it a whole tooth".
///
/// Moved from the desktop's `tier_actions::tier_form`.
#[must_use]
pub fn non_integral_index_warning(indices: &[f64]) -> Option<String> {
    let mut fractional: Vec<String> = indices
        .iter()
        .filter(|v| (**v - v.round()).abs() > 1e-3)
        .map(|v| format!("{v:.3}"))
        .collect();
    fractional.dedup();
    if fractional.is_empty() {
        return None;
    }
    Some(format!(
        "Note: non-integral index position(s) {} -- check this was intentional.",
        fractional.join(", ")
    ))
}

#[cfg(test)]
mod arithmetic_tests;
#[cfg(test)]
mod tests;