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
472
473
474
475
476
477
478
use cairo::ScaledFont;
use xi_unicode::LineBreakIterator;
use super::LineMetric;
pub(crate) fn calculate_line_metrics(text: &str, font: &ScaledFont, width: f64) -> Vec<LineMetric> {
// first pass, completely naive and inefficient. Check at every break to see if line longer
// than width.
//
// See https://raphlinus.github.io/rust/skribo/text/2019/04/26/skribo-progress.html for
// some other ideas for better efficiency
//
// Notes:
// hard breaks: cr, lf, line break, para char. Mandated by unicode
//
// So, every time there's a a hard break, must break.
//
// soft-hyphen, don't need to deal with this round. Looks like automatic hyphenation, but
// with unicode codepoint. Don't special case, let if break for now.
//
// For soft breaks, then I need to check line widths etc.
//
// - what happens when even smallest break is wider than width?
// One word is considered the smallest unit, don't break below words for now.
//
// Use font extents height (it's different from text extents height,
// which relates to bounding box)
//
// For baseline, use use `FontExtent.ascent`. Needs to be positive?
// see https://glyphsapp.com/tutorials/vertical-metrics
// https://stackoverflow.com/questions/27631736/meaning-of-top-ascent-baseline-descent-bottom-and-leading-in-androids-font
// https://www.cairographics.org/manual/cairo-cairo-scaled-font-t.html#cairo-font-extents-t
let mut line_metrics = Vec::new();
let mut line_start = 0;
let mut prev_break = 0;
let mut y_offset = 0.0;
// vertical measures constant across all lines for now (cairo toy text)
let height = font.extents().height;
let baseline = font.extents().ascent;
for (line_break, is_hard_break) in LineBreakIterator::new(text) {
if !is_hard_break {
// this section is for soft breaks
let curr_str = &text[line_start..line_break];
let curr_width = font.text_extents(curr_str).x_advance;
if curr_width > width {
// since curr_width is longer than desired line width, it's time to break ending
// at the previous break.
// Except! what if this break is at first possible break. Then prev_break needs to
// be moved to current break.
// This leads to an extra call, in next section, on an empty string for handling
// prev_break..line_break. But it's a little clearer without more logic, and when
// perf matters all of this will be rewritten anyways. If desired otherwise, add
// in a flag after next add_line_metric.
if prev_break == line_start {
prev_break = line_break;
}
// first do the line to prev break
add_line_metric(
text,
line_start,
prev_break,
baseline,
height,
&mut y_offset,
&mut line_metrics,
);
// Now handle the graphemes between prev_break and current break. The
// implementation depends on how we're treating a single line that's wider than
// desired width. For now, just assume that the word will get cutoff when rendered.
//
// If it's shorter than desired width, just continue.
let curr_str = &text[prev_break..line_break];
let curr_width = font.text_extents(curr_str).x_advance;
if curr_width > width {
add_line_metric(
text,
prev_break,
line_break,
baseline,
height,
&mut y_offset,
&mut line_metrics,
);
line_start = line_break;
prev_break = line_break;
} else {
// Since curr_width < width, don't break and just continue
line_start = prev_break;
prev_break = line_break;
}
} else {
// Since curr_width < width, don't break and just continue
prev_break = line_break;
}
} else {
// this section is for hard breaks
// even when there's a hard break, need to check first to see if width is too wide. If
// it is, need to break at the previous soft break first.
let curr_str = &text[line_start..line_break];
let curr_width = font.text_extents(curr_str).x_advance;
if curr_width > width {
// if line is too wide but can't break down anymore, just skip to the next
// add_line_metric. But here, since prev_break is not equal to line_start, that
// means there another break opportunity so take it.
//
// TODO consider refactoring to make more parallel with above soft break
// comparison.
if prev_break != line_start {
add_line_metric(
text,
line_start,
prev_break,
baseline,
height,
&mut y_offset,
&mut line_metrics,
);
line_start = prev_break;
}
}
// now do the hard break
add_line_metric(
text,
line_start,
line_break,
baseline,
height,
&mut y_offset,
&mut line_metrics,
);
line_start = line_break;
prev_break = line_break;
}
}
line_metrics
}
fn add_line_metric(
text: &str,
start_offset: usize,
end_offset: usize,
baseline: f64,
height: f64,
y_offset: &mut f64,
line_metrics: &mut Vec<LineMetric>,
) {
let line = &text[start_offset..end_offset];
let trailing_whitespace = count_trailing_whitespace(line);
let line_metric = LineMetric {
start_offset,
end_offset,
trailing_whitespace,
baseline,
height,
y_offset: *y_offset,
};
line_metrics.push(line_metric);
*y_offset += height;
}
// TODO: is non-breaking space trailing whitespace? Check with dwrite and
// coretext
fn count_trailing_whitespace(line: &str) -> usize {
line.chars().rev().take_while(|c| c.is_whitespace()).count()
}
#[cfg(test)]
mod test {
use super::super::*;
use super::*;
fn test_metrics_with_width(
width: f64,
expected: Vec<LineMetric>,
input: &str,
font: &ScaledFont,
) {
let line_metrics = calculate_line_metrics(input, &font, width);
for (i, (metric, exp)) in line_metrics.iter().zip(expected).enumerate() {
println!("calculated: {:?}\nexpected: {:?}", metric, exp);
assert_eq!(metric.range(), exp.range());
assert_eq!(metric.trailing_whitespace, exp.trailing_whitespace);
assert!(
metric.y_offset < exp.y_offset + ((i as f64 + 1.0) * 3.0)
&& metric.y_offset > exp.y_offset - ((i as f64 + 1.0) * 3.0)
);
assert!(metric.baseline < exp.baseline + 3.0 && metric.baseline > exp.baseline - 3.0);
assert!(metric.height < exp.height + 3.0 && metric.height > exp.height - 3.0);
}
}
#[test]
#[cfg(target_os = "linux")]
fn test_hard_soft_break_end() {
// This tests that the hard break is not handled before the soft break when the hard break
// exceeds text layout width. In this case, it's the last line `best text!` which is too
// long. The line should be soft-broken at the space before the EOL breaks.
let input = "piet text is the best text!";
let width = 50.0;
let font = CairoFont::new(FontFamily::SANS_SERIF).resolve_simple(12.0);
let line_metrics = calculate_line_metrics(input, &font, width);
// Some print debugging, in case font size/width needs to be changed in future because of
// brittle tests
println!(
"{}: \"piet text \"",
font.text_extents("piet text ").x_advance
);
for lm in &line_metrics {
let line_text = &input[lm.start_offset..lm.end_offset];
println!(
"{}: {:?}",
font.text_extents(line_text).x_advance,
line_text
);
}
assert_eq!(line_metrics.len(), 5);
}
#[test]
#[cfg(target_os = "macos")]
fn test_hard_soft_break_end() {
// This tests that the hard break is not handled before the soft break when the hard break
// exceeds text layout width. In this case, it's the last line `best text!` which is too
// long. The line should be soft-broken at the space before the EOL breaks.
let input = "piet text is the best text!";
let width = 50.0;
let font = CairoFont::new(FontFamily::SANS_SERIF).resolve_simple(14.0);
let line_metrics = calculate_line_metrics(input, &font, width);
// Some print debugging, in case font size/width needs to be changed in future because of
// brittle tests
println!(
"{}: \"piet text \"",
font.text_extents("piet text ").x_advance
);
for lm in &line_metrics {
let line_text = &input[lm.range()];
println!(
"{}: {:?}",
font.text_extents(line_text).x_advance,
line_text
);
}
assert_eq!(line_metrics.len(), 5);
}
#[test]
fn test_hard_soft_break_start() {
// this tests that a single word followed by hard break that exceeds layout width is
// correctly broken, and that there is no extra line metric created (e.g. a [0,0] line offset preceding)
let input = "piet\ntext";
let width = 10.0;
let font = CairoFont::new(FontFamily::SANS_SERIF).resolve_simple(12.0);
let line_metrics = calculate_line_metrics(input, &font, width);
// Some print debugging, in case font size/width needs to be changed in future because of
// brittle tests
println!("{}: \"piet\n\"", font.text_extents("piet\n").x_advance);
println!("{}: \"text\"", font.text_extents("text").x_advance);
for lm in &line_metrics {
let line_text = &input[lm.range()];
println!(
"{}: {:?}",
font.text_extents(line_text).x_advance,
line_text
);
}
println!("line_metrics: {:?}", line_metrics);
assert_eq!(line_metrics.len(), 2);
}
// TODO do a super-short length, to make sure the behavior is correct
// when first break comes directly after the first word. I think I fixed it, but should have a
// more explicit test.
//
// TODO add a macos specific test (I fudged this one to work for now)
//
// Test at three different widths: small, medium, large.
// - small is every word being split.
// - medium is one split.
// - large is no split.
//
// Also test empty string input
#[test]
fn test_basic_calculate_line_metrics() {
// Setup input, width, and expected
let input = "piet text most best";
use xi_unicode::LineBreakIterator;
for (offset, line_break) in LineBreakIterator::new(input) {
println!("{}:{}", offset, line_break);
}
let width_small = 30.0;
let expected_small = vec![
LineMetric {
start_offset: 0,
end_offset: 5,
trailing_whitespace: 1,
y_offset: 0.,
baseline: 12.0,
height: 14.0,
},
LineMetric {
start_offset: 5,
end_offset: 10,
trailing_whitespace: 1,
y_offset: 14.0,
baseline: 12.0,
height: 14.0,
},
LineMetric {
start_offset: 10,
end_offset: 15,
trailing_whitespace: 1,
y_offset: 28.0,
baseline: 12.0,
height: 14.0,
},
LineMetric {
start_offset: 15,
end_offset: 19,
trailing_whitespace: 0,
y_offset: 42.0,
baseline: 12.0,
height: 14.0,
},
];
let width_medium = 70.0;
let expected_medium = vec![
LineMetric {
start_offset: 0,
end_offset: 10,
trailing_whitespace: 1,
y_offset: 0.0,
baseline: 12.0,
height: 14.0,
},
LineMetric {
start_offset: 10,
end_offset: 19,
trailing_whitespace: 0,
y_offset: 14.0,
baseline: 12.0,
height: 14.0,
},
];
let width_large = 125.0;
let expected_large = vec![LineMetric {
start_offset: 0,
end_offset: 19,
trailing_whitespace: 0,
y_offset: 0.0,
baseline: 12.0,
height: 14.0,
}];
let empty_input = "";
let expected_empty = vec![LineMetric {
start_offset: 0,
end_offset: 0,
trailing_whitespace: 0,
y_offset: 0.0,
baseline: 12.0,
height: 14.0,
}];
// setup cairo layout
let font = CairoFont::new(FontFamily::SANS_SERIF).resolve_simple(13.0);
println!(
"piet text width: {}",
font.text_extents("piet text").x_advance
); // 55
println!(
"most best width: {}",
font.text_extents("most best").x_advance
); // 65
println!(
"piet text most best width: {}",
font.text_extents("piet text most best").x_advance
); // 124
test_metrics_with_width(width_small, expected_small, input, &font);
test_metrics_with_width(width_medium, expected_medium, input, &font);
test_metrics_with_width(width_large, expected_large, input, &font);
test_metrics_with_width(width_small, expected_empty, empty_input, &font);
}
#[test]
#[cfg(target_os = "linux")]
// TODO determine if we need to test macos too for this. I don't think it's a big deal right
// now, just wanted to make sure hard breaks work.
fn test_basic_calculate_line_metrics_hard_break() {
// Setup input, width, and expected
let input = "piet\ntext most\nbest";
use xi_unicode::LineBreakIterator;
for (offset, line_break) in LineBreakIterator::new(input) {
println!("{}:{}", offset, line_break);
}
let width_small = 25.0;
let expected_small = vec![
LineMetric {
start_offset: 0,
end_offset: 5,
trailing_whitespace: 1,
y_offset: 0.0,
baseline: 12.0,
height: 14.0,
},
LineMetric {
start_offset: 5,
end_offset: 10,
trailing_whitespace: 1,
y_offset: 14.0,
baseline: 12.0,
height: 14.0,
},
LineMetric {
start_offset: 10,
end_offset: 15,
trailing_whitespace: 1,
y_offset: 28.0,
baseline: 12.0,
height: 14.0,
},
LineMetric {
start_offset: 15,
end_offset: 19,
trailing_whitespace: 0,
y_offset: 42.0,
baseline: 12.0,
height: 14.0,
},
];
// setup cairo layout
let font = CairoFont::new(FontFamily::SANS_SERIF).resolve_simple(13.0);
test_metrics_with_width(width_small, expected_small, input, &font);
}
#[test]
fn test_count_trailing_whitespace() {
assert_eq!(count_trailing_whitespace(" 1 "), 1);
assert_eq!(count_trailing_whitespace(" 2 "), 2);
assert_eq!(count_trailing_whitespace(" 3 \n"), 3);
}
}