1use alpha2_model::{FONT_SIZE_FIT_STEPS, FontSizeFit};
4use alpha2_text::{ShapedText, TextClamp};
5
6use crate::text::MAX_FONT_PIXELS;
7
8#[derive(Copy, Clone, Debug, PartialEq)]
10pub struct FittedSize {
11 pub font_size: f32,
13 pub font_pixels: f32,
15}
16
17pub(crate) fn pixels(font_size: f32, unit: f32) -> f32 {
19 (font_size * unit).clamp(1.0, MAX_FONT_PIXELS)
20}
21
22#[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 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#[derive(Copy, Clone, Debug, PartialEq)]
76pub(crate) struct BoxedLines {
77 pub lines: alpha2_text::LineMetrics,
79 pub truncated: bool,
81 pub overflow: bool,
83 pub fits: bool,
85}
86
87pub(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
112pub(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;