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)]
12pub 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 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)]
40pub 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
66pub 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 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
108pub 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 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 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 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 max_width,
233 flow.wrap,
234 spacing,
235 flow.line_break_provider,
236 &mut self.broken,
237 )
238 .map_err(map_break)?;
239 let options = flow.layout_options(line_advance, bidi.direction(), width);
240 let layout = logical
241 .layout_into(
242 flow.text,
243 typefaces,
244 flow.features,
245 &broken,
246 options,
247 LayoutBuffers::new(
248 &mut self.scratch,
249 &mut *output.glyphs,
250 &mut *output.runs,
251 &mut *output.lines,
252 &mut *output.carets,
253 ),
254 )
255 .map_err(|error| match error {
256 LayoutError::InsufficientScratchCapacity { minimum } => {
257 AttemptError::Grow(BufferKind::Scratch, minimum)
258 }
259 error => AttemptError::Public(WorkspaceError::Layout(error)),
260 })?;
261 Ok(LayoutResult {
262 lines: layout.lines().len(),
263 runs: layout.runs().len(),
264 glyphs: layout.glyphs().len(),
265 carets: layout.carets().len(),
266 })
267 }
268
269 fn prepare(&mut self, text: &str) -> Result<(), WorkspaceError> {
270 let glyphs = text.chars().count();
271 let initial = glyphs.min(self.limits.glyphs);
272 self.grow(BufferKind::Glyphs, initial)
273 }
274
275 fn grow(&mut self, kind: BufferKind, required: usize) -> Result<(), WorkspaceError> {
276 let limit = match kind {
277 BufferKind::Runs => self.limits.runs,
278 BufferKind::Glyphs => self.limits.glyphs,
279 BufferKind::Scratch => self.limits.scratch_glyphs,
280 BufferKind::Lines => self.limits.lines,
281 };
282 if required > limit {
283 return Err(kind.limit_error(required, limit));
284 }
285 let projected = self
286 .projected_bytes(kind, required)
287 .ok_or(WorkspaceError::DimensionOverflow)?;
288 if projected > self.limits.memory_bytes {
289 return Err(WorkspaceError::MemoryLimit {
290 required: projected,
291 limit: self.limits.memory_bytes,
292 });
293 }
294 match kind {
295 BufferKind::Runs => {
296 resize_slots(&mut self.bidi, required, BidiRun::empty())?;
297 resize_slots(&mut self.logical, required, LogicalRun::empty())?;
298 resize_slots(&mut self.initial_runs, required, GlyphRun::empty())
299 }
300 BufferKind::Glyphs => {
301 resize_slots(&mut self.initial_glyphs, required, ShapedGlyph::default())
302 }
303 BufferKind::Scratch => {
304 resize_slots(&mut self.scratch, required, ShapedGlyph::default())
305 }
306 BufferKind::Lines => resize_slots(&mut self.broken, required, BrokenLine::empty()),
307 }
308 }
309
310 fn projected_bytes(&self, kind: BufferKind, required: usize) -> Option<usize> {
311 let added = match kind {
312 BufferKind::Runs => additional_bytes(&self.bidi, required)?
313 .checked_add(additional_bytes(&self.logical, required)?)?
314 .checked_add(additional_bytes(&self.initial_runs, required)?)?,
315 BufferKind::Glyphs => additional_bytes(&self.initial_glyphs, required)?,
316 BufferKind::Scratch => additional_bytes(&self.scratch, required)?,
317 BufferKind::Lines => additional_bytes(&self.broken, required)?,
318 };
319 self.resident_bytes().checked_add(added)
320 }
321}
322
323#[derive(Clone, Copy)]
324enum BufferKind {
325 Runs,
326 Glyphs,
327 Scratch,
328 Lines,
329}
330
331impl BufferKind {
332 const fn limit_error(self, required: usize, limit: usize) -> WorkspaceError {
333 match self {
334 Self::Runs => WorkspaceError::RunLimit { required, limit },
335 Self::Glyphs => WorkspaceError::GlyphLimit { required, limit },
336 Self::Scratch => WorkspaceError::ScratchLimit { required, limit },
337 Self::Lines => WorkspaceError::LineLimit { required, limit },
338 }
339 }
340}
341
342enum AttemptError {
343 Grow(BufferKind, usize),
344 Public(WorkspaceError),
345}
346
347impl From<WorkspaceError> for AttemptError {
348 fn from(error: WorkspaceError) -> Self {
349 Self::Public(error)
350 }
351}
352
353fn map_logical(error: LayoutError) -> AttemptError {
354 match error {
355 LayoutError::InsufficientRunCapacity { required } => {
356 AttemptError::Grow(BufferKind::Runs, required)
357 }
358 error => AttemptError::Public(WorkspaceError::Layout(error)),
359 }
360}
361
362fn map_shape(error: LayoutError) -> AttemptError {
363 match error {
364 LayoutError::InsufficientRunCapacity { required } => {
365 AttemptError::Grow(BufferKind::Runs, required)
366 }
367 LayoutError::InsufficientGlyphCapacity { minimum } => {
368 AttemptError::Grow(BufferKind::Glyphs, minimum)
369 }
370 error => AttemptError::Public(WorkspaceError::Layout(error)),
371 }
372}
373
374fn map_break(error: LayoutError) -> AttemptError {
375 match error {
376 LayoutError::InsufficientLineCapacity { required } => {
377 AttemptError::Grow(BufferKind::Lines, required)
378 }
379 error => AttemptError::Public(WorkspaceError::Layout(error)),
380 }
381}
382
383fn resize_slots<T: Clone>(
384 slots: &mut Vec<T>,
385 length: usize,
386 value: T,
387) -> Result<(), WorkspaceError> {
388 if length <= slots.len() {
389 return Ok(());
390 }
391 slots
392 .try_reserve_exact(length - slots.len())
393 .map_err(|_| WorkspaceError::Allocation)?;
394 slots.resize(length, value);
395 Ok(())
396}
397
398fn vec_bytes<T>(values: &Vec<T>) -> usize {
399 values.capacity().saturating_mul(size_of::<T>())
400}
401
402fn additional_bytes<T>(values: &Vec<T>, required: usize) -> Option<usize> {
403 required
404 .saturating_sub(values.capacity())
405 .checked_mul(size_of::<T>())
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use crate::shaping::{
412 FlowPoint, FontAccessError, FontId, FontMetrics, GlyphId, GlyphSource, SimpleTypeface,
413 };
414
415 struct Source;
416
417 impl GlyphSource for Source {
418 fn id(&self) -> FontId {
419 FontId::new(1)
420 }
421
422 fn metrics(&self) -> Result<FontMetrics, FontAccessError> {
423 Ok(FontMetrics::default())
424 }
425
426 fn glyph_for(&self, character: char) -> Result<Option<GlyphId>, FontAccessError> {
427 Ok(Some(GlyphId::new(character as u16)))
428 }
429
430 fn glyph_advance(&self, _glyph: GlyphId) -> Result<FlowPoint, FontAccessError> {
431 Ok(FlowPoint { x: 1, y: 0 })
432 }
433 }
434
435 fn limits() -> LayoutLimits {
436 LayoutLimits {
437 text_bytes: 16,
438 runs: 4,
439 glyphs: 8,
440 scratch_glyphs: 4,
441 lines: 4,
442 memory_bytes: usize::MAX,
443 }
444 }
445
446 struct OutputStorage {
447 glyphs: [PositionedGlyph; 8],
448 runs: [VisualRun; 4],
449 lines: [LayoutLine; 4],
450 carets: [CaretStop; 12],
451 }
452
453 impl OutputStorage {
454 fn new() -> Self {
455 Self {
456 glyphs: [PositionedGlyph::default(); 8],
457 runs: [VisualRun::empty(); 4],
458 lines: [LayoutLine::empty(); 4],
459 carets: [CaretStop::default(); 12],
460 }
461 }
462
463 fn with_layout<R>(
464 &mut self,
465 flow: &TextFlow<'_>,
466 typefaces: &[&dyn Typeface],
467 workspace: &mut TextWorkspace,
468 inspect: impl FnOnce(ParagraphLayout<'_>) -> R,
469 ) -> Result<R, WorkspaceError> {
470 let mut output = LayoutOutput::new(
471 &mut self.glyphs,
472 &mut self.runs,
473 &mut self.lines,
474 &mut self.carets,
475 );
476 let layout = flow.layout_into(typefaces, workspace, &mut output)?;
477 Ok(inspect(layout))
478 }
479
480 fn error(
481 &mut self,
482 flow: &TextFlow<'_>,
483 typefaces: &[&dyn Typeface],
484 workspace: &mut TextWorkspace,
485 ) -> WorkspaceError {
486 let mut output = LayoutOutput::new(
487 &mut self.glyphs,
488 &mut self.runs,
489 &mut self.lines,
490 &mut self.carets,
491 );
492 match flow.layout_into(typefaces, workspace, &mut output) {
493 Ok(_) => panic!("layout unexpectedly succeeded"),
494 Err(error) => error,
495 }
496 }
497 }
498
499 #[test]
500 fn grows_private_buffers_lazily_and_reuses_them() {
501 let limits = limits();
502 let maximum = limits.buffer_bytes().unwrap();
503 let mut workspace = TextWorkspace::new(limits);
504 assert_eq!(workspace.resident_bytes(), 0);
505 let source = Source;
506 let typeface = SimpleTypeface::new(&source);
507 let typefaces: [&dyn Typeface; 1] = [&typeface];
508 let short = TextFlow::new("a", 3).with_line_height(10);
509 let mut output = OutputStorage::new();
510 output
511 .with_layout(&short, &typefaces, &mut workspace, |_| {})
512 .unwrap();
513 let short_resident = workspace.resident_bytes();
514 assert!(short_resident > 0 && short_resident < maximum);
515
516 let flow = TextFlow::new("ab cd", 3)
517 .with_line_height(10)
518 .with_line_spacing(2);
519 output
520 .with_layout(&flow, &typefaces, &mut workspace, |layout| {
521 assert_eq!(layout.lines().len(), 2);
522 assert_eq!(layout.glyphs().len(), 5);
523 assert_eq!(layout.lines()[1].origin().y, 12);
524 })
525 .unwrap();
526 let resident = workspace.resident_bytes();
527 assert!(resident > short_resident);
528 output
529 .with_layout(&flow, &typefaces, &mut workspace, |_| {})
530 .unwrap();
531 assert_eq!(workspace.resident_bytes(), resident);
532 }
533
534 #[test]
535 fn empty_paragraph_needs_no_workspace_or_output_storage() {
536 let mut workspace = TextWorkspace::new(LayoutLimits {
537 text_bytes: 0,
538 runs: 0,
539 glyphs: 0,
540 scratch_glyphs: 0,
541 lines: 0,
542 memory_bytes: 0,
543 });
544 let source = Source;
545 let typeface = SimpleTypeface::new(&source);
546 let typefaces: [&dyn Typeface; 1] = [&typeface];
547 let mut glyphs = [];
548 let mut runs = [];
549 let mut lines = [];
550 let mut carets = [];
551 let mut output = LayoutOutput::new(&mut glyphs, &mut runs, &mut lines, &mut carets);
552
553 let layout = TextFlow::new("", 0)
554 .layout_into(&typefaces, &mut workspace, &mut output)
555 .unwrap();
556
557 assert!(layout.glyphs().is_empty());
558 assert!(layout.runs().is_empty());
559 assert!(layout.lines().is_empty());
560 assert!(layout.carets().is_empty());
561 assert_eq!(workspace.resident_bytes(), 0);
562 }
563
564 #[test]
565 fn reports_caller_output_capacity_without_owning_a_second_copy() {
566 let mut workspace = TextWorkspace::new(limits());
567 let source = Source;
568 let typeface = SimpleTypeface::new(&source);
569 let typefaces: [&dyn Typeface; 1] = [&typeface];
570 let flow = TextFlow::new("ab", 3).with_line_height(10);
571 let mut glyphs = [PositionedGlyph::default(); 1];
572 let mut runs = [VisualRun::empty(); 2];
573 let mut lines = [LayoutLine::empty(); 1];
574 let mut carets = [CaretStop::default(); 3];
575 let mut output = LayoutOutput::new(&mut glyphs, &mut runs, &mut lines, &mut carets);
576
577 let error = match flow.layout_into(&typefaces, &mut workspace, &mut output) {
578 Ok(_) => panic!("layout unexpectedly succeeded"),
579 Err(error) => error,
580 };
581 assert_eq!(
582 error,
583 WorkspaceError::Layout(LayoutError::InsufficientPositionedCapacity { minimum: 2 })
584 );
585 }
586
587 #[test]
588 fn breaking_and_alignment_widths_are_independent() {
589 let mut workspace = TextWorkspace::new(limits());
590 let source = Source;
591 let typeface = SimpleTypeface::new(&source);
592 let typefaces: [&dyn Typeface; 1] = [&typeface];
593 let flow = TextFlow::new("ab cd", 3)
594 .with_width(10)
595 .with_line_height(10)
596 .with_alignment(crate::layout::Alignment::Center);
597 let mut output = OutputStorage::new();
598
599 output
600 .with_layout(&flow, &typefaces, &mut workspace, |layout| {
601 assert_eq!(layout.lines().len(), 2);
602 assert_eq!(layout.lines()[0].origin().x, 3);
603 assert_eq!(layout.lines()[1].origin().x, 4);
604 })
605 .unwrap();
606 }
607
608 #[test]
609 fn unbounded_layout_does_not_align_or_ellipsize() {
610 let mut workspace = TextWorkspace::new(limits());
611 let source = Source;
612 let typeface = SimpleTypeface::new(&source);
613 let typefaces: [&dyn Typeface; 1] = [&typeface];
614 let flow = TextFlow::new("ab", 1)
615 .without_width()
616 .with_line_height(10)
617 .with_wrap(crate::layout::WrapMode::NoWrap)
618 .with_alignment(crate::layout::Alignment::Center)
619 .with_overflow(crate::layout::Overflow::Ellipsis);
620 let mut output = OutputStorage::new();
621
622 output
623 .with_layout(&flow, &typefaces, &mut workspace, |layout| {
624 assert_eq!(layout.lines()[0].origin().x, 0);
625 assert_eq!(layout.glyphs().len(), 2);
626 })
627 .unwrap();
628 }
629
630 #[test]
631 fn memory_limit_rejects_growth_before_allocation() {
632 let mut limits = limits();
633 limits.memory_bytes = 0;
634 let mut workspace = TextWorkspace::new(limits);
635 let source = Source;
636 let typeface = SimpleTypeface::new(&source);
637 let typefaces: [&dyn Typeface; 1] = [&typeface];
638 let flow = TextFlow::new("a", 3).with_line_height(10);
639 let mut output = OutputStorage::new();
640
641 assert!(matches!(
642 output.error(&flow, &typefaces, &mut workspace),
643 WorkspaceError::MemoryLimit {
644 required: _,
645 limit: 0
646 }
647 ));
648 assert_eq!(workspace.resident_bytes(), 0);
649 }
650
651 #[test]
652 fn retained_storage_sets_the_minimum_memory_limit() {
653 let mut workspace = TextWorkspace::new(limits());
654 let source = Source;
655 let typeface = SimpleTypeface::new(&source);
656 let typefaces: [&dyn Typeface; 1] = [&typeface];
657 let flow = TextFlow::new("ab", 3).with_line_height(10);
658 let mut output = OutputStorage::new();
659 output
660 .with_layout(&flow, &typefaces, &mut workspace, |_| {})
661 .unwrap();
662 let resident = workspace.resident_bytes();
663
664 workspace.set_memory_limit(resident).unwrap();
665 assert_eq!(workspace.limits().memory_bytes, resident);
666 assert_eq!(
667 workspace.set_memory_limit(resident - 1),
668 Err(WorkspaceError::MemoryLimit {
669 required: resident,
670 limit: resident - 1,
671 })
672 );
673 assert_eq!(workspace.limits().memory_bytes, resident);
674 }
675
676 #[test]
677 fn rejects_text_before_using_workspace_capacity() {
678 let mut workspace = TextWorkspace::new(LayoutLimits {
679 text_bytes: 2,
680 ..limits()
681 });
682 let source = Source;
683 let typeface = SimpleTypeface::new(&source);
684 let typefaces: [&dyn Typeface; 1] = [&typeface];
685 let flow = TextFlow::new("abc", 3).with_line_height(10);
686
687 let mut output = OutputStorage::new();
688 assert_eq!(
689 output.error(&flow, &typefaces, &mut workspace),
690 WorkspaceError::TextLimit {
691 required: 3,
692 limit: 2,
693 }
694 );
695 }
696
697 #[test]
698 fn rejects_dimensions_outside_layout_coordinates() {
699 let mut workspace = TextWorkspace::new(limits());
700 let source = Source;
701 let typeface = SimpleTypeface::new(&source);
702 let typefaces: [&dyn Typeface; 1] = [&typeface];
703 let flow = TextFlow::new("a", usize::MAX).with_line_height(10);
704
705 let mut output = OutputStorage::new();
706 assert_eq!(
707 output.error(&flow, &typefaces, &mut workspace),
708 WorkspaceError::DimensionOverflow
709 );
710 }
711
712 #[test]
713 fn ellipsis_is_shaped_and_excluded_from_caret_navigation() {
714 let mut workspace = TextWorkspace::new(limits());
715 let source = Source;
716 let typeface = SimpleTypeface::new(&source);
717 let typefaces: [&dyn Typeface; 1] = [&typeface];
718 let flow = TextFlow::new("ab cd", 3)
719 .with_line_height(10)
720 .with_max_lines(1)
721 .with_overflow(crate::layout::Overflow::Ellipsis);
722 let mut output = OutputStorage::new();
723 output
724 .with_layout(&flow, &typefaces, &mut workspace, |layout| {
725 assert_eq!(layout.lines().len(), 1);
726 assert_eq!(
727 layout.lines()[0].text(),
728 crate::shaping::TextRange::new(0, 2)
729 );
730 assert_eq!(layout.glyphs().len(), 3);
731 assert_eq!(
732 layout.glyphs()[2].glyph_id(),
733 GlyphId::new('\u{2026}' as u16)
734 );
735 assert!(layout.runs()[1].is_synthetic());
736 assert_eq!(
737 layout.runs()[1].text(),
738 crate::shaping::TextRange::new(2, 2)
739 );
740 assert_eq!(layout.carets().len(), 3);
741 assert_eq!(layout.carets().last().unwrap().text_offset, 2);
742 })
743 .unwrap();
744 }
745
746 #[test]
747 fn no_wrap_ellipsis_replaces_horizontal_overflow() {
748 let mut workspace = TextWorkspace::new(LayoutLimits {
749 scratch_glyphs: 5,
750 ..limits()
751 });
752 let source = Source;
753 let typeface = SimpleTypeface::new(&source);
754 let typefaces: [&dyn Typeface; 1] = [&typeface];
755 let flow = TextFlow::new("abcde", 3)
756 .with_line_height(10)
757 .with_wrap(crate::layout::WrapMode::NoWrap)
758 .with_overflow(crate::layout::Overflow::Ellipsis);
759 let mut output = OutputStorage::new();
760 output
761 .with_layout(&flow, &typefaces, &mut workspace, |layout| {
762 assert_eq!(layout.lines().len(), 1);
763 assert_eq!(
764 layout.lines()[0].text(),
765 crate::shaping::TextRange::new(0, 2)
766 );
767 assert_eq!(layout.lines()[0].advance(), 3);
768 assert_eq!(layout.glyphs().len(), 3);
769 assert_eq!(
770 layout.glyphs()[2].glyph_id(),
771 GlyphId::new('\u{2026}' as u16)
772 );
773 })
774 .unwrap();
775 }
776
777 #[test]
778 fn rtl_ellipsis_occupies_the_visual_start() {
779 let mut workspace = TextWorkspace::new(limits());
780 let source = Source;
781 let typeface = SimpleTypeface::new(&source);
782 let typefaces: [&dyn Typeface; 1] = [&typeface];
783 let flow = TextFlow::new("ab cd", 3)
784 .with_line_height(10)
785 .with_direction(crate::bidi::BaseDirection::RightToLeft)
786 .with_max_lines(1)
787 .with_overflow(crate::layout::Overflow::Ellipsis);
788 let mut output = OutputStorage::new();
789 output
790 .with_layout(&flow, &typefaces, &mut workspace, |layout| {
791 assert!(layout.runs()[0].is_synthetic());
792 assert_eq!(
793 layout.glyphs()[0].glyph_id(),
794 GlyphId::new('\u{2026}' as u16)
795 );
796 assert_eq!(layout.glyphs()[0].origin.x, 0);
797 assert_eq!(layout.glyphs()[1].origin.x, 1);
798 })
799 .unwrap();
800 }
801}