crcbl-ui 0.2.1

Crucible immediate-mode GUI
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
//! Fonts an application registers with [`Ui::register_font`]: what a
//! `font-family` list selects by name, what it measures and draws in, and what
//! a name nothing is registered under falls back to.

use glam::Vec2;

use super::tests::{frame, idle};
use super::*;
use crate::draw_list::{DrawCommand, DrawList};
use crate::font::face::{SYNTHETIC_BOLD_EM, Synthesis};
use crate::font::{Font, FontMetrics, GlyphId, ReservedFamilyName};
use crate::style::Declaration;

/// A font whose every Latin-1 glyph is `advance` thousandths of an em wide, on
/// lines exactly one em tall.
fn fixed_pitch(advance: f32) -> &'static Font {
    Font::fixed_pitch(
        FontMetrics {
            units_per_em: 1000,
            ascent: 800.0,
            descent: -200.0,
            line_gap: 0.0,
        },
        advance,
    )
}

const TEXT: &str = "WIDE";
const SIZE: f32 = 20.0;

/// One frame of a span `class` holding [`TEXT`] at [`SIZE`] under `css`,
/// returning its size and what it emitted.
fn span_in(ui: &mut Ui, css: &str, class: &str) -> (Vec2, DrawList) {
    ui.add_stylesheet("fonts.css", css);
    let mut key = None;
    frame(ui, idle(), |ui| {
        key = Some(ui.span(class, TEXT, &[Declaration::FontSize(SIZE)]).key);
    });
    let (min, max) = ui.rect(key.expect("built")).expect("laid out");
    let mut list = DrawList::new();
    ui.emit(&mut list);
    (max - min, list)
}

/// The one glyph run `list` holds: its font and glyphs.
fn glyph_run(list: &DrawList) -> (Font, Vec<crate::font::layout::PositionedGlyph>) {
    let runs: Vec<_> = list
        .commands()
        .iter()
        .filter_map(|command| match command {
            DrawCommand::Glyphs { font, glyphs, .. } => Some((font.clone(), glyphs.clone())),
            _ => None,
        })
        .collect();
    assert_eq!(runs.len(), 1, "not one glyph run: {}", runs.len());
    runs.into_iter().next().expect("one run")
}

/// **A font parsed at run time registers by value**, draws its span, and is
/// let go with the tree: the registry holds a clone, not a leak.
#[test]
fn a_font_read_at_run_time_draws_and_is_let_go_with_the_tree() {
    let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(crate::font::SANS_TTF);
    let font = Font::parse(std::sync::Arc::clone(&bytes)).expect("parses");
    let id = font.id();
    let mut ui = Ui::new();
    ui.register_font("found on disk", font)
        .expect("not reserved");
    let (_, list) = span_in(
        &mut ui,
        ".a { font-family: \"found on disk\", bitmap; }",
        ".a",
    );
    let (drawn, _) = glyph_run(&list);
    assert_eq!(drawn.id(), id, "the run is not in the registered font");
    assert_eq!(
        std::sync::Arc::strong_count(&bytes),
        2,
        "the font holds the bytes it was given, not a copy"
    );
    drop((drawn, list, ui));
    assert_eq!(
        std::sync::Arc::strong_count(&bytes),
        1,
        "the tree and its draw list let the font go"
    );
}

/// **A font registered by reference is that font**, not a parse of its bytes:
/// the run it draws carries its identity, which is what the atlas keys on.
#[test]
fn a_font_registered_by_reference_is_the_same_font() {
    let font = Font::parse(crate::font::SANS_TTF).expect("parses");
    let mut ui = Ui::new();
    ui.register_font("by reference", &font)
        .expect("not reserved");
    let (_, list) = span_in(
        &mut ui,
        ".a { font-family: \"by reference\", bitmap; }",
        ".a",
    );
    assert_eq!(glyph_run(&list).0.id(), font.id());
}

/// **A registered font is what a span measures in**, by quoted name or bare
/// words in any case: [`TEXT`]'s width is its advances and its height the
/// font's one-em line — not what `sans-serif`, the list's fallback, measures.
#[test]
fn a_registered_font_measures_the_spans_that_name_it() {
    let font = fixed_pitch(500.0);
    let css = r#"
        .quoted { font-family: "ROBOTO", sans-serif; }
        .bare { font-family: roboto, sans-serif; }
        .alone { font-family: Roboto; }
        .sans { font-family: sans-serif; }
    "#;
    let mut sans_ui = Ui::new();
    let (sans, _) = span_in(&mut sans_ui, css, ".sans");

    // Four glyphs half an em wide at 20px, on a 20px line.
    let want = Vec2::new(4.0 * 0.5 * SIZE, SIZE);
    assert_ne!(sans, want, "the fixture measures like sans-serif");
    for class in [".quoted", ".bare", ".alone"] {
        let mut ui = Ui::new();
        ui.register_font("Roboto", font).expect("not reserved");
        let (size, _) = span_in(&mut ui, css, class);
        assert_eq!(size, want, "{class} did not measure in the registered font");
    }
}

/// **A registered font is what a span draws in**: one glyph run of that font,
/// its glyphs the font's own ids at its advances.
#[test]
fn a_registered_font_is_the_font_its_spans_glyph_run_draws_in() {
    let font = fixed_pitch(500.0);
    let mut ui = Ui::new();
    ui.register_font("roboto", font).expect("not reserved");
    let (_, list) = span_in(&mut ui, ".a { font-family: roboto, bitmap; }", ".a");

    let (drawn, glyphs) = glyph_run(&list);
    assert_eq!(
        drawn.id(),
        font.id(),
        "the run is not in the registered font"
    );
    assert_eq!(glyphs.len(), TEXT.len());
    for (at, glyph) in glyphs.iter().enumerate() {
        assert_eq!(glyph.glyph, GlyphId(1));
        assert_eq!(glyph.offset.x, at as f32 * 0.5 * SIZE);
    }
    assert!(
        !list
            .commands()
            .iter()
            .any(|command| matches!(command, DrawCommand::Text { .. })),
        "the span also drew in the bitmap font"
    );
}

/// **A name nothing is registered under falls back as an unknown name always
/// did**: to the list's built-in family, and — for a list naming none — to the
/// family the span had without the declaration, inherited or an earlier
/// rule's.
#[test]
fn an_unregistered_family_draws_in_what_the_list_falls_back_to() {
    let other = fixed_pitch(250.0);
    let reference = |css: &str| span_in(&mut Ui::new(), css, ".a");
    let (sans, _) = reference(".a { font-family: sans-serif; }");
    let (bitmap, _) = reference(".a { font-family: bitmap; }");
    assert_ne!(sans, bitmap);

    let cases = [
        (".a { font-family: roboto, sans-serif; }", sans),
        (".a { font-family: roboto, bitmap; }", bitmap),
        // An earlier rule's family stands.
        (
            ".a { font-family: sans-serif; } .a { font-family: roboto; }",
            sans,
        ),
        // The initial family stands.
        (".a { font-family: roboto; }", bitmap),
    ];
    for (css, want) in cases {
        let mut ui = Ui::new();
        // Registered under another name: this one is still unregistered.
        ui.register_font("inter", other).expect("not reserved");
        let (size, list) = span_in(&mut ui, css, ".a");
        assert_eq!(size, want, "{css}");
        let drew_sans = list
            .commands()
            .iter()
            .any(|command| matches!(command, DrawCommand::Glyphs { .. }));
        assert_eq!(drew_sans, want == sans, "{css} drew in the wrong font");
    }

    // Inherited: the parent's family is the child's fallback.
    let mut ui = Ui::new();
    ui.add_stylesheet(
        "fonts.css",
        ".column { font-family: sans-serif; } .a { font-family: roboto; }",
    );
    let mut key = None;
    frame(&mut ui, idle(), |ui| {
        ui.block(".column", &[], |ui| {
            key = Some(ui.span(".a", TEXT, &[Declaration::FontSize(SIZE)]).key);
        });
    });
    let (min, max) = ui.rect(key.expect("built")).expect("laid out");
    assert_eq!(
        max - min,
        sans,
        "an unregistered name dropped the inherited family"
    );
}

/// **Registering a name again replaces its font**, and the spans in it are
/// measured again rather than answered from the cache; a name no list could
/// select by is refused.
#[test]
fn registering_a_name_again_replaces_its_font_and_reserved_names_are_refused() {
    let narrow = fixed_pitch(250.0);
    let wide = fixed_pitch(750.0);
    let css = ".a { font-family: roboto, sans-serif; }";
    let mut ui = Ui::new();
    ui.register_font("roboto", narrow).expect("not reserved");
    let (first, _) = span_in(&mut ui, css, ".a");
    ui.register_font("ROBOTO", wide).expect("not reserved");
    let (second, list) = span_in(&mut ui, css, ".a");
    assert_eq!(first.x, 4.0 * 0.25 * SIZE);
    assert_eq!(
        second.x,
        4.0 * 0.75 * SIZE,
        "the replaced font's width stuck"
    );
    assert_eq!(glyph_run(&list).0.id(), wide.id());

    for name in [
        "",
        "bitmap",
        "Atkinson Hyperlegible",
        "Sans-Serif",
        "serif",
        "inherit",
    ] {
        assert_eq!(
            ui.register_font(name, wide),
            Err(ReservedFamilyName(name.to_owned())),
            "`{name}` was registered"
        );
    }
}

/// **A span's glyph run emitted into a scaled list is the same run in window
/// pixels**: its origin, its size and every pen offset times the scale, the
/// glyphs and the text as they were — so the run is rasterised at the scaled
/// size, not stretched from the logical one.
#[test]
fn a_tree_glyph_run_scales_its_origin_size_and_pen_offsets() {
    let css = ".s { font-family: sans-serif; }";
    let mut ui = Ui::new();
    let (_, logical) = span_in(&mut ui, css, ".s");
    let mut scaled = DrawList::new();
    scaled.set_scale(1.5);
    ui.emit(&mut scaled);

    let run = |list: &DrawList| {
        list.commands()
            .iter()
            .find_map(|command| match command {
                DrawCommand::Glyphs {
                    origin,
                    size,
                    glyphs,
                    text,
                    ..
                } => Some((*origin, *size, glyphs.clone(), text.clone())),
                _ => None,
            })
            .expect("the span draws a glyph run")
    };
    let (origin, size, glyphs, text) = run(&logical);
    let (scaled_origin, scaled_size, scaled_glyphs, scaled_text) = run(&scaled);
    assert_eq!(scaled_origin, origin * 1.5);
    assert_eq!(scaled_size, size * 1.5);
    assert_eq!(scaled_text, text);
    assert_eq!(scaled_glyphs.len(), glyphs.len());
    for (scaled, glyph) in scaled_glyphs.iter().zip(&glyphs) {
        assert_eq!(scaled.glyph, glyph.glyph);
        assert_eq!(scaled.offset, glyph.offset * 1.5);
    }
    assert!(
        glyphs.iter().any(|glyph| glyph.offset.x > 0.0),
        "every pen at zero would pass a missing offset scale"
    );
}

/// A face of the [`fixed_pitch`] metrics, `advance` thousandths of an em wide.
fn face(advance: f32, weight: f32, italic: bool) -> &'static Font {
    Font::fixed_pitch_face(
        FontMetrics {
            units_per_em: 1000,
            ascent: 800.0,
            descent: -200.0,
            line_gap: 0.0,
        },
        advance,
        weight,
        italic,
    )
}

/// **A span draws in the face of its family that its weight and style
/// select**: a bold face registered beside a regular one is a second face,
/// not a replacement; a weight between them goes where CSS's rule sends it;
/// and an italic the family has no face for is the chosen face sheared, not
/// the regular one.
#[test]
fn a_span_draws_in_the_face_its_weight_and_style_select() {
    let regular = face(400.0, 400.0, false);
    let bold = face(600.0, 700.0, false);
    let italic = Synthesis {
        bold: false,
        italic: true,
    };
    let css = r"
        .a { font-family: family; }
        .bold { font-weight: bold; }
        .semibold { font-weight: 600; }
        .light { font-weight: 300; }
        .italic { font-style: italic; }
    ";
    let cases = [
        (".a", regular.clone(), 0.4),
        (".a.bold", bold.clone(), 0.6),
        // Above 500, up first: 700 before 400.
        (".a.semibold", bold.clone(), 0.6),
        // Below 400, down first and then up: nothing below, so 400.
        (".a.light", regular.clone(), 0.4),
        (".a.italic", regular.synthesized(italic), 0.4),
        (".a.bold.italic", bold.synthesized(italic), 0.6),
    ];
    for (class, want, em) in cases {
        let mut ui = Ui::new();
        ui.register_font("family", regular).expect("not reserved");
        ui.register_font("FAMILY", bold).expect("not reserved");
        let (size, list) = span_in(&mut ui, css, class);
        assert_eq!(glyph_run(&list).0, want, "{class} drew in the wrong face");
        assert_eq!(
            size.x,
            4.0 * em * SIZE,
            "{class} measured in the wrong face"
        );
    }
}

/// **A built-in parsed family with no bold or italic face is synthesised**,
/// inherited from a block, and measured wider by the bold's advance; **the
/// bitmap font ignores both**, measuring and drawing as it always did.
#[test]
fn a_family_without_the_face_is_synthesised_and_the_bitmap_font_ignores_it() {
    let mut ui = Ui::new();
    ui.add_stylesheet(
        "fonts.css",
        ".column { font-weight: 700; font-style: italic; } .sans { font-family: sans-serif; } \
         .bitmap { font-family: bitmap; }",
    );
    let mut keys = None;
    frame(&mut ui, idle(), |ui| {
        let plain = ui.span(".sans", TEXT, &[Declaration::FontSize(SIZE)]).key;
        let (mut sans, mut bitmap) = (plain, plain);
        ui.block(".column", &[], |ui| {
            sans = ui.span(".sans", TEXT, &[Declaration::FontSize(SIZE)]).key;
            bitmap = ui.span(".bitmap", TEXT, &[Declaration::FontSize(SIZE)]).key;
        });
        let flat = ui.span(".bitmap", TEXT, &[Declaration::FontSize(SIZE)]).key;
        keys = Some((plain, sans, bitmap, flat));
    });
    let (plain, sans, bitmap, flat) = keys.expect("built");
    let width = |key| {
        let (min, max) = ui.rect(key).expect("laid out");
        (max - min).x
    };
    let mut list = DrawList::new();
    ui.emit(&mut list);
    let fonts: Vec<Font> = list
        .commands()
        .iter()
        .filter_map(|command| match command {
            DrawCommand::Glyphs { font, .. } => Some(font.clone()),
            _ => None,
        })
        .collect();
    let both = Synthesis {
        bold: true,
        italic: true,
    };
    assert_eq!(
        fonts,
        [Font::sans().clone(), Font::sans().synthesized(both)],
        "the inherited weight and style did not synthesise the committed face"
    );
    let units = f32::from(Font::sans().metrics().units_per_em);
    let widened =
        TEXT.len() as f32 * units * SYNTHETIC_BOLD_EM * Font::sans().metrics().scale(SIZE);
    assert!(
        (width(sans) - width(plain) - widened).abs() <= 1.0,
        "the bold measured {} wider rather than {widened}",
        width(sans) - width(plain)
    );
    assert_eq!(
        width(bitmap),
        width(flat),
        "the bitmap font took the weight"
    );
    let texts = list
        .commands()
        .iter()
        .filter(|command| matches!(command, DrawCommand::Text { .. }))
        .count();
    assert_eq!(texts, 2, "a bitmap span stopped drawing as bitmap text");
}