teksilo-text 0.28.1

Text backend for Teksilo — shaping, line breaking and glyph rasterization via text-typeset.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! Non-destructive per-editor default typography.
//!
//! [`EditorTypographyDefaults`] lets a host widget give a `RichTextEditor` a
//! *default* font family, line height, and first-line indent that apply only to
//! runs / blocks carrying **no explicit override** — the way a stylesheet
//! default applies until an inline style wins. These values are never written
//! back into the bound [`TextDocument`](text_document::TextDocument): they are
//! filled onto the disposable layout *snapshot* (`FlowSnapshot` / `BlockSnapshot`,
//! already detached from live document state) just before it is handed to the
//! typesetter. So they create no undo entry, never set `document.modified`, and
//! never touch a run / block the user actually authored.
//!
//! Size is deliberately **not** modelled here — preferred text size is a
//! logical font-scale on the engine
//! ([`RichTextEngine::set_font_scale`](crate::RichTextEngine::set_font_scale)),
//! not a per-run default fill. The one size filled per run is that of the
//! engine's text style
//! ([`RichTextEngine::set_text_style`](crate::RichTextEngine::set_text_style)),
//! filled after these defaults, for text the document leaves
//! unsized.

use text_document::{BlockSnapshot, FlowElementSnapshot, FlowSnapshot, FragmentContent};

/// Per-editor default typography, applied to snapshot runs / blocks that carry
/// no explicit override. Cheap to clone; a default-valued instance is a no-op
/// (see the private `needs_snapshot_fill`) so editors that never set it pay
/// nothing.
#[derive(Debug, Clone, PartialEq)]
pub struct EditorTypographyDefaults {
    /// Fallback family for text runs whose `TextFormat.font_family` is `None`.
    /// `None` keeps the typesetter's own registry default (today's behavior).
    pub font_family: Option<String>,
    /// Line-height multiplier for blocks whose `BlockFormat.line_height` is
    /// `None`. `1.0` = normal single spacing (identical to the unset path).
    pub line_height: f32,
    /// First-line indent in logical px for body blocks whose
    /// `BlockFormat.text_indent` is `None`. Not applied to headings or list
    /// items. `0.0` = no indent (identical to the unset path).
    pub first_line_indent: f32,
    /// Space above each body paragraph, in logical px, for blocks whose
    /// `BlockFormat.top_margin` is `None`. Not applied to headings or list
    /// items. `0.0` = no extra space (identical to the unset path).
    pub paragraph_spacing_before: f32,
    /// Space below each body paragraph, in logical px, for blocks whose
    /// `BlockFormat.bottom_margin` is `None`. Not applied to headings or list
    /// items. `0.0` = no extra space (identical to the unset path).
    pub paragraph_spacing_after: f32,
}

impl Default for EditorTypographyDefaults {
    fn default() -> Self {
        Self {
            font_family: None,
            line_height: 1.0,
            first_line_indent: 0.0,
            paragraph_spacing_before: 0.0,
            paragraph_spacing_after: 0.0,
        }
    }
}

/// Whether `d` would change anything if filled onto a snapshot. When `false`,
/// the engine skips cloning the snapshot entirely, so every existing consumer
/// that never sets defaults pays zero cost.
pub(crate) fn needs_snapshot_fill(d: &EditorTypographyDefaults) -> bool {
    d.font_family.is_some()
        || (d.line_height - 1.0).abs() > f32::EPSILON
        || d.first_line_indent.abs() > f32::EPSILON
        || d.paragraph_spacing_before.abs() > f32::EPSILON
        || d.paragraph_spacing_after.abs() > f32::EPSILON
}

/// Fill `d`'s defaults into every block of an owned flow snapshot, recursing
/// into tables and sub-frames. Mutates the snapshot only — never the document.
pub(crate) fn apply_to_flow(flow: &mut FlowSnapshot, d: &EditorTypographyDefaults) {
    apply_to_elements(&mut flow.elements, d);
}

fn apply_to_elements(elements: &mut [FlowElementSnapshot], d: &EditorTypographyDefaults) {
    for el in elements {
        match el {
            FlowElementSnapshot::Block(b) => apply_to_block(b, d),
            FlowElementSnapshot::Table(t) => {
                for cell in &mut t.cells {
                    for b in &mut cell.blocks {
                        apply_to_block(b, d);
                    }
                }
            }
            FlowElementSnapshot::Frame(fr) => apply_to_elements(&mut fr.elements, d),
        }
    }
}

/// Fill `d`'s defaults into one block snapshot's unset fields.
pub(crate) fn apply_to_block(block: &mut BlockSnapshot, d: &EditorTypographyDefaults) {
    if block.block_format.line_height.is_none() {
        block.block_format.line_height = Some(d.line_height);
    }
    // First-line indent + paragraph spacing are body-paragraph conventions:
    // never applied to a heading or a list item (keeps titles and bullets on
    // their own rhythm, flush with the margin).
    let is_heading = block.block_format.heading_level.unwrap_or(0) != 0;
    let is_list_item = block.list_info.is_some();
    if !is_heading && !is_list_item {
        if block.block_format.text_indent.is_none() {
            block.block_format.text_indent = Some(d.first_line_indent.round() as i32);
        }
        if block.block_format.top_margin.is_none() {
            block.block_format.top_margin = Some(d.paragraph_spacing_before.round() as i32);
        }
        if block.block_format.bottom_margin.is_none() {
            block.block_format.bottom_margin = Some(d.paragraph_spacing_after.round() as i32);
        }
    }
    if let Some(family) = &d.font_family {
        if block.fragments.is_empty() {
            // An empty paragraph has no fragment for the family default to
            // land on, so the typesetter resolved no font at all and fell
            // back to the registry's default face for the line's metrics —
            // the empty line measured in the UI font, then snapped to the
            // prose font on the first keystroke (the caret resized and every
            // block below shifted). A synthetic empty fragment carries the
            // default family so the empty line measures in the same face its
            // first character will use. Snapshot-only, like every fill here:
            // the live document and the a11y walk never see it.
            block.fragments.push(FragmentContent::Text {
                text: String::new(),
                format: text_document::TextFormat {
                    font_family: Some(family.clone()),
                    ..Default::default()
                },
                offset: 0,
                length: 0,
                element_id: 0,
                word_starts: Vec::new(),
            });
        } else {
            for frag in &mut block.fragments {
                if let FragmentContent::Text { format, .. } = frag
                    && format.font_family.is_none()
                {
                    format.font_family = Some(family.clone());
                }
            }
        }
    }
}

/// Whether [`apply_to_block_params`] would change anything.
///
/// Narrower than [`needs_snapshot_fill`] on purpose: by the time a block is
/// `BlockLayoutParams`, the indent and margin defaults have already been
/// resolved to concrete `f32`s, so only the two fields that still carry an
/// unset state can be defaulted. Checking those two avoids cloning a block on
/// the streaming hot path for a default that could not apply to it.
pub(crate) fn needs_params_fill(d: &EditorTypographyDefaults) -> bool {
    d.font_family.is_some() || (d.line_height - 1.0).abs() > f32::EPSILON
}

/// Fill `d`'s defaults into one already-converted block's unset fields.
///
/// The `BlockLayoutParams`-level counterpart of [`apply_to_block`], for the
/// streaming paths ([`RichTextEngine::append_block`] /
/// [`layout_window`](crate::RichTextEngine::layout_window)) that shape params directly
/// rather than going through a `FlowSnapshot`. Without it those paths would
/// ignore the engine's typography defaults that `layout_full` honours, and a
/// view that laid out its first screen with `layout_full` and grew with
/// `append_block` would render the two halves in different fonts.
///
/// Only `font_family` and `line_height_multiplier` are filled, because they are
/// the only fields still `Option` at this level. `text_indent` / `top_margin` /
/// `bottom_margin` were resolved during the snapshot→params conversion, so a
/// caller constructing params owns them outright — which is also what the
/// uniform-row invariant needs, since it requires them to be zero.
///
/// [`RichTextEngine::append_block`]: crate::RichTextEngine::append_block
pub(crate) fn apply_to_block_params(
    params: &mut text_typeset::layout::block::BlockLayoutParams,
    d: &EditorTypographyDefaults,
) {
    if params.line_height_multiplier.is_none() {
        params.line_height_multiplier = Some(d.line_height);
    }
    if let Some(family) = &d.font_family {
        for frag in &mut params.fragments {
            if frag.font_family.is_none() {
                frag.font_family = Some(family.clone());
            }
        }
    }
}

/// The family and size of an engine's text style
/// ([`RichTextEngine::set_text_style`](crate::RichTextEngine::set_text_style)),
/// filled onto the text that names neither, after the typography defaults: a
/// run's own format wins, then [`EditorTypographyDefaults::font_family`], then
/// this.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct BaseFont {
    pub family: String,
    /// Whole pixels, as text-typeset sizes every run: a style's `13.5` shapes
    /// at 13 in a label too.
    pub size_px: u32,
}

/// Fill `base` into every block of an owned flow snapshot, recursing into
/// tables and sub-frames. Mutates the snapshot only, never the document.
pub(crate) fn apply_base_to_flow(flow: &mut FlowSnapshot, base: &BaseFont) {
    apply_base_to_elements(&mut flow.elements, base);
}

fn apply_base_to_elements(elements: &mut [FlowElementSnapshot], base: &BaseFont) {
    for el in elements {
        match el {
            FlowElementSnapshot::Block(b) => apply_base_to_block(b, base),
            FlowElementSnapshot::Table(t) => {
                for cell in &mut t.cells {
                    for b in &mut cell.blocks {
                        apply_base_to_block(b, base);
                    }
                }
            }
            FlowElementSnapshot::Frame(fr) => apply_base_to_elements(&mut fr.elements, base),
        }
    }
}

/// Fill `base` into one block snapshot's text that names no family or size.
///
/// An empty paragraph gets an empty fragment carrying it, for the reason
/// [`apply_to_block`] gives one the default family: the empty line is measured
/// in the face and size its first character will take.
pub(crate) fn apply_base_to_block(block: &mut BlockSnapshot, base: &BaseFont) {
    if block.fragments.is_empty() {
        block.fragments.push(FragmentContent::Text {
            text: String::new(),
            format: text_document::TextFormat::default(),
            offset: 0,
            length: 0,
            element_id: 0,
            word_starts: Vec::new(),
        });
    }
    for frag in &mut block.fragments {
        if let FragmentContent::Text { format, .. } = frag {
            if format.font_family.is_none() {
                format.font_family = Some(base.family.clone());
            }
            if format.font_point_size.is_none() {
                format.font_point_size = Some(base.size_px);
            }
        }
    }
}

/// The `BlockLayoutParams`-level counterpart of [`apply_base_to_block`], for
/// the streaming paths [`apply_to_block_params`] serves.
pub(crate) fn apply_base_to_block_params(
    params: &mut text_typeset::layout::block::BlockLayoutParams,
    base: &BaseFont,
) {
    for frag in &mut params.fragments {
        if frag.image_name.is_some() {
            continue;
        }
        if frag.font_family.is_none() {
            frag.font_family = Some(base.family.clone());
        }
        if frag.font_point_size.is_none() {
            frag.font_point_size = Some(base.size_px);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use text_document::{BlockFormat, BlockSnapshot, ListInfo, ListStyle, TextFormat};

    fn block(text: &str, format: TextFormat, block_format: BlockFormat) -> BlockSnapshot {
        let len = text.chars().count();
        BlockSnapshot {
            block_id: 0,
            position: 0,
            length: len,
            text: text.to_string(),
            fragments: vec![FragmentContent::Text {
                text: text.to_string(),
                format,
                offset: 0,
                length: len,
                element_id: 0,
                word_starts: Vec::new(),
            }],
            block_format,
            list_info: None,
            parent_frame_id: None,
            table_cell: None,
            paint_highlights: Vec::new(),
        }
    }

    fn defaults() -> EditorTypographyDefaults {
        EditorTypographyDefaults {
            font_family: Some("Literata".into()),
            line_height: 1.5,
            first_line_indent: 28.0,
            paragraph_spacing_before: 12.0,
            paragraph_spacing_after: 6.0,
        }
    }

    fn frag_family(b: &BlockSnapshot) -> Option<&str> {
        let FragmentContent::Text { format, .. } = &b.fragments[0] else {
            panic!("expected text fragment");
        };
        format.font_family.as_deref()
    }

    #[test]
    fn default_is_a_noop() {
        assert!(!needs_snapshot_fill(&EditorTypographyDefaults::default()));
    }

    #[test]
    fn any_set_field_requests_fill() {
        assert!(needs_snapshot_fill(&EditorTypographyDefaults {
            font_family: Some("X".into()),
            ..Default::default()
        }));
        assert!(needs_snapshot_fill(&EditorTypographyDefaults {
            line_height: 1.5,
            ..Default::default()
        }));
        assert!(needs_snapshot_fill(&EditorTypographyDefaults {
            first_line_indent: 24.0,
            ..Default::default()
        }));
        assert!(needs_snapshot_fill(&EditorTypographyDefaults {
            paragraph_spacing_before: 10.0,
            ..Default::default()
        }));
    }

    #[test]
    fn fills_unset_body_block() {
        let mut b = block("Hello", TextFormat::default(), BlockFormat::default());
        apply_to_block(&mut b, &defaults());
        assert_eq!(b.block_format.line_height, Some(1.5));
        assert_eq!(b.block_format.text_indent, Some(28));
        assert_eq!(b.block_format.top_margin, Some(12));
        assert_eq!(b.block_format.bottom_margin, Some(6));
        assert_eq!(frag_family(&b), Some("Literata"));
    }

    #[test]
    fn does_not_override_explicit_values() {
        let block_format = BlockFormat {
            line_height: Some(2.0),
            text_indent: Some(4),
            top_margin: Some(3),
            bottom_margin: Some(5),
            ..Default::default()
        };
        let format = TextFormat {
            font_family: Some("Courier".into()),
            ..Default::default()
        };
        let mut b = block("Hi", format, block_format);
        apply_to_block(&mut b, &defaults());
        assert_eq!(b.block_format.line_height, Some(2.0));
        assert_eq!(b.block_format.text_indent, Some(4));
        assert_eq!(b.block_format.top_margin, Some(3));
        assert_eq!(b.block_format.bottom_margin, Some(5));
        assert_eq!(frag_family(&b), Some("Courier"));
    }

    #[test]
    fn heading_gets_leading_and_font_but_not_indent() {
        let block_format = BlockFormat {
            heading_level: Some(1),
            ..Default::default()
        };
        let mut b = block("Title", TextFormat::default(), block_format);
        apply_to_block(&mut b, &defaults());
        assert_eq!(b.block_format.line_height, Some(1.5));
        assert_eq!(
            b.block_format.text_indent, None,
            "headings must not be first-line indented"
        );
        assert_eq!(
            b.block_format.top_margin, None,
            "headings must not get body paragraph spacing"
        );
        assert_eq!(frag_family(&b), Some("Literata"));
    }

    #[test]
    fn an_empty_block_gets_a_synthetic_fragment_carrying_the_default_family() {
        let mut b = block("", TextFormat::default(), BlockFormat::default());
        b.fragments.clear();
        apply_to_block(&mut b, &defaults());
        assert_eq!(
            b.fragments.len(),
            1,
            "a fragment-less block must gain one synthetic fragment, or the \
             typesetter measures its empty line in the registry default face \
             and the line resizes on the first keystroke"
        );
        let FragmentContent::Text {
            text,
            format,
            length,
            ..
        } = &b.fragments[0]
        else {
            panic!("expected a text fragment");
        };
        assert!(text.is_empty());
        assert_eq!(*length, 0);
        assert_eq!(format.font_family.as_deref(), Some("Literata"));
    }

    #[test]
    fn no_family_default_synthesizes_no_fragment() {
        let mut b = block("", TextFormat::default(), BlockFormat::default());
        b.fragments.clear();
        let d = EditorTypographyDefaults {
            first_line_indent: 28.0,
            ..Default::default()
        };
        apply_to_block(&mut b, &d);
        assert!(
            b.fragments.is_empty(),
            "without a family default the synthetic fragment would change \
             nothing — the fill must stay a no-op"
        );
    }

    #[test]
    fn a_block_with_fragments_gains_no_synthetic_one() {
        let mut b = block("Hello", TextFormat::default(), BlockFormat::default());
        apply_to_block(&mut b, &defaults());
        assert_eq!(b.fragments.len(), 1);
    }

    #[test]
    fn list_item_is_not_indented() {
        let mut b = block("Item", TextFormat::default(), BlockFormat::default());
        b.list_info = Some(ListInfo {
            list_id: 1,
            style: ListStyle::Disc,
            indent: 0,
            marker: "•".into(),
            item_index: 0,
        });
        apply_to_block(&mut b, &defaults());
        assert_eq!(
            b.block_format.text_indent, None,
            "list items must not be first-line indented"
        );
        assert_eq!(b.block_format.line_height, Some(1.5));
    }

    fn base() -> BaseFont {
        BaseFont {
            family: "Noto Sans".into(),
            size_px: 13,
        }
    }

    fn frag_size(b: &BlockSnapshot) -> Option<u32> {
        let FragmentContent::Text { format, .. } = &b.fragments[0] else {
            panic!("expected text fragment");
        };
        format.font_point_size
    }

    #[test]
    fn a_base_font_fills_what_the_run_leaves_unnamed() {
        let mut b = block("Hello", TextFormat::default(), BlockFormat::default());
        apply_base_to_block(&mut b, &base());
        assert_eq!(frag_family(&b), Some("Noto Sans"));
        assert_eq!(frag_size(&b), Some(13));
    }

    #[test]
    fn a_run_keeps_the_family_and_size_it_names() {
        let named = TextFormat {
            font_family: Some("Literata".into()),
            font_point_size: Some(30),
            ..Default::default()
        };
        let mut b = block("Hello", named, BlockFormat::default());
        apply_base_to_block(&mut b, &base());
        assert_eq!(frag_family(&b), Some("Literata"));
        assert_eq!(frag_size(&b), Some(30));
    }

    #[test]
    fn the_typography_defaults_family_comes_before_the_base_font() {
        let mut b = block("Hello", TextFormat::default(), BlockFormat::default());
        apply_to_block(&mut b, &defaults());
        apply_base_to_block(&mut b, &base());
        assert_eq!(frag_family(&b), Some("Literata"));
        assert_eq!(frag_size(&b), Some(13));
    }

    #[test]
    fn an_empty_block_measures_in_the_base_font() {
        let mut b = block("", TextFormat::default(), BlockFormat::default());
        b.fragments.clear();
        apply_base_to_block(&mut b, &base());
        assert_eq!(b.fragments.len(), 1);
        assert_eq!(frag_family(&b), Some("Noto Sans"));
        assert_eq!(frag_size(&b), Some(13));
    }
}