Skip to main content

alpha2_layout/
lib.rs

1//! Where alpha2 text and layout boxes lie, without a GPU.
2//!
3//! A text style or a layout generator's box tree becomes the requests the text host
4//! (`alpha2-text`) draws and the rectangles they fill. The engine draws from the same requests
5//! and rectangles, so a host without a GPU (a wasm page, the Python package) measures exactly
6//! what a render draws. [`json`] writes the measurements in the JSON form every binding
7//! returns.
8
9mod fit;
10pub mod json;
11pub mod layout;
12mod report;
13mod text;
14pub mod text_animation;
15
16use std::fmt;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19
20use alpha2_text::{TextFont, TextRasterError};
21
22pub use fit::FittedSize;
23pub use layout::{
24    LAYOUT_WRAP_SLACK, LayoutBounds, NodeBounds, NodeRects, ResolvedLayout, fit_texts,
25    layout_texts, measure_layout, resolve, shape_texts,
26};
27pub use report::{ClusterReport, LineReport, TextLayoutReport, WordReport, text_layout};
28pub use text::{
29    MAX_FONT_PIXELS, MAX_PADDING_PIXELS, MAX_STROKE_PIXELS, ShadowPixels, TextAnimation, TextAt,
30    TextBounds, TextDraw, animated_text_key, fit_text, font_pixels, layout_text_key, measure_text,
31    rgba8, shadow_pixels, shaped_key, stroke_pixels, text_draw, text_fill, text_key, text_request,
32    text_request_at, text_spans,
33};
34
35/// The size in pixels of a picture text and layouts are placed on. Never empty, and within
36/// the largest frame the engine draws ([`alpha2_media::MAX_FRAME_DIMENSION`],
37/// [`alpha2_media::MAX_FRAME_PIXELS`]).
38#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
39pub struct PictureSize {
40    width: u32,
41    height: u32,
42}
43
44/// Why a size is not a [`PictureSize`].
45#[derive(Copy, Clone, Debug, Eq, PartialEq)]
46#[non_exhaustive]
47pub enum PictureSizeError {
48    /// A side is zero.
49    Empty,
50    /// A side, or the area, is larger than any frame the engine draws.
51    TooLarge,
52}
53
54impl fmt::Display for PictureSizeError {
55    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
56        formatter.write_str(match self {
57            Self::Empty => "picture dimensions must be non-zero",
58            Self::TooLarge => "picture dimensions exceed the largest frame",
59        })
60    }
61}
62
63impl std::error::Error for PictureSizeError {}
64
65impl PictureSize {
66    /// A picture of `width` by `height` pixels.
67    ///
68    /// # Errors
69    /// Returns [`PictureSizeError`] for an empty side or a size larger than any frame.
70    pub const fn new(width: u32, height: u32) -> Result<Self, PictureSizeError> {
71        if width == 0 || height == 0 {
72            Err(PictureSizeError::Empty)
73        } else if width > alpha2_media::MAX_FRAME_DIMENSION
74            || height > alpha2_media::MAX_FRAME_DIMENSION
75            || (width as u64) * (height as u64) > alpha2_media::MAX_FRAME_PIXELS
76        {
77            Err(PictureSizeError::TooLarge)
78        } else {
79            Ok(Self { width, height })
80        }
81    }
82
83    /// Width in pixels.
84    #[must_use]
85    pub const fn width(self) -> u32 {
86        self.width
87    }
88
89    /// Height in pixels.
90    #[must_use]
91    pub const fn height(self) -> u32 {
92        self.height
93    }
94
95    /// The shorter side in pixels, which lengths (font sizes included) are fractions of.
96    #[must_use]
97    #[allow(clippy::cast_precision_loss)]
98    pub fn unit(self) -> f32 {
99        self.width.min(self.height) as f32
100    }
101}
102
103/// A rectangle as fractions of the canvas, y down.
104#[derive(Copy, Clone, Debug, PartialEq)]
105pub struct CanvasRect {
106    /// Left edge, a fraction of the canvas width.
107    pub left: f32,
108    /// Top edge, a fraction of the canvas height.
109    pub top: f32,
110    /// Right edge, a fraction of the canvas width.
111    pub right: f32,
112    /// Bottom edge, a fraction of the canvas height.
113    pub bottom: f32,
114}
115
116/// A text's first and last alphabetic baselines, as fractions of the canvas (or picture)
117/// height, y down.
118#[derive(Copy, Clone, Debug, PartialEq)]
119pub struct Baselines {
120    /// The first line's baseline.
121    pub first: f32,
122    /// The last line's baseline: the first's for one line.
123    pub last: f32,
124}
125
126/// Why a font file could not be registered ([`fonts_from_files`]).
127#[derive(Debug)]
128#[non_exhaustive]
129pub enum FontFileError {
130    /// The file could not be read.
131    Read {
132        /// The file.
133        path: PathBuf,
134        /// Why.
135        error: std::io::Error,
136    },
137    /// The file holds no face the text host draws at `face_index`.
138    Invalid {
139        /// The file.
140        path: PathBuf,
141        /// The face, counted from 0 within a collection.
142        face_index: u32,
143        /// The text host's reason.
144        error: TextRasterError,
145    },
146}
147
148impl fmt::Display for FontFileError {
149    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150        match self {
151            Self::Read { path, error } => write!(formatter, "font {}: {error}", path.display()),
152            Self::Invalid {
153                path,
154                face_index,
155                error,
156            } => write!(
157                formatter,
158                "font {} face {face_index}: {error}",
159                path.display()
160            ),
161        }
162    }
163}
164
165impl std::error::Error for FontFileError {
166    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
167        match self {
168            Self::Read { error, .. } => Some(error),
169            Self::Invalid { error, .. } => Some(error),
170        }
171    }
172}
173
174/// The faces a host registers from a list of font files, and each file's bytes.
175#[derive(Clone, Debug)]
176pub struct FontFiles {
177    /// Every face, in fallback order, sharing its file's bytes.
178    pub faces: Vec<TextFont>,
179    /// Each file's bytes, read once, in the order given.
180    pub bytes: Vec<Arc<[u8]>>,
181}
182
183/// Loads the fonts at `paths` in fallback order, as a host registers them.
184///
185/// Each file's family is its file stem. Every face of a collection is registered in order,
186/// sharing the file's bytes, so its weights can be matched. A measurement and a render given
187/// the same paths draw with the same faces.
188///
189/// # Errors
190/// Returns [`FontFileError`] naming the first file that cannot be read or holds no face the
191/// text host draws.
192pub fn fonts_from_files(paths: &[impl AsRef<Path>]) -> Result<FontFiles, FontFileError> {
193    let mut fonts = Vec::with_capacity(paths.len());
194    let mut files = Vec::with_capacity(paths.len());
195    for path in paths {
196        let path = path.as_ref();
197        let bytes: Arc<[u8]> = std::fs::read(path)
198            .map_err(|error| FontFileError::Read {
199                path: path.to_owned(),
200                error,
201            })?
202            .into();
203        let family = path
204            .file_stem()
205            .map_or_else(String::new, |stem| stem.to_string_lossy().into_owned());
206        for face_index in 0..alpha2_text::face_count(&bytes) {
207            alpha2_text::check_font(&bytes, face_index).map_err(|error| {
208                FontFileError::Invalid {
209                    path: path.to_owned(),
210                    face_index,
211                    error,
212                }
213            })?;
214            fonts.push(TextFont {
215                family: family.clone(),
216                bytes: Arc::clone(&bytes),
217                face_index,
218            });
219        }
220        files.push(bytes);
221    }
222    Ok(FontFiles {
223        faces: fonts,
224        bytes: files,
225    })
226}
227
228#[cfg(test)]
229mod tests;