Skip to main content

textflow/
workspace.rs

1use crate::bidi::{BidiError, BidiRun, BidiText};
2use crate::layout::{
3    BrokenLine, GlyphRun, LayoutBuffers, LayoutError, LayoutLine, LogicalRun, LogicalRuns,
4    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)]
12/// Runtime limits for lazily allocated private pipeline storage.
13pub struct LayoutLimits {
14    pub text_bytes: usize,
15    pub runs: usize,
16    pub glyphs: usize,
17    pub scratch_glyphs: usize,
18    pub lines: usize,
19    pub memory_bytes: usize,
20}
21
22impl LayoutLimits {
23    /// Element storage for private buffers at their limits.
24    ///
25    /// Final output and allocator bookkeeping are not included.
26    pub fn buffer_bytes(self) -> Option<usize> {
27        let run_bytes = size_of::<BidiRun>()
28            .checked_add(size_of::<LogicalRun>())?
29            .checked_add(size_of::<GlyphRun>())?
30            .checked_mul(self.runs)?;
31        let glyph_bytes = size_of::<ShapedGlyph>().checked_mul(self.glyphs)?;
32        run_bytes
33            .checked_add(glyph_bytes)?
34            .checked_add(size_of::<ShapedGlyph>().checked_mul(self.scratch_glyphs)?)?
35            .checked_add(size_of::<BrokenLine>().checked_mul(self.lines)?)
36    }
37}
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40/// Failure to admit, allocate, or lay out a paragraph with a workspace.
41pub enum WorkspaceError {
42    Allocation,
43    MemoryLimit { required: usize, limit: usize },
44    TextLimit { required: usize, limit: usize },
45    RunLimit { required: usize, limit: usize },
46    GlyphLimit { required: usize, limit: usize },
47    ScratchLimit { required: usize, limit: usize },
48    LineLimit { required: usize, limit: usize },
49    DimensionOverflow,
50    Bidi(BidiError),
51    Layout(LayoutError),
52}
53
54impl From<BidiError> for WorkspaceError {
55    fn from(error: BidiError) -> Self {
56        Self::Bidi(error)
57    }
58}
59
60impl From<LayoutError> for WorkspaceError {
61    fn from(error: LayoutError) -> Self {
62        Self::Layout(error)
63    }
64}
65
66/// Caller-owned storage for final paragraph products.
67pub struct LayoutOutput<'a> {
68    glyphs: &'a mut [PositionedGlyph],
69    runs: &'a mut [VisualRun],
70    lines: &'a mut [LayoutLine],
71    carets: &'a mut [CaretStop],
72}
73
74impl<'a> LayoutOutput<'a> {
75    /// Combines final glyph, run, line, and caret slices into one output target.
76    pub fn new(
77        glyphs: &'a mut [PositionedGlyph],
78        runs: &'a mut [VisualRun],
79        lines: &'a mut [LayoutLine],
80        carets: &'a mut [CaretStop],
81    ) -> Self {
82        Self {
83            glyphs,
84            runs,
85            lines,
86            carets,
87        }
88    }
89
90    pub(crate) fn layout(&self, result: LayoutResult) -> ParagraphLayout<'_> {
91        ParagraphLayout::from_parts(
92            &self.lines[..result.lines],
93            &self.runs[..result.runs],
94            &self.glyphs[..result.glyphs],
95            &self.carets[..result.carets],
96        )
97    }
98}
99
100#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
101pub(crate) struct LayoutResult {
102    lines: usize,
103    runs: usize,
104    glyphs: usize,
105    carets: usize,
106}
107
108/// Reusable heap storage for private paragraph-layout intermediates.
109pub struct TextWorkspace {
110    limits: LayoutLimits,
111    bidi: Vec<BidiRun>,
112    logical: Vec<LogicalRun>,
113    initial_glyphs: Vec<ShapedGlyph>,
114    initial_runs: Vec<GlyphRun>,
115    broken: Vec<BrokenLine>,
116    scratch: Vec<ShapedGlyph>,
117}
118
119impl TextWorkspace {
120    /// Creates an empty workspace that grows within `limits` on demand.
121    pub const fn new(limits: LayoutLimits) -> Self {
122        Self {
123            limits,
124            bidi: Vec::new(),
125            logical: Vec::new(),
126            initial_glyphs: Vec::new(),
127            initial_runs: Vec::new(),
128            broken: Vec::new(),
129            scratch: Vec::new(),
130        }
131    }
132
133    pub const fn limits(&self) -> LayoutLimits {
134        self.limits
135    }
136
137    /// Updates the private-buffer byte limit without releasing retained capacity.
138    pub fn set_memory_limit(&mut self, memory_bytes: usize) -> Result<(), WorkspaceError> {
139        let required = self.resident_bytes();
140        if required > memory_bytes {
141            return Err(WorkspaceError::MemoryLimit {
142                required,
143                limit: memory_bytes,
144            });
145        }
146        self.limits.memory_bytes = memory_bytes;
147        Ok(())
148    }
149
150    pub(crate) fn layout_into(
151        &mut self,
152        flow: &TextFlow<'_>,
153        typefaces: &[&dyn Typeface],
154        output: &mut LayoutOutput<'_>,
155    ) -> Result<LayoutResult, WorkspaceError> {
156        if flow.text.len() > self.limits.text_bytes {
157            return Err(WorkspaceError::TextLimit {
158                required: flow.text.len(),
159                limit: self.limits.text_bytes,
160            });
161        }
162        self.prepare(flow.text)?;
163        loop {
164            match self.try_layout(flow, typefaces, output) {
165                Ok(result) => return Ok(result),
166                Err(AttemptError::Grow(kind, required)) => self.grow(kind, required)?,
167                Err(AttemptError::Public(error)) => return Err(error),
168            }
169        }
170    }
171
172    /// Returns allocated element capacity for private pipeline buffers.
173    pub fn resident_bytes(&self) -> usize {
174        vec_bytes(&self.bidi)
175            .saturating_add(vec_bytes(&self.logical))
176            .saturating_add(vec_bytes(&self.initial_glyphs))
177            .saturating_add(vec_bytes(&self.initial_runs))
178            .saturating_add(vec_bytes(&self.broken))
179            .saturating_add(vec_bytes(&self.scratch))
180    }
181
182    fn try_layout(
183        &mut self,
184        flow: &TextFlow<'_>,
185        typefaces: &[&dyn Typeface],
186        output: &mut LayoutOutput<'_>,
187    ) -> Result<LayoutResult, AttemptError> {
188        let max_width =
189            i32::try_from(flow.max_width).map_err(|_| WorkspaceError::DimensionOverflow)?;
190        let width = flow
191            .width
192            .map(i32::try_from)
193            .transpose()
194            .map_err(|_| WorkspaceError::DimensionOverflow)?;
195        let line_height =
196            i32::try_from(flow.line_height).map_err(|_| WorkspaceError::DimensionOverflow)?;
197        let line_spacing =
198            i32::try_from(flow.line_spacing).map_err(|_| WorkspaceError::DimensionOverflow)?;
199        let line_advance = line_height
200            .checked_add(line_spacing)
201            .ok_or(WorkspaceError::DimensionOverflow)?;
202        let bidi = BidiText::resolve(
203            flow.text,
204            0..flow.text.len(),
205            flow.base_direction,
206            &mut self.bidi,
207        )
208        .map_err(|error| match error {
209            BidiError::InsufficientCapacity { required } => {
210                AttemptError::Grow(BufferKind::Runs, required)
211            }
212            error => AttemptError::Public(WorkspaceError::Bidi(error)),
213        })?;
214        let logical = LogicalRuns::resolve(flow.text, &bidi, typefaces, &mut self.logical)
215            .map_err(map_logical)?;
216        let shaped = logical
217            .shape_into(
218                flow.text,
219                typefaces,
220                flow.features,
221                &mut self.initial_glyphs,
222                &mut self.initial_runs,
223            )
224            .map_err(map_shape)?;
225        let spacing = TextSpacing {
226            letter: flow.letter_spacing,
227            word: flow.word_spacing,
228        };
229        let broken = shaped
230            .break_into_with_provider(
231                flow.text,
232                crate::layout::BreakConfig {
233                    max_width,
234                    mode: flow.wrap,
235                    spacing,
236                    breaks: flow.line_break_provider,
237                    widths: flow.line_width_provider,
238                    max_lines: flow.max_lines,
239                },
240                &mut self.broken,
241            )
242            .map_err(map_break)?;
243        let options = flow.layout_options(line_advance, bidi.direction(), width);
244        let layout = logical
245            .layout_into(
246                flow.text,
247                typefaces,
248                flow.features,
249                &broken,
250                crate::layout::ParagraphConfig::new(options, flow.line_width_provider),
251                LayoutBuffers::new(
252                    &mut self.scratch,
253                    &mut *output.glyphs,
254                    &mut *output.runs,
255                    &mut *output.lines,
256                    &mut *output.carets,
257                ),
258            )
259            .map_err(|error| match error {
260                LayoutError::InsufficientScratchCapacity { minimum } => {
261                    AttemptError::Grow(BufferKind::Scratch, minimum)
262                }
263                error => AttemptError::Public(WorkspaceError::Layout(error)),
264            })?;
265        Ok(LayoutResult {
266            lines: layout.lines().len(),
267            runs: layout.runs().len(),
268            glyphs: layout.glyphs().len(),
269            carets: layout.carets().len(),
270        })
271    }
272
273    fn prepare(&mut self, text: &str) -> Result<(), WorkspaceError> {
274        let glyphs = text.chars().count();
275        let initial = glyphs.min(self.limits.glyphs);
276        self.grow(BufferKind::Glyphs, initial)
277    }
278
279    fn grow(&mut self, kind: BufferKind, required: usize) -> Result<(), WorkspaceError> {
280        let limit = match kind {
281            BufferKind::Runs => self.limits.runs,
282            BufferKind::Glyphs => self.limits.glyphs,
283            BufferKind::Scratch => self.limits.scratch_glyphs,
284            BufferKind::Lines => self.limits.lines,
285        };
286        if required > limit {
287            return Err(kind.limit_error(required, limit));
288        }
289        let projected = self
290            .projected_bytes(kind, required)
291            .ok_or(WorkspaceError::DimensionOverflow)?;
292        if projected > self.limits.memory_bytes {
293            return Err(WorkspaceError::MemoryLimit {
294                required: projected,
295                limit: self.limits.memory_bytes,
296            });
297        }
298        match kind {
299            BufferKind::Runs => {
300                resize_slots(&mut self.bidi, required, BidiRun::empty())?;
301                resize_slots(&mut self.logical, required, LogicalRun::empty())?;
302                resize_slots(&mut self.initial_runs, required, GlyphRun::empty())
303            }
304            BufferKind::Glyphs => {
305                resize_slots(&mut self.initial_glyphs, required, ShapedGlyph::default())
306            }
307            BufferKind::Scratch => {
308                resize_slots(&mut self.scratch, required, ShapedGlyph::default())
309            }
310            BufferKind::Lines => resize_slots(&mut self.broken, required, BrokenLine::empty()),
311        }
312    }
313
314    fn projected_bytes(&self, kind: BufferKind, required: usize) -> Option<usize> {
315        let added = match kind {
316            BufferKind::Runs => additional_bytes(&self.bidi, required)?
317                .checked_add(additional_bytes(&self.logical, required)?)?
318                .checked_add(additional_bytes(&self.initial_runs, required)?)?,
319            BufferKind::Glyphs => additional_bytes(&self.initial_glyphs, required)?,
320            BufferKind::Scratch => additional_bytes(&self.scratch, required)?,
321            BufferKind::Lines => additional_bytes(&self.broken, required)?,
322        };
323        self.resident_bytes().checked_add(added)
324    }
325}
326
327#[derive(Clone, Copy)]
328enum BufferKind {
329    Runs,
330    Glyphs,
331    Scratch,
332    Lines,
333}
334
335impl BufferKind {
336    const fn limit_error(self, required: usize, limit: usize) -> WorkspaceError {
337        match self {
338            Self::Runs => WorkspaceError::RunLimit { required, limit },
339            Self::Glyphs => WorkspaceError::GlyphLimit { required, limit },
340            Self::Scratch => WorkspaceError::ScratchLimit { required, limit },
341            Self::Lines => WorkspaceError::LineLimit { required, limit },
342        }
343    }
344}
345
346enum AttemptError {
347    Grow(BufferKind, usize),
348    Public(WorkspaceError),
349}
350
351impl From<WorkspaceError> for AttemptError {
352    fn from(error: WorkspaceError) -> Self {
353        Self::Public(error)
354    }
355}
356
357fn map_logical(error: LayoutError) -> AttemptError {
358    match error {
359        LayoutError::InsufficientRunCapacity { required } => {
360            AttemptError::Grow(BufferKind::Runs, required)
361        }
362        error => AttemptError::Public(WorkspaceError::Layout(error)),
363    }
364}
365
366fn map_shape(error: LayoutError) -> AttemptError {
367    match error {
368        LayoutError::InsufficientRunCapacity { required } => {
369            AttemptError::Grow(BufferKind::Runs, required)
370        }
371        LayoutError::InsufficientGlyphCapacity { minimum } => {
372            AttemptError::Grow(BufferKind::Glyphs, minimum)
373        }
374        error => AttemptError::Public(WorkspaceError::Layout(error)),
375    }
376}
377
378fn map_break(error: LayoutError) -> AttemptError {
379    match error {
380        LayoutError::InsufficientLineCapacity { required } => {
381            AttemptError::Grow(BufferKind::Lines, required)
382        }
383        error => AttemptError::Public(WorkspaceError::Layout(error)),
384    }
385}
386
387fn resize_slots<T: Clone>(
388    slots: &mut Vec<T>,
389    length: usize,
390    value: T,
391) -> Result<(), WorkspaceError> {
392    if length <= slots.len() {
393        return Ok(());
394    }
395    slots
396        .try_reserve_exact(length - slots.len())
397        .map_err(|_| WorkspaceError::Allocation)?;
398    slots.resize(length, value);
399    Ok(())
400}
401
402fn vec_bytes<T>(values: &Vec<T>) -> usize {
403    values.capacity().saturating_mul(size_of::<T>())
404}
405
406fn additional_bytes<T>(values: &Vec<T>, required: usize) -> Option<usize> {
407    required
408        .saturating_sub(values.capacity())
409        .checked_mul(size_of::<T>())
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415    use crate::shaping::{
416        FlowPoint, FontAccessError, FontId, FontMetrics, GlyphId, GlyphSource, SimpleTypeface,
417    };
418
419    struct Source;
420
421    impl GlyphSource for Source {
422        fn id(&self) -> FontId {
423            FontId::new(1)
424        }
425
426        fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
427            Ok(FontMetrics::default())
428        }
429
430        fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
431            Ok(Some(GlyphId::new(character as u16)))
432        }
433
434        fn glyph_advance(&self, _glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
435            Ok(FlowPoint { x: 1, y: 0 })
436        }
437    }
438
439    fn limits() -> LayoutLimits {
440        LayoutLimits {
441            text_bytes: 16,
442            runs: 4,
443            glyphs: 8,
444            scratch_glyphs: 4,
445            lines: 4,
446            memory_bytes: usize::MAX,
447        }
448    }
449
450    struct OutputStorage {
451        glyphs: [PositionedGlyph; 8],
452        runs: [VisualRun; 4],
453        lines: [LayoutLine; 4],
454        carets: [CaretStop; 12],
455    }
456
457    impl OutputStorage {
458        fn new() -> Self {
459            Self {
460                glyphs: [PositionedGlyph::default(); 8],
461                runs: [VisualRun::empty(); 4],
462                lines: [LayoutLine::empty(); 4],
463                carets: [CaretStop::default(); 12],
464            }
465        }
466
467        fn with_layout<R>(
468            &mut self,
469            flow: &TextFlow<'_>,
470            typefaces: &[&dyn Typeface],
471            workspace: &mut TextWorkspace,
472            inspect: impl FnOnce(ParagraphLayout<'_>) -> R,
473        ) -> Result<R, WorkspaceError> {
474            let mut output = LayoutOutput::new(
475                &mut self.glyphs,
476                &mut self.runs,
477                &mut self.lines,
478                &mut self.carets,
479            );
480            let layout = flow.layout_into(typefaces, workspace, &mut output)?;
481            Ok(inspect(layout))
482        }
483
484        fn error(
485            &mut self,
486            flow: &TextFlow<'_>,
487            typefaces: &[&dyn Typeface],
488            workspace: &mut TextWorkspace,
489        ) -> WorkspaceError {
490            let mut output = LayoutOutput::new(
491                &mut self.glyphs,
492                &mut self.runs,
493                &mut self.lines,
494                &mut self.carets,
495            );
496            match flow.layout_into(typefaces, workspace, &mut output) {
497                Ok(_) => panic!("layout unexpectedly succeeded"),
498                Err(error) => error,
499            }
500        }
501    }
502
503    #[test]
504    fn grows_private_buffers_lazily_and_reuses_them() {
505        let limits = limits();
506        let maximum = limits.buffer_bytes().unwrap();
507        let mut workspace = TextWorkspace::new(limits);
508        assert_eq!(workspace.resident_bytes(), 0);
509        let source = Source;
510        let typeface = SimpleTypeface::new(&source);
511        let typefaces: [&dyn Typeface; 1] = [&typeface];
512        let short = TextFlow::new("a", 3).with_line_height(10);
513        let mut output = OutputStorage::new();
514        output
515            .with_layout(&short, &typefaces, &mut workspace, |_| {})
516            .unwrap();
517        let short_resident = workspace.resident_bytes();
518        assert!(short_resident > 0 && short_resident < maximum);
519
520        let flow = TextFlow::new("ab cd", 3)
521            .with_line_height(10)
522            .with_line_spacing(2);
523        output
524            .with_layout(&flow, &typefaces, &mut workspace, |layout| {
525                assert_eq!(layout.lines().len(), 2);
526                assert_eq!(layout.glyphs().len(), 5);
527                assert_eq!(layout.lines()[1].origin().y, 12);
528            })
529            .unwrap();
530        let resident = workspace.resident_bytes();
531        assert!(resident > short_resident);
532        output
533            .with_layout(&flow, &typefaces, &mut workspace, |_| {})
534            .unwrap();
535        assert_eq!(workspace.resident_bytes(), resident);
536    }
537
538    #[test]
539    fn empty_paragraph_needs_no_workspace_or_output_storage() {
540        let mut workspace = TextWorkspace::new(LayoutLimits {
541            text_bytes: 0,
542            runs: 0,
543            glyphs: 0,
544            scratch_glyphs: 0,
545            lines: 0,
546            memory_bytes: 0,
547        });
548        let source = Source;
549        let typeface = SimpleTypeface::new(&source);
550        let typefaces: [&dyn Typeface; 1] = [&typeface];
551        let mut glyphs = [];
552        let mut runs = [];
553        let mut lines = [];
554        let mut carets = [];
555        let mut output = LayoutOutput::new(&mut glyphs, &mut runs, &mut lines, &mut carets);
556
557        let layout = TextFlow::new("", 0)
558            .layout_into(&typefaces, &mut workspace, &mut output)
559            .unwrap();
560
561        assert!(layout.glyphs().is_empty());
562        assert!(layout.runs().is_empty());
563        assert!(layout.lines().is_empty());
564        assert!(layout.carets().is_empty());
565        assert_eq!(workspace.resident_bytes(), 0);
566    }
567
568    #[test]
569    fn reports_caller_output_capacity_without_owning_a_second_copy() {
570        let mut workspace = TextWorkspace::new(limits());
571        let source = Source;
572        let typeface = SimpleTypeface::new(&source);
573        let typefaces: [&dyn Typeface; 1] = [&typeface];
574        let flow = TextFlow::new("ab", 3).with_line_height(10);
575        let mut glyphs = [PositionedGlyph::default(); 1];
576        let mut runs = [VisualRun::empty(); 2];
577        let mut lines = [LayoutLine::empty(); 1];
578        let mut carets = [CaretStop::default(); 3];
579        let mut output = LayoutOutput::new(&mut glyphs, &mut runs, &mut lines, &mut carets);
580
581        let error = match flow.layout_into(&typefaces, &mut workspace, &mut output) {
582            Ok(_) => panic!("layout unexpectedly succeeded"),
583            Err(error) => error,
584        };
585        assert_eq!(
586            error,
587            WorkspaceError::Layout(LayoutError::InsufficientPositionedCapacity { minimum: 2 })
588        );
589    }
590
591    #[test]
592    fn breaking_and_alignment_widths_are_independent() {
593        let mut workspace = TextWorkspace::new(limits());
594        let source = Source;
595        let typeface = SimpleTypeface::new(&source);
596        let typefaces: [&dyn Typeface; 1] = [&typeface];
597        let flow = TextFlow::new("ab cd", 3)
598            .with_width(10)
599            .with_line_height(10)
600            .with_alignment(crate::layout::Alignment::Center);
601        let mut output = OutputStorage::new();
602
603        output
604            .with_layout(&flow, &typefaces, &mut workspace, |layout| {
605                assert_eq!(layout.lines().len(), 2);
606                assert_eq!(layout.lines()[0].origin().x, 3);
607                assert_eq!(layout.lines()[1].origin().x, 4);
608            })
609            .unwrap();
610    }
611
612    #[test]
613    fn unbounded_layout_does_not_align_or_ellipsize() {
614        let mut workspace = TextWorkspace::new(limits());
615        let source = Source;
616        let typeface = SimpleTypeface::new(&source);
617        let typefaces: [&dyn Typeface; 1] = [&typeface];
618        let flow = TextFlow::new("ab", 1)
619            .without_width()
620            .with_line_height(10)
621            .with_wrap(crate::layout::WrapMode::NoWrap)
622            .with_alignment(crate::layout::Alignment::Center)
623            .with_overflow(crate::layout::Overflow::Ellipsis);
624        let mut output = OutputStorage::new();
625
626        output
627            .with_layout(&flow, &typefaces, &mut workspace, |layout| {
628                assert_eq!(layout.lines()[0].origin().x, 0);
629                assert_eq!(layout.glyphs().len(), 2);
630            })
631            .unwrap();
632    }
633
634    #[test]
635    fn memory_limit_rejects_growth_before_allocation() {
636        let mut limits = limits();
637        limits.memory_bytes = 0;
638        let mut workspace = TextWorkspace::new(limits);
639        let source = Source;
640        let typeface = SimpleTypeface::new(&source);
641        let typefaces: [&dyn Typeface; 1] = [&typeface];
642        let flow = TextFlow::new("a", 3).with_line_height(10);
643        let mut output = OutputStorage::new();
644
645        assert!(matches!(
646            output.error(&flow, &typefaces, &mut workspace),
647            WorkspaceError::MemoryLimit {
648                required: _,
649                limit: 0
650            }
651        ));
652        assert_eq!(workspace.resident_bytes(), 0);
653    }
654
655    #[test]
656    fn retained_storage_sets_the_minimum_memory_limit() {
657        let mut workspace = TextWorkspace::new(limits());
658        let source = Source;
659        let typeface = SimpleTypeface::new(&source);
660        let typefaces: [&dyn Typeface; 1] = [&typeface];
661        let flow = TextFlow::new("ab", 3).with_line_height(10);
662        let mut output = OutputStorage::new();
663        output
664            .with_layout(&flow, &typefaces, &mut workspace, |_| {})
665            .unwrap();
666        let resident = workspace.resident_bytes();
667
668        workspace.set_memory_limit(resident).unwrap();
669        assert_eq!(workspace.limits().memory_bytes, resident);
670        assert_eq!(
671            workspace.set_memory_limit(resident - 1),
672            Err(WorkspaceError::MemoryLimit {
673                required: resident,
674                limit: resident - 1,
675            })
676        );
677        assert_eq!(workspace.limits().memory_bytes, resident);
678    }
679
680    #[test]
681    fn rejects_text_before_using_workspace_capacity() {
682        let mut workspace = TextWorkspace::new(LayoutLimits {
683            text_bytes: 2,
684            ..limits()
685        });
686        let source = Source;
687        let typeface = SimpleTypeface::new(&source);
688        let typefaces: [&dyn Typeface; 1] = [&typeface];
689        let flow = TextFlow::new("abc", 3).with_line_height(10);
690
691        let mut output = OutputStorage::new();
692        assert_eq!(
693            output.error(&flow, &typefaces, &mut workspace),
694            WorkspaceError::TextLimit {
695                required: 3,
696                limit: 2,
697            }
698        );
699    }
700
701    #[test]
702    fn rejects_dimensions_outside_layout_coordinates() {
703        let mut workspace = TextWorkspace::new(limits());
704        let source = Source;
705        let typeface = SimpleTypeface::new(&source);
706        let typefaces: [&dyn Typeface; 1] = [&typeface];
707        let flow = TextFlow::new("a", usize::MAX).with_line_height(10);
708
709        let mut output = OutputStorage::new();
710        assert_eq!(
711            output.error(&flow, &typefaces, &mut workspace),
712            WorkspaceError::DimensionOverflow
713        );
714    }
715
716    #[test]
717    fn ellipsis_is_shaped_and_excluded_from_caret_navigation() {
718        let mut workspace = TextWorkspace::new(limits());
719        let source = Source;
720        let typeface = SimpleTypeface::new(&source);
721        let typefaces: [&dyn Typeface; 1] = [&typeface];
722        let flow = TextFlow::new("ab cd", 3)
723            .with_line_height(10)
724            .with_max_lines(1)
725            .with_overflow(crate::layout::Overflow::Ellipsis);
726        let mut output = OutputStorage::new();
727        output
728            .with_layout(&flow, &typefaces, &mut workspace, |layout| {
729                assert_eq!(layout.lines().len(), 1);
730                assert_eq!(
731                    layout.lines()[0].text(),
732                    crate::shaping::TextRange::new(0, 2)
733                );
734                assert_eq!(layout.glyphs().len(), 3);
735                assert_eq!(
736                    layout.glyphs()[2].glyph_id(),
737                    GlyphId::new('\u{2026}' as u16)
738                );
739                assert!(layout.runs()[1].is_synthetic());
740                assert_eq!(
741                    layout.runs()[1].text(),
742                    crate::shaping::TextRange::new(2, 2)
743                );
744                assert_eq!(layout.carets().len(), 3);
745                assert_eq!(layout.carets().last().unwrap().text_offset, 2);
746            })
747            .unwrap();
748    }
749
750    #[test]
751    fn no_wrap_ellipsis_replaces_horizontal_overflow() {
752        let mut workspace = TextWorkspace::new(LayoutLimits {
753            scratch_glyphs: 5,
754            ..limits()
755        });
756        let source = Source;
757        let typeface = SimpleTypeface::new(&source);
758        let typefaces: [&dyn Typeface; 1] = [&typeface];
759        let flow = TextFlow::new("abcde", 3)
760            .with_line_height(10)
761            .with_wrap(crate::layout::WrapMode::NoWrap)
762            .with_overflow(crate::layout::Overflow::Ellipsis);
763        let mut output = OutputStorage::new();
764        output
765            .with_layout(&flow, &typefaces, &mut workspace, |layout| {
766                assert_eq!(layout.lines().len(), 1);
767                assert_eq!(
768                    layout.lines()[0].text(),
769                    crate::shaping::TextRange::new(0, 2)
770                );
771                assert_eq!(layout.lines()[0].advance(), 3);
772                assert_eq!(layout.glyphs().len(), 3);
773                assert_eq!(
774                    layout.glyphs()[2].glyph_id(),
775                    GlyphId::new('\u{2026}' as u16)
776                );
777            })
778            .unwrap();
779    }
780
781    #[test]
782    fn rtl_ellipsis_occupies_the_visual_start() {
783        let mut workspace = TextWorkspace::new(limits());
784        let source = Source;
785        let typeface = SimpleTypeface::new(&source);
786        let typefaces: [&dyn Typeface; 1] = [&typeface];
787        let flow = TextFlow::new("ab cd", 3)
788            .with_line_height(10)
789            .with_direction(crate::bidi::BaseDirection::RightToLeft)
790            .with_max_lines(1)
791            .with_overflow(crate::layout::Overflow::Ellipsis);
792        let mut output = OutputStorage::new();
793        output
794            .with_layout(&flow, &typefaces, &mut workspace, |layout| {
795                assert!(layout.runs()[0].is_synthetic());
796                assert_eq!(
797                    layout.glyphs()[0].glyph_id(),
798                    GlyphId::new('\u{2026}' as u16)
799                );
800                assert_eq!(layout.glyphs()[0].origin.x, 0);
801                assert_eq!(layout.glyphs()[1].origin.x, 1);
802            })
803            .unwrap();
804    }
805}