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.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-10-15
Size
541.1 KB
Downloads
9
Checksum
67f9c361d04f05b0299dd8e9ef5e2a0120d67be36205a76945eb5f7ef90443be
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
//! 原子のラベルを組む
//!
//! `H_2O` や `SO_4^{2-}` のような、下付きと上付きを含む文字列を字形の並びに直す。
//! 座標は、x がラベルの左端から、y がベースラインから下向きを正として測る。
//!
//! ラベルは大文字ごとに部分へ切れる。`CH_3` なら `C` と `H_3` の 2 つである。
//! 結合は、この部分か、ラベル全体の墨の縁で止まる。

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


/// 置かれた 1 つの字形
#[derive(Debug, Clone, PartialEq)]
pub struct Placed {
    /// 字形番号。フォントがその文字を持たなければ None
    pub glyph: Option<u16>,
    pub character: char,
    /// ラベルの左端からの位置
    pub x: f64,
    /// ベースラインからの位置。下向きが正
    pub y: f64,
    /// 大きさ。1 なら素の大きさ
    pub size: f64,
}


/// 墨の占める範囲
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Extent {
    pub left: f64,
    pub right: f64,
    /// ベースラインより上は負
    pub top: f64,
    pub bottom: f64,
}


impl Extent {
    /// 墨がまったくないかどうか
    pub fn is_blank(&self) -> bool {
        self.right <= self.left && self.bottom <= self.top
    }

    /// 2 つを包む範囲
    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),
        }
    }

    /// 四方へ広げる
    pub fn grow(&self, amount: f64) -> Extent {
        Extent {
            left: self.left - amount,
            right: self.right + amount,
            top: self.top - amount,
            bottom: self.bottom + amount,
        }
    }
}


/// 組み上がったラベル
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Label {
    pub placed: Vec<Placed>,
    /// 大文字ごとに切った部分の墨の範囲
    pub part: Vec<Extent>,
    /// ラベル全体の墨の範囲
    pub extent: Extent,
    /// 送り幅の合計
    pub width: f64,
}


/// ラベルの文字列を組む
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}
}


/// 結合を切り詰めるときに使う範囲。番号を書かなければラベル全体
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(),
    }
}


/// 組み立ての途中の持ち物
struct Work {
    placed: Vec<Placed>,
    /// 部分の切れ目。placed の添字
    boundary: Vec<usize>,
    pen: f64,
}


/// いま置いている場所の決まりごと
#[derive(Debug, Clone, Copy)]
struct Setting {
    size: f64,
    /// ベースラインからの位置。下向きが正
    shift: f64,
    /// 波括弧の入れ子の深さ
    depth: usize,
    /// 上付きの中かどうか。電荷の記号をここで持ち上げる
    charge: bool,
}


/// 文字を順に置いていく。波括弧と下付き・上付きで自分を呼び直す
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);
            }
        }
    }
}


/// 下付きと上付きが連れていく 1 つ。波括弧のまとまりか、そうでなければ 1 文字
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);
        }
    }
}


/// 添字の後ろに空きを入れる
///
/// 次に来るのが素の字のときだけ入れる。添字が続くとき(`O_4^{2-}` の 4 と 2)や、
/// まとまりの終わりでは入れない
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;
}


/// 字形を 1 つ置き、送り幅だけ筆を進める
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;
}


/// 数式の軸を中心に描かれた記号かどうか
fn is_sign(character: char) -> bool {
    matches!(character, '+' | '\u{2212}' | '\u{b1}' | '\u{2213}')
}


/// 電荷の記号を持ち上げる量。その字の大きさを 1 として測る
///
/// 数字はベースラインに乗るが、+ や − は数式の軸を中心に描かれるので、
/// そのまま並べると数字より低く見える。中心が数字の中心に来るまで持ち上げる
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)
}


/// 下付きと上付きの大きさ。掛けるだけだと入れ子で際限なく小さくなるので、下限で止める
fn shrink(size: f64, style: &Style) -> f64 {
    (size * style.script_size).max(style.script_floor).min(size)
}


/// ラベルの中のハイフンは負電荷の記号である。見た目の合う字形に替える
fn sign(character: char) -> char {
    match character {
        '-' => '\u{2212}',
        other => other,
    }
}


/// 部分ごとの墨の範囲を測る
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
}


/// 字形 1 つの墨の範囲
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 は 3 番目
        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};
        // O_4^{2-} の 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
        );
        // 末尾の添字の後ろには入れない
        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);
    }
}