crabshell-ui 0.9.1

Widgets, styles, layout, text and text editing, focus, hit testing and invalidation for Crabshell
Documentation
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! `cx.measure_text` and fonts bundled with `cx.add_font`.

use std::cell::Cell;
use std::rc::Rc;

use cosmic_text::fontdb::Source;

use super::{Harness, capture_logs, node_at, rect_at};
use crate::text::{Fonts, TextNode};
use crate::{Align, Content, Font, Rect, Row, Style, Text, TextSystem, Window};

/// DejaVu Sans's bytes, leaked as `include_bytes!` would keep them, or
/// `None` with a message on a machine that keeps the file elsewhere.
fn dejavu() -> Option<&'static [u8]> {
  font_file("DejaVuSans.ttf")
}

/// The bytes of the font file `name` from a usual directory, leaked, or
/// `None` with a message.
fn font_file(name: &str) -> Option<&'static [u8]> {
  for dir in [
    "/usr/share/fonts/dejavu",
    "/usr/share/fonts/truetype/dejavu",
    "/usr/share/fonts/TTF",
    "/usr/share/fonts/noto-emoji",
  ] {
    if let Ok(bytes) = std::fs::read(format!("{dir}/{name}")) {
      return Some(Box::leak(bytes.into_boxed_slice()));
    }
  }
  eprintln!("skipped: {name} isn't in any of the usual places");
  None
}

/// A window with one `Text` showing `content` in `font`.
fn text_window(h: &mut Harness, content: &str, font: Font) -> Window {
  let row = Row::new()
    .align(Align::Start)
    .child(Text::new(content.to_owned()).style(Style::new().font(font)));
  h.window(h.panel().child(row), 600.0, 60.0)
}

/// Whether every glyph of the text at `path` is drawn from a bundled font.
fn drawn_from_bundled(window: &Window, text: &TextSystem, path: &[usize]) -> bool {
  let view = window.view();
  let Content::Text(shown) = node_at(view.root(), path).content() else {
    panic!("a text node has text content");
  };
  let fonts = text.font_system();
  let mut glyphs = shown
    .runs()
    .flat_map(|run| run.glyphs.into_owned())
    .peekable();
  glyphs.peek().is_some()
    && glyphs.all(|glyph| {
      fonts
        .db()
        .face(glyph.font_id)
        .is_some_and(|face| matches!(face.source, Source::Binary(_)))
    })
}

#[test]
fn measuring_agrees_with_a_text() {
  for font in [
    Font::new("sans-serif", 15.0),
    Font::new("sans-serif", 13.0).weight(700),
    // Not installed: fontconfig's best match, as for a `Text`.
    Font::new("No Such Family 1234", 13.0),
  ] {
    let mut h = Harness::new();
    let window = text_window(&mut h, "clicked 12 times", font);
    let laid_out = rect_at(&window, &[0, 0]);
    let measured = h.cx.measure_text("clicked 12 times", font);
    assert!(measured.width > 20.0, "{measured:?}");
    assert_eq!(measured.width.ceil(), laid_out.width, "{font:?}");
    assert_eq!(measured.height, laid_out.height, "{font:?}");
    assert_eq!(measured.line_height, measured.height);
    // Noto Sans reaches past its line box: these are the font's own.
    assert!(
      measured.ascent > 0.0 && measured.descent > 0.0,
      "{measured:?}"
    );
  }
}

#[test]
fn an_empty_string_is_one_empty_line() {
  let h = Harness::new();
  let measured = h.cx.measure_text("", Font::DEFAULT);
  assert_eq!(measured.width, 0.0);
  // The default font is 13 pixels with a line height of round(13 * 1.2).
  assert_eq!(measured.line_height, 16.0);
  assert_eq!(measured.height, 16.0);
  assert!(measured.ascent > 0.0, "{measured:?}");
}

#[test]
fn each_line_break_adds_a_line() {
  let h = Harness::new();
  let font = Font::DEFAULT;
  let long = h.cx.measure_text("a longer second line", font);
  let both = h.cx.measure_text("short\na longer second line", font);
  assert_eq!(both.width, long.width);
  assert_eq!(both.height, 2.0 * both.line_height);
  let three = h.cx.measure_text("one\ntwo\n", font);
  assert_eq!(three.height, 3.0 * three.line_height);
}

#[test]
fn a_binding_measures_while_its_window_lays_out() {
  // The binding reruns when layout writes `geometry`, from the flush
  // inside `Window::layout`: the fonts must not be borrowed then.
  let mut h = Harness::new();
  let geometry = h.cx.signal(Rect::default());
  let seen = Rc::new(Cell::new((0.0, 0.0)));
  let cx = h.cx.clone();
  let record = Rc::clone(&seen);
  let row = Row::new()
    .align(Align::Start)
    .geometry(geometry)
    .child(Text::new(move || {
      let width = cx.measure_text("abc", Font::DEFAULT).width;
      record.set((geometry.get().width, width));
      format!("{width}")
    }));
  h.window(h.panel().child(row), 400.0, 30.0);
  let (row_width, measured) = seen.get();
  assert_eq!(row_width, 400.0, "the binding didn't run after layout");
  assert!(measured > 10.0, "measured {measured}");
}

#[test]
fn a_bundled_family_needs_no_fontconfig() {
  let Some(bytes) = dejavu() else { return };
  let mut fonts = Fonts::new();
  fonts.add(bytes);
  let mut node = TextNode::new();
  node.set_content(String::from("clicked 12 times"));
  node.prepare(Font::new("dejavu sans", 13.0), &mut fonts);
  let measured = fonts.measure("clicked 12 times", Font::new("DejaVu Sans", 13.0));
  assert!(measured.width > 20.0, "{measured:?}");
  assert!(!fonts.fontconfig_started());
  let glyphs: Vec<u16> = node
    .runs()
    .flat_map(|run| run.glyphs.into_owned())
    .map(|glyph| glyph.glyph_id)
    .collect();
  assert!(glyphs.iter().all(|&id| id != 0), "{glyphs:?}");
  // A character DejaVu Sans lacks still falls back through fontconfig.
  node.set_content(String::from("a\u{4E00}"));
  node.prepare(Font::new("DejaVu Sans", 13.0), &mut fonts);
  assert!(fonts.fontconfig_started());
}

#[test]
fn bytes_that_hold_no_font_are_logged_and_ignored() {
  let h = Harness::new();
  let logs = capture_logs(|| h.cx.add_font(b"not a font"));
  assert!(logs.contains("bundled font"), "{logs}");
  let faces = h.text.font_system().db().len();
  assert_eq!(faces, 0);
}

#[test]
fn a_font_added_later_shapes_laid_out_text_again() {
  let Some(bytes) = dejavu() else { return };
  let mut h = Harness::new();
  let window = text_window(&mut h, "hello", Font::new("DejaVu Sans", 13.0));
  // fontconfig's file first.
  assert!(!drawn_from_bundled(&window, &h.text, &[0, 0]));
  assert!(!window.needs_layout());
  h.cx.add_font(bytes);
  assert!(window.needs_layout());
  h.frame(&window);
  assert!(drawn_from_bundled(&window, &h.text, &[0, 0]));
  assert!(!window.needs_layout());
}

#[test]
fn a_font_added_later_repaints_text_that_kept_its_size() {
  let Some(bold) = font_file("DejaVuSans-Bold.ttf") else {
    return;
  };
  let mut h = Harness::new();
  let style = Style::new()
    .font(Font::new("DejaVu Sans", 13.0))
    .width(200.0);
  let row = Row::new()
    .align(Align::Start)
    .child(Text::new("hello").style(style));
  let window = h.window(h.panel().child(row), 600.0, 60.0);
  window.take_damage();
  let text = rect_at(&window, &[0, 0]);
  h.cx.add_font(bold);
  h.frame(&window);
  // Its box didn't move, but its glyphs may have changed.
  let damage = window.take_damage();
  assert!(
    damage.iter().any(|area| area.union(text) == *area),
    "{damage:?} misses {text:?}"
  );
}

/// Each glyph's face in `node`: whether it is bundled, and its weight.
fn glyph_faces(node: &TextNode, fonts: &mut Fonts) -> Vec<(bool, u16)> {
  let db = fonts.font_system().db();
  node
    .runs()
    .flat_map(|run| run.glyphs.into_owned())
    .filter_map(|glyph| db.face(glyph.font_id))
    .map(|face| (matches!(face.source, Source::Binary(_)), face.weight.0))
    .collect()
}

/// `content` shaped in DejaVu Sans at `weight`.
fn dejavu_text(fonts: &mut Fonts, weight: u16) -> TextNode {
  let mut node = TextNode::new();
  node.set_content(String::from("hello"));
  node.prepare(Font::new("DejaVu Sans", 13.0).weight(weight), fonts);
  node
}

#[test]
fn a_bundled_bold_leaves_regular_text_to_fontconfig() {
  let Some(bold) = font_file("DejaVuSans-Bold.ttf") else {
    return;
  };
  let mut fonts = Fonts::new();
  fonts.add(bold);
  let node = dejavu_text(&mut fonts, 700);
  assert!(!fonts.fontconfig_started());
  assert!(
    glyph_faces(&node, &mut fonts)
      .iter()
      .all(|&face| face == (true, 700))
  );
  // No bundled face has weight 400, so fontconfig's file is used.
  let node = dejavu_text(&mut fonts, 400);
  assert!(fonts.fontconfig_started());
  let faces = glyph_faces(&node, &mut fonts);
  assert!(faces.iter().all(|&face| face == (false, 400)), "{faces:?}");
}

#[test]
fn a_bundled_regular_keeps_the_installed_bold() {
  let Some(regular) = dejavu() else { return };
  let mut fonts = Fonts::new();
  dejavu_text(&mut fonts, 400);
  dejavu_text(&mut fonts, 700);
  fonts.add(regular);
  let faces = glyph_faces(&dejavu_text(&mut fonts, 700), &mut fonts);
  assert!(faces.iter().all(|&face| face == (false, 700)), "{faces:?}");
  let faces = glyph_faces(&dejavu_text(&mut fonts, 400), &mut fonts);
  assert!(faces.iter().all(|&face| face == (true, 400)), "{faces:?}");
}

#[test]
fn a_bundled_variable_font_serves_the_weights_it_spans() {
  let Some(emoji) = font_file("NotoEmoji-VariableFont_wght.ttf") else {
    return;
  };
  let mut fonts = Fonts::new();
  fonts.add(emoji);
  // Its weight axis runs from 300 to 700.
  for weight in [300, 600, 700] {
    let font = Font::new("Noto Emoji", 13.0).weight(weight);
    assert_eq!(fonts.family(&font).as_deref(), Some("Noto Emoji"));
  }
  assert!(!fonts.fontconfig_started());
  fonts.family(&Font::new("Noto Emoji", 13.0).weight(900));
  assert!(fonts.fontconfig_started());
}

#[test]
fn a_replaced_face_is_never_read_back() {
  let Some(regular) = dejavu() else { return };
  let mut fonts = Fonts::new();
  dejavu_text(&mut fonts, 400);
  let path = fonts
    .font_system()
    .db()
    .faces()
    .find_map(|face| match &face.source {
      Source::File(path) | Source::SharedFile(path, _) => Some(path.clone()),
      Source::Binary(_) => None,
    })
    .expect("fontconfig loaded a file");
  // As for a collection's face that was read with another one and never
  // asked for by its own number.
  fonts.loaded.clear();
  fonts.add(regular);
  let name = fonts.load((path, 0));
  assert_eq!(name.as_deref(), Some("DejaVu Sans"));
  let files = fonts
    .font_system()
    .db()
    .faces()
    .filter(|face| !matches!(face.source, Source::Binary(_)))
    .count();
  assert_eq!(files, 0, "the replaced face was read again");
}

#[test]
fn measuring_takes_letter_spacing_as_a_text_does() {
  let plain = Font::new("sans-serif", 13.0);
  let spaced = plain.letter_spacing(2.0);
  let mut h = Harness::new();
  let window = text_window(&mut h, "clicked 12 times", spaced);
  let laid_out = rect_at(&window, &[0, 0]);
  let wide = h.cx.measure_text("clicked 12 times", spaced);
  let narrow = h.cx.measure_text("clicked 12 times", plain);
  assert!(wide.width > narrow.width + 20.0, "{wide:?} {narrow:?}");
  assert_eq!(wide.width.ceil(), laid_out.width);
}

#[test]
fn a_bundled_upright_face_leaves_italic_to_fontconfig() {
  let Some(regular) = dejavu() else { return };
  let Some(oblique) = font_file("DejaVuSans-Oblique.ttf") else {
    return;
  };
  let slanted = |fonts: &mut Fonts, italic: bool| {
    let font = Font::new("DejaVu Sans", 13.0);
    let mut node = TextNode::new();
    node.set_content(String::from("hello"));
    node.prepare(if italic { font.italic() } else { font }, fonts);
    let db = fonts.font_system().db();
    let faces: Vec<_> = node
      .runs()
      .flat_map(|run| run.glyphs.into_owned())
      .filter_map(|glyph| db.face(glyph.font_id))
      .map(|face| (matches!(face.source, Source::Binary(_)), face.style))
      .collect();
    faces
  };
  let mut fonts = Fonts::new();
  fonts.add(regular);
  assert!(
    slanted(&mut fonts, false)
      .iter()
      .all(|&(bundled, _)| bundled)
  );
  assert!(!fonts.fontconfig_started());
  let faces = slanted(&mut fonts, true);
  assert!(fonts.fontconfig_started());
  assert!(
    faces
      .iter()
      .all(|&(bundled, style)| !bundled && style != cosmic_text::fontdb::Style::Normal),
    "{faces:?}"
  );

  // A bundled oblique face serves italic text without fontconfig.
  let mut fonts = Fonts::new();
  fonts.add(oblique);
  let faces = slanted(&mut fonts, true);
  assert!(faces.iter().all(|&(bundled, _)| bundled), "{faces:?}");
  assert!(!fonts.fontconfig_started());
}

/// The pixels the glyphs of the text at `[0, 0]` in `window` cover as
/// swash rasterizes them unhinted at scale 1, from the text's corner:
/// left, top, right and bottom. An oracle for `ink` that doesn't read
/// outlines.
fn rasterized(window: &Window, text: &TextSystem) -> (f32, f32, f32, f32) {
  let view = window.view();
  let Content::Text(shown) = node_at(view.root(), &[0, 0]).content() else {
    panic!("a text node has text content");
  };
  let mut fonts = text.font_system();
  let mut cache = cosmic_text::SwashCache::new();
  let mut bounds = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
  for run in shown.runs() {
    for glyph in run.glyphs.iter() {
      // On a baseline at 0, which `physical` keeps whole.
      let physical = glyph.physical((0.0, 0.0), 1.0);
      let mut key = physical.cache_key;
      key.flags |= cosmic_text::CacheKeyFlags::DISABLE_HINTING;
      let image = cache
        .get_image_uncached(&mut fonts, key)
        .expect("the glyph rasterizes");
      let left = (physical.x + image.placement.left) as f32;
      let top = (physical.y - image.placement.top) as f32 + run.line_y;
      bounds.0 = bounds.0.min(left);
      bounds.1 = bounds.1.min(top);
      bounds.2 = bounds.2.max(left + image.placement.width as f32);
      bounds.3 = bounds.3.max(top + image.placement.height as f32);
    }
  }
  bounds
}

#[test]
fn ink_is_the_box_the_glyphs_draw() {
  // Noto Sans Italic's f hangs left of its origin and past its advance,
  // as a Nerd Font icon in a monospace cell does.
  for (content, font) in [
    ("f", Font::new("sans-serif", 40.0).italic()),
    ("j", Font::new("sans-serif", 40.0)),
    ("Hello", Font::new("sans-serif", 18.0)),
  ] {
    let mut h = Harness::new();
    let window = text_window(&mut h, content, font);
    let measured = h.cx.measure_text(content, font);
    let ink = measured.ink;
    let (left, top, right, bottom) = rasterized(&window, &h.text);
    // Antialiasing rounds a pixel out on each side.
    let near = |ink: f32, pixel: f32| (ink - pixel).abs() <= 1.0;
    assert!(near(ink.x, left), "{content}: {ink:?} vs left {left}");
    assert!(near(ink.y, top), "{content}: {ink:?} vs top {top}");
    assert!(near(ink.right(), right), "{content}: {ink:?} vs {right}");
    assert!(near(ink.bottom(), bottom), "{content}: {ink:?} vs {bottom}");
    assert!(ink.width > 0.0 && ink.height > 0.0, "{ink:?}");
  }
  let h = Harness::new();
  let italic = h
    .cx
    .measure_text("f", Font::new("sans-serif", 40.0).italic());
  assert!(italic.ink.x < 0.0, "{italic:?}");
  assert!(italic.ink.right() > italic.width, "{italic:?}");
  let j = h.cx.measure_text("j", Font::new("sans-serif", 40.0));
  assert!(j.ink.x < 0.0, "{j:?}");
}

#[test]
fn ink_takes_each_line_and_no_blank() {
  let h = Harness::new();
  let font = Font::new("sans-serif", 20.0);
  for blank in ["", " ", "  \t ", "\n"] {
    assert_eq!(
      h.cx.measure_text(blank, font).ink,
      Rect::default(),
      "{blank:?}"
    );
  }
  let one = h.cx.measure_text("x", font);
  let two = h.cx.measure_text("x\nx", font);
  assert_eq!(two.ink.x, one.ink.x);
  assert_eq!(two.ink.y, one.ink.y);
  assert_eq!(two.ink.width, one.ink.width);
  assert_eq!(two.ink.height, one.ink.height + one.line_height);
  // A leading space moves the ink right by its advance.
  let spaced = h.cx.measure_text(" x", font);
  let space = h.cx.measure_text(" ", font).width;
  assert!(
    (spaced.ink.x - (one.ink.x + space)).abs() < 0.01,
    "{spaced:?}"
  );
}

#[test]
fn a_curves_box_holds_where_it_turns_not_its_control_points() {
  let bounds = |points: &[(f32, f32)]| {
    let mut found = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
    let mut add = |x: f32, y: f32| {
      found = (
        found.0.min(x),
        found.1.min(y),
        found.2.max(x),
        found.3.max(y),
      );
    };
    add(points[0].0, points[0].1);
    crate::text::curve_extremes(points, &mut add);
    found
  };
  // An icon converted from SVG often has no point on a curve's extremes.
  assert_eq!(
    bounds(&[(0.0, 0.0), (5.0, 10.0), (10.0, 0.0)]),
    (0.0, 0.0, 10.0, 5.0)
  );
  assert_eq!(
    bounds(&[(0.0, 0.0), (0.0, 10.0), (10.0, 10.0), (10.0, 0.0)]),
    (0.0, 0.0, 10.0, 7.5)
  );
  let (left, _, right, _) = bounds(&[(0.0, 0.0), (-6.0, 4.0), (16.0, 4.0), (10.0, 0.0)]);
  assert!(left < -1.0 && left > -6.0, "{left}");
  assert!(right > 11.0 && right < 16.0, "{right}");
  assert_eq!(bounds(&[(0.0, 0.0), (3.0, -4.0)]), (0.0, -4.0, 3.0, 0.0));
}

#[test]
fn a_color_bitmap_glyphs_ink_is_its_pixels() {
  let Some(bytes) = font_file("NotoColorEmoji.ttf") else {
    return;
  };
  let h = Harness::new();
  h.cx.add_font(bytes);
  let measured = h.cx.measure_text("😀", Font::new("Noto Color Emoji", 20.0));
  let ink = measured.ink;
  assert!(ink.width > 10.0 && ink.height > 10.0, "{measured:?}");
  assert!(ink.width <= measured.width + 2.0, "{measured:?}");
}

#[test]
fn a_colr_glyphs_ink_is_its_color_layers() {
  // A COLR font's base glyph is often an empty outline drawn by its
  // layers; Twemoji is the one installed here, with LibreWolf.
  let Ok(bytes) = std::fs::read("/opt/librewolf/fonts/TwemojiMozilla.ttf") else {
    eprintln!("skipped: no Twemoji Mozilla");
    return;
  };
  let h = Harness::new();
  h.cx.add_font(Box::leak(bytes.into_boxed_slice()));
  let measured = h.cx.measure_text("😀", Font::new("Twemoji Mozilla", 20.0));
  let ink = measured.ink;
  assert!(ink.width > 10.0 && ink.height > 10.0, "{measured:?}");
}

#[test]
fn measuring_glyphs_again_builds_no_outlines_until_a_font_is_added() {
  let mut fonts = Fonts::new();
  let font = Font::new("sans-serif", 18.0);
  let first = fonts.measure("hello world", font);
  let built = fonts.glyphs_built;
  // h, e, l, o, w, r and d as outlines; the space's empty outline tries
  // a bitmap once, as a COLR glyph's would, and is kept as blank.
  assert_eq!(built, (7, 1));
  assert_eq!(fonts.measure("hello world", font), first);
  fonts.measure("held lower", font);
  assert_eq!(fonts.glyphs_built, built, "the same glyphs");
  fonts.measure("hello", Font::new("sans-serif", 20.0));
  assert_eq!(fonts.glyphs_built, (11, 1), "another size");

  let Some(bytes) = dejavu() else { return };
  fonts.add(bytes);
  fonts.measure("hello", font);
  assert_eq!(
    fonts.glyphs_built,
    (15, 1),
    "measured again after a font came"
  );
}

#[test]
fn the_ink_cache_keeps_at_most_its_cap() {
  let mut fonts = Fonts::new();
  // Each size is another glyph to the cache.
  for step in 0..=crate::text::INK_GLYPHS {
    fonts.measure("x", Font::new("sans-serif", 8.0 + step as f32 / 64.0));
    assert!(fonts.ink.len() <= crate::text::INK_GLYPHS);
  }
  assert_eq!(fonts.ink.len(), 1, "it started again at the cap");
}