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