-
Notifications
You must be signed in to change notification settings - Fork 45
/
lib.rs
370 lines (327 loc) · 11.4 KB
/
lib.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
use unicode_segmentation::UnicodeSegmentation;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use textwrap::core;
use textwrap::word_separators::{AsciiSpace, UnicodeBreakProperties, WordSeparator};
use textwrap::word_splitters::{split_words, HyphenSplitter, NoHyphenation, WordSplitter};
use textwrap::wrap_algorithms::{wrap_first_fit, wrap_optimal_fit};
#[wasm_bindgen]
extern "C" {
// https://github.com/rustwasm/wasm-bindgen/issues/2069#issuecomment-774038243
type ExtendedTextMetrics;
#[wasm_bindgen(method, getter, js_name = actualBoundingBoxLeft)]
fn actual_bounding_box_left(this: &ExtendedTextMetrics) -> f64;
#[wasm_bindgen(method, getter, js_name = actualBoundingBoxRight)]
fn actual_bounding_box_right(this: &ExtendedTextMetrics) -> f64;
#[wasm_bindgen(method, getter, js_name = actualBoundingBoxAscent)]
fn actual_bounding_box_ascent(this: &ExtendedTextMetrics) -> f64;
#[wasm_bindgen(method, getter, js_name = actualBoundingBoxDescent)]
fn actual_bounding_box_descent(this: &ExtendedTextMetrics) -> f64;
// TODO: Enable when Firefox and Edge support these methods, see
// https://developer.mozilla.org/en-US/docs/Web/API/TextMetrics
//
// #[wasm_bindgen(method, getter, js_name = fontBoundingBoxAscent)]
// fn font_bounding_box_ascent(this: &ExtendedTextMetrics) -> f64;
//
// #[wasm_bindgen(method, getter, js_name = fontBoundingBoxDescent)]
// fn font_bounding_box_descent(this: &ExtendedTextMetrics) -> f64;
#[wasm_bindgen(method, getter)]
fn width(this: &ExtendedTextMetrics) -> f64;
}
fn canvas_width(ctx: &web_sys::CanvasRenderingContext2d, text: &str) -> f64 {
ctx.measure_text(text).unwrap().width()
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct CanvasWord<'a> {
word: &'a str,
width: f64,
whitespace: &'a str,
whitespace_width: f64,
penalty: &'a str,
penalty_width: f64,
}
impl<'a> CanvasWord<'a> {
fn from(ctx: &'_ web_sys::CanvasRenderingContext2d, word: core::Word<'a>) -> Self {
CanvasWord {
word: word.word,
width: canvas_width(ctx, word.word),
whitespace: word.whitespace,
whitespace_width: canvas_width(ctx, word.whitespace),
penalty: word.penalty,
penalty_width: canvas_width(ctx, word.penalty),
}
}
fn break_apart(
self,
ctx: &'_ web_sys::CanvasRenderingContext2d,
max_width: f64,
) -> Vec<CanvasWord<'a>> {
if self.width <= max_width {
return vec![self];
}
let mut start = 0;
let mut words = Vec::new();
for (idx, grapheme) in self.word.grapheme_indices(true) {
let with_grapheme = &self.word[start..idx + grapheme.len()];
let without_grapheme = &self.word[start..idx];
if idx > 0 && canvas_width(&ctx, with_grapheme) > max_width {
// The part without the grapheme fits on the line. We
// give it a width of max_width instead of its natural
// width to ensure that it takes up the full line.
//
// Otherwise, we can end up with a situation where a
// text fits in _fewer_ lines when the line width is
// _smaller_. This happens with proportional fonts,
// such as the sans-serif or serif fonts. An example
// text which illustrates the problem is:
//
// i XYZ
//
// Line width: 42px. Normal break, XYZ doesn't fit on
// first line:
//
// i
// XYZ
//
// Line width: 41px. XYZ takes up 41.1px, so it is
// broken apart. The first part now fits on the first
// line:
//
// i XY
// Z
//
// Line width: 39px. There is no longer room for XY on
// the first line:
//
// i
// XY
// Z
//
// Line width: 28px. XY takes up 28.9px, so it is
// broken apart. YZ takes up 26.7px, so everything
// suddenly fits on two lines again:
//
// i X
// YZ
//
// We can be a more "natural" or "monotone" behavior
// by making the parts take up at least the full line
// width.
let natural_width = canvas_width(ctx, &without_grapheme);
words.push(CanvasWord {
word: &without_grapheme,
width: max_width.max(natural_width),
whitespace: "",
whitespace_width: 0.0,
penalty: "",
penalty_width: 0.0,
});
start = idx;
}
}
words.push(CanvasWord {
word: &self.word[start..],
width: canvas_width(ctx, &self.word[start..]),
whitespace: self.whitespace,
whitespace_width: self.whitespace_width,
penalty: self.penalty,
penalty_width: self.penalty_width,
});
words
}
}
const PRECISION: usize = 10;
impl core::Fragment for CanvasWord<'_> {
#[inline]
fn width(&self) -> usize {
(self.width * PRECISION as f64) as usize
}
#[inline]
fn whitespace_width(&self) -> usize {
(self.whitespace_width * PRECISION as f64) as usize
}
#[inline]
fn penalty_width(&self) -> usize {
(self.penalty_width * PRECISION as f64) as usize
}
}
fn draw_path(
ctx: &web_sys::CanvasRenderingContext2d,
style: &str,
(mut x, mut y): (f64, f64),
steps: &[(f64, f64)],
) {
ctx.save();
ctx.set_stroke_style(&style.into());
ctx.begin_path();
ctx.move_to(x, y);
for (delta_x, delta_y) in steps {
x += delta_x;
y += delta_y;
ctx.line_to(x, y);
}
ctx.stroke();
ctx.restore();
}
// We offset all text by the width of the round slider. This ensures
// no clipping due to anti-aliasing.
const X_OFFSET: f64 = 8.0;
fn draw_word(
ctx: &web_sys::CanvasRenderingContext2d,
x: f64,
y: f64,
word: &CanvasWord,
last_word: bool,
) -> Result<(), JsValue> {
ctx.fill_text(word.word, x, y)?;
draw_path(
ctx,
"orange",
(x, y - 10.0),
&[(0.0, 10.0), (word.width, 0.0)],
);
ctx.save();
ctx.set_font("10px sans-serif");
ctx.set_text_align("center");
ctx.set_text_baseline("top");
ctx.fill_text(
&format!("{:.1}px", word.width),
x + word.width / 2.0,
y + 3.0,
)?;
ctx.restore();
let x = x + word.width;
if last_word {
ctx.fill_text(word.penalty, x, y)?;
draw_path(ctx, "red", (x, y), &[(word.penalty_width, 0.0)]);
} else {
ctx.fill_text(word.whitespace, x, y)?;
draw_path(ctx, "lightblue", (x, y), &[(word.whitespace_width, 0.0)]);
}
Ok(())
}
#[wasm_bindgen]
#[derive(Copy, Clone, Debug)]
pub enum WasmWordSeparator {
AsciiSpace = "AsciiSpace",
UnicodeBreakProperties = "UnicodeBreakProperties",
}
#[wasm_bindgen]
#[derive(Copy, Clone, Debug)]
pub enum WasmWordSplitter {
NoHyphenation = "NoHyphenation",
HyphenSplitter = "HyphenSplitter",
}
#[wasm_bindgen]
#[derive(Copy, Clone, Debug)]
pub enum WasmWrapAlgorithm {
FirstFit = "FirstFit",
OptimalFit = "OptimalFit",
}
#[wasm_bindgen]
#[derive(Copy, Clone, Debug)]
pub struct WasmOptions {
pub width: usize,
pub break_words: bool,
pub word_separator: WasmWordSeparator,
pub word_splitter: WasmWordSplitter,
pub wrap_algorithm: WasmWrapAlgorithm,
}
#[wasm_bindgen]
impl WasmOptions {
#[wasm_bindgen(constructor)]
pub fn new(
width: usize,
break_words: bool,
word_separator: WasmWordSeparator,
word_splitter: WasmWordSplitter,
wrap_algorithm: WasmWrapAlgorithm,
) -> WasmOptions {
WasmOptions {
width,
break_words,
word_separator,
word_splitter,
wrap_algorithm,
}
}
}
#[wasm_bindgen]
pub fn draw_wrapped_text(
ctx: &web_sys::CanvasRenderingContext2d,
options: &WasmOptions,
text: &str,
) -> Result<(), JsValue> {
console_error_panic_hook::set_once();
let metrics: web_sys::TextMetrics = ctx.measure_text("│").unwrap();
let metrics: ExtendedTextMetrics = metrics.unchecked_into();
// TODO: use metrics.font_bounding_box_ascent() +
// metrics.font_bounding_box_descent() and measure "" instead of a
// tall character when supported by Firefox.
let line_height = metrics.actual_bounding_box_ascent() + metrics.actual_bounding_box_descent();
let baseline_distance = 1.5 * line_height;
let word_separator: Box<dyn WordSeparator> = match options.word_separator {
WasmWordSeparator::AsciiSpace => Box::new(AsciiSpace),
WasmWordSeparator::UnicodeBreakProperties => Box::new(UnicodeBreakProperties),
_ => Err("WasmOptions has an invalid word_separator field")?,
};
let word_splitter: Box<dyn WordSplitter> = match options.word_splitter {
WasmWordSplitter::NoHyphenation => Box::new(NoHyphenation),
WasmWordSplitter::HyphenSplitter => Box::new(HyphenSplitter),
_ => Err("WasmOptions has an invalid word_splitter field")?,
};
let mut lineno = 0;
for line in text.split('\n') {
let words = word_separator.find_words(line);
let split_words = split_words(words, &word_splitter);
let canvas_words = split_words
.flat_map(|word| {
let canvas_word = CanvasWord::from(ctx, word);
if options.break_words {
canvas_word.break_apart(ctx, options.width as f64)
} else {
vec![canvas_word]
}
})
.collect::<Vec<_>>();
let line_lengths = [options.width * PRECISION];
let wrapped_words = match options.wrap_algorithm {
WasmWrapAlgorithm::FirstFit => wrap_first_fit(&canvas_words, &line_lengths),
WasmWrapAlgorithm::OptimalFit => wrap_optimal_fit(&canvas_words, &line_lengths),
_ => Err("WasmOptions has an invalid wrap_algorithm field")?,
};
for words_in_line in wrapped_words {
lineno += 1;
let mut x = X_OFFSET;
let y = baseline_distance * lineno as f64;
for (i, word) in words_in_line.iter().enumerate() {
let last_word = i == words_in_line.len() - 1;
draw_word(ctx, x, y, word, last_word)?;
x += word.width;
x += if last_word {
word.penalty_width
} else {
word.whitespace_width
};
}
ctx.save();
ctx.set_font("10px sans-serif");
ctx.fill_text(
&format!("{:.1}px", x - X_OFFSET),
1.5 * X_OFFSET + options.width as f64,
y,
)?;
ctx.restore();
}
}
draw_path(
ctx,
"blue",
(
X_OFFSET + options.width as f64,
metrics.actual_bounding_box_ascent(),
),
&[(0.0, baseline_distance * lineno as f64)],
);
Ok(())
}