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
use crate::font::{self, Font};
use crate::layout::{Content, Layout, Shape};
use crate::node::class_name;
use crate::outline;
use crate::text::{escape, number, spacing_mark};
use std::collections::BTreeMap;
pub const DARKEN: f64 = 0.011;
fn collect(placed: &Layout, found: &mut Vec<u16>) {
match &placed.content {
Content::Glyph {glyph, ..} => found.push(*glyph),
Content::Group(children) => {
for child in children {
collect(&child.layout, found);
}
}
Content::Rule => {}
}
}
fn stamp(label: &str, glyphs: &[u16]) -> String {
let mut hash: u64 = 0xcbf29ce484222325;
for byte in label.as_bytes() {
hash = (hash ^ *byte as u64).wrapping_mul(0x100000001b3);
}
for glyph in glyphs {
for byte in glyph.to_be_bytes() {
hash = (hash ^ byte as u64).wrapping_mul(0x100000001b3);
}
}
let digits = b"0123456789abcdefghijklmnopqrstuvwxyz";
let mut out = String::new();
for _ in 0..8 {
out.push(digits[(hash % 36) as usize] as char);
hash /= 36;
}
out
}
pub fn render(placed: &Layout, font: &Font, shape: Shape, label: &str) -> String {
render_weighted(placed, font, shape, label, DARKEN)
}
pub fn render_weighted(
placed: &Layout,
font: &Font,
shape: Shape,
label: &str,
darken: f64,
) -> String {
let width = placed.width.max(0.01);
let height = (placed.height + placed.depth).max(0.01);
let mut glyphs = Vec::new();
collect(placed, &mut glyphs);
let mark = stamp(label, &glyphs);
let mut body = String::new();
let mut used: BTreeMap<u16, String> = BTreeMap::new();
let mut needs_font = shape == Shape::Text;
write(placed, font, shape, &mark, darken, 0.0, 0.0, &mut body, &mut used, &mut needs_font);
let mut out = format!(
concat!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{}em\" height=\"{}em\"",
" viewBox=\"0 {} {} {}\" style=\"vertical-align:{}em;overflow:visible\"",
" fill=\"currentColor\" xml:space=\"preserve\" role=\"img\" aria-label=\"{}\""
),
number(width),
number(height),
number(-placed.height),
number(width),
number(height),
number(-placed.depth),
escape(label)
);
if needs_font {
out.push_str(&format!(
" font-family=\"{}, {}\"",
escape(font::family(font)),
font::FALLBACK
));
}
out.push('>');
if !used.is_empty() {
out.push_str("<defs>");
for (glyph, path) in &used {
out.push_str(&format!("<path id=\"{mark}-{glyph}\" d=\"{path}\"/>"));
}
out.push_str("</defs>");
}
out.push_str(&body);
out.push_str("</svg>");
out
}
#[allow(clippy::too_many_arguments)]
fn write(
placed: &Layout,
font: &Font,
shape: Shape,
mark: &str,
darken: f64,
x: f64,
y: f64,
out: &mut String,
used: &mut BTreeMap<u16, String>,
needs_font: &mut bool,
) {
match &placed.content {
Content::Glyph {text, glyph, class, size, italic, bold, stretch} => {
let missing = *glyph == 0 && !text.is_empty();
if (shape == Shape::Outline || text.is_empty()) && !missing {
write_outline(font, *glyph, *size, mark, darken, x, y, out, used);
return;
}
if text.is_empty() {
return;
}
if missing {
*needs_font = true;
}
write_text(text, *class, *size, *italic, *bold, *stretch, x, y, out);
}
Content::Rule => {
out.push_str(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/>",
number(x),
number(y - placed.height),
number(placed.width),
number(placed.height + placed.depth)
));
}
Content::Group(children) => {
for child in children {
let (at_x, at_y) = (x + child.x, y + child.y);
write(&child.layout, font, shape, mark, darken, at_x, at_y, out, used, needs_font);
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn write_outline(
font: &Font,
glyph: u16,
size: f64,
mark: &str,
darken: f64,
x: f64,
y: f64,
out: &mut String,
used: &mut BTreeMap<u16, String>,
) {
let scale = size / font::units_per_em(font);
if let std::collections::btree_map::Entry::Vacant(slot) = used.entry(glyph) {
let drawn = font::outline_of(font, glyph);
if drawn.segment.is_empty() {
return;
}
slot.insert(outline::path_data(&drawn, 1.0, 0.0, 0.0));
}
let weight = if darken > 0.0 && scale > 0.0 {
format!(
" stroke=\"currentColor\" stroke-width=\"{}\" stroke-linejoin=\"round\"",
number(darken / scale)
)
} else {
String::new()
};
out.push_str(&format!(
"<use href=\"#{mark}-{glyph}\" transform=\"translate({} {}) scale({})\"{weight}/>",
number(x),
number(y),
number(scale)
));
}
#[allow(clippy::too_many_arguments)]
fn write_text(
text: &str,
class: crate::node::Class,
size: f64,
italic: bool,
bold: bool,
stretch: f64,
x: f64,
y: f64,
out: &mut String,
) {
let shown: String = text.chars().map(spacing_mark).collect();
let mut attributes = format!(" class=\"{}\" font-size=\"{}\"", class_name(class), number(size));
if italic {
attributes.push_str(" font-style=\"italic\"");
}
if bold {
attributes.push_str(" font-weight=\"bold\"");
}
if stretch == 1.0 {
out.push_str(&format!(
"<text x=\"{}\" y=\"{}\"{attributes}>{}</text>",
number(x),
number(y),
escape(&shown)
));
return;
}
out.push_str(&format!(
"<text transform=\"translate({} {}) scale(1 {})\"{attributes}>{}</text>",
number(x),
number(y),
number(stretch),
escape(&shown)
));
}
#[cfg(test)]
mod tests {
use super::*;
use crate::font;
use crate::layout::layout;
use crate::node::Style;
use crate::parse::parse;
fn sample() -> Font {
let data = std::fs::read("font/latinmodern-math.otf").expect("cannot read the test font");
font::load(data).unwrap()
}
fn svg(source: &str, shape: Shape, display: bool) -> String {
let font = sample();
let placed = layout(&parse(source).unwrap(), &font, 1.0, Style::Auto, display);
render(&placed, &font, shape, source)
}
#[test]
fn wraps_the_whole_formula() {
let out = svg("x", Shape::Text, false);
assert!(out.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\""));
assert!(out.ends_with("</svg>"));
assert!(out.contains("aria-label=\"x\""));
}
#[test]
fn ink_outside_the_advance_is_not_clipped() {
assert!(svg("x", Shape::Outline, false).contains("overflow:visible"));
}
#[test]
fn text_puts_letters_on_the_baseline() {
let out = svg("xy", Shape::Text, false);
assert!(out.contains("<text x=\"0\" y=\"0\""));
assert!(out.contains("font-family=\"Latin Modern Math, serif\""));
}
#[test]
fn outlines_are_shared_between_repeats() {
let out = svg("xxx", Shape::Outline, false);
assert_eq!(out.matches("<path id=").count(), 1);
assert_eq!(out.matches("<use href=").count(), 3);
assert!(!out.contains("font-family"));
}
#[test]
fn characters_the_font_lacks_stay_as_text() {
let out = svg(r"\text{日本語}", Shape::Outline, false);
assert!(out.contains("<text"), "{out}");
assert!(out.contains("font-family"));
}
#[test]
fn outlines_are_thickened_to_match_text() {
assert!(svg("x", Shape::Outline, false).contains("stroke-width="));
let font = sample();
let node = crate::parse::parse("x").unwrap();
let placed = layout(&node, &font, 1.0, Style::Auto, false);
let plain = render_weighted(&placed, &font, Shape::Outline, "x", 0.0);
assert!(!plain.contains("stroke"), "still thickens when 0 is passed");
}
#[test]
fn outlines_carry_no_text() {
let out = svg(r"\frac{a}{b}", Shape::Outline, false);
assert!(!out.contains("<text"));
assert!(out.contains("<rect"));
assert!(out.contains("<path id="));
}
#[test]
fn each_formula_gets_its_own_ids() {
let first = svg("x + y", Shape::Outline, false);
let second = svg(r"\frac{a}{b}", Shape::Outline, false);
let again = svg("x + y", Shape::Outline, false);
assert_eq!(first, again, "the same formula gets the same mark");
let mark = |out: &str| {
let at = out.find("<path id=\"").unwrap() + 10;
out[at..at + 8].to_string()
};
assert_ne!(mark(&first), mark(&second), "different formulas get different marks");
}
#[test]
fn escapes_the_label_and_the_text() {
let out = svg("a<b", Shape::Text, false);
assert!(out.contains("aria-label=\"a<b\""));
assert!(out.contains("><</text>"));
}
#[test]
fn the_view_box_covers_height_and_depth() {
let font = sample();
let node = parse(r"\frac{a}{b}").unwrap();
let placed = layout(&node, &font, 1.0, Style::Auto, false);
let out = render(&placed, &font, Shape::Outline, "");
let expected = format!(
"viewBox=\"0 {} {} {}\"",
number(-placed.height),
number(placed.width),
number(placed.height + placed.depth)
);
assert!(out.contains(&expected), "{out}");
}
}