slate-text 1.0.1

Native text shaping and rasterization for the slate-framework UI framework
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
//! Tests for byte-aware multi-line layout (`shape_document` / `wrap_document`).
//!
//! The mock backend below sets each glyph's `cluster` to the source byte offset
//! of its character (real backends do the same via the HarfBuzz convention), so
//! the over-wide-word grapheme break can be verified by byte offset.

use std::cell::Cell;

use slate_text::error::TextError;
use slate_text::font_handle::FontHandle;
use slate_text::types::{
    FontDescriptor, FontId, FontMetrics, GlyphBitmap, GlyphBounds, ShapedGlyph, ShapedLine,
};
use slate_text::{Font, TextBackend, shape_document, shape_words, wrap_document};

// ── Mock font/backend ────────────────────────────────────────────────────────

struct MockFont {
    handle: FontHandle,
    metrics: FontMetrics,
}

impl Font for MockFont {
    fn handle(&self) -> FontHandle {
        self.handle
    }
    fn metrics(&self) -> FontMetrics {
        self.metrics
    }
    fn size_lpx(&self) -> f32 {
        16.0
    }
    fn scale(&self) -> f32 {
        1.0
    }
}

/// Non-space char = 10 lpx, space = 5 lpx. `cluster` = byte offset of the char
/// in the shaped string; `line_height = 12 - (-4) + 2 = 18`.
struct MockBackend;

impl MockBackend {
    fn font() -> MockFont {
        MockFont {
            handle: FontHandle::from_face_id(0x1000, 16.0, 1.0),
            metrics: FontMetrics {
                ascent_lpx: 12.0,
                descent_lpx: -4.0,
                line_gap_lpx: 2.0,
                x_height_lpx: 8.0,
                cap_height_lpx: 10.0,
                units_per_em: 2048,
            },
        }
    }
}

fn shape_line_impl(font: &MockFont, text: &str) -> ShapedLine {
    let mut pen = 0.0f32;
    let mut byte = 0usize;
    let glyphs: Vec<ShapedGlyph> = text
        .chars()
        .map(|c| {
            let advance = if c == ' ' { 5.0 } else { 10.0 };
            let g = ShapedGlyph {
                glyph_id: byte as u32,
                font_id: FontId::PRIMARY,
                font_handle: Default::default(),
                x_advance_lpx: advance,
                position_lpx: [pen, 0.0],
                cluster: byte as u32,
                direction: slate_text::Direction::Ltr,
            };
            pen += advance;
            byte += c.len_utf8();
            g
        })
        .collect();
    let width: f32 = glyphs.iter().map(|g| g.x_advance_lpx).sum();
    ShapedLine {
        glyphs,
        width_lpx: width,
        ascent_lpx: font.metrics.ascent_lpx,
        descent_lpx: font.metrics.descent_lpx,
        y_offset_lpx: 0.0,
        base_direction: slate_text::Direction::Ltr,
        runs: Vec::new(),
    }
}

impl TextBackend for MockBackend {
    type Font = MockFont;

    fn load_font(&mut self, _f: &str, _s: f32, _sc: f32) -> Result<Self::Font, TextError> {
        Ok(MockBackend::font())
    }
    fn load_font_from_bytes(
        &mut self,
        _b: &'static [u8],
        _s: f32,
        _sc: f32,
    ) -> Result<Self::Font, TextError> {
        Ok(MockBackend::font())
    }
    fn shape_line(&self, font: &Self::Font, text: &str) -> Result<ShapedLine, TextError> {
        Ok(shape_line_impl(font, text))
    }
    fn rasterize_glyph(&self, _f: &Self::Font, _g: u32, _v: u8) -> Result<GlyphBitmap, TextError> {
        Ok(GlyphBitmap {
            width: 8,
            height: 12,
            bearing_x_lpx: 1.0,
            bearing_y_lpx: 10.0,
            advance_x_lpx: 10.0,
            alpha: vec![0xFF; 96],
        })
    }
    fn glyph_raster_bounds(&self, _f: &Self::Font, _g: u32) -> Result<GlyphBounds, TextError> {
        Ok(GlyphBounds {
            width: 8,
            height: 12,
        })
    }
    fn enumerate_system_fonts(&self) -> Result<Vec<FontDescriptor>, TextError> {
        Ok(vec![])
    }
}

/// `shape_line`-counting backend (interior mutability) to prove re-fit shapes
/// nothing.
struct CountingBackend {
    calls: Cell<usize>,
}

impl TextBackend for CountingBackend {
    type Font = MockFont;
    fn load_font(&mut self, _f: &str, _s: f32, _sc: f32) -> Result<Self::Font, TextError> {
        Ok(MockBackend::font())
    }
    fn load_font_from_bytes(
        &mut self,
        _b: &'static [u8],
        _s: f32,
        _sc: f32,
    ) -> Result<Self::Font, TextError> {
        Ok(MockBackend::font())
    }
    fn shape_line(&self, font: &Self::Font, text: &str) -> Result<ShapedLine, TextError> {
        self.calls.set(self.calls.get() + 1);
        Ok(shape_line_impl(font, text))
    }
    fn rasterize_glyph(&self, _f: &Self::Font, _g: u32, _v: u8) -> Result<GlyphBitmap, TextError> {
        Ok(GlyphBitmap {
            width: 8,
            height: 12,
            bearing_x_lpx: 1.0,
            bearing_y_lpx: 10.0,
            advance_x_lpx: 10.0,
            alpha: vec![0xFF; 96],
        })
    }
    fn glyph_raster_bounds(&self, _f: &Self::Font, _g: u32) -> Result<GlyphBounds, TextError> {
        Ok(GlyphBounds {
            width: 8,
            height: 12,
        })
    }
    fn enumerate_system_fonts(&self) -> Result<Vec<FontDescriptor>, TextError> {
        Ok(vec![])
    }
}

const LINE_HEIGHT: f32 = 18.0;

// ── Test 1: shape_words populates source_byte_range ───────────────────────────

#[test]
fn shape_words_records_source_byte_ranges() {
    let mut backend = MockBackend;
    let font = backend.load_font("mock", 16.0, 1.0).unwrap();

    // ASCII: the inter-word space is now its own preserved item (word,
    // space-run, word) rather than a collapsed implicit gap.
    let (items, _) = shape_words(&backend, &font, "ab cd").unwrap();
    assert_eq!(items.len(), 3);
    assert_eq!(items[0].source_byte_range, 0..2);
    assert!(!items[0].is_space_run);
    assert!(items[1].is_space_run);
    assert_eq!(items[1].source_byte_range, 2..3);
    assert_eq!(items[2].source_byte_range, 3..5);
    assert!(!items[2].is_space_run);

    // CJK (3 bytes each): text words flank a space run.
    let (items, _) = shape_words(&backend, &font, "你 好").unwrap();
    assert_eq!(items[0].source_byte_range, 0..3);
    assert_eq!(items[2].source_byte_range, 4..7);

    // Emoji (4 bytes).
    let (items, _) = shape_words(&backend, &font, "😀 x").unwrap();
    assert_eq!(items[0].source_byte_range, 0..4);
    assert_eq!(items[2].source_byte_range, 5..6);
}

// ── Test 2: byte-aware wrap → contiguous ranges covering 0..len ───────────────

#[test]
fn wrap_yields_contiguous_byte_ranges() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "aa bb cc"; // each word 20 lpx, space 5
    let doc = shape_document(&backend, &font, text).unwrap();

    // width 50: "aa bb" (45) fits, +cc would be 70 → 2 lines.
    let layout = wrap_document(&doc, 50.0);
    assert_eq!(layout.lines.len(), 2);
    assert_eq!(layout.lines[0].byte_start, 0);
    assert_eq!(layout.lines[0].byte_end, 6); // "aa bb " incl joining space
    assert_eq!(layout.lines[1].byte_start, 6);
    assert_eq!(layout.lines[1].byte_end, text.len()); // 8

    // Contiguous + full coverage.
    assert_eq!(layout.lines[0].byte_end, layout.lines[1].byte_start);
    assert_eq!(layout.lines[0].byte_start, 0);
    assert_eq!(layout.lines.last().unwrap().byte_end, text.len());
}

// ── Test 3: hard newline + empty paragraph ────────────────────────────────────

#[test]
fn hard_newline_splits_lines() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let doc = shape_document(&backend, &font, "a\nb").unwrap();
    let layout = wrap_document(&doc, 1000.0);

    assert_eq!(layout.lines.len(), 2);
    assert_eq!(layout.lines[0].byte_start, 0);
    assert_eq!(layout.lines[0].byte_end, 2); // "a" + folded '\n'
    assert_eq!(layout.lines[1].byte_start, 2);
    assert_eq!(layout.lines[1].byte_end, 3);
    assert_eq!(layout.lines[0].line.y_offset_lpx, 0.0);
    assert_eq!(layout.lines[1].line.y_offset_lpx, LINE_HEIGHT);
}

#[test]
fn empty_paragraph_is_full_height_blank_line() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "a\n\nb"; // bytes: a=0 \n=1 \n=2 b=3
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 1000.0);

    assert_eq!(layout.lines.len(), 3);
    // Middle line is the empty paragraph: zero glyphs but full line height.
    assert!(layout.lines[1].line.glyphs.is_empty());
    assert_eq!(layout.lines[1].byte_start, 2);
    assert_eq!(layout.lines[1].byte_end, 3);
    // Cumulative y is monotonic.
    assert!(layout.lines[0].line.y_offset_lpx < layout.lines[1].line.y_offset_lpx);
    assert!(layout.lines[1].line.y_offset_lpx < layout.lines[2].line.y_offset_lpx);
    // Coverage is gap-free and total.
    assert_eq!(layout.lines[0].byte_start, 0);
    assert_eq!(layout.lines.last().unwrap().byte_end, text.len());
}

// ── Test 4: auto-height ───────────────────────────────────────────────────────

#[test]
fn total_height_is_sum_of_line_heights() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let doc = shape_document(&backend, &font, "aa bb cc").unwrap();
    let layout = wrap_document(&doc, 50.0); // 2 lines

    assert_eq!(layout.line_height_lpx, LINE_HEIGHT);
    assert_eq!(
        layout.total_height_lpx,
        layout.lines.len() as f32 * LINE_HEIGHT
    );
    assert_eq!(layout.total_height_lpx, 2.0 * LINE_HEIGHT);
}

// ── Test 5: re-wrap does zero re-shaping ──────────────────────────────────────

#[test]
fn rewrap_at_new_width_does_no_reshaping() {
    let backend = CountingBackend {
        calls: Cell::new(0),
    };
    let font = MockBackend::font();

    let doc = shape_document(&backend, &font, "Hello world test again").unwrap();
    let after_shape = backend.calls.get();
    assert!(after_shape > 0, "shaping should call shape_line");

    let lines_a = wrap_document(&doc, 80.0);
    assert_eq!(
        backend.calls.get(),
        after_shape,
        "first wrap must add zero shape_line calls"
    );

    let lines_b = wrap_document(&doc, 40.0);
    assert_eq!(
        backend.calls.get(),
        after_shape,
        "re-wrap at a new width must add zero shape_line calls"
    );

    assert!(lines_b.lines.len() >= lines_a.lines.len());
}

// ── Multi-space shaping (ASCII space preserved) ───────────────────────────────

#[test]
fn multi_space_run_contributes_to_line_width() {
    let backend = MockBackend;
    let font = MockBackend::font();
    // "a     b": a=10, 5 spaces=25, b=10 → 45 lpx all on one wide line.
    let doc = shape_document(&backend, &font, "a     b").unwrap();
    let layout = wrap_document(&doc, 1000.0);
    assert_eq!(layout.lines.len(), 1);
    assert!(
        (layout.lines[0].line.width_lpx - 45.0).abs() < 0.01,
        "width should include all 5 spaces: {}",
        layout.lines[0].line.width_lpx
    );
}

#[test]
fn multi_space_wraps_at_run_boundary_and_absorbs_trailing() {
    let backend = MockBackend;
    let font = MockBackend::font();
    // "aaaa     bbbb": aaaa=40, 5 spaces=25, bbbb=40. width 60 fits aaaa but
    // not aaaa+run+bbbb → wrap at the run; trailing spaces absorbed (line0
    // stays 40 wide, bbbb starts at x0 on line1).
    let text = "aaaa     bbbb";
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 60.0);
    assert_eq!(layout.lines.len(), 2);
    assert!(
        (layout.lines[0].line.width_lpx - 40.0).abs() < 0.01,
        "line0 must not count absorbed trailing spaces: {}",
        layout.lines[0].line.width_lpx
    );
    assert!(
        (layout.lines[1].line.width_lpx - 40.0).abs() < 0.01,
        "line1 (bbbb) must start at x0, no leading spaces: {}",
        layout.lines[1].line.width_lpx
    );
    // Coverage stays contiguous and total; absorbed spaces fold into line0.
    assert_eq!(layout.lines[0].byte_start, 0);
    assert_eq!(layout.lines[0].byte_end, layout.lines[1].byte_start);
    assert_eq!(layout.lines.last().unwrap().byte_end, text.len());
}

#[test]
fn caret_advances_by_space_width_through_run() {
    let backend = MockBackend;
    let font = MockBackend::font();
    // "a     b": byte 0=a, bytes 1..6 = spaces, byte 6 = b. Space = 5 lpx.
    let doc = shape_document(&backend, &font, "a     b").unwrap();
    let layout = wrap_document(&doc, 1000.0);
    // After 'a' (byte 1): x = 10.
    assert_eq!(layout.caret_position(1), (0, 10.0, 0.0));
    // Each space byte advances by 5.
    assert_eq!(layout.caret_position(2), (0, 15.0, 0.0));
    assert_eq!(layout.caret_position(3), (0, 20.0, 0.0));
    assert_eq!(layout.caret_position(4), (0, 25.0, 0.0));
    assert_eq!(layout.caret_position(5), (0, 30.0, 0.0));
    assert_eq!(layout.caret_position(6), (0, 35.0, 0.0));
    // After 'b': x = 45.
    assert_eq!(layout.caret_position(7), (0, 45.0, 0.0));
}

#[test]
fn byte_at_line_x_inside_space_run() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "a     b";
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 1000.0);
    // x in the middle of the 2nd space (pen 15..20, mid 17.5) → byte 3.
    assert_eq!(layout.byte_at_line_x(text, 0, 18.0), 3);
    // x just past 'a' leading edge of first space → byte 1.
    assert_eq!(layout.byte_at_line_x(text, 0, 11.0), 1);
}

#[test]
fn pure_leading_whitespace_is_addressable() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "     "; // 5 spaces, no words.
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 1000.0);
    assert_eq!(layout.lines.len(), 1);
    assert!((layout.lines[0].line.width_lpx - 25.0).abs() < 0.01);
    // Every space byte is caret-addressable.
    assert_eq!(layout.caret_position(0), (0, 0.0, 0.0));
    assert_eq!(layout.caret_position(3), (0, 15.0, 0.0));
    assert_eq!(layout.caret_position(5), (0, 25.0, 0.0));
}

// ── Test 6: over-width word breaks at grapheme boundaries ─────────────────────

#[test]
fn over_width_word_breaks_at_grapheme_boundaries() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "aaaaa"; // one 50-lpx word
    let doc = shape_document(&backend, &font, text).unwrap();

    // max_width 25: 2 chars (20) fit, a 3rd (30) overflows → break.
    let layout = wrap_document(&doc, 25.0);
    assert!(
        layout.lines.len() >= 2,
        "over-wide word must break into >=2 lines"
    );
    for line in &layout.lines {
        assert!(
            line.line.width_lpx <= 25.0,
            "no broken piece may exceed max_width: {}",
            line.line.width_lpx
        );
    }
    // Byte ranges stay contiguous and cover the whole word.
    assert_eq!(layout.lines[0].byte_start, 0);
    assert_eq!(layout.lines.last().unwrap().byte_end, text.len());
    for w in layout.lines.windows(2) {
        assert_eq!(w[0].byte_end, w[1].byte_start);
    }
}

// ── Test 7: caret-at-boundary resolves to next line ───────────────────────────

#[test]
fn line_for_byte_at_wrap_boundary_picks_next_line() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "aa bb cc";
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 50.0); // line0 [0,6), line1 [6,8)

    assert_eq!(layout.line_for_byte(0), 0);
    assert_eq!(layout.line_for_byte(5), 0);
    // Byte 6 is the end of line 0 AND start of line 1 → resolves to line 1.
    assert_eq!(layout.line_for_byte(6), 1);
    // Document end resolves to the final line.
    assert_eq!(layout.line_for_byte(8), 1);
}

// ── Mandatory breaks + CRLF normalization (caret-precise) ─────────────────────

#[test]
fn crlf_no_stray_glyph_and_caret_end_after_b() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "ab\r\ncd"; // bytes: a=0 b=1 \r=2 \n=3 c=4 d=5
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 1000.0);

    assert_eq!(layout.lines.len(), 2, "CRLF must hard-break into two lines");
    // No glyph is keyed to a terminator byte (2 = '\r', 3 = '\n') — the `\r` is
    // never shaped into a glyph.
    for vline in &layout.lines {
        for g in &vline.line.glyphs {
            assert!(
                g.cluster != 2 && g.cluster != 3,
                "a glyph was keyed to a CRLF terminator byte ({})",
                g.cluster
            );
        }
    }
    // Caret-addressable end of line 0 stops after 'b' (byte 2), not the `\r`.
    assert_eq!(layout.line_caret_end(text, 0), 2);
    // Coverage gap-free and total: line0 0..4 (folds "\r\n"), line1 4..6.
    assert_eq!(
        (layout.lines[0].byte_start, layout.lines[0].byte_end),
        (0, 4)
    );
    assert_eq!(
        (layout.lines[1].byte_start, layout.lines[1].byte_end),
        (4, 6)
    );
}

#[test]
fn unicode_separator_caret_end_excludes_separator() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "ab\u{2028}cd"; // U+2028 is 3 bytes (2..5)
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 1000.0);

    assert_eq!(layout.lines.len(), 2);
    assert_eq!(layout.line_caret_end(text, 0), 2); // after 'b', not the separator
    assert_eq!(layout.lines[1].byte_start, "ab\u{2028}".len());
    assert_eq!(layout.lines[1].byte_end, text.len());
}

#[test]
fn crlf_caret_roundtrip() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "ab\r\ncd";
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 1000.0);
    // Line 0 addressable bytes: 0,1,2 (end after 'b'). Line 1: 4,5,6.
    for &(line_idx, byte) in &[(0usize, 0usize), (0, 1), (0, 2), (1, 4), (1, 5), (1, 6)] {
        let (_, x, _) = layout.caret_position(byte);
        assert_eq!(
            layout.byte_at_line_x(text, line_idx, x),
            byte,
            "x={x} on line {line_idx} should map back to byte {byte}"
        );
    }
}

#[test]
fn caret_position_maps_byte_to_line_x_y() {
    let backend = MockBackend;
    let font = MockBackend::font();
    let text = "aa bb cc"; // each char 10 lpx, space 5
    let doc = shape_document(&backend, &font, text).unwrap();
    let layout = wrap_document(&doc, 50.0); // line0 "aa bb" [0,6), line1 "cc" [6,8)

    // Start of doc: line 0, x 0, y 0.
    assert_eq!(layout.caret_position(0), (0, 0.0, 0.0));
    // After "aa" (2 glyphs * 10): line 0, x 20.
    assert_eq!(layout.caret_position(2), (0, 20.0, 0.0));
    // Byte 6 is the wrap boundary → line 1 head (x 0, y = line_height).
    assert_eq!(layout.caret_position(6), (1, 0.0, LINE_HEIGHT));
    // Document end: line 1, x = "cc" width (20).
    assert_eq!(layout.caret_position(8), (1, 20.0, LINE_HEIGHT));
}