pub struct LayoutEngine { /* private fields */ }Expand description
Word-aware, alignment-capable layout engine.
Carries two optional caches to improve throughput in GUI loops and other scenarios where the same (or similarly-sized) text is laid out repeatedly:
scratch— a reusablePositionedGlyphbuffer. On everySelf::layout_with_strategycall the buffer is cleared (keeping its allocated capacity) and refilled, so the heap allocation survives across calls.break_cache_text/break_cache_ops— the last source string and its precomputed UAX #14 break opportunities. When the caller re-lays out the same text (e.g. after a window resize) the expensivecrate::linebreak::LineBreakerpass is skipped.dirty_ranges— byte offset ranges in the source text that have changed since the last layout pass. When non-empty, the next layout call will re-break all affected lines. Cleared automatically bySelf::layout_if_dirtyafter a successful relayout.
Implementations§
Source§impl LayoutEngine
impl LayoutEngine
Sourcepub fn mark_dirty(&mut self, range: Range<usize>)
pub fn mark_dirty(&mut self, range: Range<usize>)
Mark a byte range of the source text as modified (content changed, inserted, or deleted). The next layout call will re-layout lines affected by this range.
Multiple overlapping or disjoint ranges can be accumulated before
triggering a layout pass. All dirty markers are cleared automatically
by Self::layout_if_dirty after a successful relayout.
Sourcepub fn clear_dirty(&mut self)
pub fn clear_dirty(&mut self)
Clear all dirty markers.
Called automatically by Self::layout_if_dirty after a layout pass.
You can also call this manually to discard pending dirty state without
triggering a relayout (e.g. after discarding the associated text edit).
Sourcepub fn has_dirty(&self) -> bool
pub fn has_dirty(&self) -> bool
Returns true if any text range has been marked dirty since the last
Self::clear_dirty or Self::layout_if_dirty call.
Sourcepub fn layout_if_dirty<F>(
&mut self,
cached: Option<LayoutResult>,
layout_fn: F,
) -> LayoutResult
pub fn layout_if_dirty<F>( &mut self, cached: Option<LayoutResult>, layout_fn: F, ) -> LayoutResult
Relayout only if dirty; otherwise return the cached layout result.
cached: the previousLayoutResultto return unchanged when no dirty ranges are pending and a cached result is available.layout_fn: a closure that produces a freshLayoutResultwhen a relayout is needed. The closure receives&mut LayoutEngineso it can call any of the layout methods directly.
After a relayout layout_fn is invoked, all dirty markers are cleared
automatically. If the engine is clean and cached is None, the
closure is still called (there is nothing to return otherwise).
Sourcepub fn layout(
&mut self,
source_text: &str,
runs: &[ShapedRun],
constraints: &LayoutConstraints,
alignment: TextAlignment,
font_metrics: Option<&FontVerticalMetrics>,
) -> Result<LayoutResult, OxiTextError>
pub fn layout( &mut self, source_text: &str, runs: &[ShapedRun], constraints: &LayoutConstraints, alignment: TextAlignment, font_metrics: Option<&FontVerticalMetrics>, ) -> Result<LayoutResult, OxiTextError>
Lays out runs over source_text, wrapping at line-break opportunities.
When the icu feature is enabled the layout uses CLDR-compliant line
breaking via [Self::layout_cldr] (better quality for CJK, Thai, and
other complex scripts). Without the icu feature this falls back to
UAX #14 line breaking via the greedy (first-fit) algorithm.
To explicitly request UAX #14 line breaking regardless of the icu
feature, use Self::layout_uax14.
source_textmust be the exact string the runs were shaped from, so thatShapedGlyph::clusterbyte offsets index into it.constraints.max_widthof0.0disables wrapping (single line per mandatory break).alignmentcontrols horizontal placement withinmax_width.font_metrics, when supplied, drives accurate line height; otherwise a size-proportional fallback is used.
§Errors
Currently infallible for well-formed input; returns Err only for
forward compatibility.
Sourcepub fn layout_uax14(
&mut self,
source_text: &str,
runs: &[ShapedRun],
constraints: &LayoutConstraints,
alignment: TextAlignment,
font_metrics: Option<&FontVerticalMetrics>,
) -> Result<LayoutResult, OxiTextError>
pub fn layout_uax14( &mut self, source_text: &str, runs: &[ShapedRun], constraints: &LayoutConstraints, alignment: TextAlignment, font_metrics: Option<&FontVerticalMetrics>, ) -> Result<LayoutResult, OxiTextError>
Lays out runs using UAX #14 (unicode-linebreak) line breaking,
regardless of whether the icu feature is compiled in.
This is the explicit opt-out from CLDR line breaking. Use this when you need a consistent UAX #14 code path independent of feature flags, for example in tests that compare break positions.
Uses the greedy (first-fit) algorithm. For Knuth-Plass optimal breaking
call LayoutEngine::layout_with_strategy directly with
BreakingStrategy::KnuthPlass.
§Errors
Currently infallible for well-formed input; returns Err only for
forward compatibility.
Sourcepub fn layout_with_strategy(
&mut self,
source_text: &str,
runs: &[ShapedRun],
constraints: &LayoutConstraints,
alignment: TextAlignment,
font_metrics: Option<&FontVerticalMetrics>,
strategy: BreakingStrategy,
) -> Result<LayoutResult, OxiTextError>
pub fn layout_with_strategy( &mut self, source_text: &str, runs: &[ShapedRun], constraints: &LayoutConstraints, alignment: TextAlignment, font_metrics: Option<&FontVerticalMetrics>, strategy: BreakingStrategy, ) -> Result<LayoutResult, OxiTextError>
Lays out runs over source_text using the specified breaking
strategy.
This is the full-featured entry point. LayoutEngine::layout is a
convenience wrapper that always uses BreakingStrategy::Greedy.
When strategy is BreakingStrategy::KnuthPlass and
constraints.max_width > 0, the algorithm calls
crate::knuth_plass::optimal_breaks to compute globally optimal
break positions before positioning glyphs. If the KP solver finds no
feasible solution it automatically falls back to the greedy algorithm.
§Errors
Currently infallible for well-formed input; returns Err only for
forward compatibility.
Sourcepub fn layout_with_break_points(
&mut self,
source_text: &str,
runs: &[ShapedRun],
constraints: &LayoutConstraints,
alignment: TextAlignment,
font_metrics: Option<&FontVerticalMetrics>,
break_points: &[usize],
) -> Result<LayoutResult, OxiTextError>
pub fn layout_with_break_points( &mut self, source_text: &str, runs: &[ShapedRun], constraints: &LayoutConstraints, alignment: TextAlignment, font_metrics: Option<&FontVerticalMetrics>, break_points: &[usize], ) -> Result<LayoutResult, OxiTextError>
Lays out runs using externally-supplied break point byte offsets.
Identical to LayoutEngine::layout_with_strategy (greedy algorithm)
except that instead of computing UAX #14 break opportunities internally,
this method treats every offset in break_points as an
crate::linebreak::LineBreak::Allowed opportunity. This allows
callers — e.g. the facade or ICU-backed pipeline — to inject their own
(CLDR-compliant) break points without re-running the built-in linebreaker.
§Arguments
source_text— the source string the runs were shaped from.runs— shaped glyph runs.constraints— layout constraints (max width, font size).alignment— horizontal text alignment.font_metrics— optional font vertical metrics.break_points— slice of UTF-8 byte offsets where line breaks are permitted. The slice need not be sorted (it will be searched with binary search after sorting internally).
§Errors
Currently infallible for well-formed input.
Sourcepub fn layout_vertical(
&mut self,
_source_text: &str,
runs: &[ShapedRun],
max_column_height: f32,
font_size: f32,
_font_metrics: Option<&FontVerticalMetrics>,
) -> Result<LayoutResult, OxiTextError>
pub fn layout_vertical( &mut self, _source_text: &str, runs: &[ShapedRun], max_column_height: f32, font_size: f32, _font_metrics: Option<&FontVerticalMetrics>, ) -> Result<LayoutResult, OxiTextError>
Lays out runs in vertical top-to-bottom flow.
Each glyph advances the cursor downward by its vertical advance (falling
back to font_size when no vmtx data is available). When
max_column_height > 0.0, the text wraps into additional columns once
the current column’s height would be exceeded; each column advances the
x origin by font_size * 1.2.
A “line” in this context is one vertical column of glyphs. The
returned Line structs therefore index into the column-by-column
glyph list, and ParagraphMetrics::line_count equals the number of
columns used.
Note: bidi reordering is not applied in vertical mode; vertical CJK text is always read top-to-bottom in column order.
§Errors
Currently infallible for well-formed input; returns Err only for
forward compatibility.
Sourcepub fn layout_paragraphs(
&mut self,
paragraphs: &[&str],
shaped_runs_per_paragraph: &[&[ShapedRun]],
constraints: &LayoutConstraints,
para_spacing: f32,
options: &LayoutOptions,
font_metrics: Option<&FontVerticalMetrics>,
) -> Result<LayoutResult, OxiTextError>
pub fn layout_paragraphs( &mut self, paragraphs: &[&str], shaped_runs_per_paragraph: &[&[ShapedRun]], constraints: &LayoutConstraints, para_spacing: f32, options: &LayoutOptions, font_metrics: Option<&FontVerticalMetrics>, ) -> Result<LayoutResult, OxiTextError>
Lays out multiple paragraphs stacked vertically.
Each paragraph is laid out independently using LayoutEngine::layout
(greedy algorithm). The y-positions of each paragraph’s glyphs and line
baselines are offset by the accumulated height of all previous paragraphs
plus para_spacing between them.
The returned LayoutResult has all glyphs and lines merged into a
single flat list. ParagraphMetrics reflects the combined extent.
§Errors
Propagates any error returned by the inner LayoutEngine::layout
calls.
Sourcepub fn layout_with_options(
&mut self,
source_text: &str,
shaped_runs: &[ShapedRun],
max_width: f32,
options: &LayoutOptions,
font_metrics: Option<&FontVerticalMetrics>,
font_size: f32,
) -> Result<LayoutResult, OxiTextError>
pub fn layout_with_options( &mut self, source_text: &str, shaped_runs: &[ShapedRun], max_width: f32, options: &LayoutOptions, font_metrics: Option<&FontVerticalMetrics>, font_size: f32, ) -> Result<LayoutResult, OxiTextError>
Lays out a single text block using comprehensive crate::options::LayoutOptions.
This is a unified entry point that dispatches to the appropriate layout
path based on crate::options::LayoutOptions::flow_direction and applies optional
post-processing (truncation).
Tab stop handling for \t characters: when a glyph’s cluster character
is \t, the cursor advances to the next tab stop instead of using the
glyph’s natural advance. The positioned glyph’s x is placed at the
pre-tab cursor position (the whitespace gap itself is empty).
§Errors
Propagates any error returned by the inner layout calls.
Source§impl LayoutEngine
impl LayoutEngine
Sourcepub fn layout_styled_runs(
&mut self,
runs: &[StyledRun],
source_text: &str,
max_width: f32,
options: &LayoutOptions,
) -> Result<LayoutResult, OxiTextError>
pub fn layout_styled_runs( &mut self, runs: &[StyledRun], source_text: &str, max_width: f32, options: &LayoutOptions, ) -> Result<LayoutResult, OxiTextError>
Lays out a slice of pre-shaped StyledRuns with baseline alignment.
§Algorithm
- Flatten all glyphs from all runs into a single sequence, tagging each with its run’s vertical metrics and pixel size.
- Compute UAX #14 line-break opportunities from a synthetic “cluster
string” built from the cluster byte offsets; use greedy wrapping
against
max_width. - Group glyphs into lines.
- For each line compute:
line_ascender = max(run.ascent_px)across all runs on the line.line_descender = max(run.descent_px)across all runs on the line.
- Assign
baseline_y = cursor_y + line_ascender. Each glyph’syisbaseline_y + (line_ascender − run_ascender), lifting shorter-ascender glyphs up so their own ascender aligns with the tallest. - Advance
cursor_y += line_ascender + line_descender + line_gap + options.paragraph_spacing.
§Parameters
runs– pre-shaped runs in logical order.source_text– the original string the runs were shaped from (required for UAX #14 linebreak analysis; cluster offsets in eachShapedGlyphindex into this string).max_width– maximum line width in pixels;0.0disables wrapping.options– paragraph options (paragraph_spacing is used as extra leading after each line).
§Errors
Currently infallible for well-formed input; returns Err only for
forward compatibility.
Trait Implementations§
Source§impl Debug for LayoutEngine
impl Debug for LayoutEngine
Source§impl Default for LayoutEngine
impl Default for LayoutEngine
Source§fn default() -> LayoutEngine
fn default() -> LayoutEngine
Auto Trait Implementations§
impl Freeze for LayoutEngine
impl RefUnwindSafe for LayoutEngine
impl Send for LayoutEngine
impl Sync for LayoutEngine
impl Unpin for LayoutEngine
impl UnsafeUnpin for LayoutEngine
impl UnwindSafe for LayoutEngine
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more