Skip to main content

textflow/
workspace.rs

1use crate::bidi::{BidiError, BidiRun, BidiText};
2use crate::layout::{
3    BrokenLine, GlyphRun, LayoutBuffers, LayoutError, LayoutLine, LayoutOptions, LogicalRun,
4    LogicalRuns, ParagraphLayout, VisualRun,
5};
6use crate::shaping::{CaretStop, PositionedGlyph, ShapedGlyph, Typeface};
7use crate::TextFlow;
8use alloc::vec::Vec;
9use core::mem::size_of;
10
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub struct LayoutLimits {
13    pub text_bytes: usize,
14    pub runs: usize,
15    pub visual_runs: usize,
16    pub glyphs: usize,
17    pub scratch_glyphs: usize,
18    pub lines: usize,
19    pub carets: usize,
20}
21
22impl LayoutLimits {
23    pub fn buffer_bytes(self) -> Option<usize> {
24        let run_bytes = size_of::<BidiRun>()
25            .checked_add(size_of::<LogicalRun>())?
26            .checked_add(size_of::<GlyphRun>())?
27            .checked_mul(self.runs)?;
28        let glyph_bytes = size_of::<ShapedGlyph>()
29            .checked_add(size_of::<PositionedGlyph>())?
30            .checked_mul(self.glyphs)?;
31        run_bytes
32            .checked_add(glyph_bytes)?
33            .checked_add(size_of::<VisualRun>().checked_mul(self.visual_runs)?)?
34            .checked_add(size_of::<ShapedGlyph>().checked_mul(self.scratch_glyphs)?)?
35            .checked_add(
36                size_of::<BrokenLine>()
37                    .checked_add(size_of::<LayoutLine>())?
38                    .checked_mul(self.lines)?,
39            )?
40            .checked_add(size_of::<CaretStop>().checked_mul(self.carets)?)
41    }
42}
43
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45pub enum WorkspaceError {
46    Allocation,
47    TextLimit { required: usize, limit: usize },
48    DimensionOverflow,
49    Bidi(BidiError),
50    Layout(LayoutError),
51}
52
53impl From<BidiError> for WorkspaceError {
54    fn from(error: BidiError) -> Self {
55        Self::Bidi(error)
56    }
57}
58
59impl From<LayoutError> for WorkspaceError {
60    fn from(error: LayoutError) -> Self {
61        Self::Layout(error)
62    }
63}
64
65pub struct TextWorkspace {
66    limits: LayoutLimits,
67    bidi: Vec<BidiRun>,
68    logical: Vec<LogicalRun>,
69    initial_glyphs: Vec<ShapedGlyph>,
70    initial_runs: Vec<GlyphRun>,
71    broken: Vec<BrokenLine>,
72    scratch: Vec<ShapedGlyph>,
73    glyphs: Vec<PositionedGlyph>,
74    runs: Vec<VisualRun>,
75    lines: Vec<LayoutLine>,
76    carets: Vec<CaretStop>,
77}
78
79impl TextWorkspace {
80    pub fn try_new(limits: LayoutLimits) -> Result<Self, WorkspaceError> {
81        Ok(Self {
82            limits,
83            bidi: slots(limits.runs, BidiRun::empty())?,
84            logical: slots(limits.runs, LogicalRun::empty())?,
85            initial_glyphs: slots(limits.glyphs, ShapedGlyph::default())?,
86            initial_runs: slots(limits.runs, GlyphRun::empty())?,
87            broken: slots(limits.lines, BrokenLine::empty())?,
88            scratch: slots(limits.scratch_glyphs, ShapedGlyph::default())?,
89            glyphs: slots(limits.glyphs, PositionedGlyph::default())?,
90            runs: slots(limits.visual_runs, VisualRun::empty())?,
91            lines: slots(limits.lines, LayoutLine::empty())?,
92            carets: slots(limits.carets, CaretStop::default())?,
93        })
94    }
95
96    pub const fn limits(&self) -> LayoutLimits {
97        self.limits
98    }
99
100    pub(crate) fn layout<'workspace>(
101        &'workspace mut self,
102        flow: &TextFlow<'_>,
103        typefaces: &[&dyn Typeface],
104    ) -> Result<ParagraphLayout<'workspace>, WorkspaceError> {
105        if flow.text.len() > self.limits.text_bytes {
106            return Err(WorkspaceError::TextLimit {
107                required: flow.text.len(),
108                limit: self.limits.text_bytes,
109            });
110        }
111        let max_width =
112            i32::try_from(flow.max_width).map_err(|_| WorkspaceError::DimensionOverflow)?;
113        let line_height =
114            i32::try_from(flow.line_height).map_err(|_| WorkspaceError::DimensionOverflow)?;
115        let line_spacing =
116            i32::try_from(flow.line_spacing).map_err(|_| WorkspaceError::DimensionOverflow)?;
117        let line_advance = line_height
118            .checked_add(line_spacing)
119            .ok_or(WorkspaceError::DimensionOverflow)?;
120        let bidi = BidiText::resolve(
121            flow.text,
122            0..flow.text.len(),
123            flow.base_direction,
124            &mut self.bidi,
125        )?;
126        let logical = LogicalRuns::resolve(flow.text, &bidi, typefaces, &mut self.logical)?;
127        let shaped = logical.shape_into(
128            flow.text,
129            typefaces,
130            flow.features,
131            &mut self.initial_glyphs,
132            &mut self.initial_runs,
133        )?;
134        let broken = shaped.break_into(flow.text, max_width, &mut self.broken)?;
135        Ok(logical.layout_into(
136            flow.text,
137            typefaces,
138            flow.features,
139            &broken,
140            LayoutOptions::new(line_advance).with_origin(flow.origin),
141            LayoutBuffers::new(
142                &mut self.scratch,
143                &mut self.glyphs,
144                &mut self.runs,
145                &mut self.lines,
146                &mut self.carets,
147            ),
148        )?)
149    }
150}
151
152fn slots<T: Clone>(length: usize, value: T) -> Result<Vec<T>, WorkspaceError> {
153    let mut slots = Vec::new();
154    slots
155        .try_reserve_exact(length)
156        .map_err(|_| WorkspaceError::Allocation)?;
157    slots.resize(length, value);
158    Ok(slots)
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use crate::shaping::{
165        FlowPoint, FontAccessError, FontId, FontMetrics, GlyphId, GlyphSource, SimpleTypeface,
166    };
167
168    struct Source;
169
170    impl GlyphSource for Source {
171        fn id(&self) -> FontId {
172            FontId::new(1)
173        }
174
175        fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
176            Ok(FontMetrics::default())
177        }
178
179        fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
180            Ok(Some(GlyphId::new(character as u16)))
181        }
182
183        fn glyph_advance(&self, _glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
184            Ok(FlowPoint { x: 1, y: 0 })
185        }
186    }
187
188    fn limits() -> LayoutLimits {
189        LayoutLimits {
190            text_bytes: 16,
191            runs: 4,
192            visual_runs: 4,
193            glyphs: 8,
194            scratch_glyphs: 4,
195            lines: 4,
196            carets: 12,
197        }
198    }
199
200    #[test]
201    fn reuses_fixed_capacity_for_layout() {
202        let limits = limits();
203        assert!(limits.buffer_bytes().is_some_and(|bytes| bytes > 0));
204        let mut workspace = TextWorkspace::try_new(limits).unwrap();
205        let source = Source;
206        let typeface = SimpleTypeface::new(&source);
207        let typefaces: [&dyn Typeface; 1] = [&typeface];
208        let flow = TextFlow::new("ab cd", 3)
209            .with_line_height(10)
210            .with_line_spacing(2);
211        let layout = flow.layout(&typefaces, &mut workspace).unwrap();
212
213        assert_eq!(layout.lines().len(), 2);
214        assert_eq!(layout.glyphs().len(), 5);
215        assert_eq!(layout.lines()[1].origin().y, 12);
216    }
217
218    #[test]
219    fn rejects_text_before_using_workspace_capacity() {
220        let mut workspace = TextWorkspace::try_new(LayoutLimits {
221            text_bytes: 2,
222            ..limits()
223        })
224        .unwrap();
225        let source = Source;
226        let typeface = SimpleTypeface::new(&source);
227        let typefaces: [&dyn Typeface; 1] = [&typeface];
228        let flow = TextFlow::new("abc", 3).with_line_height(10);
229
230        assert_eq!(
231            flow.layout(&typefaces, &mut workspace).err().unwrap(),
232            WorkspaceError::TextLimit {
233                required: 3,
234                limit: 2,
235            }
236        );
237    }
238
239    #[test]
240    fn rejects_dimensions_outside_layout_coordinates() {
241        let mut workspace = TextWorkspace::try_new(limits()).unwrap();
242        let source = Source;
243        let typeface = SimpleTypeface::new(&source);
244        let typefaces: [&dyn Typeface; 1] = [&typeface];
245        let flow = TextFlow::new("a", usize::MAX).with_line_height(10);
246
247        assert_eq!(
248            flow.layout(&typefaces, &mut workspace).err().unwrap(),
249            WorkspaceError::DimensionOverflow
250        );
251    }
252}