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