Skip to main content

xpict_core/
labels.rs

1//! Atom-label orientation and backbone bond insets.
2//!
3//! Caller supplies SVG-space atom coordinates. Labels split into an
4//! **atom-center** part (sits on the atom) and an optional **traveling**
5//! part (extends away from the molecule). `OH` on the left of a mol becomes
6//! `HO` with `O` still at the atom; abbreviations like `GlcA` have no
7//! traveling part — the first or last glyph is the center depending on the
8//! bond approach side.
9//!
10//! Orientation follows RDKit MolDraw2D (`E`/`W`/`N`/`S`). **All** chem scripts
11//! (H-counts, charges, star-label markup, symbols, bold/italic) go through
12//! [`crate::markup::parse_label_markup`] → [`ScriptRole`] fake scripts,
13//! outlined as glyph **paths**, not ``<text>``.
14
15use crate::font::{self, ChemGlyph, FaceStyle, ScriptRole};
16use crate::geom::Shape;
17use crate::markup;
18use crate::metrics::{label_weight_standoff_px, LABEL_GAP_PX};
19
20/// Which side the traveling text extends toward (RDKit OrientType).
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum LabelSide {
23    /// Bond approaches from the left; traveling text extends east (right).
24    East,
25    /// Bond approaches from the right; traveling text extends west (left).
26    West,
27    /// Bond approaches from below; traveling text extends north (up, −Y SVG).
28    North,
29    /// Bond approaches from above; traveling text extends south (down, +Y SVG).
30    South,
31}
32
33/// Atom-center glyph(s) vs optional traveling H / charge.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct LabelParts {
36    pub center: String,
37    /// Traveling H run (`"H"`, `"H2"`, …) or empty.
38    pub traveling: String,
39    /// Formal charge (`0` = none). Drawn as a superscript.
40    pub charge: i32,
41}
42
43/// One placed atom label in SVG space (+Y down).
44#[derive(Debug, Clone)]
45pub struct PlacedLabel {
46    /// Original input label (for re-outline / halo).
47    pub raw: String,
48    /// Display string for ``data-text`` (unicode scripts when possible).
49    pub text: String,
50    /// Left edge of the advance (SVG text origin), baseline at [`Self::y`].
51    pub origin_x: f64,
52    pub y: f64,
53    pub atom_x: f64,
54    pub atom_y: f64,
55    pub side: LabelSide,
56    /// Bond inset from the atom toward neighbors (isotropic: center glyph
57    /// advance/ink width + gap). Per-bond shortening uses directional ink
58    /// support via [`place_backbone`].
59    pub clearance: f64,
60    /// Outlined glyph path `d` (empty when no ink).
61    pub path_d: String,
62}
63
64/// Build a display label from element, implicit H count, and formal charge.
65///
66/// Silent carbons (`C` with charge 0) return `None`. Hydrogens become
67/// ``OH`` / ``NH2``; charge is left for [`crate::depict`] / callers that
68/// append via `AtomIn.charge`, or pass `charge` here to bake it in (RDKit
69/// host path).
70pub fn atom_display_label(element: &str, imp_hs: u32, charge: i32) -> Option<String> {
71    if element == "C" && charge == 0 {
72        return None;
73    }
74    if element == "*" {
75        return Some("*".into());
76    }
77    let mut text = element.to_string();
78    if imp_hs == 1 {
79        text = format!("{element}H");
80    } else if imp_hs > 1 {
81        text = format!("{element}H{imp_hs}");
82    }
83    if charge != 0 {
84        let sign = if charge > 0 { "+" } else { "−" };
85        let mag = charge.unsigned_abs();
86        text = if mag == 1 {
87            format!("{text}{sign}")
88        } else {
89            format!("{text}{mag}{sign}")
90        };
91    }
92    Some(text)
93}
94
95/// Split a raw label into center + traveling H + charge.
96///
97/// Accepts backend strings like ``NH2``, ``OH``, ``NH4+``, ``O−``, ``*``,
98/// and marked forms ``$R_1$`` / ``R^2`` (markup stays on ``center`` for
99/// [`parse_label_markup`]). Bare underscores (``my_name``) are **not**
100/// treated as scripts at split time.
101pub fn split_label(raw: &str) -> LabelParts {
102    let s = raw.trim();
103    if s.is_empty() {
104        return LabelParts {
105            center: String::new(),
106            traveling: String::new(),
107            charge: 0,
108        };
109    }
110    // Keep `$…$` intact so the markup parser still sees the chem zone.
111    let (body, charge) = if s.starts_with('$') && s.ends_with('$') && s.len() >= 2 {
112        // Charge rarely wraps the dollars; strip charge outside only.
113        (s.to_string(), 0)
114    } else {
115        strip_charge(s)
116    };
117    if body == "*" {
118        return LabelParts {
119            center: "*".into(),
120            traveling: String::new(),
121            charge,
122        };
123    }
124    // Explicit markup: `$…$`, `^`, or braced `_{…}` — no H-split.
125    let has_markup = body.contains('$')
126        || body.contains('^')
127        || body.contains("_{")
128        || body.contains("\\")
129        || body.contains("**")
130        || (body.contains('*') && body != "*");
131    if has_markup {
132        return LabelParts {
133            center: body,
134            traveling: String::new(),
135            charge,
136        };
137    }
138    let bytes = body.as_bytes();
139    if !bytes.is_empty() && bytes[0].is_ascii_uppercase() {
140        let mut i = 1usize;
141        if bytes.len() > 1 && bytes[1].is_ascii_lowercase() {
142            i = 2;
143        }
144        let (elem, rest) = body.split_at(i);
145        if let Some(travel) = parse_h_suffix(rest) {
146            return LabelParts {
147                center: elem.to_string(),
148                traveling: travel.to_string(),
149                charge,
150            };
151        }
152    }
153    LabelParts {
154        center: body.to_string(),
155        traveling: String::new(),
156        charge,
157    }
158}
159
160fn strip_charge(s: &str) -> (String, i32) {
161    let chars: Vec<char> = s.chars().collect();
162    if chars.is_empty() {
163        return (String::new(), 0);
164    }
165    // Trailing + / − / - / ⁺ / ⁻, optional leading magnitude or repeated signs.
166    let last = *chars.last().unwrap();
167    let is_plus = last == '+' || last == '⁺';
168    let is_minus = last == '-' || last == '−' || last == '⁻';
169    if !is_plus && !is_minus {
170        return (s.to_string(), 0);
171    }
172    let sign: i32 = if is_plus { 1 } else { -1 };
173    let mut i = chars.len() - 1;
174    // Collapse repeated ++++ / ----
175    while i > 0 {
176        let c = chars[i - 1];
177        let same = (sign > 0 && (c == '+' || c == '⁺'))
178            || (sign < 0 && (c == '-' || c == '−' || c == '⁻'));
179        if same {
180            i -= 1;
181        } else {
182            break;
183        }
184    }
185    let n_signs = (chars.len() - i) as i32;
186    let without_sign: String = chars[..i].iter().collect();
187    // ``NH4+`` → H-count owns the digits; charge mag is just the sign count.
188    // ``Fe3+`` / ``N2+`` → digits before the sign are the charge magnitude.
189    if without_sign.contains('H') {
190        // Element…H… — don't steal H-count digits for the charge.
191        return (without_sign, sign * n_signs);
192    }
193    let mut j = i;
194    while j > 0 && chars[j - 1].is_ascii_digit() {
195        j -= 1;
196    }
197    let mag = if j < i {
198        let digits: String = chars[j..i].iter().collect();
199        digits.parse::<i32>().unwrap_or(n_signs).max(1)
200    } else {
201        n_signs
202    };
203    let body: String = chars[..j].iter().collect();
204    (body, sign * mag)
205}
206
207fn parse_h_suffix(rest: &str) -> Option<&str> {
208    if rest.is_empty() {
209        return None;
210    }
211    let bytes = rest.as_bytes();
212    if bytes[0] != b'H' {
213        return None;
214    }
215    let mut i = 1usize;
216    while i < bytes.len() && bytes[i].is_ascii_digit() {
217        i += 1;
218    }
219    // Only pure H / Hn — no trailing junk (NHAc, etc.).
220    if i == rest.len() {
221        Some(rest)
222    } else {
223        None
224    }
225}
226
227fn h_count(parts: &LabelParts) -> u32 {
228    let t = parts.traveling.as_str();
229    if t.is_empty() || !t.starts_with('H') {
230        return 0;
231    }
232    if t.len() == 1 {
233        return 1;
234    }
235    t[1..].parse().unwrap_or(1)
236}
237
238/// Orient a label from the sum of neighbor vectors (SVG +Y down).
239///
240/// Matches RDKit ``getAtomOrientation`` (70° vertical slope; degree-1 prefers
241/// E/W; degree-0 defaults East except O/F/S/Cl-class → West).
242pub fn label_side(atom: (f64, f64), neighbors: &[(f64, f64)]) -> LabelSide {
243    label_side_for(atom, neighbors, None)
244}
245
246/// Like [`label_side`] but degree-0 Hs-first elements use West (RDKit).
247pub fn label_side_for(
248    atom: (f64, f64),
249    neighbors: &[(f64, f64)],
250    element: Option<&str>,
251) -> LabelSide {
252    const VERT_SLOPE: f64 = 2.747477; // tan(70°)
253    if neighbors.is_empty() {
254        // RDKit: O, F, S, Cl, … list H first → West.
255        const HS_FIRST: &[&str] = &["O", "F", "S", "Cl", "Br", "I", "Se", "Te", "At"];
256        if element.is_some_and(|e| HS_FIRST.contains(&e)) {
257            return LabelSide::West;
258        }
259        return LabelSide::East;
260    }
261    let (ax, ay) = atom;
262    let mut sx = 0.0;
263    let mut sy = 0.0;
264    for &(nx, ny) in neighbors {
265        sx += nx - ax;
266        sy += ny - ay;
267    }
268    let islope = if sx.abs() > 1e-4 { sy / sx } else { 1000.0 };
269    let mut orient = if islope.abs() <= VERT_SLOPE {
270        if sx > 0.0 {
271            LabelSide::West
272        } else {
273            LabelSide::East
274        }
275    } else if sy > 0.0 {
276        // SVG +Y down → neighbor sum south → label extends North (away).
277        LabelSide::North
278    } else {
279        LabelSide::South
280    };
281
282    // Degree-1: never N/S (RDKit).
283    if neighbors.len() == 1 && matches!(orient, LabelSide::North | LabelSide::South) {
284        if islope.abs() > VERT_SLOPE {
285            orient = LabelSide::East;
286        } else if sx > 0.0 {
287            orient = LabelSide::West;
288        } else {
289            orient = LabelSide::East;
290        }
291    }
292
293    // Degree-3: keep N/S when a near-vertical bond points that way.
294    if neighbors.len() == 3 && matches!(orient, LabelSide::North | LabelSide::South) {
295        for &(nx, ny) in neighbors {
296            let dx = nx - ax;
297            let dy = ny - ay;
298            if dx.abs() < 1e-9 {
299                if dy > 0.0 {
300                    orient = LabelSide::North;
301                } else {
302                    orient = LabelSide::South;
303                }
304                break;
305            }
306            let ang = (dy / dx).atan().to_degrees();
307            if (80.0..100.0).contains(&ang) && orient == LabelSide::North {
308                break;
309            }
310            if (-100.0..-80.0).contains(&ang) && orient == LabelSide::South {
311                break;
312            }
313        }
314    }
315
316    orient
317}
318
319fn charge_glyphs(charge: i32, style: FaceStyle) -> Vec<ChemGlyph> {
320    if charge == 0 {
321        return Vec::new();
322    }
323    let mag = charge.unsigned_abs();
324    let sign = if charge > 0 { '+' } else { '-' };
325    // Formal charge stays on the element baseline (not a fake superscript).
326    // N/S orientation already stacks travel+charge on a second line; raising
327    // the glyph again made top charges float and bottom charges crowd the N.
328    // Explicit caret markup (`R^{2+}`) still goes through parse_label_markup.
329    let mut out = Vec::new();
330    if mag != 1 {
331        for ch in mag.to_string().chars() {
332            out.push(ChemGlyph {
333                ch,
334                role: ScriptRole::Normal,
335                face: style,
336            });
337        }
338    }
339    out.push(ChemGlyph {
340        ch: sign,
341        role: ScriptRole::Normal,
342        face: style,
343    });
344    out
345}
346
347fn h_travel_glyphs(parts: &LabelParts, style: FaceStyle) -> Vec<ChemGlyph> {
348    let n = h_count(parts);
349    if n == 0 {
350        return Vec::new();
351    }
352    // Braced ``H_{n}`` so subscript works outside ``$…$`` (bare ``_`` does not).
353    let marked = if n == 1 {
354        "H".to_string()
355    } else {
356        format!("H_{{{n}}}")
357    };
358    markup::parse_label_markup(&marked, style)
359}
360
361fn center_glyphs(parts: &LabelParts, style: FaceStyle) -> Vec<ChemGlyph> {
362    markup::parse_label_markup(&parts.center, style)
363}
364
365/// Glyphs in draw order for an orientation (atom-center first for E; …).
366fn glyphs_for_side(parts: &LabelParts, side: LabelSide, style: FaceStyle) -> Vec<ChemGlyph> {
367    let center = center_glyphs(parts, style);
368    let travel = h_travel_glyphs(parts, style);
369    let charge = charge_glyphs(parts.charge, style);
370    match side {
371        LabelSide::East | LabelSide::South | LabelSide::North => {
372            let mut g = center;
373            g.extend(travel);
374            g.extend(charge);
375            g
376        }
377        LabelSide::West => {
378            // Travel + charge left of center (RDKit reverses pieces for W).
379            let mut g = charge;
380            g.extend(travel);
381            g.extend(center);
382            g
383        }
384    }
385}
386
387/// Plain display string after orientation (``OH`` / ``HO`` / ``NH₂+``).
388pub fn compose_label(parts: &LabelParts, side: LabelSide) -> String {
389    let glyphs = glyphs_for_side(parts, side, FaceStyle::Regular);
390    glyphs_to_data_text(&glyphs)
391}
392
393fn glyphs_to_data_text(glyphs: &[ChemGlyph]) -> String {
394    let mut out = String::new();
395    for g in glyphs {
396        match g.role {
397            ScriptRole::Normal => out.push(g.ch),
398            ScriptRole::Subscript => out.push(subscript_char(g.ch)),
399            ScriptRole::Superscript => out.push(superscript_char(g.ch)),
400        }
401    }
402    out
403}
404
405fn subscript_char(ch: char) -> char {
406    match ch {
407        '0' => '₀',
408        '1' => '₁',
409        '2' => '₂',
410        '3' => '₃',
411        '4' => '₄',
412        '5' => '₅',
413        '6' => '₆',
414        '7' => '₇',
415        '8' => '₈',
416        '9' => '₉',
417        _ => ch,
418    }
419}
420
421fn superscript_char(ch: char) -> char {
422    match ch {
423        '+' => '⁺',
424        '-' => '⁻',
425        '0' => '⁰',
426        '1' => '¹',
427        '2' => '²',
428        '3' => '³',
429        '4' => '⁴',
430        '5' => '⁵',
431        '6' => '⁶',
432        '7' => '⁷',
433        '8' => '⁸',
434        '9' => '⁹',
435        _ => ch,
436    }
437}
438
439fn advance_glyphs_px(glyphs: &[ChemGlyph], font_px: f64, style: FaceStyle) -> f64 {
440    if glyphs.is_empty() {
441        return 0.0;
442    }
443    let face = font::face_metrics(style);
444    let (_shape, adv_em) = font::outline_chem_run_em(glyphs, style);
445    adv_em * (font_px / face.upem)
446}
447
448#[cfg(test)]
449fn advance_px(text: &str, font_px: f64, style: FaceStyle) -> f64 {
450    if text.is_empty() {
451        return 0.0;
452    }
453    let glyphs: Vec<_> = text
454        .chars()
455        .map(|ch| ChemGlyph {
456            ch,
457            role: ScriptRole::Normal,
458            face: style,
459        })
460        .collect();
461    advance_glyphs_px(&glyphs, font_px, style)
462}
463
464fn baseline_offset(font_px: f64, style: FaceStyle) -> f64 {
465    let face = font::face_metrics(style);
466    0.5 * (face.cap_height / face.upem) * font_px
467}
468
469/// Atom-center glyph(s) for clearance / anchoring (element token, or one
470/// base glyph of an abbreviation — never a script mark or digit alone).
471fn center_anchor_glyphs(parts: &LabelParts, side: LabelSide, style: FaceStyle) -> Vec<ChemGlyph> {
472    let center = center_glyphs(parts, style);
473    if center.is_empty() {
474        return Vec::new();
475    }
476    if !parts.traveling.is_empty() || parts.charge != 0 {
477        return center;
478    }
479    let normals: Vec<ChemGlyph> = center
480        .iter()
481        .copied()
482        .filter(|g| g.role == ScriptRole::Normal)
483        .collect();
484    if normals.is_empty() {
485        return center;
486    }
487    let g = match side {
488        LabelSide::East | LabelSide::South | LabelSide::North => normals[0],
489        LabelSide::West => *normals.last().unwrap(),
490    };
491    vec![g]
492}
493
494/// Advance from string start to the start of the center glyph (E/W runs).
495fn prefix_before_center(
496    parts: &LabelParts,
497    side: LabelSide,
498    font_px: f64,
499    style: FaceStyle,
500) -> f64 {
501    match side {
502        LabelSide::East | LabelSide::North | LabelSide::South => 0.0,
503        LabelSide::West => {
504            if parts.traveling.is_empty() && parts.charge == 0 {
505                let center = center_glyphs(parts, style);
506                let normals: Vec<_> = center
507                    .iter()
508                    .enumerate()
509                    .filter(|(_, g)| g.role == ScriptRole::Normal)
510                    .collect();
511                let Some(&(idx, _)) = normals.last() else {
512                    return 0.0;
513                };
514                return advance_glyphs_px(&center[..idx], font_px, style);
515            }
516            let mut prefix = charge_glyphs(parts.charge, style);
517            prefix.extend(h_travel_glyphs(parts, style));
518            advance_glyphs_px(&prefix, font_px, style)
519        }
520    }
521}
522
523/// Full oriented label ink AABB relative to the atom (SVG +Y down).
524///
525/// Used for bond shortening so traveling H and charge superscripts clear
526/// bond ends when a neighbor approaches from that side. Atom-center
527/// isotropic [`PlacedLabel::clearance`] still uses [`center_glyph_ink_rel`].
528fn label_clearance_ink_rel(
529    parts: &LabelParts,
530    side: LabelSide,
531    font_px: f64,
532    style: FaceStyle,
533) -> (f64, Option<(f64, f64, f64, f64)>) {
534    let (center_adv, _) = center_glyph_ink_rel(parts, side, font_px, style);
535    let prefix = prefix_before_center(parts, side, font_px, style);
536    let origin_x = -prefix - 0.5 * center_adv;
537    let baseline = baseline_offset(font_px, style);
538    // Atom at (0, 0); outline_placed uses atom_x for N/S centering.
539    let Some(shape) = outline_placed(parts, side, origin_x, baseline, 0.0, 0.0, font_px, style)
540    else {
541        return (center_adv, None);
542    };
543    let ink = shape.bounds().map(|(x0, y0, x1, y1)| (x0, x1, y0, y1));
544    (center_adv, ink)
545}
546
547/// Ink AABB of the center glyph relative to the atom (SVG +Y down).
548fn center_glyph_ink_rel(
549    parts: &LabelParts,
550    side: LabelSide,
551    font_px: f64,
552    style: FaceStyle,
553) -> (f64, Option<(f64, f64, f64, f64)>) {
554    let anchor = center_anchor_glyphs(parts, side, style);
555    if anchor.is_empty() {
556        return (0.0, None);
557    }
558    // ``*`` uses the custom star metrics.
559    if anchor.len() == 1 && anchor[0].ch == '*' && anchor[0].role == ScriptRole::Normal {
560        let face = font::face_metrics(style);
561        let scale = font_px / face.upem;
562        let (shape, adv_em) = font::outline_star_em(style);
563        let advance = adv_em * scale;
564        let half = 0.5 * advance;
565        let base = baseline_offset(font_px, style);
566        let ink = shape.bounds().map(|(x0, y0, x1, y1)| {
567            (
568                x0 * scale - half,
569                x1 * scale - half,
570                base - y1 * scale,
571                base - y0 * scale,
572            )
573        });
574        return (advance, ink);
575    }
576    let face = font::face_metrics(style);
577    let scale = font_px / face.upem;
578    let (shape, adv_em) = font::outline_chem_run_em(&anchor, style);
579    let advance = adv_em * scale;
580    let half = 0.5 * advance;
581    let base = baseline_offset(font_px, style);
582    let ink = shape.and_then(|s| s.bounds()).map(|(x0, y0, x1, y1)| {
583        (
584            x0 * scale - half,
585            x1 * scale - half,
586            base - y1 * scale,
587            base - y0 * scale,
588        )
589    });
590    (advance, ink)
591}
592
593fn aabb_support(xmin: f64, xmax: f64, ymin: f64, ymax: f64, ux: f64, uy: f64) -> f64 {
594    let sx = if ux >= 0.0 { xmax } else { xmin };
595    let sy = if uy >= 0.0 { ymax } else { ymin };
596    sx * ux + sy * uy
597}
598
599fn clearance_toward(
600    advance: f64,
601    ink: Option<(f64, f64, f64, f64)>,
602    ux: f64,
603    uy: f64,
604    standoff: f64,
605) -> f64 {
606    let half = 0.5 * advance;
607    let ink_reach = ink
608        .map(|(x0, x1, y0, y1)| aabb_support(x0, x1, y0, y1, ux, uy).max(0.0))
609        .unwrap_or(0.0);
610    half.max(ink_reach) + LABEL_GAP_PX + standoff
611}
612
613fn clearance_isotropic(advance: f64, ink: Option<(f64, f64, f64, f64)>, standoff: f64) -> f64 {
614    let mut half = 0.5 * advance;
615    if let Some((x0, x1, _, _)) = ink {
616        half = half.max(0.5 * (x1 - x0));
617    }
618    half + LABEL_GAP_PX + standoff
619}
620
621/// Outline chem label glyphs at the placed origin (SVG +Y down).
622fn outline_placed(
623    parts: &LabelParts,
624    side: LabelSide,
625    origin_x: f64,
626    baseline_y: f64,
627    atom_x: f64,
628    _atom_y: f64,
629    font_px: f64,
630    style: FaceStyle,
631) -> Option<Shape> {
632    let face = font::face_metrics(style);
633    let scale = font_px / face.upem;
634    let line_gap = 1.1 * (face.cap_height / face.upem) * font_px;
635
636    match side {
637        LabelSide::East | LabelSide::West => {
638            let glyphs = glyphs_for_side(parts, side, style);
639            font::compile_chem_shapes(&glyphs, origin_x, baseline_y, font_px, "start", style)
640        }
641        LabelSide::North | LabelSide::South => {
642            // Stack: center on atom; travel (+ charge) above (N) or below (S).
643            let center = center_glyphs(parts, style);
644            let mut travel = h_travel_glyphs(parts, style);
645            travel.extend(charge_glyphs(parts.charge, style));
646            let (c_shape, c_adv_em) = font::outline_chem_run_em(&center, style);
647            let c_adv = c_adv_em * scale;
648            let c_origin_x = atom_x - 0.5 * c_adv;
649            let mut acc = c_shape.map(|s| {
650                s.scale(scale, -scale, 0.0, 0.0)
651                    .translate(c_origin_x, baseline_y)
652            });
653            if !travel.is_empty() {
654                let (t_shape, t_adv_em) = font::outline_chem_run_em(&travel, style);
655                let t_adv = t_adv_em * scale;
656                let t_origin_x = atom_x - 0.5 * t_adv;
657                let t_y = if side == LabelSide::North {
658                    baseline_y - line_gap
659                } else {
660                    baseline_y + line_gap
661                };
662                if let Some(ts) = t_shape {
663                    let placed = ts.scale(scale, -scale, 0.0, 0.0).translate(t_origin_x, t_y);
664                    acc = Some(match acc.take() {
665                        Some(a) => a.union(&placed),
666                        None => placed,
667                    });
668                }
669            }
670            acc.filter(|s| !s.is_empty())
671        }
672    }
673}
674
675/// Place one label so the atom-center glyph sits on `(atom_x, atom_y)`.
676pub fn place_label(
677    raw: &str,
678    atom_x: f64,
679    atom_y: f64,
680    side: LabelSide,
681    font_px: f64,
682    style: FaceStyle,
683) -> PlacedLabel {
684    place_label_weighted(
685        raw,
686        atom_x,
687        atom_y,
688        side,
689        font_px,
690        style,
691        crate::metrics::WEIGHT_MIN,
692    )
693}
694
695/// Like [`place_label`], with mol ``weight`` increasing bond↔label clearance.
696pub fn place_label_weighted(
697    raw: &str,
698    atom_x: f64,
699    atom_y: f64,
700    side: LabelSide,
701    font_px: f64,
702    style: FaceStyle,
703    weight: f64,
704) -> PlacedLabel {
705    let parts = split_label(raw);
706    let text = compose_label(&parts, side);
707    let (center_adv, ink) = center_glyph_ink_rel(&parts, side, font_px, style);
708    let prefix = prefix_before_center(&parts, side, font_px, style);
709    let origin_x = atom_x - prefix - 0.5 * center_adv;
710    let y = atom_y + baseline_offset(font_px, style);
711    let standoff = label_weight_standoff_px(weight);
712    let clearance = clearance_isotropic(center_adv, ink, standoff);
713    let path_d = outline_placed(&parts, side, origin_x, y, atom_x, atom_y, font_px, style)
714        .map(|s| s.to_svg_d())
715        .unwrap_or_default();
716    PlacedLabel {
717        raw: raw.to_string(),
718        text,
719        origin_x,
720        y,
721        atom_x,
722        atom_y,
723        side,
724        clearance,
725        path_d,
726    }
727}
728
729/// Glyph ink for a placed label (halo / occupancy).
730pub fn label_ink_shape(pl: &PlacedLabel, font_px: f64, style: FaceStyle) -> Option<Shape> {
731    let parts = split_label(&pl.raw);
732    outline_placed(
733        &parts,
734        pl.side,
735        pl.origin_x,
736        pl.y,
737        pl.atom_x,
738        pl.atom_y,
739        font_px,
740        style,
741    )
742}
743
744/// Shorten a bond segment by end insets (same as Python `bonds.shorten`).
745pub fn shorten_bond(
746    x1: f64,
747    y1: f64,
748    x2: f64,
749    y2: f64,
750    gap1: f64,
751    gap2: f64,
752) -> (f64, f64, f64, f64) {
753    let dx = x2 - x1;
754    let dy = y2 - y1;
755    let length = (dx * dx + dy * dy).sqrt().max(1e-9);
756    if gap1 + gap2 >= length {
757        let mx = 0.5 * (x1 + x2);
758        let my = 0.5 * (y1 + y2);
759        return (mx, my, mx, my);
760    }
761    let ux = dx / length;
762    let uy = dy / length;
763    (
764        x1 + ux * gap1,
765        y1 + uy * gap1,
766        x2 - ux * gap2,
767        y2 - uy * gap2,
768    )
769}
770
771/// Atom input for backbone + label placement.
772#[derive(Debug, Clone)]
773pub struct AtomIn {
774    pub x: f64,
775    pub y: f64,
776    /// Display label (`None` / empty → no label).
777    pub label: Option<String>,
778}
779
780/// Bond as atom index pair into [`place_backbone`] atoms slice.
781#[derive(Debug, Clone, Copy)]
782pub struct BondIn {
783    pub begin: usize,
784    pub end: usize,
785}
786
787/// Shortened bond endpoints in SVG space.
788#[derive(Debug, Clone, Copy)]
789pub struct BondOut {
790    pub x1: f64,
791    pub y1: f64,
792    pub x2: f64,
793    pub y2: f64,
794}
795
796/// Place all atom labels and shorten bond endpoints into label clearances.
797///
798/// ``weight`` (≥ 1) thickens bond↔label standoff so fat ink clears fat stems.
799pub fn place_backbone(
800    atoms: &[AtomIn],
801    bonds: &[BondIn],
802    font_px: f64,
803    style: FaceStyle,
804    weight: f64,
805) -> (Vec<BondOut>, Vec<Option<PlacedLabel>>) {
806    let standoff = label_weight_standoff_px(weight);
807    let n = atoms.len();
808    let mut nbrs: Vec<Vec<(f64, f64)>> = vec![Vec::new(); n];
809    for b in bonds {
810        if b.begin < n && b.end < n {
811            nbrs[b.begin].push((atoms[b.end].x, atoms[b.end].y));
812            nbrs[b.end].push((atoms[b.begin].x, atoms[b.begin].y));
813        }
814    }
815
816    let mut metrics: Vec<Option<(f64, Option<(f64, f64, f64, f64)>)>> = Vec::with_capacity(n);
817    let mut labels: Vec<Option<PlacedLabel>> = Vec::with_capacity(n);
818    for (i, atom) in atoms.iter().enumerate() {
819        let raw = atom.label.as_deref().unwrap_or("").trim();
820        if raw.is_empty() {
821            labels.push(None);
822            metrics.push(None);
823            continue;
824        }
825        let parts = split_label(raw);
826        let elem = parts.center.as_str();
827        let side = label_side_for((atom.x, atom.y), &nbrs[i], Some(elem));
828        // Full label ink (H + charge) so bonds do not clip superscripts.
829        metrics.push(Some(label_clearance_ink_rel(&parts, side, font_px, style)));
830        labels.push(Some(place_label_weighted(
831            raw, atom.x, atom.y, side, font_px, style, weight,
832        )));
833    }
834
835    let mut out_bonds = Vec::with_capacity(bonds.len());
836    for b in bonds {
837        if b.begin >= n || b.end >= n {
838            out_bonds.push(BondOut {
839                x1: 0.0,
840                y1: 0.0,
841                x2: 0.0,
842                y2: 0.0,
843            });
844            continue;
845        }
846        let a = &atoms[b.begin];
847        let c = &atoms[b.end];
848        let dx = c.x - a.x;
849        let dy = c.y - a.y;
850        let len = (dx * dx + dy * dy).sqrt().max(1e-9);
851        let ux = dx / len;
852        let uy = dy / len;
853        let gap1 = match metrics[b.begin] {
854            Some((adv, ink)) => clearance_toward(adv, ink, ux, uy, standoff),
855            None => 0.0,
856        };
857        let gap2 = match metrics[b.end] {
858            Some((adv, ink)) => clearance_toward(adv, ink, -ux, -uy, standoff),
859            None => 0.0,
860        };
861        let (x1, y1, x2, y2) = shorten_bond(a.x, a.y, c.x, c.y, gap1, gap2);
862        out_bonds.push(BondOut { x1, y1, x2, y2 });
863    }
864
865    (out_bonds, labels)
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871    use crate::metrics::{FONT_PX, LABEL_GAP_PX};
872
873    #[test]
874    fn split_oh_and_nh2() {
875        let oh = split_label("OH");
876        assert_eq!(oh.center, "O");
877        assert_eq!(oh.traveling, "H");
878        let nh2 = split_label("NH2");
879        assert_eq!(nh2.center, "N");
880        assert_eq!(nh2.traveling, "H2");
881        let cl = split_label("Cl");
882        assert_eq!(cl.center, "Cl");
883        assert!(cl.traveling.is_empty());
884        let glc = split_label("GlcA");
885        assert_eq!(glc.center, "GlcA");
886        assert!(glc.traveling.is_empty());
887    }
888
889    #[test]
890    fn atom_display_label_appends_implicit_h() {
891        assert_eq!(atom_display_label("O", 1, 0).as_deref(), Some("OH"));
892        assert_eq!(atom_display_label("N", 2, 0).as_deref(), Some("NH2"));
893        assert_eq!(atom_display_label("N", 4, 1).as_deref(), Some("NH4+"));
894        assert_eq!(atom_display_label("O", 0, -1).as_deref(), Some("O−"));
895        assert_eq!(atom_display_label("C", 3, 0), None);
896        // Charged carbon keeps H (RDKit): [CH3+] → CH3+.
897        assert_eq!(atom_display_label("C", 3, 1).as_deref(), Some("CH3+"));
898        assert_eq!(atom_display_label("*", 0, 0).as_deref(), Some("*"));
899    }
900
901    #[test]
902    fn split_charge_and_ammonium() {
903        let n = split_label("NH4+");
904        assert_eq!(n.center, "N");
905        assert_eq!(n.traveling, "H4");
906        assert_eq!(n.charge, 1);
907        let o = split_label("O−");
908        assert_eq!(o.center, "O");
909        assert_eq!(o.charge, -1);
910        let star = split_label("*");
911        assert_eq!(star.center, "*");
912    }
913
914    #[test]
915    fn oh_flips_on_west() {
916        let parts = split_label("OH");
917        assert_eq!(compose_label(&parts, LabelSide::East), "OH");
918        assert_eq!(compose_label(&parts, LabelSide::West), "HO");
919    }
920
921    #[test]
922    fn nh2_uses_subscript() {
923        let parts = split_label("NH2");
924        assert_eq!(compose_label(&parts, LabelSide::East), "NH₂");
925        assert_eq!(compose_label(&parts, LabelSide::West), "H₂N");
926        // Same pathway as braced markup (bare ``H_2`` is literal outside ``$``).
927        let via_markup = markup::parse_label_markup("H_{2}", FaceStyle::Regular);
928        assert_eq!(via_markup.len(), 2);
929        assert_eq!(via_markup[0].ch, 'H');
930        assert_eq!(via_markup[1].role, ScriptRole::Subscript);
931    }
932
933    #[test]
934    fn star_label_scripts_via_markup() {
935        // Bare underscore is literal (``my_name``-safe).
936        assert_eq!(compose_label(&split_label("R_1"), LabelSide::East), "R_1");
937        assert_eq!(
938            compose_label(&split_label("my_name"), LabelSide::East),
939            "my_name"
940        );
941        assert_eq!(compose_label(&split_label("$R_1$"), LabelSide::East), "R₁");
942        assert_eq!(compose_label(&split_label("R^2"), LabelSide::East), "R²");
943        assert_eq!(
944            compose_label(&split_label("R^{2+}"), LabelSide::East),
945            "R²⁺"
946        );
947        assert_eq!(
948            compose_label(&split_label(r"$\alpha$"), LabelSide::East),
949            "α"
950        );
951        assert_eq!(compose_label(&split_label("**R**"), LabelSide::East), "R");
952        let pl = place_label(
953            "$R_1$",
954            0.0,
955            0.0,
956            LabelSide::East,
957            FONT_PX,
958            FaceStyle::Regular,
959        );
960        assert_eq!(pl.text, "R₁");
961        assert!(!pl.path_d.is_empty());
962        // West anchors on R (not the subscript digit).
963        let west = place_label(
964            "$R_1$",
965            0.0,
966            0.0,
967            LabelSide::West,
968            FONT_PX,
969            FaceStyle::Regular,
970        );
971        assert_eq!(west.text, "R₁");
972        assert!(west.origin_x < 0.0 || west.origin_x.abs() < FONT_PX);
973    }
974
975    #[test]
976    fn charge_is_plain_not_superscript() {
977        // Formal charge rides the same baseline as the element (not a raised
978        // script). N/S stacking already moves the charge off the atom; a
979        // second superscript lift made top too high and bottom crowded.
980        let parts = split_label("NH4+");
981        assert_eq!(compose_label(&parts, LabelSide::East), "NH₄+");
982        assert_eq!(compose_label(&split_label("N+"), LabelSide::East), "N+");
983        assert_eq!(compose_label(&split_label("Fe2+"), LabelSide::East), "Fe2+");
984        assert_eq!(compose_label(&split_label("O−"), LabelSide::East), "O-");
985        // Explicit caret markup still superscripts.
986        assert_eq!(
987            compose_label(&split_label("R^{2+}"), LabelSide::East),
988            "R²⁺"
989        );
990    }
991
992    #[test]
993    fn formal_charge_glyphs_are_normal_role() {
994        // Role-level guard: reintroducing ``^`` in charge_glyphs would pass
995        // loose ink tolerances but fail here.
996        for (raw, sign) in [("N+", '+'), ("O-", '-'), ("Fe3+", '+')] {
997            let g = charge_glyphs(split_label(raw).charge, FaceStyle::Regular);
998            assert!(
999                !g.is_empty() && g.iter().all(|x| x.role == ScriptRole::Normal),
1000                "{raw}: expected Normal charge glyphs, got {g:?}"
1001            );
1002            assert_eq!(g.last().map(|x| x.ch), Some(sign));
1003        }
1004        let fe = charge_glyphs(split_label("Fe3+").charge, FaceStyle::Regular);
1005        assert_eq!(fe.iter().map(|x| x.ch).collect::<String>(), "3+");
1006        // Caret markup path still uses Superscript (contrast).
1007        let caret = markup::parse_label_markup("^+", FaceStyle::Regular);
1008        assert_eq!(caret.len(), 1);
1009        assert_eq!(caret[0].role, ScriptRole::Superscript);
1010    }
1011
1012    #[test]
1013    fn charge_shares_element_baseline_east_and_west() {
1014        let style = FaceStyle::Regular;
1015        for side in [LabelSide::East, LabelSide::West] {
1016            let n = place_label("N", 0.0, 0.0, side, FONT_PX, style);
1017            let np = place_label("N+", 0.0, 0.0, side, FONT_PX, style);
1018            let (_nx0, ny0, _nx1, _ny1) = label_ink_shape(&n, FONT_PX, style)
1019                .expect("N")
1020                .bounds()
1021                .expect("N ink");
1022            let (_px0, py0, _px1, _py1) = label_ink_shape(&np, FONT_PX, style)
1023                .expect("N+")
1024                .bounds()
1025                .expect("N+ ink");
1026            // Superscript would lift the label top by ~0.5×cap (~0.35×FONT_PX).
1027            assert!(
1028                py0 > ny0 - 0.12 * FONT_PX,
1029                "{side:?}: N+ top {py0} rose too far above N top {ny0} (still superscript?)"
1030            );
1031        }
1032
1033        // Contrast: math-mode superscript + *does* lift ink above formal N+.
1034        let formal = place_label("N+", 0.0, 0.0, LabelSide::East, FONT_PX, style);
1035        let raised = place_label("$N^+$", 0.0, 0.0, LabelSide::East, FONT_PX, style);
1036        assert_eq!(raised.text, "N⁺");
1037        let (_, fy0, _, _) = label_ink_shape(&formal, FONT_PX, style)
1038            .unwrap()
1039            .bounds()
1040            .unwrap();
1041        let (_, ry0, _, _) = label_ink_shape(&raised, FONT_PX, style)
1042            .unwrap()
1043            .bounds()
1044            .unwrap();
1045        assert!(
1046            ry0 < fy0 - 0.15 * FONT_PX,
1047            "$N^+$ should sit above formal N+ ({ry0} vs {fy0}); contrast probe broken?"
1048        );
1049    }
1050
1051    #[test]
1052    fn north_south_charge_stack_without_script_lift() {
1053        let style = FaceStyle::Regular;
1054        let face = font::face_metrics(style);
1055        let line_gap = 1.1 * (face.cap_height / face.upem) * FONT_PX;
1056
1057        let north_n = place_label("N", 0.0, 0.0, LabelSide::North, FONT_PX, style);
1058        let north_np = place_label("N+", 0.0, 0.0, LabelSide::North, FONT_PX, style);
1059        let (_, n_top, _, _) = label_ink_shape(&north_n, FONT_PX, style)
1060            .unwrap()
1061            .bounds()
1062            .unwrap();
1063        let (_, np_top, _, _) = label_ink_shape(&north_np, FONT_PX, style)
1064            .unwrap()
1065            .bounds()
1066            .unwrap();
1067        let rise = n_top - np_top; // SVG +Y down: smaller y is higher
1068        assert!(
1069            rise > 0.45 * line_gap,
1070            "north charge should stack above N; rise={rise}, line_gap={line_gap}"
1071        );
1072        assert!(
1073            rise < line_gap + 0.55 * FONT_PX,
1074            "north charge rose {rise} (line_gap={line_gap}); script lift on top of stack?"
1075        );
1076
1077        let south_n = place_label("N", 0.0, 0.0, LabelSide::South, FONT_PX, style);
1078        let south_np = place_label("N+", 0.0, 0.0, LabelSide::South, FONT_PX, style);
1079        let (_, _, _, n_bot) = label_ink_shape(&south_n, FONT_PX, style)
1080            .unwrap()
1081            .bounds()
1082            .unwrap();
1083        let (_, _, _, np_bot) = label_ink_shape(&south_np, FONT_PX, style)
1084            .unwrap()
1085            .bounds()
1086            .unwrap();
1087        let drop = np_bot - n_bot;
1088        assert!(
1089            drop > 0.45 * line_gap,
1090            "south charge should stack below N; drop={drop}, line_gap={line_gap}"
1091        );
1092        // Without script lift the charge sits fully on the lower baseline —
1093        // drop reaches ~line_gap + charge height, not a cramped half-step.
1094        assert!(
1095            drop > line_gap * 0.85,
1096            "south charge crowded against N: drop={drop}, line_gap={line_gap}"
1097        );
1098    }
1099
1100    #[test]
1101    fn quaternary_n_plus_north_south_orientation_keeps_charge_clear() {
1102        // Me4N+-like: four neighbors; force N/S label side and require the
1103        // charge stack to clear the element ink (the visual failure mode).
1104        let style = FaceStyle::Regular;
1105        for (side, neighbors) in [
1106            (
1107                LabelSide::North,
1108                [(10.0, 12.0), (-10.0, 12.0), (8.0, -4.0), (-8.0, -4.0)],
1109            ),
1110            (
1111                LabelSide::South,
1112                [(10.0, -12.0), (-10.0, -12.0), (8.0, 4.0), (-8.0, 4.0)],
1113            ),
1114        ] {
1115            let got = label_side((0.0, 0.0), &neighbors);
1116            assert_eq!(got, side, "fixture neighbors should orient {side:?}");
1117            let bare = place_label("N", 0.0, 0.0, side, FONT_PX, style);
1118            let charged = place_label("N+", 0.0, 0.0, side, FONT_PX, style);
1119            let (_, bn0, _, bn1) = label_ink_shape(&bare, FONT_PX, style)
1120                .unwrap()
1121                .bounds()
1122                .unwrap();
1123            let (_, cn0, _, cn1) = label_ink_shape(&charged, FONT_PX, style)
1124                .unwrap()
1125                .bounds()
1126                .unwrap();
1127            match side {
1128                LabelSide::North => {
1129                    // Charge above: full label top clears bare N top by a
1130                    // real stack step (not a half-raised superscript).
1131                    assert!(
1132                        bn0 - cn0 > 0.35 * FONT_PX,
1133                        "north N+ must extend above N: bare_top={bn0} charged_top={cn0}"
1134                    );
1135                    assert!(
1136                        bn0 - cn0 < 1.4 * FONT_PX,
1137                        "north N+ floated too far: bare_top={bn0} charged_top={cn0}"
1138                    );
1139                }
1140                LabelSide::South => {
1141                    assert!(
1142                        cn1 - bn1 > 0.35 * FONT_PX,
1143                        "south N+ must extend below N: bare_bot={bn1} charged_bot={cn1}"
1144                    );
1145                    assert!(
1146                        cn1 - bn1 < 1.4 * FONT_PX,
1147                        "south N+ dropped too far / odd: bare_bot={bn1} charged_bot={cn1}"
1148                    );
1149                }
1150                _ => unreachable!(),
1151            }
1152        }
1153    }
1154
1155    #[test]
1156    fn charge_extends_east_bond_clearance() {
1157        // Center-only clearance ignores the superscript; full-label ink must
1158        // push the bond end past the charge when approached from the east.
1159        let style = FaceStyle::Regular;
1160        let bare = split_label("O");
1161        let charged = split_label("O+");
1162        let (adv_o, ink_o) = label_clearance_ink_rel(&bare, LabelSide::East, FONT_PX, style);
1163        let (adv_op, ink_op) = label_clearance_ink_rel(&charged, LabelSide::East, FONT_PX, style);
1164        let east_o = clearance_toward(adv_o, ink_o, 1.0, 0.0, 0.0);
1165        let east_op = clearance_toward(adv_op, ink_op, 1.0, 0.0, 0.0);
1166        assert!(
1167            east_op > east_o + 0.8,
1168            "O+ east clearance {east_op} should exceed bare O {east_o} by charge width"
1169        );
1170        // West approach still clears the element (charge is on the east).
1171        let west_o = clearance_toward(adv_o, ink_o, -1.0, 0.0, 0.0);
1172        let west_op = clearance_toward(adv_op, ink_op, -1.0, 0.0, 0.0);
1173        assert!(
1174            (west_op - west_o).abs() < 0.5,
1175            "west clearance should stay near the element: O={west_o} O+={west_op}"
1176        );
1177    }
1178
1179    #[test]
1180    fn backbone_shortens_into_charge_from_charge_side() {
1181        // Stronger west neighbor → East label (charge to the right); weaker
1182        // east neighbor so a bond still approaches from the charge side.
1183        let atoms = vec![
1184            AtomIn {
1185                x: -40.0,
1186                y: 0.0,
1187                label: None,
1188            },
1189            AtomIn {
1190                x: 0.0,
1191                y: 0.0,
1192                label: Some("O+".into()),
1193            },
1194            AtomIn {
1195                x: 25.0,
1196                y: 0.0,
1197                label: None,
1198            },
1199        ];
1200        let bonds = vec![BondIn { begin: 0, end: 1 }, BondIn { begin: 1, end: 2 }];
1201        let (out, labels) = place_backbone(&atoms, &bonds, FONT_PX, FaceStyle::Regular, 1.0);
1202        let lab = labels[1].as_ref().expect("O+");
1203        assert_eq!(
1204            lab.side,
1205            LabelSide::East,
1206            "expected East charge side, got {:?}",
1207            lab.side
1208        );
1209        assert!(
1210            lab.text.contains('⁺') || lab.text.contains('+'),
1211            "expected charge in label text, got {}",
1212            lab.text
1213        );
1214        // Right-hand bond must stop short of the atom past the charge ink.
1215        let o_adv = advance_px("O", FONT_PX, FaceStyle::Regular);
1216        let gap_from_o = out[1].x1 - 0.0;
1217        assert!(
1218            gap_from_o > 0.5 * o_adv + LABEL_GAP_PX + 0.8,
1219            "right bond must clear charge: gap={gap_from_o}, half_O={}",
1220            0.5 * o_adv
1221        );
1222        // Bare O with the same skeleton shortens less on the charge side.
1223        let atoms_bare = vec![
1224            AtomIn {
1225                x: -40.0,
1226                y: 0.0,
1227                label: None,
1228            },
1229            AtomIn {
1230                x: 0.0,
1231                y: 0.0,
1232                label: Some("O".into()),
1233            },
1234            AtomIn {
1235                x: 25.0,
1236                y: 0.0,
1237                label: None,
1238            },
1239        ];
1240        let (out_bare, _) = place_backbone(&atoms_bare, &bonds, FONT_PX, FaceStyle::Regular, 1.0);
1241        assert!(
1242            gap_from_o > out_bare[1].x1 + 0.5,
1243            "O+ gap {gap_from_o} should exceed bare O gap {}",
1244            out_bare[1].x1
1245        );
1246    }
1247
1248    #[test]
1249    fn glca_does_not_flip() {
1250        let parts = split_label("GlcA");
1251        assert_eq!(compose_label(&parts, LabelSide::East), "GlcA");
1252        assert_eq!(compose_label(&parts, LabelSide::West), "GlcA");
1253    }
1254
1255    #[test]
1256    fn side_from_neighbors() {
1257        assert_eq!(label_side((0.0, 0.0), &[(10.0, 0.0)]), LabelSide::West);
1258        assert_eq!(label_side((0.0, 0.0), &[(-10.0, 0.0)]), LabelSide::East);
1259        // Steep vertical, degree > 1 → N/S.
1260        assert_eq!(
1261            label_side((0.0, 0.0), &[(1.0, 10.0), (-1.0, 10.0)]),
1262            LabelSide::North
1263        );
1264    }
1265
1266    #[test]
1267    fn oh_center_stays_on_atom() {
1268        let style = FaceStyle::Regular;
1269        let east = place_label("OH", 100.0, 50.0, LabelSide::East, FONT_PX, style);
1270        let west = place_label("OH", 100.0, 50.0, LabelSide::West, FONT_PX, style);
1271        assert_eq!(east.text, "OH");
1272        assert_eq!(west.text, "HO");
1273        assert!(!east.path_d.is_empty());
1274        assert!(east.path_d.contains('M'));
1275        let o_adv = advance_px("O", FONT_PX, style);
1276        assert!((east.origin_x + 0.5 * o_adv - 100.0).abs() < 1e-6);
1277        let h_adv = advance_px("H", FONT_PX, style);
1278        assert!((west.origin_x + h_adv + 0.5 * o_adv - 100.0).abs() < 1e-6);
1279        assert!((east.clearance - (0.5 * o_adv + LABEL_GAP_PX)).abs() < 1e-6);
1280        assert!(east.clearance < advance_px("OH", FONT_PX, style) * 0.5 + LABEL_GAP_PX - 0.1);
1281    }
1282
1283    #[test]
1284    fn n_diagonal_clearance_uses_ink_support() {
1285        let parts = split_label("N");
1286        let (adv, ink) = center_glyph_ink_rel(&parts, LabelSide::East, FONT_PX, FaceStyle::Regular);
1287        let horiz = clearance_toward(adv, ink, 1.0, 0.0, 0.0);
1288        let diag = clearance_toward(
1289            adv,
1290            ink,
1291            std::f64::consts::FRAC_1_SQRT_2,
1292            std::f64::consts::FRAC_1_SQRT_2,
1293            0.0,
1294        );
1295        assert!((horiz - (0.5 * adv + LABEL_GAP_PX)).abs() < 1e-6);
1296        assert!(diag > horiz + 0.3);
1297    }
1298
1299    #[test]
1300    fn backbone_weight_increases_bond_label_standoff() {
1301        use crate::metrics::label_weight_standoff_px;
1302        let atoms = vec![
1303            AtomIn {
1304                x: 0.0,
1305                y: 0.0,
1306                label: None,
1307            },
1308            AtomIn {
1309                x: 40.0,
1310                y: 0.0,
1311                label: Some("OH".into()),
1312            },
1313        ];
1314        let bonds = vec![BondIn { begin: 0, end: 1 }];
1315        let (out1, labs1) = place_backbone(&atoms, &bonds, FONT_PX, FaceStyle::Regular, 1.0);
1316        let (out2, labs2) = place_backbone(&atoms, &bonds, FONT_PX, FaceStyle::Regular, 2.0);
1317        let c1 = labs1[1].as_ref().unwrap().clearance;
1318        let c2 = labs2[1].as_ref().unwrap().clearance;
1319        let extra = label_weight_standoff_px(2.0) - label_weight_standoff_px(1.0);
1320        assert!((c2 - c1 - extra).abs() < 1e-6);
1321        assert!((40.0 - out1[0].x2) < (40.0 - out2[0].x2) - 0.5);
1322    }
1323
1324    #[test]
1325    fn backbone_shortens_into_oh() {
1326        let atoms = vec![
1327            AtomIn {
1328                x: 0.0,
1329                y: 0.0,
1330                label: None,
1331            },
1332            AtomIn {
1333                x: 40.0,
1334                y: 0.0,
1335                label: Some("OH".into()),
1336            },
1337        ];
1338        let bonds = vec![BondIn { begin: 0, end: 1 }];
1339        let (out, labels) = place_backbone(
1340            &atoms,
1341            &bonds,
1342            FONT_PX,
1343            FaceStyle::Regular,
1344            crate::metrics::WEIGHT_MIN,
1345        );
1346        assert!(labels[1].is_some());
1347        let lab = labels[1].as_ref().unwrap();
1348        assert_eq!(lab.text, "OH");
1349        assert!(out[0].x2 < 40.0);
1350        assert!((40.0 - out[0].x2 - lab.clearance).abs() < 1e-6);
1351    }
1352
1353    #[test]
1354    fn backbone_n_diagonal_standoff_exceeds_half_advance() {
1355        let atoms = vec![
1356            AtomIn {
1357                x: 0.0,
1358                y: 0.0,
1359                label: None,
1360            },
1361            AtomIn {
1362                x: 30.0,
1363                y: 30.0,
1364                label: Some("N".into()),
1365            },
1366        ];
1367        let bonds = vec![BondIn { begin: 0, end: 1 }];
1368        let (out, labels) = place_backbone(
1369            &atoms,
1370            &bonds,
1371            FONT_PX,
1372            FaceStyle::Regular,
1373            crate::metrics::WEIGHT_MIN,
1374        );
1375        let lab = labels[1].as_ref().unwrap();
1376        let n_adv = advance_px("N", FONT_PX, FaceStyle::Regular);
1377        let gap = ((out[0].x2 - 30.0).powi(2) + (out[0].y2 - 30.0).powi(2)).sqrt();
1378        assert!(gap > 0.5 * n_adv + LABEL_GAP_PX + 0.3);
1379        assert!((lab.clearance - (0.5 * n_adv + LABEL_GAP_PX)).abs() < 1e-6);
1380    }
1381
1382    #[test]
1383    fn star_label_emits_path() {
1384        let pl = place_label(
1385            "*",
1386            10.0,
1387            10.0,
1388            LabelSide::East,
1389            FONT_PX,
1390            FaceStyle::Regular,
1391        );
1392        assert_eq!(pl.text, "*");
1393        assert!(!pl.path_d.is_empty());
1394    }
1395
1396    #[test]
1397    fn split_empty_charges_and_non_h_suffix() {
1398        let empty = split_label("  ");
1399        assert!(empty.center.is_empty());
1400        assert_eq!(empty.charge, 0);
1401
1402        let fe = split_label("Fe3+");
1403        assert_eq!(fe.center, "Fe");
1404        assert_eq!(fe.charge, 3);
1405        assert!(fe.traveling.is_empty());
1406
1407        let n2 = split_label("N2+");
1408        assert_eq!(n2.center, "N");
1409        assert_eq!(n2.charge, 2);
1410
1411        let multi = split_label("O++");
1412        assert_eq!(multi.center, "O");
1413        assert_eq!(multi.charge, 2);
1414
1415        // Trailing junk after H → whole body is center (NHAc).
1416        let nhac = split_label("NHAc");
1417        assert_eq!(nhac.center, "NHAc");
1418        assert!(nhac.traveling.is_empty());
1419    }
1420
1421    #[test]
1422    fn label_side_degree0_and_vertical_degree1() {
1423        assert_eq!(label_side_for((0.0, 0.0), &[], Some("O")), LabelSide::West);
1424        assert_eq!(label_side_for((0.0, 0.0), &[], Some("C")), LabelSide::East);
1425        // Degree-1 steep vertical → forced East (RDKit).
1426        assert_eq!(label_side((0.0, 0.0), &[(0.0, 20.0)]), LabelSide::East);
1427    }
1428
1429    #[test]
1430    fn label_side_degree3_keeps_north_south() {
1431        // Three neighbors with a near-vertical bond.
1432        let side = label_side((0.0, 0.0), &[(10.0, 2.0), (-10.0, 2.0), (0.0, 15.0)]);
1433        assert_eq!(side, LabelSide::North);
1434
1435        let south = label_side((0.0, 0.0), &[(10.0, -2.0), (-10.0, -2.0), (0.0, -15.0)]);
1436        assert_eq!(south, LabelSide::South);
1437    }
1438
1439    #[test]
1440    fn north_south_nh2_stacks_and_compose_charge() {
1441        let north = place_label(
1442            "NH2",
1443            50.0,
1444            50.0,
1445            LabelSide::North,
1446            FONT_PX,
1447            FaceStyle::Regular,
1448        );
1449        let south = place_label(
1450            "NH2",
1451            50.0,
1452            50.0,
1453            LabelSide::South,
1454            FONT_PX,
1455            FaceStyle::Regular,
1456        );
1457        assert!(north.path_d.contains('M'));
1458        assert!(south.path_d.contains('M'));
1459        assert_eq!(north.text, "NH₂");
1460        let ink = label_ink_shape(&north, FONT_PX, FaceStyle::Regular);
1461        assert!(ink.is_some());
1462
1463        let parts = split_label("Fe2+");
1464        assert_eq!(compose_label(&parts, LabelSide::East), "Fe2+");
1465        let west_abbr = place_label(
1466            "GlcA",
1467            0.0,
1468            0.0,
1469            LabelSide::West,
1470            FONT_PX,
1471            FaceStyle::Regular,
1472        );
1473        assert!(!west_abbr.path_d.is_empty());
1474    }
1475
1476    #[test]
1477    fn shorten_bond_collapse_and_oob_backbone() {
1478        let (x1, y1, x2, y2) = shorten_bond(0.0, 0.0, 5.0, 0.0, 4.0, 4.0);
1479        assert!((x1 - 2.5).abs() < 1e-9);
1480        assert!((x2 - 2.5).abs() < 1e-9);
1481        assert!((y1 - y2).abs() < 1e-9);
1482
1483        let atoms = vec![AtomIn {
1484            x: 0.0,
1485            y: 0.0,
1486            label: Some("O".into()),
1487        }];
1488        let bonds = vec![BondIn { begin: 0, end: 9 }];
1489        let (out, labels) = place_backbone(&atoms, &bonds, FONT_PX, FaceStyle::Regular, 1.0);
1490        assert!(labels[0].is_some());
1491        assert_eq!(out[0].x1, 0.0);
1492        assert_eq!(out[0].x2, 0.0);
1493    }
1494
1495    #[test]
1496    fn charged_west_oh_and_empty_label_skipped() {
1497        let pl = place_label(
1498            "OH+",
1499            10.0,
1500            10.0,
1501            LabelSide::West,
1502            FONT_PX,
1503            FaceStyle::Regular,
1504        );
1505        assert!(pl.text.contains('⁺') || pl.text.contains('+'));
1506        assert!(!pl.path_d.is_empty());
1507
1508        let atoms = vec![
1509            AtomIn {
1510                x: 0.0,
1511                y: 0.0,
1512                label: Some("   ".into()),
1513            },
1514            AtomIn {
1515                x: 20.0,
1516                y: 0.0,
1517                label: None,
1518            },
1519        ];
1520        let (_, labels) = place_backbone(
1521            &atoms,
1522            &[BondIn { begin: 0, end: 1 }],
1523            FONT_PX,
1524            FaceStyle::Regular,
1525            1.0,
1526        );
1527        assert!(labels[0].is_none());
1528        assert!(labels[1].is_none());
1529    }
1530
1531    #[test]
1532    fn script_digits_and_empty_place() {
1533        // Charge magnitude is plain digits + sign; H-counts stay subscript.
1534        let fe = split_label("Fe10+");
1535        assert_eq!(fe.charge, 10);
1536        assert_eq!(compose_label(&fe, LabelSide::East), "Fe10+");
1537
1538        let nh9 = compose_label(&split_label("NH9"), LabelSide::East);
1539        assert!(nh9.contains('₉'));
1540
1541        let nh3 = compose_label(&split_label("NH3"), LabelSide::East);
1542        assert!(nh3.contains('₃'));
1543        assert_eq!(compose_label(&split_label("Fe4+"), LabelSide::East), "Fe4+");
1544
1545        // H-count subscripts (charges are plain, not raised digits).
1546        for (raw, needle) in [
1547            ("NH4", '₄'),
1548            ("NH5", '₅'),
1549            ("NH6", '₆'),
1550            ("NH7", '₇'),
1551            ("NH8", '₈'),
1552        ] {
1553            let t = compose_label(&split_label(raw), LabelSide::East);
1554            assert!(t.contains(needle), "{raw} → {t}");
1555        }
1556        for mag in 5..=9 {
1557            let raw = format!("Fe{mag}+");
1558            assert_eq!(
1559                compose_label(&split_label(&raw), LabelSide::East),
1560                format!("Fe{mag}+")
1561            );
1562        }
1563
1564        let empty = place_label("", 0.0, 0.0, LabelSide::East, FONT_PX, FaceStyle::Regular);
1565        assert!(empty.path_d.is_empty());
1566        assert!(empty.text.is_empty());
1567    }
1568
1569    #[test]
1570    fn degree3_near_vertical_bond_angles() {
1571        // ~85° and ~-85° bonds exercise the atan degree windows.
1572        let north = label_side(
1573            (0.0, 0.0),
1574            &[
1575                (1.0, 10.0), // near vertical south neighbor sum → North
1576                (8.0, 1.0),
1577                (-8.0, 1.0),
1578            ],
1579        );
1580        assert_eq!(north, LabelSide::North);
1581        let south = label_side((0.0, 0.0), &[(1.0, -10.0), (8.0, -1.0), (-8.0, -1.0)]);
1582        assert_eq!(south, LabelSide::South);
1583    }
1584}