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
//! 位置と寸法の決まったまとまりを SVG にする
//!
//! 座標の 1 は文字サイズの 1 em にあたる。ベースラインが y = 0 で、上が負である。
//!
//! 字形は 2 通りに書き出せる。文字として置くと、表示する側に同じフォントが要るかわりに
//! 選んで写せる。輪郭として置くと、フォントが要らなくなるかわりに写せなくなる。
use crate::font::{self, Font};
use crate::layout::{Content, Layout, Shape};
use crate::node::class_name;
use crate::outline;
use crate::text::{escape, number};
use std::collections::BTreeMap;
/// 組み合わせた文字を、文字として書き出すときの代わり。単独で置ける字形に替える
fn spacing_mark(character: char) -> char {
match character {
'\u{300}' => '\u{60}',
'\u{301}' => '\u{b4}',
'\u{302}' => '\u{2c6}',
'\u{303}' => '\u{2dc}',
'\u{304}' => '\u{af}',
'\u{306}' => '\u{2d8}',
'\u{307}' => '\u{2d9}',
'\u{308}' => '\u{a8}',
'\u{30c}' => '\u{2c7}',
'\u{20d7}' => '\u{2192}',
other => other,
}
}
/// 輪郭で描くときに字形を太らせる量(em)
///
/// ブラウザは文字を描くとき、細い線が薄く沈まないように少しだけ太らせる。輪郭にはそれが
/// 掛からないので、同じ書体の地の文と並べると輪郭のほうが薄く見える。その差を埋める。
/// 忠実な輪郭がほしいときは [`render_weighted`] に 0 を渡す。
pub const DARKEN: f64 = 0.011;
/// 使う字形を先に数える。id に付ける印を決めるのに要る
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 => {}
}
}
/// id にぶつからない印を付けるための番号
///
/// 同じページに式をいくつも置くと、`<use>` は文書の中で最初に見つかった id を引いてしまう。
/// 式ごとに違う印を付けて、取り違えないようにする。中身が同じ式なら同じ印になるが、
/// 指す先も同じなので困らない。
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
}
/// まとまりを 1 つの `<svg>` にする。label は代替テキストになる
pub fn render(placed: &Layout, font: &Font, shape: Shape, label: &str) -> String {
render_weighted(placed, font, shape, label, DARKEN)
}
/// 太らせる量を決めて書き出す。0 を渡すと字形の輪郭をそのまま描く
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} => {
// フォントが持たない文字(\text の中の日本語など)は輪郭を描けないので、
// そこだけ文字として置く。表示する側の書体まかせになる
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);
}
}
}
}
/// 字形を輪郭で置く。同じ字形は defs に 1 つだけ入れて、use で呼ぶ
#[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));
}
// 太らせる量は em で決めるので、字形の単位に直してから渡す。
// 線の太さは transform で縮むぶん、あらかじめ割り戻しておく
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("試験用のフォントを読めません");
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"), "0 を渡しても太らせています");
}
#[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, "同じ式なら同じ印になる");
let mark = |out: &str| {
let at = out.find("<path id=\"").unwrap() + 10;
out[at..at + 8].to_string()
};
assert_ne!(mark(&first), mark(&second), "式が違えば印も違う");
}
#[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}");
}
}