Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.2.0528.5 KB2026-10-160.1.1542.8 KB2026-10-150.1.0541.1 KB2026-10-15
Version
0.1.1
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
542.8 KB
Downloads
9
Checksum
2e36f65a5798a2a0281457d1ed7f5a4e1a74967fea2880b4961ede38808a3682
Dependencies
None

label.rs

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
//! Builds atom labels
//!
//! Turns a string with subscripts and superscripts, such as `H_2O` or `SO_4^{2-}`, into a
//! sequence of glyphs.
//! In coordinates, x is measured from the left end of the label,
//! and y from the baseline, with down as positive.
//!
//! A label is split into parts at each capital letter. `CH_3` has two: `C` and `H_3`.
//! A bond stops at the edge of the ink of one of these parts, or of the whole label.

use crate::font::{self, Font};
use crate::style::Style;


/// One placed glyph
#[derive(Debug, Clone, PartialEq)]
pub struct Placed {
    /// Glyph ID. None if the font does not have the character
    pub glyph: Option<u16>,
    pub character: char,
    /// Position from the left end of the label
    pub x: f64,
    /// Position from the baseline. Down is positive
    pub y: f64,
    /// Size. 1 is the base size
    pub size: f64,
}


/// The extent covered by ink
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Extent {
    pub left: f64,
    pub right: f64,
    /// Negative above the baseline
    pub top: f64,
    pub bottom: f64,
}


impl Extent {
    /// Whether there is no ink at all
    pub fn is_blank(&self) -> bool {
        self.right <= self.left && self.bottom <= self.top
    }

    /// The extent that contains both
    pub fn union(&self, other: &Extent) -> Extent {
        if self.is_blank() {
            return *other;
        }

        if other.is_blank() {
            return *self;
        }

        Extent {
            left: self.left.min(other.left),
            right: self.right.max(other.right),
            top: self.top.min(other.top),
            bottom: self.bottom.max(other.bottom),
        }
    }

    /// Expands the extent on all four sides
    pub fn grow(&self, amount: f64) -> Extent {
        Extent {
            left: self.left - amount,
            right: self.right + amount,
            top: self.top - amount,
            bottom: self.bottom + amount,
        }
    }
}


/// A built label
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Label {
    pub placed: Vec<Placed>,
    /// Ink extent of each part, split at capital letters
    pub part: Vec<Extent>,
    /// Ink extent of the whole label
    pub extent: Extent,
    /// Sum of the advances
    pub width: f64,
}


/// Builds a label from its string
pub fn build(source: &str, font: &Font, style: &Style) -> Label {
    let character: Vec<char> = source.chars().collect();
    let mut work = Work {placed: Vec::new(), boundary: Vec::new(), pen: 0.0};
    let start = Setting {size: 1.0, shift: 0.0, depth: 0, charge: false};
    place(&mut work, &character, &mut 0, start, font, style);

    let part = measure_part(&work, font);
    let extent = part.iter().fold(Extent::default(), |found, one| found.union(one));

    Label {placed: work.placed, part, extent, width: work.pen}
}


/// The extent used to cut back a bond. If no number is written, the whole label
pub fn clip_extent(label: &Label, number: Option<usize>) -> Option<Extent> {
    match number {
        None => Some(label.extent),
        Some(order) => label.part.get(order.checked_sub(1)?).copied(),
    }
}


/// State held while building
struct Work {
    placed: Vec<Placed>,
    /// Boundaries between parts, as indexes into placed
    boundary: Vec<usize>,
    pen: f64,
}


/// Settings in effect where glyphs are being placed now
#[derive(Debug, Clone, Copy)]
struct Setting {
    size: f64,
    /// Position from the baseline. Down is positive
    shift: f64,
    /// Nesting depth of braces
    depth: usize,
    /// Whether this is inside a superscript. Charge signs are raised there
    charge: bool,
}


/// Places the characters in order. Calls itself for braces, subscripts, and superscripts
fn place(
    work: &mut Work,
    character: &[char],
    index: &mut usize,
    setting: Setting,
    font: &Font,
    style: &Style,
) {
    while *index < character.len() {
        match character[*index] {
            '}' => {
                if setting.depth > 0 {
                    *index += 1;

                    return;
                }

                *index += 1;
            }
            '{' => {
                *index += 1;
                let inner = Setting {depth: setting.depth + 1, ..setting};
                place(work, character, index, inner, font, style);
            }
            '_' => {
                *index += 1;
                let inner = Setting {
                    size: shrink(setting.size, style),
                    shift: setting.shift + style.subscript_drop * setting.size,
                    ..setting
                };
                unit(work, character, index, inner, font, style);
                loosen(work, character, *index, setting, style);
            }
            '^' => {
                *index += 1;
                let inner = Setting {
                    size: shrink(setting.size, style),
                    shift: setting.shift - style.superscript_rise * setting.size,
                    charge: true,
                    ..setting
                };
                unit(work, character, index, inner, font, style);
                loosen(work, character, *index, setting, style);
            }
            found => {
                *index += 1;

                if setting.depth == 0 && found.is_ascii_uppercase() && !work.placed.is_empty() {
                    work.boundary.push(work.placed.len());
                }

                put(work, sign(found), setting, font);
            }
        }
    }
}


/// The one item that a subscript or superscript takes with it.
/// A group in braces, or else a single character
fn unit(
    work: &mut Work,
    character: &[char],
    index: &mut usize,
    setting: Setting,
    font: &Font,
    style: &Style,
) {
    match character.get(*index) {
        None => {}
        Some('{') => {
            *index += 1;
            let inner = Setting {depth: setting.depth + 1, ..setting};
            place(work, character, index, inner, font, style);
        }
        Some(found) => {
            let one = sign(*found);
            *index += 1;
            put(work, one, setting, font);
        }
    }
}


/// Adds space after a script
///
/// Space is added only when the next character is a plain one. It is not added when scripts
/// follow each other (the 4 and the 2 in `O_4^{2-}`), or at the end of a group
fn loosen(work: &mut Work, character: &[char], at: usize, setting: Setting, style: &Style) {
    if matches!(character.get(at), Some('_' | '^' | '}') | None) {
        return;
    }

    work.pen += style.script_space * setting.size;
}


/// Places one glyph and moves the pen forward by its advance
fn put(work: &mut Work, character: char, setting: Setting, font: &Font) {
    let glyph = font::glyph_of(font, character);
    let advance = match glyph {
        Some(found) => font::advance(font, found),
        None => font::fallback_metric(character).0,
    };
    let lift = match glyph {
        Some(found) if setting.charge && is_sign(character) => raise(font, found) * setting.size,
        _ => 0.0,
    };

    work.placed.push(Placed {
        glyph,
        character,
        x: work.pen,
        y: setting.shift - lift,
        size: setting.size,
    });
    work.pen += advance * setting.size;
}


/// Whether the character is a sign drawn centered on the math axis
fn is_sign(character: char) -> bool {
    matches!(character, '+' | '\u{2212}' | '\u{b1}' | '\u{2213}')
}


/// How far to raise a charge sign, measured with the size of the character as 1
///
/// Digits are placed on the baseline, but + and − are drawn centered on the math axis, so
/// they look lower than the digits when placed as they are. A sign is raised until its center
/// is level with the center of a digit
fn raise(font: &Font, glyph: u16) -> f64 {
    let (height, depth) = font::extent(font, glyph);
    let middle = (height - depth) / 2.0;

    (font::digit_height(font) / 2.0 - middle).max(0.0)
}


/// Size of a subscript or superscript. Multiplying alone would make nested ones smaller without
/// limit, so the size stops at a lower limit
fn shrink(size: f64, style: &Style) -> f64 {
    (size * style.script_size).max(style.script_floor).min(size)
}


/// A hyphen in a label is a negative charge sign. It is replaced with a glyph that looks right
fn sign(character: char) -> char {
    match character {
        '-' => '\u{2212}',
        other => other,
    }
}


/// Measures the ink extent of each part
fn measure_part(work: &Work, font: &Font) -> Vec<Extent> {
    if work.placed.is_empty() {
        return Vec::new();
    }

    let mut edge = vec![0];
    edge.extend(work.boundary.iter().copied());
    edge.push(work.placed.len());

    let mut found = Vec::new();

    for window in edge.windows(2) {
        let mut extent = Extent::default();

        for placed in &work.placed[window[0]..window[1]] {
            extent = extent.union(&measure_one(placed, font));
        }

        found.push(extent);
    }

    found
}


/// Ink extent of one glyph
fn measure_one(placed: &Placed, font: &Font) -> Extent {
    match placed.glyph {
        Some(glyph) => {
            let (left, right) = font::bearing(font, glyph);
            let (height, depth) = font::extent(font, glyph);
            let advance = font::advance(font, glyph);

            Extent {
                left: placed.x + left * placed.size,
                right: placed.x + (advance - right) * placed.size,
                top: placed.y - height * placed.size,
                bottom: placed.y + depth * placed.size,
            }
        }
        None => {
            let (advance, height, depth) = font::fallback_metric(placed.character);

            Extent {
                left: placed.x,
                right: placed.x + advance * placed.size,
                top: placed.y - height * placed.size,
                bottom: placed.y + depth * placed.size,
            }
        }
    }
}


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

    #[test]
    fn an_empty_label_takes_no_room() {
        let label = build("", &sample(), &Style::default());
        assert!(label.placed.is_empty());
        assert!(label.part.is_empty());
        assert_eq!(label.width, 0.0);
        assert!(label.extent.is_blank());
    }

    #[test]
    fn letters_line_up_from_the_left() {
        let font = sample();
        let label = build("OH", &font, &Style::default());
        assert_eq!(label.placed.len(), 2);
        assert_eq!(label.placed[0].x, 0.0);
        assert!(label.placed[1].x > 0.0);
        assert_eq!(label.placed[1].y, 0.0);
        assert!(label.extent.right > label.extent.left);
        assert!(label.extent.top < 0.0);
    }

    #[test]
    fn a_subscript_is_smaller_and_sits_lower() {
        let font = sample();
        let style = Style::default();
        let label = build("H_2O", &font, &style);
        assert_eq!(label.placed.len(), 3);
        assert_eq!(label.placed[1].character, '2');
        assert_eq!(label.placed[1].size, style.script_size);
        assert!(label.placed[1].y > 0.0);
        assert_eq!(label.placed[2].character, 'O');
        assert_eq!(label.placed[2].size, 1.0);
        assert_eq!(label.placed[2].y, 0.0);
    }

    #[test]
    fn a_superscript_sits_higher() {
        let font = sample();
        let label = build("Na^+", &font, &Style::default());
        assert_eq!(label.placed.len(), 3);
        assert!(label.placed[2].y < 0.0);
        assert!(label.placed[2].size < 1.0);
    }

    #[test]
    fn a_letter_after_a_subscript_gets_a_little_room() {
        let font = sample();
        let style = Style::default();
        let tight = Style {script_space: 0.0, ..style};
        let loose = build("H_2SO_4", &font, &style);
        let close = build("H_2SO_4", &font, &tight);
        // S is the third one
        assert_eq!(loose.placed[2].character, 'S');
        let room = loose.placed[2].x - close.placed[2].x;
        assert!((room - style.script_space).abs() < 1e-9, "空きが {room} です");
    }

    #[test]
    fn scripts_that_follow_each_other_stay_tight() {
        let font = sample();
        let style = Style::default();
        let tight = Style {script_space: 0.0, ..style};
        // No space goes between the 4 and the 2 in O_4^{2-}
        let loose = build("SO_4^{2-}", &font, &style);
        let close = build("SO_4^{2-}", &font, &tight);
        let places = |label: &Label| label.placed.iter().map(|one| one.x).collect::<Vec<f64>>();
        assert_eq!(places(&loose), places(&close));
    }

    #[test]
    fn the_room_does_not_hang_off_the_end() {
        let font = sample();
        let style = Style::default();
        let tight = Style {script_space: 0.0, ..style};
        assert_eq!(
            build("H_2O", &font, &style).width,
            build("H_2O", &font, &tight).width + style.script_space
        );
        // No space goes after a script at the end
        assert_eq!(
            build("SO_4", &font, &style).width,
            build("SO_4", &font, &tight).width
        );
    }

    #[test]
    fn a_charge_sign_lines_up_with_a_digit() {
        let font = sample();
        let style = Style::default();
        let plus = build("Na^+", &font, &style);
        let two = build("Na^2", &font, &style);
        let sign = &plus.placed[2];
        let digit = &two.placed[2];
        let box_of = |placed: &Placed| {
            let glyph = placed.glyph.unwrap();
            let (height, depth) = font::extent(&font, glyph);

            (placed.y - height * placed.size, placed.y + depth * placed.size)
        };
        let (sign_top, sign_bottom) = box_of(sign);
        let (digit_top, digit_bottom) = box_of(digit);
        let sign_middle = (sign_top + sign_bottom) / 2.0;
        let digit_middle = (digit_top + digit_bottom) / 2.0;
        assert!((sign_middle - digit_middle).abs() < 1e-9, "+ が数字と高さで揃っていません");
        assert!(sign.y < two.placed[1].y, "+ が上がっていません");
    }

    #[test]
    fn a_minus_in_a_charge_rises_too() {
        let font = sample();
        let style = Style::default();
        let charge = build("SO_4^{2-}", &font, &style);
        let digit = &charge.placed[3];
        let minus = &charge.placed[4];
        assert_eq!(minus.character, '\u{2212}');
        assert!(minus.y < digit.y, "負号が持ち上がっていません");
    }

    #[test]
    fn a_sign_outside_a_charge_stays_where_it_is() {
        let font = sample();
        let style = Style::default();
        let plain = build("A+B", &font, &style);
        assert_eq!(plain.placed[1].character, '+');
        assert_eq!(plain.placed[1].y, 0.0, "上付きでない + が動いています");
    }

    #[test]
    fn a_group_holds_more_than_one_character() {
        let font = sample();
        let label = build("SO_4^{2-}", &font, &Style::default());
        let text: String = label.placed.iter().map(|placed| placed.character).collect();
        assert_eq!(text, "SO42\u{2212}");
        assert!(label.placed[3].y < 0.0);
        assert!(label.placed[4].y < 0.0);
    }

    #[test]
    fn nested_scripts_stop_shrinking() {
        let font = sample();
        let style = Style::default();
        let label = build("H_{2_{2_{2}}}", &font, &style);
        let size: Vec<f64> = label.placed.iter().map(|placed| placed.size).collect();
        assert_eq!(size[0], 1.0);
        assert_eq!(size[1], style.script_size);
        assert_eq!(size[2], style.script_floor);
        assert_eq!(size[3], style.script_floor, "下限を割り込んでいます");
    }

    #[test]
    fn capitals_cut_the_label_into_parts() {
        let font = sample();
        let style = Style::default();
        assert_eq!(build("CH_3", &font, &style).part.len(), 2);
        assert_eq!(build("H_3C", &font, &style).part.len(), 2);
        assert_eq!(build("H_2SO_4", &font, &style).part.len(), 3);
        assert_eq!(build("C", &font, &style).part.len(), 1);
    }

    #[test]
    fn the_first_part_of_ch3_is_the_carbon() {
        let font = sample();
        let label = build("CH_3", &font, &Style::default());
        let carbon = label.part[0];
        let rest = label.part[1];
        assert!(carbon.right <= rest.left + 1e-9);
        assert_eq!(carbon.left, label.extent.left);
        assert!(rest.right > carbon.right);
    }

    #[test]
    fn the_whole_box_is_the_default_for_clipping() {
        let font = sample();
        let label = build("CH_3", &font, &Style::default());
        assert_eq!(clip_extent(&label, None), Some(label.extent));
        assert_eq!(clip_extent(&label, Some(1)), Some(label.part[0]));
        assert_eq!(clip_extent(&label, Some(3)), None);
        assert_eq!(clip_extent(&label, Some(0)), None);
    }

    #[test]
    fn a_character_the_font_does_not_have_still_takes_room() {
        let font = sample();
        let label = build("\u{3042}", &font, &Style::default());
        assert_eq!(label.placed.len(), 1);
        assert_eq!(label.placed[0].glyph, None);
        assert!(label.width > 0.0);
    }
}