Skip to main content

alpha2_layout/
fit.rs

1//! Fitting a text's font size to its box, shared by text styles and layout texts.
2
3use alpha2_model::{FONT_SIZE_FIT_STEPS, FontSizeFit};
4use alpha2_text::{ShapedText, TextClamp};
5
6use crate::text::MAX_FONT_PIXELS;
7
8/// The font size a text draws at.
9#[derive(Copy, Clone, Debug, PartialEq)]
10pub struct FittedSize {
11    /// As a fraction of the picture's shorter side.
12    pub font_size: f32,
13    /// In pixels, clamped to what the text host draws.
14    pub font_pixels: f32,
15}
16
17/// The pixel size of a font `font_size` of a picture's shorter side of `unit` pixels.
18pub(crate) fn pixels(font_size: f32, unit: f32) -> f32 {
19    (font_size * unit).clamp(1.0, MAX_FONT_PIXELS)
20}
21
22/// The largest candidate size in `fit`'s range at which `fits` holds, else its `min`. Without
23/// a fit it is `base`. See [`FontSizeFit`] for the candidates.
24///
25/// Bisection compares only exact multiples of `1 / FONT_SIZE_FIT_STEPS`, so the sizes tried,
26/// and the size found, are the same on every platform.
27///
28/// # Errors
29/// Returns the first error of `fits`.
30#[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)]
31pub(crate) fn fit_font_size<E>(
32    base: f32,
33    fit: Option<FontSizeFit>,
34    unit: f32,
35    mut fits: impl FnMut(f32) -> Result<bool, E>,
36) -> Result<FittedSize, E> {
37    let size = |font_size: f32| FittedSize {
38        font_size,
39        font_pixels: pixels(font_size, unit),
40    };
41    let Some(fit) = fit else {
42        return Ok(size(base));
43    };
44    let low = fit.min;
45    let high = fit.max.unwrap_or(base).max(low);
46    if fits(pixels(high, unit))? {
47        return Ok(size(high));
48    }
49    if low >= high || !fits(pixels(low, unit))? {
50        return Ok(size(low));
51    }
52    // Index 0 is `low`, which fits, and the last is `high`, which does not.
53    let first = (low * FONT_SIZE_FIT_STEPS).floor() as i64 + 1;
54    let last = (high * FONT_SIZE_FIT_STEPS).ceil() as i64 - 1;
55    let candidate = |index: i64| {
56        if index == 0 {
57            low
58        } else {
59            (first + index - 1) as f32 / FONT_SIZE_FIT_STEPS
60        }
61    };
62    let (mut fitting, mut over) = (0_i64, (last - first + 1).max(0) + 1);
63    while over - fitting > 1 {
64        let middle = fitting + (over - fitting) / 2;
65        if fits(pixels(candidate(middle), unit))? {
66            fitting = middle;
67        } else {
68            over = middle;
69        }
70    }
71    Ok(size(candidate(fitting)))
72}
73
74/// Lines of `shaped` in a box `max_width` by `max_height` pixels (non-positive for none).
75#[derive(Copy, Clone, Debug, PartialEq)]
76pub(crate) struct BoxedLines {
77    /// The lines drawn, cut at the clamp point when `clamp`.
78    pub lines: alpha2_text::LineMetrics,
79    /// Whether the clamp discarded lines.
80    pub truncated: bool,
81    /// Whether the drawn lines split a word or are taller than the box.
82    pub overflow: bool,
83    /// Whether every line fits the box uncut, within `max_lines`, the height and the width.
84    pub fits: bool,
85}
86
87/// How `shaped` lies in its box, cut by `clamp` when it has one. `max_lines` also counts for
88/// [`BoxedLines::fits`] when there is no clamp.
89pub(crate) fn boxed_lines(
90    shaped: &ShapedText,
91    max_width: f32,
92    max_height: f32,
93    max_lines: Option<u32>,
94    clamp: bool,
95) -> BoxedLines {
96    let limit = shaped.line_limit(max_lines, max_height);
97    let cut = shaped.lines_within(max_width, limit);
98    let drawn = if clamp {
99        cut
100    } else {
101        shaped.lines_within(max_width, None)
102    };
103    let taller = |height: f32| max_height > 0.0 && height > max_height;
104    BoxedLines {
105        lines: drawn.lines,
106        truncated: drawn.truncated,
107        overflow: drawn.splits_word || taller(drawn.lines.height),
108        fits: !cut.truncated && !cut.splits_word && !taller(cut.lines.height),
109    }
110}
111
112/// A text host clamp for `clamp` in a box `max_height` pixels tall (non-positive for none).
113pub(crate) fn text_clamp(clamp: &alpha2_model::LineClamp, max_height: f32) -> TextClamp {
114    TextClamp {
115        max_lines: clamp.max_lines,
116        max_height,
117        ellipsis: clamp.block_ellipsis.text().map(str::to_owned),
118    }
119}
120
121#[cfg(test)]
122#[path = "fit_tests.rs"]
123mod tests;