cranpose-ui-graphics 0.12.0

Geometry, units, paths and render data for Cranpose UI
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
//! Typography data structures (font styles, weights, text styles)
//!
//! These are the *drawing-side* text types: the smallest description of a run
//! of text that [`crate::DrawScope`] can hand to a renderer. The full typography
//! model (annotated strings, span/paragraph styles, decorations, hyphenation)
//! lives in `cranpose-ui`, which is above this crate in the dependency graph —
//! `cranpose-ui` maps a [`DrawTextStyle`] onto that richer model, and both
//! measurement and rasterization go through that one mapping.

use crate::geometry::Size;

/// Font style (normal, italic, oblique)
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FontStyle {
    /// Upright letterforms.
    #[default]
    Normal,
    /// Slanted letterforms from the face's italic design.
    Italic,
    /// Rendered as [`FontStyle::Italic`]; no font in the stack ships a separate
    /// oblique face.
    Oblique,
}

/// Font weight (100-900)
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FontWeight(pub u16);

impl FontWeight {
    /// Thin, weight 100.
    pub const THIN: FontWeight = FontWeight(100);
    /// Extra light, weight 200.
    pub const EXTRA_LIGHT: FontWeight = FontWeight(200);
    /// Light, weight 300.
    pub const LIGHT: FontWeight = FontWeight(300);
    /// Normal, weight 400.
    pub const NORMAL: FontWeight = FontWeight(400);
    /// Medium, weight 500.
    pub const MEDIUM: FontWeight = FontWeight(500);
    /// Semi bold, weight 600.
    pub const SEMI_BOLD: FontWeight = FontWeight(600);
    /// Bold, weight 700.
    pub const BOLD: FontWeight = FontWeight(700);
    /// Extra bold, weight 800.
    pub const EXTRA_BOLD: FontWeight = FontWeight(800);
    /// Black, weight 900.
    pub const BLACK: FontWeight = FontWeight(900);

    /// Clamps to the `1..=1000` range every font backend accepts.
    pub const fn new(weight: u16) -> Self {
        if weight < 1 {
            Self(1)
        } else if weight > 1000 {
            Self(1000)
        } else {
            Self(weight)
        }
    }

    /// Returns the weight as a number from 1 to 1000.
    pub const fn value(self) -> u16 {
        self.0
    }
}

impl Default for FontWeight {
    fn default() -> Self {
        Self::NORMAL
    }
}

/// Horizontal placement of the text block inside the box it is drawn in.
///
/// This aligns the *block*, not the individual lines: every line of a
/// multi-line string starts at the block's left edge, matching how the
/// framework's `Text` composable is laid out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextAlign {
    /// The block starts at the left edge of the box.
    #[default]
    Left,
    /// The block is centered horizontally in the box.
    Center,
    /// The block ends at the right edge of the box.
    Right,
}

/// Vertical placement of the text block inside the box it is drawn in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextVerticalAlign {
    /// The text block starts at the top of the box.
    #[default]
    Top,
    /// The text block is centered vertically in the box.
    Center,
    /// The text block ends at the bottom of the box.
    Bottom,
    /// The box's **top edge** is the first line's baseline. Use this when a
    /// layout is specified in baselines rather than boxes; the text then
    /// extends above the edge by
    /// [`TextMeasurement::first_baseline`](crate::TextMeasurement::first_baseline).
    Baseline,
}

/// Where the leading — the difference between a line's box and the font's own
/// ascent-plus-descent extent — is spent.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum LineHeightAlignment {
    /// All of it below the glyphs.
    Top,
    /// Split evenly, with the odd whole pixel below the baseline.
    Center,
    #[default]
    /// Split in the font's own ascent-to-descent ratio.
    Proportional,
    /// All of it above the glyphs.
    Bottom,
}

/// Which edges of a text block give their leading back.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum LineHeightTrim {
    /// The first line gives back its leading above the glyphs.
    FirstLineTop,
    /// The last line gives back its leading below the glyphs.
    LastLineBottom,
    /// The first line gives back its leading above the glyphs and the last line below them.
    #[default]
    Both,
    /// Neither edge gives its leading back.
    None,
}

/// What a requested line height means when the font does not fit inside it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum LineHeightMode {
    /// The request wins and the glyphs overflow their box.
    #[default]
    Fixed,
    /// The font's own extent is a floor. This is what Android does.
    Minimum,
    /// The font's extent, whatever was requested.
    Tight,
}

/// How a line of text sits inside the height it was given, and what a
/// paragraph gives back at its edges.
///
/// Text is laid out by AOSP's `StaticLayout` rule, as Jetpack Compose lays it
/// out: whole-pixel metrics, the leading placed by `alignment`, and the
/// leading above the first line and below the last given back by `trim`. The
/// [`Default`] is Compose's own, which is what a style that names none gets.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LineHeightStyle {
    /// Where the leading of each line is spent.
    pub alignment: LineHeightAlignment,
    /// Which edges of the text block give their leading back.
    pub trim: LineHeightTrim,
    /// What a requested line height means when the font does not fit inside it.
    pub mode: LineHeightMode,
}

impl Default for LineHeightStyle {
    fn default() -> Self {
        Self {
            alignment: LineHeightAlignment::Proportional,
            trim: LineHeightTrim::Both,
            mode: LineHeightMode::Fixed,
        }
    }
}

/// Everything [`crate::DrawScope`] needs to measure and draw a run of text.
///
/// A style is a plain value: sizes are already in scope (logical) units, and
/// every field is resolved — there is no inheritance or theme lookup at draw
/// time. Build one once and reuse it; measurement is cached on the
/// `(text, style)` pair, so a style rebuilt with identical values still hits
/// the cache.
#[derive(Clone, Debug, PartialEq)]
pub struct DrawTextStyle {
    /// Family name to resolve against the fonts the app registered. `None`
    /// asks for the framework's default family.
    ///
    /// Only *named* families resolve: file-backed families are loaded by the
    /// app at startup and looked up by the name in their font tables.
    pub font_family: Option<String>,
    /// Size of the text, in scope units. A non-positive or non-finite value uses
    /// `DEFAULT_FONT_SIZE`.
    pub font_size: f32,
    /// Weight of the face, from 1 to 1000.
    pub font_weight: FontWeight,
    /// Normal or italic face.
    pub font_style: FontStyle,
    /// Extra advance inserted between characters, in scope units.
    pub letter_spacing: f32,
    /// Distance between consecutive baselines. `None` uses the font's natural
    /// line height.
    pub line_height: Option<f32>,
    /// How the line sits inside that height. `None` takes
    /// [`LineHeightStyle::default`], as a composed `Text` does.
    pub line_height_style: Option<LineHeightStyle>,
    /// How the text block is placed horizontally inside its box.
    pub align: TextAlign,
    /// How the text block is placed vertically inside its box.
    pub vertical_align: TextVerticalAlign,
}

impl DrawTextStyle {
    /// The size used when a style carries a non-positive or non-finite one.
    /// Matches the framework-wide text default.
    pub const DEFAULT_FONT_SIZE: f32 = 14.0;

    /// Creates a style with the given font size, in scope units, and defaults for every other
    /// field.
    pub fn new(font_size: f32) -> Self {
        Self {
            font_size,
            ..Self::default()
        }
    }

    /// Sets the font family by name. An empty name selects the framework default family.
    pub fn with_font_family(mut self, family: impl Into<String>) -> Self {
        let family = family.into();
        self.font_family = (!family.is_empty()).then_some(family);
        self
    }

    /// Sets the font size, in scope units.
    pub fn with_font_size(mut self, font_size: f32) -> Self {
        self.font_size = font_size;
        self
    }

    /// Sets the font weight.
    pub fn with_weight(mut self, weight: FontWeight) -> Self {
        self.font_weight = weight;
        self
    }

    /// Sets the font style.
    pub fn with_style(mut self, style: FontStyle) -> Self {
        self.font_style = style;
        self
    }

    /// Sets the extra advance between characters, in scope units.
    pub fn with_letter_spacing(mut self, letter_spacing: f32) -> Self {
        self.letter_spacing = letter_spacing;
        self
    }

    /// Sets the distance between baselines, in scope units. A non-finite value clears it.
    pub fn with_line_height(mut self, line_height: f32) -> Self {
        self.line_height = line_height.is_finite().then_some(line_height);
        self
    }

    /// Asks for a line-height policy other than the default one.
    pub fn with_line_height_style(mut self, line_height_style: LineHeightStyle) -> Self {
        self.line_height_style = Some(line_height_style);
        self
    }

    /// Sets how the text block is placed horizontally inside its box.
    pub fn with_align(mut self, align: TextAlign) -> Self {
        self.align = align;
        self
    }

    /// Sets how the text block is placed vertically inside its box.
    pub fn with_vertical_align(mut self, vertical_align: TextVerticalAlign) -> Self {
        self.vertical_align = vertical_align;
        self
    }

    /// The font size a measurer/rasterizer will actually use. Non-finite and
    /// non-positive sizes fall back to [`DrawTextStyle::DEFAULT_FONT_SIZE`] instead
    /// of producing NaN geometry.
    pub fn resolved_font_size(&self) -> f32 {
        if self.font_size.is_finite() && self.font_size > 0.0 {
            self.font_size
        } else {
            Self::DEFAULT_FONT_SIZE
        }
    }

    /// The letter spacing a measurer will actually use.
    pub fn resolved_letter_spacing(&self) -> f32 {
        if self.letter_spacing.is_finite() {
            self.letter_spacing
        } else {
            0.0
        }
    }

    /// The line height a measurer will actually use, given the font's natural
    /// one. `natural` is only consulted when the style leaves it unset.
    pub fn resolved_line_height(&self, natural: f32) -> f32 {
        match self.line_height {
            Some(height) if height.is_finite() && height > 0.0 => height,
            _ => natural,
        }
    }
}

impl Default for DrawTextStyle {
    fn default() -> Self {
        Self {
            font_family: None,
            font_size: Self::DEFAULT_FONT_SIZE,
            font_weight: FontWeight::NORMAL,
            font_style: FontStyle::Normal,
            letter_spacing: 0.0,
            line_height: None,
            line_height_style: None,
            align: TextAlign::Left,
            vertical_align: TextVerticalAlign::Top,
        }
    }
}

/// What a string occupies once laid out — the answer
/// [`DrawScope::measure_text`](crate::DrawScope::measure_text) gives, and
/// exactly the box `draw_text` fills.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextMeasurement {
    /// Tight block size: the widest line by its total advance, and
    /// `line_count * line_height` tall.
    pub size: Size,
    /// Baseline-to-baseline distance.
    pub line_height: f32,
    /// Distance from the top of the block down to the first line's baseline.
    /// Subtract it from a baseline y to get the top-left a `_at` draw wants.
    pub first_baseline: f32,
    /// Number of laid-out lines. `1` for an empty string.
    pub line_count: usize,
}

impl TextMeasurement {
    /// The measurement of an empty string: no extent, but still one line's
    /// worth of vertical metrics so callers can lay out an empty label.
    pub fn empty(line_height: f32, first_baseline: f32) -> Self {
        Self {
            size: Size::ZERO,
            line_height,
            first_baseline,
            line_count: 1,
        }
    }
}

/// Font-backed measurement, injected into a [`crate::DrawScopeDefault`] by the
/// UI layer.
///
/// This crate holds no fonts, so a draw scope cannot measure text on its own.
/// `cranpose-ui` installs an implementation that forwards to the very text
/// stack the `Text` composable uses, which is what keeps
/// [`DrawScope::measure_text`](crate::DrawScope::measure_text) and the glyphs
/// the renderer rasterizes in agreement. Without one installed a scope falls
/// back to [`estimate_text_measurement`], which is good enough for layout
/// smoke tests and wrong for anything that has to line up with real glyphs.
pub trait DrawTextMeasurer {
    /// Returns the size and line metrics of `text` laid out in `style`.
    fn measure_text(&self, text: &str, style: &DrawTextStyle) -> TextMeasurement;
}

/// Font-free estimate used when no [`DrawTextMeasurer`] is installed.
///
/// Assumes a 0.6 em advance per character and the 0.8/-0.2 em ascent/descent
/// split typical of a UI sans face, laid out by the default
/// [`LineHeightStyle`]: a line without a requested height is the face's own
/// 1 em, and the leading a requested one adds is split in the face's
/// proportions and given back above the first line and below the last. So the
/// shape of the result matches what a real font measurer returns even though
/// the numbers do not.
pub fn estimate_text_measurement(text: &str, style: &DrawTextStyle) -> TextMeasurement {
    const CHAR_WIDTH_RATIO: f32 = 0.6;
    const ASCENT_RATIO: f32 = 0.8;
    const NATURAL_LINE_HEIGHT_RATIO: f32 = 1.0;

    let font_size = style.resolved_font_size();
    let letter_spacing = style.resolved_letter_spacing().max(0.0);
    let natural_line_height = font_size * NATURAL_LINE_HEIGHT_RATIO;
    let line_height = style.resolved_line_height(natural_line_height);
    let leading = line_height - natural_line_height;
    let first_baseline = font_size * ASCENT_RATIO;

    if text.is_empty() {
        return TextMeasurement::empty(line_height, first_baseline);
    }

    let mut line_count = 0usize;
    let mut width = 0.0f32;
    for line in text.split('\n') {
        line_count += 1;
        let chars = line.chars().count();
        let advance = chars as f32 * (font_size * CHAR_WIDTH_RATIO + letter_spacing);
        width = width.max(advance);
    }

    TextMeasurement {
        size: Size::new(width, line_count as f32 * line_height - leading),
        line_height,
        first_baseline,
        line_count,
    }
}

#[cfg(test)]
#[path = "tests/typography_tests.rs"]
mod tests;