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
//! Turns a figure whose positions are already set into SVG
//!
//! A coordinate of 1 equals 1 em of the font size. The width and height are also written in
//! em, so the figure scales with the text around it. The color is left to currentColor.
//!
//! Glyphs can be written out in two ways. Placed as outlines, they need no font on the viewing
//! side and look the same wherever they are opened, but they cannot be selected and copied.
//! Placed as text, they can be selected and copied and the output is smaller, but the viewing
//! side needs the same font.
//!
//! A character the typeface does not have cannot be drawn as an outline, so it is placed as
//! text either way.
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};
/// How glyphs are written out
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
/// Place as outlines. The viewing side needs no font
Outline,
/// Place as text. It can be selected and copied, but the viewing side needs the same font
Text,
}
/// Turns a figure into one `<svg>`. label becomes the alternative text
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)
));
// When the figure is placed in a line of text, put the baseline of its letters on the
// baseline of the text around it. A replaced element sits with its bottom edge on the
// baseline by default, so lower the figure by that amount
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)));
// Put the bonds first and the letters after. Where they overlap, the letters are on top
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
}
/// The atoms placed in the figure, and the name under it
fn every_atom(figure: &Figure) -> impl Iterator<Item = &PlacedAtom> {
figure.atom.iter().chain(figure.name.iter())
}
/// The glyph outlines. They are put together in one 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}\"/>"));
}
/// Places glyphs as text
///
/// While letters of the same size and height follow one another, they go into one `<text>`,
/// and a list of x values sets the position of each letter.
/// The advances are not left to the browser, so the letters line up in the same places as
/// the outlines
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;
}
}
}
/// Whether the two may go into the same `<text>`
fn continues(first: &Placed, next: &Placed) -> bool {
next.glyph.is_some() && next.size == first.size && next.y == first.y
}
/// Turns a run of letters with the same size and height into one `<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)
));
}
/// The bond lines. They are put together in one 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)
));
}
/// The wedge triangles. Filled ones and unfilled ones are kept apart, each kind in one 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)
));
}
}
}
/// The circle of an aromatic ring
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)
));
}
}
/// Formats a point the way it is written inside a path
fn spot(point: (f64, f64)) -> String {
format!("{} {}", number(point.0), number(point.1))
}
/// Characters the typeface does not have. They cannot be drawn as outlines, so they are
/// placed as text
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();
// The figure's bottom edge is below the baseline by the letters' depth plus the margin
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];
// It is closed with three vertices
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 and H have the same size and height, so they share one.
// 3 is lowered, so it gets its own
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() {
// The size of the figure is the same with outlines and with text
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>"));
}
}