Skip to main content

LayoutEngine

Struct LayoutEngine 

Source
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 reusable PositionedGlyph buffer. On every Self::layout_with_strategy call 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 expensive crate::linebreak::LineBreaker pass 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 by Self::layout_if_dirty after a successful relayout.

Implementations§

Source§

impl LayoutEngine

Source

pub fn new() -> Self

Creates a new layout engine.

Source

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.

Source

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).

Source

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.

Source

pub fn layout_if_dirty<F>( &mut self, cached: Option<LayoutResult>, layout_fn: F, ) -> LayoutResult
where F: FnOnce(&mut LayoutEngine) -> LayoutResult,

Relayout only if dirty; otherwise return the cached layout result.

  • cached: the previous LayoutResult to return unchanged when no dirty ranges are pending and a cached result is available.
  • layout_fn: a closure that produces a fresh LayoutResult when a relayout is needed. The closure receives &mut LayoutEngine so 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).

Source

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_text must be the exact string the runs were shaped from, so that ShapedGlyph::cluster byte offsets index into it.
  • constraints.max_width of 0.0 disables wrapping (single line per mandatory break).
  • alignment controls horizontal placement within max_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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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

Source

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
  1. Flatten all glyphs from all runs into a single sequence, tagging each with its run’s vertical metrics and pixel size.
  2. Compute UAX #14 line-break opportunities from a synthetic “cluster string” built from the cluster byte offsets; use greedy wrapping against max_width.
  3. Group glyphs into lines.
  4. 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.
  5. Assign baseline_y = cursor_y + line_ascender. Each glyph’s y is baseline_y + (line_ascender − run_ascender), lifting shorter-ascender glyphs up so their own ascender aligns with the tallest.
  6. 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 each ShapedGlyph index into this string).
  • max_width – maximum line width in pixels; 0.0 disables 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

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for LayoutEngine

Source§

fn default() -> LayoutEngine

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.