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, TextSpacing, 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 spacing = TextSpacing {
135            letter: flow.letter_spacing,
136            word: flow.word_spacing,
137        };
138        let broken = shaped.break_into_with_provider(
139            flow.text,
140            max_width,
141            flow.wrap,
142            spacing,
143            flow.line_break_provider,
144            &mut self.broken,
145        )?;
146        Ok(logical.layout_into(
147            flow.text,
148            typefaces,
149            flow.features,
150            &broken,
151            LayoutOptions::new(line_advance)
152                .with_origin(flow.origin)
153                .with_spacing(spacing)
154                .with_width(max_width)
155                .with_alignment(flow.alignment)
156                .with_direction(bidi.direction())
157                .with_max_lines(flow.max_lines)
158                .with_overflow(flow.overflow),
159            LayoutBuffers::new(
160                &mut self.scratch,
161                &mut self.glyphs,
162                &mut self.runs,
163                &mut self.lines,
164                &mut self.carets,
165            ),
166        )?)
167    }
168}
169
170fn slots<T: Clone>(length: usize, value: T) -> Result<Vec<T>, WorkspaceError> {
171    let mut slots = Vec::new();
172    slots
173        .try_reserve_exact(length)
174        .map_err(|_| WorkspaceError::Allocation)?;
175    slots.resize(length, value);
176    Ok(slots)
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use crate::shaping::{
183        FlowPoint, FontAccessError, FontId, FontMetrics, GlyphId, GlyphSource, SimpleTypeface,
184    };
185
186    struct Source;
187
188    impl GlyphSource for Source {
189        fn id(&self) -> FontId {
190            FontId::new(1)
191        }
192
193        fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
194            Ok(FontMetrics::default())
195        }
196
197        fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
198            Ok(Some(GlyphId::new(character as u16)))
199        }
200
201        fn glyph_advance(&self, _glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
202            Ok(FlowPoint { x: 1, y: 0 })
203        }
204    }
205
206    fn limits() -> LayoutLimits {
207        LayoutLimits {
208            text_bytes: 16,
209            runs: 4,
210            visual_runs: 4,
211            glyphs: 8,
212            scratch_glyphs: 4,
213            lines: 4,
214            carets: 12,
215        }
216    }
217
218    #[test]
219    fn reuses_fixed_capacity_for_layout() {
220        let limits = limits();
221        assert!(limits.buffer_bytes().is_some_and(|bytes| bytes > 0));
222        let mut workspace = TextWorkspace::try_new(limits).unwrap();
223        let source = Source;
224        let typeface = SimpleTypeface::new(&source);
225        let typefaces: [&dyn Typeface; 1] = [&typeface];
226        let flow = TextFlow::new("ab cd", 3)
227            .with_line_height(10)
228            .with_line_spacing(2);
229        let layout = flow.layout(&typefaces, &mut workspace).unwrap();
230
231        assert_eq!(layout.lines().len(), 2);
232        assert_eq!(layout.glyphs().len(), 5);
233        assert_eq!(layout.lines()[1].origin().y, 12);
234    }
235
236    #[test]
237    fn rejects_text_before_using_workspace_capacity() {
238        let mut workspace = TextWorkspace::try_new(LayoutLimits {
239            text_bytes: 2,
240            ..limits()
241        })
242        .unwrap();
243        let source = Source;
244        let typeface = SimpleTypeface::new(&source);
245        let typefaces: [&dyn Typeface; 1] = [&typeface];
246        let flow = TextFlow::new("abc", 3).with_line_height(10);
247
248        assert_eq!(
249            flow.layout(&typefaces, &mut workspace).err().unwrap(),
250            WorkspaceError::TextLimit {
251                required: 3,
252                limit: 2,
253            }
254        );
255    }
256
257    #[test]
258    fn rejects_dimensions_outside_layout_coordinates() {
259        let mut workspace = TextWorkspace::try_new(limits()).unwrap();
260        let source = Source;
261        let typeface = SimpleTypeface::new(&source);
262        let typefaces: [&dyn Typeface; 1] = [&typeface];
263        let flow = TextFlow::new("a", usize::MAX).with_line_height(10);
264
265        assert_eq!(
266            flow.layout(&typefaces, &mut workspace).err().unwrap(),
267            WorkspaceError::DimensionOverflow
268        );
269    }
270
271    #[test]
272    fn ellipsis_is_shaped_and_excluded_from_caret_navigation() {
273        let mut workspace = TextWorkspace::try_new(limits()).unwrap();
274        let source = Source;
275        let typeface = SimpleTypeface::new(&source);
276        let typefaces: [&dyn Typeface; 1] = [&typeface];
277        let flow = TextFlow::new("ab cd", 3)
278            .with_line_height(10)
279            .with_max_lines(1)
280            .with_overflow(crate::layout::Overflow::Ellipsis);
281        let layout = flow.layout(&typefaces, &mut workspace).unwrap();
282
283        assert_eq!(layout.lines().len(), 1);
284        assert_eq!(
285            layout.lines()[0].text(),
286            crate::shaping::TextRange::new(0, 2)
287        );
288        assert_eq!(layout.glyphs().len(), 3);
289        assert_eq!(
290            layout.glyphs()[2].glyph_id(),
291            GlyphId::new('\u{2026}' as u16)
292        );
293        assert!(layout.runs()[1].is_synthetic());
294        assert_eq!(
295            layout.runs()[1].text(),
296            crate::shaping::TextRange::new(2, 2)
297        );
298        assert_eq!(layout.carets().len(), 3);
299        assert_eq!(layout.carets().last().unwrap().text_offset, 2);
300    }
301
302    #[test]
303    fn no_wrap_ellipsis_replaces_horizontal_overflow() {
304        let mut workspace = TextWorkspace::try_new(LayoutLimits {
305            scratch_glyphs: 5,
306            ..limits()
307        })
308        .unwrap();
309        let source = Source;
310        let typeface = SimpleTypeface::new(&source);
311        let typefaces: [&dyn Typeface; 1] = [&typeface];
312        let flow = TextFlow::new("abcde", 3)
313            .with_line_height(10)
314            .with_wrap(crate::layout::WrapMode::NoWrap)
315            .with_overflow(crate::layout::Overflow::Ellipsis);
316        let layout = flow.layout(&typefaces, &mut workspace).unwrap();
317
318        assert_eq!(layout.lines().len(), 1);
319        assert_eq!(
320            layout.lines()[0].text(),
321            crate::shaping::TextRange::new(0, 2)
322        );
323        assert_eq!(layout.lines()[0].advance(), 3);
324        assert_eq!(layout.glyphs().len(), 3);
325        assert_eq!(
326            layout.glyphs()[2].glyph_id(),
327            GlyphId::new('\u{2026}' as u16)
328        );
329    }
330
331    #[test]
332    fn rtl_ellipsis_occupies_the_visual_start() {
333        let mut workspace = TextWorkspace::try_new(limits()).unwrap();
334        let source = Source;
335        let typeface = SimpleTypeface::new(&source);
336        let typefaces: [&dyn Typeface; 1] = [&typeface];
337        let flow = TextFlow::new("ab cd", 3)
338            .with_line_height(10)
339            .with_direction(crate::bidi::BaseDirection::RightToLeft)
340            .with_max_lines(1)
341            .with_overflow(crate::layout::Overflow::Ellipsis);
342        let layout = flow.layout(&typefaces, &mut workspace).unwrap();
343
344        assert!(layout.runs()[0].is_synthetic());
345        assert_eq!(
346            layout.glyphs()[0].glyph_id(),
347            GlyphId::new('\u{2026}' as u16)
348        );
349        assert_eq!(layout.glyphs()[0].origin.x, 0);
350        assert_eq!(layout.glyphs()[1].origin.x, 1);
351    }
352}