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
//! 位置の決まった図を SVG にする
//!
//! 座標の 1 は文字サイズの 1 em にあたる。幅と高さも em で書き出すので、
//! 図はまわりの文字に合わせて伸び縮みする。色は currentColor に任せる。
//!
//! 字形は 2 通りに書き出せる。輪郭として置くと、表示する側にフォントが要らず、
//! どこで開いても同じ形になるかわりに、選んで写せない。
//! 文字として置くと、選んで写せて出力も小さくなるかわりに、表示する側に同じフォントが要る。
//!
//! 書体が持たない文字は輪郭を描けないので、どちらの書き方でも文字として置く。
use crate::font::{self, Font};
use crate::label::Placed;
use crate::layout::{Figure, PlacedAtom};
use crate::outline;
use crate::style::Style;
use crate::text::{escape, number};
/// 字形の書き出し方
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
/// 輪郭として置く。表示する側にフォントが要らない
Outline,
/// 文字として置く。選んで写せるが、表示する側に同じフォントが要る
Text,
}
/// 図を 1 つの `<svg>` にする。label は代替テキストになる
pub fn render(figure: &Figure, font: &Font, style: &Style, shape: Shape, label: &str) -> String {
let extent = figure.extent.grow(style.margin);
let width = (extent.right - extent.left).max(style.margin * 2.0);
let height = (extent.bottom - extent.top).max(style.margin * 2.0);
let mut out = String::new();
out.push_str("<svg xmlns=\"http://www.w3.org/2000/svg\"");
out.push_str(&format!(" width=\"{}em\" height=\"{}em\"", number(width), number(height)));
out.push_str(&format!(
" viewBox=\"{} {} {} {}\"",
number(extent.left),
number(extent.top),
number(width),
number(height)
));
// 文中に置いたときに、図の中の字のベースラインがまわりの文字のベースラインに乗るようにする。
// 置き換え要素は既定で下端がベースラインに乗るので、そのぶんだけ下げる
let baseline = font::cap_height(font) / 2.0;
let drop = extent.bottom - baseline;
out.push_str(&format!(" style=\"vertical-align:{}em\"", number(-drop)));
out.push_str(&format!(" role=\"img\" aria-label=\"{}\">", escape(label)));
// 結合を先に、字を後に置く。重なったときに字が上に来る
push_bond(&mut out, figure, style);
push_wedge(&mut out, figure, style);
push_circle(&mut out, figure, style);
match shape {
Shape::Outline => push_outline(&mut out, figure, font, style),
Shape::Text => push_text(&mut out, figure, font),
}
push_fallback(&mut out, figure);
out.push_str("</svg>");
out
}
/// 図に置かれた原子と、その下の名前
fn every_atom(figure: &Figure) -> impl Iterator<Item = &PlacedAtom> {
figure.atom.iter().chain(figure.name.iter())
}
/// 字形の輪郭。1 つの path にまとめる
fn push_outline(out: &mut String, figure: &Figure, font: &Font, style: &Style) {
let unit = font::units_per_em(font);
let mut data = String::new();
for atom in every_atom(figure) {
for placed in &atom.label.placed {
let Some(glyph) = placed.glyph else {
continue;
};
let drawn = font::outline_of(font, glyph);
if drawn.segment.is_empty() {
continue;
}
let scale = placed.size / unit;
let x = atom.origin_x + placed.x;
let y = atom.origin_y + placed.y;
data.push_str(&outline::path_data(&drawn, scale, x, y));
}
}
if data.is_empty() {
return;
}
out.push_str("<path fill=\"currentColor\"");
if style.darken > 0.0 {
let weight = number(style.darken);
out.push_str(&format!(
" stroke=\"currentColor\" stroke-width=\"{weight}\" stroke-linejoin=\"round\""
));
}
out.push_str(&format!(" d=\"{data}\"/>"));
}
/// 字形を文字として置く
///
/// 大きさと高さが同じ字が続くあいだは 1 つの `<text>` にまとめ、x を並べて 1 字ずつ位置を決める。
/// 字送りをブラウザに任せないので、輪郭で描いたものと同じ位置に並ぶ
fn push_text(out: &mut String, figure: &Figure, font: &Font) {
let family = escape(font::family(font));
for atom in every_atom(figure) {
let mut start = 0;
let placed = &atom.label.placed;
while start < placed.len() {
if placed[start].glyph.is_none() {
start += 1;
continue;
}
let mut end = start + 1;
while end < placed.len() && continues(&placed[start], &placed[end]) {
end += 1;
}
push_run(out, atom, &placed[start..end], &family);
start = end;
}
}
}
/// 同じ `<text>` に入れてよいかどうか
fn continues(first: &Placed, next: &Placed) -> bool {
next.glyph.is_some() && next.size == first.size && next.y == first.y
}
/// 大きさと高さのそろった字の並びを 1 つの `<text>` にする
fn push_run(out: &mut String, atom: &PlacedAtom, run: &[Placed], family: &str) {
let mut horizontal = String::new();
let mut body = String::new();
for placed in run {
if !horizontal.is_empty() {
horizontal.push(' ');
}
horizontal.push_str(&number(atom.origin_x + placed.x));
body.push(placed.character);
}
out.push_str(&format!(
"<text x=\"{horizontal}\" y=\"{}\" font-size=\"{}\" font-family=\"{family}\" \
fill=\"currentColor\">{}</text>",
number(atom.origin_y + run[0].y),
number(run[0].size),
escape(&body)
));
}
/// 結合の線。1 つの path にまとめる
fn push_bond(out: &mut String, figure: &Figure, style: &Style) {
if figure.line.is_empty() {
return;
}
let mut data = String::new();
for line in &figure.line {
data.push('M');
data.push_str(&number(line.x1));
data.push(' ');
data.push_str(&number(line.y1));
data.push('L');
data.push_str(&number(line.x2));
data.push(' ');
data.push_str(&number(line.y2));
}
out.push_str(&format!(
"<path fill=\"none\" stroke=\"currentColor\" stroke-width=\"{}\" \
stroke-linecap=\"round\" d=\"{data}\"/>",
number(style.line_width)
));
}
/// くさびの三角形。塗るものと塗らないものを分けて 1 つずつ path にまとめる
fn push_wedge(out: &mut String, figure: &Figure, style: &Style) {
for filled in [true, false] {
let mut data = String::new();
for wedge in figure.wedge.iter().filter(|one| one.filled == filled) {
data.push('M');
data.push_str(&spot(wedge.tip));
data.push('L');
data.push_str(&spot(wedge.base[0]));
data.push('L');
data.push_str(&spot(wedge.base[1]));
data.push('Z');
}
if data.is_empty() {
continue;
}
if filled {
out.push_str(&format!("<path fill=\"currentColor\" d=\"{data}\"/>"));
} else {
out.push_str(&format!(
"<path fill=\"none\" stroke=\"currentColor\" stroke-width=\"{}\" \
stroke-linejoin=\"round\" d=\"{data}\"/>",
number(style.line_width)
));
}
}
}
/// 芳香環の丸
fn push_circle(out: &mut String, figure: &Figure, style: &Style) {
for circle in &figure.circle {
out.push_str(&format!(
"<circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"none\" stroke=\"currentColor\" \
stroke-width=\"{}\"/>",
number(circle.x),
number(circle.y),
number(circle.radius),
number(style.line_width)
));
}
}
/// 点を path の中に書く形にする
fn spot(point: (f64, f64)) -> String {
format!("{} {}", number(point.0), number(point.1))
}
/// 書体が持たない文字。輪郭を描けないので文字として置く
fn push_fallback(out: &mut String, figure: &Figure) {
for atom in every_atom(figure) {
for placed in &atom.label.placed {
if placed.glyph.is_some() {
continue;
}
let x = number(atom.origin_x + placed.x);
let y = number(atom.origin_y + placed.y);
let size = number(placed.size);
let text = escape(&placed.character.to_string());
out.push_str(&format!(
"<text x=\"{x}\" y=\"{y}\" font-size=\"{size}\" \
font-family=\"{}\" fill=\"currentColor\">{text}</text>",
font::FALLBACK
));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::font::sample;
use crate::layout::layout;
use crate::parse::parse;
fn draw(source: &str) -> String {
let font = sample();
let style = Style::default();
let figure = layout(&parse(source).unwrap(), &font, &style).unwrap();
render(&figure, &font, &style, Shape::Outline, source)
}
fn write(source: &str) -> String {
let font = sample();
let style = Style::default();
let figure = layout(&parse(source).unwrap(), &font, &style).unwrap();
render(&figure, &font, &style, Shape::Text, source)
}
#[test]
fn writes_one_svg_element() {
let found = draw("H-O-H");
assert!(found.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\""));
assert!(found.ends_with("</svg>"));
assert_eq!(found.matches("<svg").count(), 1);
}
#[test]
fn the_size_is_written_in_em() {
let found = draw("H-O-H");
assert!(found.contains("em\" height=\""));
assert!(found.contains("viewBox=\""));
}
#[test]
fn the_figure_sits_on_the_baseline_of_the_text_around_it() {
let found = draw("H-O-H");
let at = found.find("vertical-align:").expect("基準線がありません");
let rest = &found[at + "vertical-align:".len()..];
let value: f64 = rest[..rest.find("em").unwrap()].parse().unwrap();
// 図の下端は、字の深さと余白のぶんだけベースラインより下にある
assert!(value < 0.0, "図が下がっていません");
assert!(value > -1.0, "下げすぎです: {value}");
}
#[test]
fn a_taller_figure_hangs_lower() {
let flat = draw("H-H");
let tall = draw("H-[:-90]H");
let of = |markup: &str| {
let at = markup.find("vertical-align:").unwrap() + "vertical-align:".len();
let rest = &markup[at..];
rest[..rest.find("em").unwrap()].parse::<f64>().unwrap()
};
assert!(of(&tall) < of(&flat), "下へ伸びた図が下がっていません");
}
#[test]
fn the_glyphs_come_out_as_outlines() {
let found = draw("H-O-H");
assert!(found.contains("<path fill=\"currentColor\""));
assert!(found.contains("C"), "曲線の命令がありません");
}
#[test]
fn the_bonds_come_out_as_one_stroked_path() {
let found = draw("H-O-H");
assert_eq!(found.matches("stroke-linecap=\"round\"").count(), 1);
assert_eq!(found.matches("fill=\"none\"").count(), 1);
}
#[test]
fn a_molecule_with_no_bond_still_draws() {
let found = draw("H_2O");
assert!(found.contains("<path fill=\"currentColor\""));
assert!(!found.contains("fill=\"none\""));
}
#[test]
fn the_label_becomes_the_alternative_text() {
assert!(draw("O=C=O").contains("aria-label=\"O=C=O\""));
}
#[test]
fn markup_in_the_label_is_escaped() {
let font = sample();
let style = Style::default();
let figure = layout(&parse("A-B").unwrap(), &font, &style).unwrap();
let found = render(&figure, &font, &style, Shape::Outline, "<a>&");
assert!(found.contains("aria-label=\"<a>&\""));
}
#[test]
fn a_filled_wedge_is_a_closed_path() {
let found = draw("C>H");
let at = found.find("<path fill=\"currentColor\" d=\"M").expect("三角形がありません");
let data = &found[at..found[at..].find("\"/>").unwrap() + at];
// 頂点 3 つで閉じる
assert_eq!(data.matches('L').count(), 2);
assert_eq!(data.matches('Z').count(), 1);
}
#[test]
fn a_hollow_wedge_is_stroked_instead() {
let found = draw("C>|H");
assert!(found.contains("stroke-linejoin=\"round\" d=\"M"));
assert!(found.contains('Z'));
}
#[test]
fn an_aromatic_ring_writes_a_circle() {
let found = draw("**6(------)");
assert_eq!(found.matches("<circle").count(), 1);
assert!(found.contains("fill=\"none\" stroke=\"currentColor\""));
}
#[test]
fn a_plain_ring_writes_no_circle() {
assert!(!draw("*6(------)").contains("<circle"));
}
#[test]
fn the_bonds_are_written_before_the_letters() {
let found = draw("H-O-H");
let bond = found.find("fill=\"none\"").unwrap();
let glyph = found.find("<path fill=\"currentColor\"").unwrap();
assert!(bond < glyph, "字が結合の下に隠れます");
}
#[test]
fn the_text_shape_writes_letters_instead_of_outlines() {
let found = write("H-O-H");
assert_eq!(found.matches("<text").count(), 3);
assert!(!found.contains("<path fill=\"currentColor\""), "輪郭が残っています");
assert!(found.contains("font-family=\"Latin Modern Math\""));
assert!(found.contains("fill=\"none\""), "結合が消えています");
}
#[test]
fn letters_of_the_same_size_and_height_share_one_text() {
// C と H は同じ大きさと高さなので 1 つ、3 は下がるので別
let found = write("CH_3");
assert_eq!(found.matches("<text").count(), 2);
assert!(found.contains(">CH</text>"));
assert!(found.contains(">3</text>"));
}
#[test]
fn every_letter_gets_its_own_place() {
let found = write("CH_3");
let at = found.find("<text x=\"").unwrap() + "<text x=\"".len();
let list = &found[at..at + found[at..].find('"').unwrap()];
assert_eq!(list.split(' ').count(), 2, "x が 1 字ずつ並んでいません");
}
#[test]
fn the_two_shapes_place_the_letters_alike() {
// 輪郭と文字で、図の大きさが変わらない
let outline = draw("H_3C-CH_3");
let text = write("H_3C-CH_3");
let size = |markup: &str| {
let at = markup.find("viewBox=\"").unwrap() + "viewBox=\"".len();
markup[at..at + markup[at..].find('"').unwrap()].to_string()
};
assert_eq!(size(&outline), size(&text));
}
#[test]
fn a_character_the_font_lacks_is_written_as_text() {
let found = draw("\u{3042}-H");
assert!(found.contains("<text"));
assert!(found.contains("\u{3042}"));
}
#[test]
fn an_empty_source_still_makes_a_box() {
let found = draw("");
assert!(found.starts_with("<svg"));
assert!(found.ends_with("</svg>"));
}
}