app: add native rune client for record-daemon

Replaces the Vue/Tauri front end with a rune app that speaks the daemon's
existing IPC protocol: settings (general, recording, audio), match history
and game review with a scrubber, event markers and ffmpeg highlight export.
Includes tray icon, launch at login, single instance, toasts, a headless
snapshot path for checking screens, and a cargo-packager NSIS config.

Rune is pinned to 4ddf696b0f and its three patched crates are vendored under
app/vendor, since a dependency's [patch.crates-io] does not apply to the app.

The daemon's OBS bootstrap never reached its IPC server on this machine, so
the live check is a `--probe` command; the wire format is covered by tests.
This commit is contained in:
vhaudiquet committed 2026-11-15 21:53:44 +01:00
1 parent d712c4ea85
commit 0377141e4f
349 files changed
+142819

No files matched your search

+934
View File
@@ -0,0 +1,934 @@
// Copyright 2025 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Text analysis.
//!
//! Analysis is performed prior to shaping and is independent of fonts, turning a `&str` into
//! [`Analysis`].
use alloc::vec::Vec;
use core::ops::Range;
use icu_locale_core::{LanguageIdentifier, langid};
use icu_normalizer::properties::{
CanonicalComposition, CanonicalCompositionBorrowed, CanonicalDecomposition,
CanonicalDecompositionBorrowed,
};
use icu_properties::props::{BidiMirroringGlyph, GeneralCategory, GraphemeClusterBreak, Script};
use icu_properties::{
CodePointMapData, CodePointMapDataBorrowed, PropertyNamesShort, PropertyNamesShortBorrowed,
};
use icu_segmenter::options::{
LineBreakOptions, LineBreakStrictness, LineBreakWordOption, WordBreakInvariantOptions,
};
use icu_segmenter::{
GraphemeClusterSegmenter, GraphemeClusterSegmenterBorrowed, LineSegmenter,
LineSegmenterBorrowed, WordSegmenter, WordSegmenterBorrowed,
};
use parlance::{BaseDirection, BidiLevel, LineBreak, WordBreak};
use parley_data::Properties;
use crate::bidi;
use crate::break_overrides::LineBreakContext;
use crate::{AnalysisOptions, Analyzer, LineBreakConfig};
/// The result of [`Analyzer::analyze`].
#[derive(Debug, Default)]
pub struct Analysis {
/// Info for each character.
pub(crate) info: Vec<CharInfo>,
/// Bidi level for each character, parallel to `info`.
///
/// Empty if the text is all LTR.
pub(crate) levels: Vec<BidiLevel>,
/// The base bidi level of the paragraph of text.
pub(crate) paragraph_level: BidiLevel,
}
impl Analysis {
/// Create a reusable [`Analysis`].
///
/// Pass this to [`Analyzer::analyze`].
#[inline]
pub fn new() -> Self {
Self::default()
}
/// Clear the result while retaining capacity.
pub(crate) fn clear(&mut self) {
self.info.clear();
self.levels.clear();
self.paragraph_level = BidiLevel::new(0);
}
/// The per-character info in source order.
#[inline(always)]
pub fn char_info(&self) -> &[CharInfo] {
&self.info
}
/// The bidi level for each character, parallel to [`Self::char_info`].
///
/// Empty when the whole paragraph is left-to-right.
#[inline(always)]
pub fn bidi_levels(&self) -> &[BidiLevel] {
&self.levels
}
/// The base bidi level of the paragraph of text.
#[inline(always)]
pub fn paragraph_level(&self) -> BidiLevel {
self.paragraph_level
}
}
// TODO: Make `pub(crate)` once `parley_engine` owns shaping.
#[doc(hidden)]
#[expect(missing_debug_implementations, reason = "Will become private")]
pub struct AnalysisDataSources;
impl AnalysisDataSources {
#[expect(clippy::new_without_default, reason = "Will become private")]
pub fn new() -> Self {
Self
}
#[inline(always)]
pub fn properties(&self, c: char) -> Properties {
Properties::get(c)
}
#[inline(always)]
pub fn grapheme_segmenter(&self) -> GraphemeClusterSegmenterBorrowed<'_> {
const { GraphemeClusterSegmenter::new() }
}
#[inline(always)]
fn word_segmenter(&self) -> WordSegmenterBorrowed<'static> {
#[cfg(feature = "complex-scripts")]
{
WordSegmenter::new_dictionary(WordBreakInvariantOptions::default())
}
#[cfg(not(feature = "complex-scripts"))]
{
const { WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default()) }
}
}
#[inline(always)]
fn line_segmenter(&self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> {
// We use Japanese arbitrarily; see `SegmenterKey::ja_zh`.
static JA: LanguageIdentifier = langid!("ja");
let mut opt = LineBreakOptions::default();
opt.word_option = Some(key.word_option);
opt.strictness = Some(key.strictness);
opt.content_locale = key.ja_zh.then_some(&JA);
line_segmenter_impl(opt)
}
#[inline(always)]
pub fn composing_normalizer(&self) -> CanonicalCompositionBorrowed<'_> {
const { CanonicalComposition::new() }
}
#[inline(always)]
pub fn decomposing_normalizer(&self) -> CanonicalDecompositionBorrowed<'_> {
const { CanonicalDecomposition::new() }
}
#[inline(always)]
pub fn script_short_name(&self) -> PropertyNamesShortBorrowed<'static, Script> {
PropertyNamesShort::new()
}
#[inline(always)]
fn brackets(&self) -> CodePointMapDataBorrowed<'_, BidiMirroringGlyph> {
const { CodePointMapData::new() }
}
}
/// The segmenters an [`Analyzer`] has made, kept for its next texts (Rune:
/// vendor/parley_engine.patch). Making one looks up its rule data and, with `complex-scripts`,
/// loads the dictionaries; they're `'static` and `Copy`, so a kept one is the same value a new
/// one would be.
#[derive(Default)]
pub(crate) struct Segmenters {
line: Vec<(SegmenterKey, LineSegmenterBorrowed<'static>)>,
word: Option<WordSegmenterBorrowed<'static>>,
}
impl Segmenters {
fn line(&mut self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> {
if let Some((_, segmenter)) = self.line.iter().find(|(k, _)| *k == key) {
return *segmenter;
}
let segmenter = AnalysisDataSources::new().line_segmenter(key);
self.line.push((key, segmenter));
segmenter
}
fn word(&mut self) -> WordSegmenterBorrowed<'static> {
*self
.word
.get_or_insert_with(|| AnalysisDataSources::new().word_segmenter())
}
}
// `line-dictionaries` (Rune: vendor/parley_engine.patch): the line segmenter's Thai, Lao, Khmer and
// Burmese dictionaries without the word segmenter's (Chinese and Japanese words come from the host's
// `dictionary` segmenter instead).
#[cfg(any(feature = "complex-scripts", feature = "line-dictionaries"))]
#[inline(always)]
fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> {
LineSegmenter::new_dictionary(opt)
}
#[cfg(not(any(feature = "complex-scripts", feature = "line-dictionaries")))]
#[inline(always)]
fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> {
LineSegmenter::new_for_non_complex_scripts(opt)
}
/// The line segmenter configuration for a [`LineBreakConfig`].
///
/// Configurations which result in the same segmentation map to the same key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct SegmenterKey {
word_option: LineBreakWordOption,
strictness: LineBreakStrictness,
/// See [`LineBreakConfig::language`]; the only languages which impact segmentation are
/// Chinese and Japanese. These impact it in the same way, and only under
/// [`LineBreak::Normal`] and [`LineBreak::Loose`], so we only track whether one of them
/// applies.
ja_zh: bool,
}
impl SegmenterKey {
const DEFAULT: Self = Self {
word_option: LineBreakWordOption::Normal,
strictness: LineBreakStrictness::Strict,
ja_zh: false,
};
fn new(config: &LineBreakConfig) -> Self {
let strictness = match config.line_break {
LineBreak::Strict => LineBreakStrictness::Strict,
LineBreak::Normal => LineBreakStrictness::Normal,
LineBreak::Loose => LineBreakStrictness::Loose,
// We add opportunities per grapheme ourselves.
LineBreak::Anywhere => return Self::DEFAULT,
};
let word_option = match config.word_break {
WordBreak::Normal => LineBreakWordOption::Normal,
WordBreak::BreakAll => LineBreakWordOption::BreakAll,
WordBreak::KeepAll => LineBreakWordOption::KeepAll,
};
let ja_zh = match strictness {
LineBreakStrictness::Normal | LineBreakStrictness::Loose => config
.language
.is_some_and(|language| matches!(language.language(), "ja" | "zh")),
_ => false,
};
Self {
word_option,
strictness,
ja_zh,
}
}
}
/// Per-character analysis info.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct CharInfo {
/// The Unicode script this character belongs to.
pub script: Script,
flags: u16,
}
impl CharInfo {
const VARIATION_SELECTOR_SHIFT: u16 = 0;
const REGION_INDICATOR_SHIFT: u16 = 1;
const CONTROL_SHIFT: u16 = 2;
const EMOJI_OR_PICTOGRAPH_SHIFT: u16 = 3;
const CONTRIBUTES_TO_SHAPING_SHIFT: u16 = 4;
const FORCE_NORMALIZE_SHIFT: u16 = 5;
const GRAPHEME_START_SHIFT: u16 = 6;
const WORD_BOUNDARY_SHIFT: u8 = 7;
const SOFT_WRAP_OPPORTUNITY_SHIFT: u16 = 8;
const EMOJI_SHIFT: u16 = 9;
const EMOJI_PRESENTATION_SHIFT: u16 = 10;
const EMOJI_MODIFIER_SHIFT: u16 = 11;
const EMOJI_MODIFIER_BASE_SHIFT: u16 = 12;
const VARIATION_SELECTOR_MASK: u16 = 1 << Self::VARIATION_SELECTOR_SHIFT;
const REGION_INDICATOR_MASK: u16 = 1 << Self::REGION_INDICATOR_SHIFT;
const CONTROL_MASK: u16 = 1 << Self::CONTROL_SHIFT;
const EMOJI_OR_PICTOGRAPH_MASK: u16 = 1 << Self::EMOJI_OR_PICTOGRAPH_SHIFT;
const CONTRIBUTES_TO_SHAPING_MASK: u16 = 1 << Self::CONTRIBUTES_TO_SHAPING_SHIFT;
const FORCE_NORMALIZE_MASK: u16 = 1 << Self::FORCE_NORMALIZE_SHIFT;
const GRAPHEME_START_MASK: u16 = 1 << Self::GRAPHEME_START_SHIFT;
const WORD_BOUNDARY_MASK: u16 = 1 << Self::WORD_BOUNDARY_SHIFT;
const SOFT_WRAP_OPPORTUNITY_MASK: u16 = 1 << Self::SOFT_WRAP_OPPORTUNITY_SHIFT;
const EMOJI_MASK: u16 = 1 << Self::EMOJI_SHIFT;
const EMOJI_PRESENTATION_MASK: u16 = 1 << Self::EMOJI_PRESENTATION_SHIFT;
const EMOJI_MODIFIER_MASK: u16 = 1 << Self::EMOJI_MODIFIER_SHIFT;
const EMOJI_MODIFIER_BASE_MASK: u16 = 1 << Self::EMOJI_MODIFIER_BASE_SHIFT;
fn new(
script: Script,
is_variation_selector: bool,
is_region_indicator: bool,
is_control: bool,
is_emoji_or_pictograph: bool,
contributes_to_shaping: bool,
force_normalize: bool,
is_grapheme_start: bool,
is_word_boundary: bool,
is_soft_wrap_opportunity: bool,
is_emoji: bool,
is_emoji_presentation: bool,
is_emoji_modifier: bool,
is_emoji_modifier_base: bool,
) -> Self {
Self {
script,
flags: (is_variation_selector as u16) << Self::VARIATION_SELECTOR_SHIFT
| (is_region_indicator as u16) << Self::REGION_INDICATOR_SHIFT
| (is_control as u16) << Self::CONTROL_SHIFT
| (is_emoji_or_pictograph as u16) << Self::EMOJI_OR_PICTOGRAPH_SHIFT
| (contributes_to_shaping as u16) << Self::CONTRIBUTES_TO_SHAPING_SHIFT
| (force_normalize as u16) << Self::FORCE_NORMALIZE_SHIFT
| (is_grapheme_start as u16) << Self::GRAPHEME_START_SHIFT
| (is_word_boundary as u16) << Self::WORD_BOUNDARY_SHIFT
| (is_soft_wrap_opportunity as u16) << Self::SOFT_WRAP_OPPORTUNITY_SHIFT
| (is_emoji as u16) << Self::EMOJI_SHIFT
| (is_emoji_presentation as u16) << Self::EMOJI_PRESENTATION_SHIFT
| (is_emoji_modifier as u16) << Self::EMOJI_MODIFIER_SHIFT
| (is_emoji_modifier_base as u16) << Self::EMOJI_MODIFIER_BASE_SHIFT,
}
}
/// Whether this character is a variation selector.
#[inline(always)]
pub fn is_variation_selector(self) -> bool {
self.flags & Self::VARIATION_SELECTOR_MASK != 0
}
/// Whether this character is a regional indicator symbol.
#[inline(always)]
pub fn is_region_indicator(self) -> bool {
self.flags & Self::REGION_INDICATOR_MASK != 0
}
/// Whether this character is a control character.
#[inline(always)]
pub fn is_control(self) -> bool {
self.flags & Self::CONTROL_MASK != 0
}
/// Returns whether the character has either of the `Emoji` or`Extended_Pictographic` properties.
///
/// Parley Engine uses this to determine whether a character might be part of an Emoji, and so whether to do
/// more stringent checks.
///
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
#[inline(always)]
pub fn is_emoji_or_pictograph(self) -> bool {
self.flags & Self::EMOJI_OR_PICTOGRAPH_MASK != 0
}
/// Whether this character has the `Emoji` property ([UTS #51][]).
///
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
#[inline(always)]
pub fn is_emoji(self) -> bool {
self.flags & Self::EMOJI_MASK != 0
}
/// Whether this character has the `Emoji_Presentation` property ([UTS #51][]), i.e. it is
/// displayed as an emoji by default.
///
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
#[inline(always)]
pub fn is_emoji_presentation(self) -> bool {
self.flags & Self::EMOJI_PRESENTATION_MASK != 0
}
/// Whether this character has the `Emoji_Modifier` property ([UTS #51][]), i.e. it is a
/// skin tone modifier.
///
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
#[inline(always)]
pub fn is_emoji_modifier(self) -> bool {
self.flags & Self::EMOJI_MODIFIER_MASK != 0
}
/// Whether this character has the `Emoji_Modifier_Base` property ([UTS #51][]), i.e. it can
/// be followed by a skin tone modifier.
///
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
#[inline(always)]
pub fn is_emoji_modifier_base(self) -> bool {
self.flags & Self::EMOJI_MODIFIER_BASE_MASK != 0
}
/// Whether this character contributes glyphs to shaping (`false` for control characters and
/// most format characters).
#[inline(always)]
pub fn contributes_to_shaping(self) -> bool {
self.flags & Self::CONTRIBUTES_TO_SHAPING_MASK != 0
}
/// Whether this character should be normalized before glyph mapping during shaping.
#[inline(always)]
pub fn force_normalize(self) -> bool {
self.flags & Self::FORCE_NORMALIZE_MASK != 0
}
/// Whether this character begins a grapheme cluster ([UAX #29 § 3][graphemes]).
///
/// [graphemes]: https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
#[inline(always)]
pub fn is_grapheme_start(self) -> bool {
self.flags & Self::GRAPHEME_START_MASK != 0
}
/// Whether there is a word boundary before this character ([UAX #29 § 4][words]).
///
/// [words]: https://www.unicode.org/reports/tr29/#Word_Boundaries
#[inline(always)]
pub fn is_word_boundary(self) -> bool {
self.flags & Self::WORD_BOUNDARY_MASK != 0
}
/// Whether there is a soft wrap opportunity before this character ([UAX #14][line-breaking]).
///
/// Note mandatory breaks (like `\n`) are encoded as [`Whitespace`](crate::shape::Whitespace).
///
/// [line-breaking]: https://www.unicode.org/reports/tr14/
#[inline(always)]
pub fn is_soft_wrap_opportunity(self) -> bool {
self.flags & Self::SOFT_WRAP_OPPORTUNITY_MASK != 0
}
}
pub(crate) fn analyze_text(
analyzer: &mut Analyzer,
text: &str,
options: &AnalysisOptions<'_>,
analysis: &mut Analysis,
) {
/// Turns the sparse, sorted, non-overlapping `options.line_break` into a contiguous sequence of
/// `(range, segmenter key)` segments covering all of `text`.
///
/// Any region not covered by an override takes the default configuration.
struct DenseLineBreaks<'a> {
line_break: &'a [(Range<usize>, LineBreakConfig)],
/// Index of the next word break to emit.
next: usize,
/// Start of the next segment to emit.
cursor: usize,
text_len: usize,
}
impl<'a> DenseLineBreaks<'a> {
fn new(line_break: &'a [(Range<usize>, LineBreakConfig)], text_len: usize) -> Self {
Self {
line_break,
next: 0,
cursor: 0,
text_len,
}
}
}
impl Iterator for DenseLineBreaks<'_> {
type Item = (Range<usize>, SegmenterKey);
fn next(&mut self) -> Option<Self::Item> {
if self.cursor >= self.text_len {
return None;
}
// Ignore empty ranges.
while self
.line_break
.get(self.next)
.is_some_and(|(range, _)| range.is_empty())
{
self.next += 1;
}
match self.line_break.get(self.next) {
// A gap before the next override: fill it with the default up to its start.
Some((range, _)) if self.cursor < range.start => {
let segment = self.cursor..range.start;
self.cursor = range.start;
Some((segment, SegmenterKey::DEFAULT))
}
// At the next override: emit it.
Some((range, config)) => {
self.cursor = range.end;
self.next += 1;
Some((range.start..range.end, SegmenterKey::new(config)))
}
// No overrides remain: fill the default to the end.
None => {
let segment = self.cursor..self.text_len;
self.cursor = self.text_len;
Some((segment, SegmenterKey::DEFAULT))
}
}
}
}
struct LineBreakSegmentIter<'a, I: Iterator> {
text: &'a str,
segments: I,
char_indices: core::str::CharIndices<'a>,
current_char: (usize, char),
building_range_start: usize,
previous_key: SegmenterKey,
done: bool,
}
impl<'a, I> LineBreakSegmentIter<'a, I>
where
I: Iterator<Item = (Range<usize>, SegmenterKey)>,
{
fn new(text: &'a str, segments: I, first_segment: (Range<usize>, SegmenterKey)) -> Self {
let mut char_indices = text.char_indices();
let current_char_len = char_indices.next().unwrap();
Self {
text,
segments,
char_indices,
current_char: current_char_len,
building_range_start: first_segment.0.start,
previous_key: first_segment.1,
done: false,
}
}
}
impl<'a, I> Iterator for LineBreakSegmentIter<'a, I>
where
I: Iterator<Item = (Range<usize>, SegmenterKey)>,
{
type Item = (&'a str, SegmenterKey, bool);
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
for (range, key) in self.segments.by_ref() {
assert!(range.start < range.end, "Segments must not be empty");
let style_start_index = range.start;
let mut prev_char_index = self.current_char;
// Find the character at the style boundary.
while self.current_char.0 < style_start_index {
prev_char_index = self.current_char;
self.current_char = self.char_indices.next().unwrap();
}
let current_key = key;
if self.previous_key == current_key {
continue;
}
// Produce one substring for each different segmenter key run
let prev_size = prev_char_index.1.len_utf8();
let size = self.current_char.1.len_utf8();
let substring = &self.text[self.building_range_start..style_start_index + size];
let result_style = self.previous_key;
self.building_range_start = style_start_index - prev_size;
self.previous_key = current_key;
return Some((substring, result_style, false));
}
// Final segment
self.done = true;
let last_substring = &self.text[self.building_range_start..self.text.len()];
Some((last_substring, self.previous_key, true))
}
}
if text.is_empty() {
analyzer
.bidi
.resolve(core::iter::empty(), options.base_direction);
analysis.paragraph_level = analyzer.bidi.base_level();
return;
}
// Line boundaries (word break naming refers to the line boundary determination config).
//
// This breaks text into sequences with similar line boundary config (part of style
// information). If this config is consistent for all text, we use a fast path through this.
let mut segments = DenseLineBreaks::new(options.line_break, text.len());
// `text` is non-empty (checked above), so there is always at least one segment.
let first_segment = segments.next().unwrap();
let contiguous_substrings = LineBreakSegmentIter::new(text, segments, first_segment);
let mut global_offset = 0;
let mut line_boundary_positions: Vec<usize> = Vec::new();
let data_sources = AnalysisDataSources::new();
for (substring_index, (substring, segmenter_key, last)) in contiguous_substrings.enumerate() {
// Fast path for text with a single segmenter configuration.
if substring_index == 0 && last {
let mut lb_iter = analyzer
.segmenters
.line(segmenter_key)
.segment_str(substring);
let _first = lb_iter.next();
let second = lb_iter.next();
if second.is_none() {
continue;
}
let third = lb_iter.next();
if third.is_none() {
continue;
}
let iter = [second.unwrap(), third.unwrap()].into_iter().chain(lb_iter);
line_boundary_positions.extend(iter);
// Remove the unnecessary boundary at the end added by ICU4X.
line_boundary_positions.pop();
break;
}
let line_boundaries_iter = analyzer
.segmenters
.line(segmenter_key)
.segment_str(substring);
let mut substring_chars = substring.chars();
if substring_index != 0 {
global_offset -= substring_chars.next().unwrap().len_utf8();
}
// There will always be at least two characters if we are not taking the fast path for
// a single word break style substring.
let last_len = substring_chars.next_back().unwrap().len_utf8();
// Mark line boundaries (overriding word boundaries where present).
for (index, pos) in line_boundaries_iter.enumerate() {
// icu adds leading and trailing line boundaries, which we don't use.
if index == 0 || pos == substring.len() {
continue;
}
// For all but the last substring, we ignore line boundaries caused by the last
// character, as this character is carried back from the next substring, and will be
// accounted for there.
if !last && pos == substring.len() - last_len {
continue;
}
line_boundary_positions.push(pos + global_offset);
}
if !last {
global_offset += substring.len() - last_len;
}
}
// Words, and in Thai, Lao, Khmer and Burmese line breaks, that the host's dictionary finds
// (`dictionary`; Rune: vendor/parley_engine.patch).
let mut dictionary = crate::dictionary::Words::of(text, |c| data_sources.properties(c));
let before = line_boundary_positions.len();
line_boundary_positions.extend(dictionary.line_breaks());
if line_boundary_positions.len() > before {
line_boundary_positions.sort_unstable();
line_boundary_positions.dedup();
}
// Collect boundary byte positions compactly
let mut wb_iter = analyzer.segmenters.word().segment_str(text).peekable();
let mut gb_iter = data_sources
.grapheme_segmenter()
.segment_str(text)
.peekable();
// Merge boundaries - line takes precedence over word
let mut lb_iter = line_boundary_positions.iter().peekable();
let mut prev_char = None;
let mut prev_prev_char = None;
// Whether the preceding character is a mandatory break.
let mut prev_is_mandatory_linebreak = false;
// Whether the preceding character is a break-space, i.e. a space, tab or ideographic space in
// a `break_spaces` range.
let mut prev_is_break_space = false;
let mut break_spaces_iter = options.break_spaces.iter().peekable();
let mut break_anywhere_iter = options
.line_break
.iter()
.filter(|(_, config)| config.line_break == LineBreak::Anywhere)
.map(|(range, _)| range)
.peekable();
let boundary_iter = text.char_indices().map(|(byte_pos, ch)| {
// advance any stale word boundary positions
while let Some(&w) = wb_iter.peek() {
if w < byte_pos {
_ = wb_iter.next();
} else {
break;
}
}
// advance any stale grapheme boundary positions
while let Some(&g) = gb_iter.peek() {
if g < byte_pos {
_ = gb_iter.next();
} else {
break;
}
}
// advance any stale line boundary positions
while let Some(&l) = lb_iter.peek() {
if *l < byte_pos {
_ = lb_iter.next();
} else {
break;
}
}
let mut is_word = false;
if let Some(&w) = wb_iter.peek()
&& w == byte_pos
{
is_word = true;
_ = wb_iter.next();
}
let mut is_grapheme_start = false;
if let Some(&g) = gb_iter.peek()
&& g == byte_pos
{
is_grapheme_start = true;
_ = gb_iter.next();
}
let properties = data_sources.properties(ch);
// For characters requiring a dictionary for deciding word boundaries, apply
// UAX #29 Rule WB999 in case there's no dictionary (because ICU4X does not); inside a run
// the host's dictionary segmented, its boundaries decide.
if let Some(bound) = dictionary.word_at(byte_pos) {
is_word = bound;
} else if !is_word
&& is_grapheme_start
&& properties.needs_dictionary_word_break()
&& !has_word_dictionary(properties.script())
{
is_word = true;
}
let is_icu_line = if let Some(&l) = lb_iter.peek()
&& *l == byte_pos
{
_ = lb_iter.next();
true
} else {
false
};
// CSS Text 4 § 4.3.1 `break-spaces`: a soft wrap opportunity exists after each preserved
// space or tab (but never directly before a mandatory break, UAX #14 LB6).
while break_spaces_iter
.peek()
.is_some_and(|range| range.end <= byte_pos)
{
_ = break_spaces_iter.next();
}
let after_break_space = prev_is_break_space;
prev_is_break_space = break_spaces_iter
.peek()
.is_some_and(|range| range.contains(&byte_pos))
&& matches!(ch, ' ' | '\t' | '\u{3000}');
while break_anywhere_iter
.peek()
.is_some_and(|range| range.end <= byte_pos)
{
_ = break_anywhere_iter.next();
}
let is_break_anywhere = break_anywhere_iter
.peek()
.is_some_and(|range| range.contains(&byte_pos));
let is_mandatory_linebreak = properties.is_mandatory_linebreak();
// We never have a soft wrap opportunity before a mandatory break (following UAX #14 LB6),
// and we never have one right after a mandatory break: the mandatory break is handled
// separately.
let is_soft_wrap_opportunity = if is_mandatory_linebreak || prev_is_mandatory_linebreak {
false
} else {
let mut opportunity = if is_break_anywhere {
// `line-break: anywhere`: an opportunity around every grapheme.
prev_char.is_some() && is_grapheme_start
} else {
is_icu_line || after_break_space
};
// Consumers can override soft wrap opportunities, except around a mandatory
// break.
if let (Some(prev), Some(lb_override)) = (prev_char, options.line_break_override) {
let forced = lb_override(LineBreakContext {
before_before: prev_prev_char,
before: prev,
after: ch,
});
if let Some(forced) = forced {
opportunity = forced;
}
}
opportunity
};
prev_prev_char = prev_char;
prev_char = Some(ch);
prev_is_mandatory_linebreak = is_mandatory_linebreak;
(
is_soft_wrap_opportunity,
is_word,
is_grapheme_start,
ch,
properties,
)
});
let mut needs_bidi_resolution = false;
analysis.info.reserve(text.len());
for (is_soft_wrap_opportunity, is_word, is_grapheme_start, ch, properties) in boundary_iter {
let script = properties.script();
let grapheme_cluster_break = properties.grapheme_cluster_break();
let bidi_class = properties.bidi_class();
let general_category = properties.general_category();
let is_emoji_or_pictograph = properties.is_emoji_or_pictograph();
let is_variation_selector = properties.is_variation_selector();
let is_region_indicator = properties.is_region_indicator();
let force_normalize = {
// "Extend" break chars should be normalized first, with two exceptions
if matches!(grapheme_cluster_break, GraphemeClusterBreak::Extend) &&
ch as u32 != 0x200C && // Is not a Zero Width Non-Joiner &&
!is_variation_selector
{
true
} else {
// All spacing mark break chars should be normalized first.
matches!(grapheme_cluster_break, GraphemeClusterBreak::SpacingMark)
}
};
needs_bidi_resolution |= bidi::needs_bidi_resolution(bidi_class);
analysis.info.push(CharInfo::new(
script,
is_variation_selector,
is_region_indicator,
general_category == GeneralCategory::Control,
is_emoji_or_pictograph,
contributes_to_shaping(general_category, script),
force_normalize,
is_grapheme_start,
is_word,
is_soft_wrap_opportunity,
properties.is_emoji(),
properties.is_emoji_presentation(),
properties.is_emoji_modifier(),
properties.is_emoji_modifier_base(),
));
}
if needs_bidi_resolution || options.base_direction == BaseDirection::Rtl {
analyzer.bidi.resolve(
text.chars().map(|ch| {
let bidi_class = data_sources.properties(ch).bidi_class();
// TODO: maybe extend Properties to u64 to fit BidiMirroringGlyph
let bracket = data_sources.brackets().get(ch);
(ch, (bidi_class, bracket))
}),
options.base_direction,
);
core::mem::swap(&mut analysis.levels, &mut analyzer.bidi.levels);
analysis.paragraph_level = analyzer.bidi.base_level();
}
}
/// All characters contribute to shaping except:
/// - Control characters
/// - Format characters, unless they use the "Inherited" script
#[inline(always)]
pub(crate) fn contributes_to_shaping(general_category: GeneralCategory, script: Script) -> bool {
if matches!(
general_category,
GeneralCategory::Control
| GeneralCategory::LineSeparator
| GeneralCategory::ParagraphSeparator
) {
return false;
}
!(general_category == GeneralCategory::Format && script != Script::Inherited)
}
/// Whether ICU4X has a word-segmentation dictionary for this script.
///
/// If it does not, we need to apply UAX #29 Rule WB999 manually, because ICU4X does not.
///
/// This is approximate, because ICU4X actually decides based on a table of code point ranges: e.g.,
/// some Han characters do not get a dictionary check. That's only a problem if there's a run of
/// repeated such characters, which is probably not too likely to be a problem in practice.
///
/// If ICU4X does implement WB999 in the future, we can stop doing it manually (and this method can
/// be removed).
#[inline(always)]
fn has_word_dictionary(script: Script) -> bool {
cfg!(feature = "complex-scripts")
&& matches!(
script,
Script::Han
| Script::Hiragana
| Script::Thai
| Script::Lao
| Script::Khmer
| Script::Myanmar
)
}
#[cfg(test)]
mod test {
use alloc::vec::Vec;
use icu_segmenter::WordSegmenter;
use icu_segmenter::options::WordBreakInvariantOptions;
/// For some characters, determining word boundaries requires a dictionary lookup.
///
/// Without dictionaries, ICU4X reports such runs as being a single word. But note
/// UAX #29 Rule WB999 says that, without a dictionary, there should be word boundaries.
///
/// We do that patchup ourselves. Once this test starts failing, it's likely ICU4X now follows
/// that rule, and we can drop the patchup (the code calling [`super::has_word_dictionary`]).
/// Once that's the case, [`parley_data::Properties::needs_dictionary_word_break`] can also be
/// dropped.
#[test]
fn icu4x_word_segmentation_patchup_required() {
let segmenter =
WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default());
let breaks: Vec<_> = segmenter.segment_str("中文文本测试").collect();
assert_eq!(breaks, &[0, 18]);
}
}
+174
View File
@@ -0,0 +1,174 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! The analyzer API.
use core::ops::Range;
use parlance::{BaseDirection, Language, LineBreak, WordBreak};
use crate::{bidi::BidiResolver, break_overrides::LineBreakOverrideFn};
use crate::analysis::{Analysis, analyze_text};
/// Reusable scratch for [`Analyzer::analyze`].
#[derive(Default)]
pub struct Analyzer {
pub(crate) bidi: BidiResolver,
pub(crate) segmenters: crate::analysis::Segmenters,
}
impl core::fmt::Debug for Analyzer {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Analyzer").finish_non_exhaustive()
}
}
impl Analyzer {
/// Creates a new analyzer.
pub fn new() -> Self {
Self::default()
}
/// Analyze `text`, overwriting `analysis`.
///
/// This reuses the allocations of `analysis`.
pub fn analyze(&mut self, text: &str, options: &AnalysisOptions<'_>, analysis: &mut Analysis) {
analysis.clear();
analyze_text(self, text, options, analysis);
}
}
/// Configuration of line break opportunities for a range of text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct LineBreakConfig {
/// CSS `word-break`.
pub word_break: WordBreak,
/// CSS `line-break`.
pub line_break: LineBreak,
/// The content language.
///
/// Chinese and Japanese content uses tailored line breaking rules, which for example allow
/// breaks before small kana and some punctuation under [`LineBreak::Normal`] and
/// [`LineBreak::Loose`].
pub language: Option<Language>,
}
/// Options controlling [`Analyzer::analyze`].
#[derive(Clone, Copy, Default)]
pub struct AnalysisOptions<'a> {
/// The paragraph's base direction.
///
/// Defaults to [`BaseDirection::Auto`], which infers the direction from the text.
pub base_direction: BaseDirection,
/// Line breaking configuration for ranges of the source text.
///
/// Ranges must be sorted and non-overlapping, and must start and end on character boundaries of
/// the text. Empty ranges are ignored. Gaps use [`LineBreakConfig::default`].
pub line_break: &'a [(Range<usize>, LineBreakConfig)],
/// Ranges of the source text in which a soft wrap opportunity follows every space, tab, and
/// ideographic space.
///
/// This implements the additional soft wrap opportunities of
/// [CSS's white-space-collapse: break-spaces][css-break-spaces].
///
/// Outside these ranges, [UAX #14 § 6][uax-14-algorithm] is followed, which defines where soft
/// wrap opportunities exist. For example, rules LB7 and LB18 give a sequence of spaces an
/// opportunity only at its end. The ranges specified here add an opportunity after every space,
/// tab, and ideographic space, except directly before a mandatory break. This overrides the
/// "non-tailorable" UAX #14 Rule LB7, and so deviates from Unicode's line breaking algorithm.
///
/// Ranges must be sorted and non-overlapping, and must start and end on character boundaries
/// of the text. Empty ranges are ignored. Gaps apply the default rules.
///
/// [css-break-spaces]: https://www.w3.org/TR/css-text-4/#valdef-white-space-collapse-break-spaces
/// [uax-14-algorithm]: https://unicode.org/reports/tr14/#Algorithm
pub break_spaces: &'a [Range<usize>],
/// The callback which will be called as a first provider of line breaking decisions.
///
/// See [`LineBreakOverrideFn`] for more details.
pub line_break_override: Option<&'a LineBreakOverrideFn>,
}
impl core::fmt::Debug for AnalysisOptions<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("AnalysisOptions")
.field("base_direction", &self.base_direction)
.field("line_break", &self.line_break)
.field("break_spaces", &self.break_spaces)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use parlance::BidiLevel;
use super::{AnalysisOptions, Analyzer};
use crate::{Analysis, BaseDirection};
fn analyze(text: &str, base_direction: BaseDirection) -> Analysis {
let mut analyzer = Analyzer::new();
let mut analysis = Analysis::new();
analyzer.analyze(
text,
&AnalysisOptions {
base_direction,
..AnalysisOptions::default()
},
&mut analysis,
);
analysis
}
#[test]
fn explicit_rtl_resolves_numeric_and_neutral_text() {
let text = "123 / 456";
let auto = analyze(text, BaseDirection::Auto);
let rtl = analyze(text, BaseDirection::Rtl);
assert_eq!(auto.paragraph_level(), BidiLevel::new(0));
assert!(auto.paragraph_level().is_ltr());
assert!(auto.bidi_levels().is_empty());
assert_eq!(rtl.paragraph_level(), BidiLevel::new(1));
assert!(rtl.paragraph_level().is_rtl());
assert_eq!(rtl.bidi_levels().len(), text.chars().count());
for (ch, level) in text.chars().zip(rtl.bidi_levels()) {
if ch.is_ascii_digit() {
assert!(level.is_ltr());
}
}
assert!(rtl.bidi_levels().iter().any(|level| level.is_rtl()));
}
#[test]
fn explicit_ltr_takes_precedence_over_first_strong_direction() {
let text = "مرحبا hello";
let auto = analyze(text, BaseDirection::Auto);
let ltr = analyze(text, BaseDirection::Ltr);
assert!(auto.paragraph_level().is_rtl());
assert!(ltr.paragraph_level().is_ltr());
assert_ne!(auto.bidi_levels(), ltr.bidi_levels());
}
#[test]
fn explicit_rtl_preserves_ltr_run_direction() {
let analysis = analyze("hello", BaseDirection::Rtl);
assert!(analysis.paragraph_level().is_rtl());
assert!(analysis.bidi_levels().iter().all(|level| level.is_ltr()));
}
#[test]
fn explicit_direction_applies_to_empty_text() {
let analysis = analyze("", BaseDirection::Rtl);
assert!(analysis.paragraph_level().is_rtl());
assert!(analysis.bidi_levels().is_empty());
}
}
+917
View File
@@ -0,0 +1,917 @@
// Copyright 2021 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Unicode bidirectional algorithm.
use alloc::vec::Vec;
use icu_properties::props::{BidiClass, BidiMirroringGlyph, BidiPairedBracketType};
use parlance::{BaseDirection, BidiLevel};
/// Resolver for the Unicode bidirectional algorithm.
#[derive(Clone, Default)]
pub(crate) struct BidiResolver {
base_level: BidiLevel,
pub(crate) levels: Vec<BidiLevel>,
initial_types: Vec<BidiClass>,
types: Vec<BidiClass>,
brackets: Vec<(usize, char, BidiMirroringGlyph)>,
bracket_pairs: Vec<(usize, usize)>,
runs: Vec<Run>,
indices: Vec<usize>,
flags: u16,
}
impl core::fmt::Debug for BidiResolver {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("BidiResolver")
.field("base_level", &self.base_level)
.field("levels", &self.levels)
.finish_non_exhaustive()
}
}
impl BidiResolver {
/// Returns the base level of the text.
pub(crate) fn base_level(&self) -> BidiLevel {
self.base_level
}
/// Clears the resolver state.
pub(crate) fn clear(&mut self) {
self.initial_types.clear();
self.levels.clear();
self.types.clear();
self.brackets.clear();
self.bracket_pairs.clear();
self.flags = 0;
self.base_level = BidiLevel::new(0);
}
/// Resolves a paragraph with the specified base direction and
/// precomputed types.
pub(crate) fn resolve(
&mut self,
chars: impl Iterator<Item = (char, (BidiClass, BidiMirroringGlyph))>,
base_direction: BaseDirection,
) {
self.clear();
let mut needs_bidi = false;
let mut len = 0;
for (i, (ch, (t, bracket))) in chars.enumerate() {
self.initial_types.push(t);
if bracket.paired_bracket_type != BidiPairedBracketType::None {
self.brackets.push((i, ch, bracket));
}
needs_bidi = needs_bidi || mask(t) & BIDI_MASK != 0;
len += 1;
}
self.base_level = match base_direction {
BaseDirection::Auto => Self::default_level(&self.initial_types),
BaseDirection::Ltr => BidiLevel::new(0),
BaseDirection::Rtl => BidiLevel::new(1),
};
if !needs_bidi && self.base_level == BidiLevel::new(0) {
self.flags |= 1;
self.levels.resize(len, self.base_level);
return;
}
self.types.extend_from_slice(&self.initial_types);
self.resolve_levels();
self.resolve_runs();
//self.dump_sequences();
for i in 0..self.runs.len() {
if self.runs[i].in_sequence {
continue;
}
self.types.truncate(len);
self.indices.clear();
let mut cur = i;
let level = self.runs[i].level;
let sos = self.runs[i].sos;
let mut eos;
loop {
let run = &self.runs[cur];
for i in run.start..run.end {
let ty = self.types[i];
if !is_removed_by_x9(ty) {
self.types.push(ty);
self.indices.push(i);
}
}
eos = run.eos;
cur = match run.next {
Some(i) => i,
None => break,
};
}
self.resolve_sequence(level.to_u8(), sos, eos, self.indices.len());
}
for i in 0..len {
let t = self.initial_types[i];
if t == BidiClass::SegmentSeparator || t == BidiClass::ParagraphSeparator {
self.levels[i] = self.base_level;
for j in (0..i).rev() {
let t = self.initial_types[j];
if is_removed_by_x9(t) {
continue;
} else if t == BidiClass::WhiteSpace
|| is_isolate_initiator(t)
|| t == BidiClass::PopDirectionalIsolate
{
self.levels[j] = self.base_level;
} else {
break;
}
}
} else if is_removed_by_x9(t) {
if i == 0 {
self.levels[i] = self.base_level;
} else {
self.levels[i] = self.levels[i - 1];
}
//self.levels[i] = 0xFF;
}
}
for i in (0..len).rev() {
let t = self.initial_types[i];
if is_removed_by_x9(t) {
continue;
} else if t == BidiClass::WhiteSpace
|| is_isolate_initiator(t)
|| t == BidiClass::PopDirectionalIsolate
{
// UAX #9 L1: whitespace, isolate initiators and PDIs that end the paragraph take
// the paragraph's level (Rune: vendor/parley_engine.patch).
self.levels[i] = self.base_level;
} else {
break;
}
}
}
fn default_level(types: &[BidiClass]) -> BidiLevel {
let mut isolates = 0;
for ty in types {
let ty = *ty;
match ty {
BidiClass::RightToLeftIsolate
| BidiClass::LeftToRightIsolate
| BidiClass::FirstStrongIsolate => isolates += 1,
BidiClass::PopDirectionalIsolate if isolates > 0 => isolates -= 1,
BidiClass::LeftToRight | BidiClass::RightToLeft | BidiClass::ArabicLetter
if isolates == 0 =>
{
return if ty == BidiClass::LeftToRight {
BidiLevel::new(0)
} else {
BidiLevel::new(1)
};
}
_ => {}
}
}
BidiLevel::new(0)
}
fn default_level_until_pdi(types: &[BidiClass]) -> u8 {
let mut isolates = 0;
for ty in types {
let ty = *ty;
match ty {
BidiClass::RightToLeftIsolate
| BidiClass::LeftToRightIsolate
| BidiClass::FirstStrongIsolate => isolates += 1,
BidiClass::PopDirectionalIsolate => {
if isolates > 0 {
isolates -= 1;
} else {
return 0;
}
}
BidiClass::LeftToRight | BidiClass::RightToLeft | BidiClass::ArabicLetter
if isolates == 0 =>
{
return if ty == BidiClass::LeftToRight { 0 } else { 1 };
}
_ => {}
}
}
0
}
fn resolve_levels(&mut self) {
let base = self.base_level;
let len = self.types.len();
self.levels.clear();
self.levels.resize(len, BidiLevel::new(0));
let mut stack = Stack::new();
let mut overflow_isolates = 0;
let mut overflow_embedding = 0;
let mut valid_isolates = 0;
stack.push(base, BidiClass::OtherNeutral, false);
for i in 0..len {
let t = self.types[i];
let tmask = mask(t);
if tmask & EXPLICIT_MASK != 0 {
let is_isolate = tmask & ISOLATE_MASK != 0;
let is_rtl = if t == BidiClass::FirstStrongIsolate && i + 1 < len {
Self::default_level_until_pdi(&self.types[i + 1..]) == 1
} else {
tmask & RTL_MASK != 0
};
if is_isolate {
self.levels[i] = stack.embedding_level();
let os = stack.override_status();
if os != BidiClass::OtherNeutral {
self.types[i] = os;
}
}
let new_level = if is_rtl {
stack.embedding_level().next_odd()
} else {
stack.embedding_level().next_even()
};
if new_level <= BidiLevel::MAX && overflow_isolates == 0 && overflow_embedding == 0
{
if is_isolate {
valid_isolates += 1;
}
stack.push(
new_level,
if t == BidiClass::LeftToRightOverride {
BidiClass::LeftToRight
} else if t == BidiClass::RightToLeftOverride {
BidiClass::RightToLeft
} else {
BidiClass::OtherNeutral
},
is_isolate,
);
} else if is_isolate {
overflow_isolates += 1;
} else if overflow_isolates == 0 {
overflow_embedding += 1;
}
} else if t == BidiClass::PopDirectionalIsolate {
if overflow_isolates > 0 {
overflow_isolates -= 1;
} else if valid_isolates == 0 {
// empty
} else {
overflow_embedding = 0;
while !stack.isolate_status() {
stack.pop();
}
stack.pop();
valid_isolates -= 1;
}
self.levels[i] = stack.embedding_level();
if stack.override_status() != BidiClass::OtherNeutral {
self.types[i] = stack.override_status();
}
} else if t == BidiClass::PopDirectionalFormat {
self.levels[i] = stack.embedding_level();
if overflow_isolates > 0 {
// empty
} else if overflow_embedding > 0 {
overflow_embedding -= 1;
} else if !stack.isolate_status() && stack.depth >= 2 {
stack.pop();
}
} else if t == BidiClass::ParagraphSeparator {
stack.depth = 1;
overflow_isolates = 0;
overflow_embedding = 0;
valid_isolates = 0;
self.levels[i] = base;
} else if t != BidiClass::BoundaryNeutral {
self.levels[i] = stack.embedding_level();
if stack.override_status() != BidiClass::OtherNeutral {
self.types[i] = stack.override_status();
}
}
}
}
fn resolve_runs(&mut self) {
let len = self.types.len();
self.runs.clear();
let mut start = 0;
while start < len {
if !is_removed_by_x9(self.types[start]) {
break;
}
start += 1;
}
if start == len {
return;
}
let mut level = self.levels[start];
let mut offset = 0;
for i in start + 1..len {
if is_removed_by_x9(self.types[i]) {
continue;
}
if self.levels[i] != level {
self.runs.push(Run::new(level, offset, i));
offset = i;
level = self.levels[i];
}
}
if offset < len {
self.runs.push(Run::new(level, offset, len));
}
for run in &mut self.runs {
while run.start < run.end {
if is_removed_by_x9(self.types[run.start]) {
run.start += 1;
} else {
break;
}
}
while run.end > run.start {
if is_removed_by_x9(self.types[run.end - 1]) {
run.end -= 1;
} else {
break;
}
}
if run.start == run.end {
continue;
}
if self.types[run.start] == BidiClass::PopDirectionalIsolate {
run.starts_with_pdi = true;
}
let mut prev_level = self.base_level;
for i in (0..run.start).rev() {
if !is_removed_by_x9(self.types[i]) {
prev_level = self.levels[i];
break;
}
}
run.sos = type_from_level(prev_level.max(run.level));
if is_isolate_initiator(self.initial_types[run.end - 1]) {
run.ends_with_isolate = true;
run.eos = type_from_level(self.base_level.max(run.level));
} else {
let mut next_level = self.base_level;
for i in run.end..len {
if !is_removed_by_x9(self.types[i]) {
next_level = self.levels[i];
break;
}
}
run.eos = type_from_level(next_level.max(run.level));
}
}
for i in 0..self.runs.len() {
if self.runs[i].ends_with_isolate {
let level = self.runs[i].level;
for j in i + 1..self.runs.len() {
if self.runs[j].starts_with_pdi && self.runs[j].level == level {
self.runs[i].next = Some(j);
self.runs[j].in_sequence = true;
break;
}
}
}
}
}
#[expect(clippy::needless_range_loop, reason = "Deferred")]
fn resolve_sequence(&mut self, level: u8, sos: BidiClass, eos: BidiClass, len: usize) {
if len == 0 {
return;
}
const W1_MASK: u32 = mask(BidiClass::LeftToRightIsolate)
| mask(BidiClass::RightToLeftIsolate)
| mask(BidiClass::FirstStrongIsolate)
| mask(BidiClass::PopDirectionalIsolate);
const W2_MASK: u32 = mask(BidiClass::LeftToRight)
| mask(BidiClass::RightToLeft)
| mask(BidiClass::ArabicLetter);
const W4_MASK: u32 = mask(BidiClass::EuropeanSeparator) | mask(BidiClass::CommonSeparator);
let mut prev = sos;
let mut prev_strong = prev;
let types = &mut self.types[self.initial_types.len()..];
for i in 0..len {
let mut t = types[i];
let tmask = mask(t);
if t == BidiClass::NonspacingMark {
// W1
types[i] = prev;
} else {
if tmask & W1_MASK != 0 {
prev = BidiClass::OtherNeutral;
continue;
}
if t == BidiClass::EuropeanNumber {
// W2
if prev_strong == BidiClass::ArabicLetter {
t = BidiClass::ArabicNumber;
types[i] = t;
}
} else if tmask & W2_MASK != 0 {
prev_strong = t;
// W3
if t == BidiClass::ArabicLetter {
t = BidiClass::RightToLeft;
types[i] = t;
}
} else if tmask & W4_MASK != 0 && i < (len - 1) {
// W4
let mut next = types[i + 1];
if next == BidiClass::EuropeanNumber && prev_strong == BidiClass::ArabicLetter {
next = BidiClass::ArabicNumber;
}
if prev == BidiClass::EuropeanNumber && next == BidiClass::EuropeanNumber {
t = BidiClass::EuropeanNumber;
types[i] = t;
} else if t == BidiClass::CommonSeparator
&& prev == BidiClass::ArabicNumber
&& next == BidiClass::ArabicNumber
{
t = BidiClass::ArabicNumber;
types[i] = t;
}
}
prev = t;
}
}
// W5
let mut i = 0;
while i < len {
if types[i] == BidiClass::EuropeanTerminator {
let limit = find_limit(types, i, BidiClass::EuropeanTerminator);
let mut t = if i == 0 { sos } else { types[i - 1] };
if t != BidiClass::EuropeanNumber {
t = if limit == len { eos } else { types[limit] };
}
if t == BidiClass::EuropeanNumber {
for j in i..limit {
types[j] = BidiClass::EuropeanNumber;
}
}
i = limit;
}
i += 1;
}
// W6, W7
const W6_MASK: u32 = mask(BidiClass::EuropeanSeparator)
| mask(BidiClass::EuropeanTerminator)
| mask(BidiClass::CommonSeparator);
prev_strong = sos;
for i in 0..len {
let t = types[i];
if mask(t) & W6_MASK != 0 {
// W6
types[i] = BidiClass::OtherNeutral;
} else if t == BidiClass::EuropeanNumber {
// W7
if prev_strong == BidiClass::LeftToRight {
types[i] = BidiClass::LeftToRight;
}
} else if t == BidiClass::LeftToRight || t == BidiClass::RightToLeft {
prev_strong = t;
}
}
// N0
if !self.brackets.is_empty() {
let base_brackets = self.bracket_pairs.len();
let mut bracket_stack = BracketStack::new();
for i in 0..len {
if types[i] != BidiClass::OtherNeutral {
continue;
}
let index = self.indices[i];
if let Ok(index) = self.brackets.binary_search_by(|x| x.0.cmp(&index)) {
let (_, ch, bracket) = self.brackets[index];
match bracket.paired_bracket_type {
BidiPairedBracketType::Open => {
if bracket_stack.depth == MAX_BRACKET_STACK {
break;
}
bracket_stack.push(i, bracket.mirroring_glyph.unwrap());
}
BidiPairedBracketType::Close => {
if let Some(open) = bracket_stack.find_and_pop(ch) {
self.bracket_pairs.push((open, i));
}
}
_ => {}
}
}
}
if self.bracket_pairs.len() > base_brackets {
let embed_dir = if level & 1 != 0 {
BidiClass::RightToLeft
} else {
BidiClass::LeftToRight
};
let bracket_pairs = &mut self.bracket_pairs[base_brackets..];
bracket_pairs.sort_unstable_by_key(|a| a.0);
for pair in bracket_pairs {
let mut pair_dir = BidiClass::OtherNeutral;
for i in pair.0 + 1..pair.1 {
let dir = match types[i] {
BidiClass::EuropeanNumber
| BidiClass::ArabicNumber
| BidiClass::ArabicLetter
| BidiClass::RightToLeft => BidiClass::RightToLeft,
BidiClass::LeftToRight => BidiClass::LeftToRight,
_ => BidiClass::OtherNeutral,
};
if dir == BidiClass::OtherNeutral {
continue;
}
pair_dir = dir;
if dir == embed_dir {
break;
}
}
if pair_dir == BidiClass::OtherNeutral {
pair.0 = self.indices[pair.0];
pair.1 = self.indices[pair.1];
continue;
}
if pair_dir != embed_dir {
pair_dir = sos;
for i in (0..pair.0).rev() {
let dir = match types[i] {
BidiClass::EuropeanNumber
| BidiClass::ArabicNumber
| BidiClass::ArabicLetter
| BidiClass::RightToLeft => BidiClass::RightToLeft,
BidiClass::LeftToRight => BidiClass::LeftToRight,
_ => BidiClass::OtherNeutral,
};
if dir != BidiClass::OtherNeutral {
pair_dir = dir;
break;
}
}
if pair_dir == embed_dir || pair_dir == BidiClass::OtherNeutral {
pair_dir = embed_dir;
}
}
types[pair.0] = pair_dir;
types[pair.1] = pair_dir;
for i in pair.0 + 1..pair.1 {
let index = self.indices[i];
if self.initial_types[index] == BidiClass::NonspacingMark {
types[i] = pair_dir;
} else {
break;
}
}
for i in pair.1 + 1..len {
let index = self.indices[i];
if self.initial_types[index] == BidiClass::NonspacingMark {
types[i] = pair_dir;
} else {
break;
}
}
pair.0 = self.indices[pair.0];
pair.1 = self.indices[pair.1];
}
}
}
// N1, N2
const N_MASK: u32 = mask(BidiClass::ParagraphSeparator)
| mask(BidiClass::SegmentSeparator)
| mask(BidiClass::WhiteSpace)
| mask(BidiClass::OtherNeutral)
| mask(BidiClass::RightToLeftIsolate)
| mask(BidiClass::LeftToRightIsolate)
| mask(BidiClass::FirstStrongIsolate)
| mask(BidiClass::PopDirectionalIsolate);
let mut i = 0;
while i < len {
let t = types[i];
if mask(t) & N_MASK != 0 {
let offset = i;
let limit = find_limit_by_mask(types, offset, N_MASK);
let mut leading;
let mut trailing;
if offset == 0 {
leading = sos;
} else {
leading = types[offset - 1];
if leading == BidiClass::ArabicNumber || leading == BidiClass::EuropeanNumber {
leading = BidiClass::RightToLeft;
}
}
if limit == len {
trailing = eos;
} else {
trailing = types[limit];
if trailing == BidiClass::ArabicNumber || trailing == BidiClass::EuropeanNumber
{
trailing = BidiClass::RightToLeft;
}
}
let resolved = if leading == trailing {
// N1
leading
} else {
// N2
if level & 1 != 0 {
BidiClass::RightToLeft
} else {
BidiClass::LeftToRight
}
};
for j in offset..limit {
types[j] = resolved;
}
i = limit - 1;
}
i += 1;
}
// Implicit levels
if level & 1 == 0 {
// I1
for i in 0..len {
let index = self.indices[i];
let t = types[i];
if t == BidiClass::RightToLeft {
self.levels[index] = BidiLevel::new(level + 1);
} else if t != BidiClass::LeftToRight {
self.levels[index] = BidiLevel::new(level + 2);
} else {
self.levels[index] = BidiLevel::new(level);
}
}
} else {
// I2
for i in 0..len {
let index = self.indices[i];
let t = types[i];
if t != BidiClass::RightToLeft {
self.levels[index] = BidiLevel::new(level + 1);
} else {
self.levels[index] = BidiLevel::new(level);
}
}
}
}
}
/// Returns a default bidi type for a level.
pub(crate) fn type_from_level(level: BidiLevel) -> BidiClass {
if level.is_ltr() {
BidiClass::LeftToRight
} else {
BidiClass::RightToLeft
}
}
/// Computes an ordering for a sequence of bidi runs based on levels.
pub(crate) fn _reorder<F>(order: &mut [usize], levels: F)
where
F: Fn(usize) -> u8,
{
let mut max_level = 0;
let mut lowest_odd_level = 255;
for (i, o) in order.iter_mut().enumerate() {
*o = i;
let level = levels(i);
if level > max_level {
max_level = level;
}
if level & 1 != 0 && level < lowest_odd_level {
lowest_odd_level = level;
}
}
let len = order.len();
for level in (lowest_odd_level..=max_level).rev() {
let mut i = 0;
while i < len {
if levels(i) >= level {
let mut end = i + 1;
while end < len && levels(end) >= level {
end += 1;
}
let mut j = i;
let mut k = end - 1;
while j < k {
order.swap(j, k);
j += 1;
k -= 1;
}
i = end;
}
i += 1;
}
}
}
/// Returns whether the character needs bidirectional resolution.
#[inline(always)]
pub(crate) fn needs_bidi_resolution(bidi_class: BidiClass) -> bool {
mask(bidi_class) & BIDI_MASK != 0
}
const OVERRIDE_MASK: u32 = mask(BidiClass::RightToLeftEmbedding)
| mask(BidiClass::LeftToRightEmbedding)
| mask(BidiClass::RightToLeftOverride)
| mask(BidiClass::LeftToRightOverride);
const ISOLATE_MASK: u32 = mask(BidiClass::RightToLeftIsolate)
| mask(BidiClass::LeftToRightIsolate)
| mask(BidiClass::FirstStrongIsolate);
const EXPLICIT_MASK: u32 = OVERRIDE_MASK | ISOLATE_MASK;
const RTL_MASK: u32 = mask(BidiClass::RightToLeftEmbedding)
| mask(BidiClass::RightToLeftOverride)
| mask(BidiClass::RightToLeftIsolate);
const REMOVED_BY_X9_MASK: u32 =
OVERRIDE_MASK | mask(BidiClass::PopDirectionalFormat) | mask(BidiClass::BoundaryNeutral);
const BIDI_MASK: u32 = EXPLICIT_MASK
| mask(BidiClass::RightToLeft)
| mask(BidiClass::ArabicLetter)
| mask(BidiClass::ArabicNumber);
const _RESET_MASK: u32 =
ISOLATE_MASK | mask(BidiClass::PopDirectionalIsolate) | mask(BidiClass::WhiteSpace);
fn is_isolate_initiator(ty: BidiClass) -> bool {
mask(ty) & ISOLATE_MASK != 0
}
pub(crate) fn is_removed_by_x9(ty: BidiClass) -> bool {
mask(ty) & REMOVED_BY_X9_MASK != 0
}
pub(crate) fn _is_reset(ty: BidiClass) -> bool {
mask(ty) & _RESET_MASK != 0
}
fn find_limit(types: &[BidiClass], offset: usize, ty: BidiClass) -> usize {
let mut len = offset;
for &t in &types[offset..] {
if t != ty {
break;
}
len += 1;
}
len
}
fn find_limit_by_mask(types: &[BidiClass], offset: usize, mask: u32) -> usize {
let mut len = offset;
for &t in &types[offset..] {
if self::mask(t) & mask == 0 {
break;
}
len += 1;
}
len
}
#[derive(Clone)]
struct Run {
level: BidiLevel,
ends_with_isolate: bool,
starts_with_pdi: bool,
sos: BidiClass,
eos: BidiClass,
start: usize,
end: usize,
in_sequence: bool,
next: Option<usize>,
}
impl Run {
fn new(level: BidiLevel, start: usize, end: usize) -> Self {
Self {
level,
ends_with_isolate: false,
starts_with_pdi: false,
sos: BidiClass::OtherNeutral,
eos: BidiClass::OtherNeutral,
start,
end,
in_sequence: false,
next: None,
}
}
}
const MAX_STACK: usize = BidiLevel::MAX.to_u8() as usize;
struct Stack {
embedding_level: [BidiLevel; MAX_STACK + 1],
override_status: [BidiClass; MAX_STACK + 1],
isolate_status: [bool; MAX_STACK + 1],
depth: usize,
}
impl Stack {
fn new() -> Self {
Self {
depth: 0,
embedding_level: [BidiLevel::new(0); MAX_STACK + 1],
override_status: [BidiClass::OtherNeutral; MAX_STACK + 1],
isolate_status: [false; MAX_STACK + 1],
}
}
fn push(&mut self, level: BidiLevel, override_status: BidiClass, isolate_status: bool) {
let d = self.depth;
self.embedding_level[d] = level;
self.override_status[d] = override_status;
self.isolate_status[d] = isolate_status;
self.depth += 1;
}
fn pop(&mut self) {
if self.depth > 1 {
self.depth -= 1;
}
}
fn embedding_level(&self) -> BidiLevel {
self.embedding_level[self.depth - 1]
}
fn override_status(&self) -> BidiClass {
self.override_status[self.depth - 1]
}
fn isolate_status(&self) -> bool {
self.isolate_status[self.depth - 1]
}
}
const MAX_BRACKET_STACK: usize = 63;
struct BracketStack {
openers: [(usize, char); MAX_BRACKET_STACK],
depth: usize,
}
impl BracketStack {
fn new() -> Self {
Self {
openers: [(0, '\0'); MAX_BRACKET_STACK],
depth: 0,
}
}
fn push(&mut self, offset: usize, closer: char) {
self.openers[self.depth] = (offset, closer);
self.depth += 1;
}
fn find_and_pop(&mut self, closer: char) -> Option<usize> {
if self.depth == 0 {
return None;
}
for i in (0..self.depth).rev() {
let c = self.openers[i].1;
if c == closer
|| (c == '\u{232A}' && closer == '\u{3009}')
|| (c == '\u{3009}' && closer == '\u{232A}')
{
self.depth = i;
return Some(self.openers[i].0);
}
}
None
}
}
/// Turns a bidi class into a single bit, for cheap set membership testing.
const fn mask(t: BidiClass) -> u32 {
let bit = match t {
BidiClass::LeftToRight => 0,
BidiClass::RightToLeft => 1,
BidiClass::EuropeanNumber => 2,
BidiClass::EuropeanSeparator => 3,
BidiClass::EuropeanTerminator => 4,
BidiClass::ArabicNumber => 5,
BidiClass::CommonSeparator => 6,
BidiClass::ParagraphSeparator => 7,
BidiClass::SegmentSeparator => 8,
BidiClass::WhiteSpace => 9,
BidiClass::OtherNeutral => 10,
BidiClass::LeftToRightEmbedding => 11,
BidiClass::LeftToRightOverride => 12,
BidiClass::ArabicLetter => 13,
BidiClass::RightToLeftEmbedding => 14,
BidiClass::RightToLeftOverride => 15,
BidiClass::PopDirectionalFormat => 16,
BidiClass::NonspacingMark => 17,
BidiClass::BoundaryNeutral => 18,
BidiClass::FirstStrongIsolate => 19,
BidiClass::LeftToRightIsolate => 20,
BidiClass::RightToLeftIsolate => 21,
BidiClass::PopDirectionalIsolate => 22,
_ => {
debug_assert!(false, "unhandled Bidi_Class");
return 0;
}
};
1 << bit
}
+436
View File
@@ -0,0 +1,436 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Overrides for line-break opportunities.
use core::ops::RangeInclusive;
/// Context for a potential line break opportunity between two adjacent code points.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct LineBreakContext {
/// The code point before the `before` code point, if any.
pub before_before: Option<char>,
/// The code point before the potential break.
pub before: char,
/// The code point after the potential break.
pub after: char,
}
/// Line break opportunity override.
///
/// Called for each adjacent pair of Unicode code points in the text, in order, except for pairs
/// containing a mandatory break character. The [`LineBreakContext`] describes the potential break.
///
/// Returning:
/// - `Some(true)` : forces a line break opportunity between the pair
/// - `Some(false)` : suppresses any opportunity
/// - `None` : defers to the default (ICU) behavior
///
/// Note that pairs with a mandatory break aren't soft wrap opportunities. Mandatory breaks are
/// reported as [`Whitespace`][crate::shape::Whitespace].
///
/// This is typically used to force preferential line breaking decisions when it
/// comes to ASCII punctuation like `/`, `-`, etc. For example, to prevent break
/// opportunities within "1/2".
///
/// A separate use case is to match the line breaking behavior of existing systems
/// such as web browsers. See [`CHROMIUM_LINE_BREAK_OVERRIDE`] for a ready-made
/// override function that mirrors Chromium's behavior.
pub type LineBreakOverrideFn = dyn Fn(LineBreakContext) -> Option<bool> + Send + Sync;
/// A line break override function mirroring Chromium's preferred line breaking behavior.
///
/// See: <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/character_property_data_generator.cc;l=449-495>
///
/// # Differences from other browsers
///
/// ## Compared to Safari
///
/// Chromium (and this table) differs from Safari in 9 cases:
/// - A "-" followed by one of "!|$|)|/|:|;|?|]|}" is suppressed in Chromium, but broken in Safari.
///
/// ## Compared to Firefox
///
/// Firefox always defers to the default ICU behavior.
pub static CHROMIUM_LINE_BREAK_OVERRIDE: &LineBreakOverrideFn =
&(chromium_override as fn(LineBreakContext) -> Option<bool>);
fn chromium_override(cx: LineBreakContext) -> Option<bool> {
let LineBreakContext {
before_before,
before,
after,
..
} = cx;
// CSS "does not fully define where soft wrap opportunities occur".
// (https://www.w3.org/TR/css-text-3/#line-breaking)
// We find that Chrome always treats the position after a space sequence
// as a line break opportunity, despite this not matching UAX-14
// (see LB13: https://www.unicode.org/reports/tr14/#LB13; we're not currently
// aware of any others).
//
// See also https://github.com/linebender/parley/pull/485, and https://github.com/linebender/parley/issues/619.
//
// See `LazyLineBreakIterator::NextBreakablePosition`
// <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/text_break_iterator.cc;l=282-303>
if before == ' ' && after != ' ' {
return Some(true);
}
// Before consulting 'before' / 'after' pair table, check for the special "-" case.
//
// Chromium doesn't allow breaking when it looks like the minus sign is for a negative
// number like "Subtract -5 from X". But, Chromium does allow breaking when the minus
// sign is part of a long URL like "AAAA-2222".
//
// See <https://github.com/chromium/chromium/blob/c6bee15e8f336c8feabf539d8bbb540c134ec20a/third_party/blink/renderer/platform/text/text_break_iterator.cc#L224-L240>
if before == '-' && after.is_ascii_digit() {
return Some(before_before.is_some_and(|c| c.is_ascii_alphanumeric()));
}
CHROMIUM_LINE_BREAK_TABLE.lookup(before, after)
}
/// A static table mirroring Chromium's preferred line breaking behavior for `before` / `after`
/// printable ASCII code points.
static CHROMIUM_LINE_BREAK_TABLE: AsciiLineBreakTable<5> =
AsciiLineBreakTableBuilder::chromium().build::<5>();
/// A line break override table for ASCII character pairs.
///
/// See [`LineBreakOverrideFn`] for more details.
///
/// All table operations are `const`, which means that derived tables don't
/// need a runtime construction step.
///
/// The table is row-deduplicated. Each `before` character maps to
/// one of `N` distinct rows, so tables can be kept tiny.
///
/// # Example
///
/// ```
/// # use parley_engine::break_overrides::CHROMIUM_LINE_BREAK_OVERRIDE;
/// # use parley_engine::{Analysis, AnalysisOptions, Analyzer};
/// # let mut analyzer = Analyzer::new();
/// # let mut analysis = Analysis::new();
/// let text = "Hello there!";
/// let options = AnalysisOptions {
/// // Emulate Chromium:
/// line_break_override: Some(CHROMIUM_LINE_BREAK_OVERRIDE),
/// ..AnalysisOptions::default()
/// };
/// analyzer.analyze(text, &options, &mut analysis);
/// ```
#[derive(Clone, Debug)]
pub struct AsciiLineBreakTable<const N: usize> {
/// Maps each `before` character (`0..128`) to a row in `rows`.
row_of: [u8; 128],
/// The distinct rows.
rows: [Row; N],
}
impl<const N: usize> AsciiLineBreakTable<N> {
/// Look up the break override for a `(before, after)` pair.
///
/// Return semantics copied from [`LineBreakOverrideFn`].
pub const fn lookup(&self, before: char, after: char) -> Option<bool> {
let (b, a) = (before as u32, after as u32);
if b >= 128 || a >= 128 {
return None;
}
let row = &self.rows[self.row_of[b as usize] as usize];
if row.overridden & (1_u128 << a) == 0 {
return None;
}
Some(row.allow & (1_u128 << a) != 0)
}
}
/// A single deduplicated row of a [`AsciiLineBreakTable`].
#[derive(Clone, Copy, Debug)]
struct Row {
/// Bits set means the pair has an override.
overridden: u128,
/// Bits set means a break is allowed.
allow: u128,
}
/// A builder for an [`AsciiLineBreakTable`].
///
/// Construction is `const`. We create a dense `128 x 128` grid of overrides,
/// then compress it into a row-deduplicated table via [`AsciiLineBreakTableBuilder::build`].
#[derive(Clone, Debug)]
pub struct AsciiLineBreakTableBuilder {
/// Bit `after` set in row `before` means the pair has an explicit override.
overridden: [u128; 128],
/// Bit `after` set in row `before` means a break is allowed for that pair.
allow: [u128; 128],
}
impl AsciiLineBreakTableBuilder {
/// A builder that defers every pair to the default ICU behavior.
pub const fn new() -> Self {
Self {
overridden: [0; 128],
allow: [0; 128],
}
}
/// Override every pair in the cartesian product of the two inclusive ASCII
/// ranges.
///
/// # Panics
///
/// All range bounds must be printable ASCII (`<= '\u{7f}'`).
pub const fn with_pairs(
mut self,
before: RangeInclusive<char>,
after: RangeInclusive<char>,
allow_break: bool,
) -> Self {
assert!(
*before.end() as u32 <= 0x7f && *after.end() as u32 <= 0x7f,
"only printable ASCII is supported",
);
let mut before_pos = *before.start() as u32;
while before_pos <= *before.end() as u32 {
let mut after_pos = *after.start() as u32;
while after_pos <= *after.end() as u32 {
let bit = 1_u128 << after_pos;
self.overridden[before_pos as usize] |= bit;
if allow_break {
self.allow[before_pos as usize] |= bit;
} else {
self.allow[before_pos as usize] &= !bit;
}
after_pos += 1;
}
before_pos += 1;
}
self
}
/// Compress the dense grid into a row-deduplicated [`AsciiLineBreakTable`]
/// with at most `N` distinct rows.
///
/// # Panics
///
/// Panics if `N` does not exactly match the number of distinct rows required.
pub const fn build<const N: usize>(&self) -> AsciiLineBreakTable<N> {
// Row 0 is reserved as the "defer everything" row.
let mut rows = [Row {
overridden: 0,
allow: 0,
}; N];
let mut len = 1_usize;
let mut row_of = [0_u8; 128];
let mut b = 0;
while b < 128 {
let (ov, al) = (self.overridden[b], self.allow[b]);
let mut idx = 0;
let mut found = usize::MAX;
while idx < len {
if rows[idx].overridden == ov && rows[idx].allow == al {
found = idx;
break;
}
idx += 1;
}
let r = if found != usize::MAX {
found
} else {
assert!(
len < N,
"N is too small to contain table. Repeat with a larger N."
);
rows[len] = Row {
overridden: ov,
allow: al,
};
len += 1;
len - 1
};
#[expect(
clippy::cast_possible_truncation,
reason = "TODO: fix this (`N` should be `u8`, or `row_of` should contain `usize`)"
)]
{
row_of[b] = r as u8;
}
b += 1;
}
assert!(
len == N,
"N is larger than required. Repeat with a smaller N."
);
AsciiLineBreakTable { row_of, rows }
}
/// See [`CHROMIUM_LINE_BREAK_TABLE`] for more details.
const fn chromium() -> Self {
// The printable ASCII range `'!'..=0x7F`.
const ALL: RangeInclusive<char> = '!'..='\u{7f}';
Self::new()
.with_pairs(ALL, ALL, false)
.with_pairs(ALL, '('..='(', true)
.with_pairs(ALL, '<'..='<', true)
.with_pairs(ALL, '['..='[', true)
.with_pairs(ALL, '{'..='{', true)
.with_pairs('-'..='-', ALL, true)
.with_pairs('?'..='?', ALL, true)
.with_pairs('-'..='-', '$'..='$', false)
.with_pairs(ALL, '!'..='!', false)
.with_pairs('?'..='?', '"'..='"', false)
.with_pairs('?'..='?', '\''..='\'', false)
.with_pairs(ALL, ')'..=')', false)
.with_pairs(ALL, ','..=',', false)
.with_pairs(ALL, '.'..='.', false)
.with_pairs(ALL, '/'..='/', false)
.with_pairs('-'..='-', '0'..='9', false)
.with_pairs(ALL, ':'..=':', false)
.with_pairs(ALL, ';'..=';', false)
.with_pairs(ALL, '?'..='?', false)
.with_pairs(ALL, ']'..=']', false)
.with_pairs(ALL, '}'..='}', false)
.with_pairs('$'..='$', ALL, false)
.with_pairs('\''..='\'', ALL, false)
.with_pairs('('..='(', ALL, false)
.with_pairs('/'..='/', ALL, false)
.with_pairs('0'..='9', ALL, false)
.with_pairs('<'..='<', ALL, false)
.with_pairs('@'..='@', ALL, false)
.with_pairs('A'..='Z', ALL, false)
.with_pairs('['..='[', ALL, false)
.with_pairs('^'..='`', ALL, false)
.with_pairs('a'..='z', ALL, false)
.with_pairs('{'..='{', ALL, false)
.with_pairs('\u{7f}'..='\u{7f}', ALL, false)
}
}
impl Default for AsciiLineBreakTableBuilder {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::AsciiLineBreakTableBuilder;
use super::CHROMIUM_LINE_BREAK_TABLE;
use super::LineBreakContext;
use super::chromium_override;
fn cx(before_before: Option<char>, before: char, after: char) -> LineBreakContext {
LineBreakContext {
before_before,
before,
after,
}
}
#[test]
fn chromium_hyphen_digit_depends_on_preceding_char() {
// A break between '-' and a digit is allowed only when the character
// preceding the '-' is ASCII alphanumeric.
assert_eq!(chromium_override(cx(Some('D'), '-', '1')), Some(true));
assert_eq!(chromium_override(cx(Some('4'), '-', '5')), Some(true));
// Otherwise the '-' may be a minus sign, so the break is suppressed.
assert_eq!(chromium_override(cx(Some(' '), '-', '1')), Some(false));
assert_eq!(chromium_override(cx(Some('('), '-', '1')), Some(false));
// No preceding character (start of text) behaves like a non-alphanumeric
// context, matching Chromium's `last_last_ch == 0`.
assert_eq!(chromium_override(cx(None, '-', '1')), Some(false));
}
#[test]
fn chromium_ignores_uax_14_lb13() {
// Blink allows a break after a space run unconditionally.
// See comment in non-test code for more details.
for after in ['}', ')', ']', '!', '.', ',', '/', ':', ';', '?', 'b', '('] {
assert_eq!(
chromium_override(cx(None, ' ', after)),
Some(true),
"expected a break after the space, before {after:?}"
);
}
}
#[test]
fn chromium_hyphen_non_digit_defers_to_table() {
// '-' followed by a non-digit ignores `before_before` and uses the table.
assert_eq!(chromium_override(cx(Some('D'), '-', 'b')), Some(true));
assert_eq!(chromium_override(cx(None, '-', 'b')), Some(true));
// Non-ASCII after '-' defers to ICU.
assert_eq!(chromium_override(cx(Some('D'), '-', 'é')), None);
}
#[test]
fn chromium_suppresses_ascii_punctuation_breaks() {
let t = &CHROMIUM_LINE_BREAK_TABLE;
// No break before or after a slash.
assert_eq!(t.lookup('a', '/'), Some(false));
assert_eq!(t.lookup('/', 'b'), Some(false));
// No break around other punctuation.
assert_eq!(t.lookup('a', '.'), Some(false));
assert_eq!(t.lookup('a', ':'), Some(false));
// No break between letters.
assert_eq!(t.lookup('a', 'b'), Some(false));
}
#[test]
fn chromium_allows_some_breaks() {
let t = &CHROMIUM_LINE_BREAK_TABLE;
// Break allowed before opening punctuation, but only when the preceding
// character's row was not later suppressed.
assert_eq!(t.lookup(')', '('), Some(true));
assert_eq!(t.lookup(')', '<'), Some(true));
assert_eq!(t.lookup('a', '('), Some(false));
// Break allowed after '-' and '?' except when...
assert_eq!(t.lookup('-', 'b'), Some(true));
assert_eq!(t.lookup('?', 'b'), Some(true));
// ...break not allowed after '-' before a digit, or '?' before a quote.
assert_eq!(t.lookup('-', '5'), Some(false));
assert_eq!(t.lookup('?', '"'), Some(false));
}
#[test]
fn non_ascii_pairs_defer_to_icu() {
let t = &CHROMIUM_LINE_BREAK_TABLE;
assert_eq!(t.lookup('a', 'é'), None);
assert_eq!(t.lookup('é', 'a'), None);
// Space (0x20) is below the printable range, so it defers too.
assert_eq!(t.lookup('a', ' '), None);
}
#[test]
fn empty_table_defers_to_icu() {
let t = AsciiLineBreakTableBuilder::new().build::<1>();
assert_eq!(t.lookup('a', '/'), None);
assert_eq!(t.lookup('a', '('), None);
}
#[test]
fn dedup_matches_dense_for_chromium() {
let builder = AsciiLineBreakTableBuilder::chromium();
for b in 0..128_u32 {
for a in 0..128_u32 {
let bit = 1_u128 << a;
let dense = if builder.overridden[b as usize] & bit == 0 {
None
} else {
Some(builder.allow[b as usize] & bit != 0)
};
let (before, after) = (char::from_u32(b).unwrap(), char::from_u32(a).unwrap());
assert_eq!(
CHROMIUM_LINE_BREAK_TABLE.lookup(before, after),
dense,
"mismatch at (before={b:#04x}, after={a:#04x})",
);
}
}
}
}
+134
View File
@@ -0,0 +1,134 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Word boundaries for the scripts whose words need a dictionary (Thai, Lao, Khmer, Burmese,
//! Chinese and Japanese), from outside Parley (Rune: vendor/parley_engine.patch). A build without
//! `complex-scripts` links none of ICU's dictionaries; a host that has its own (a browser's
//! `Intl.Segmenter`) gives them here. Its boundaries are the words inside each such run and, in
//! Thai, Lao, Khmer and Burmese, the run's line break opportunities too, as ICU's dictionary
//! line segmenter makes them (UAX #14 breaks class SA at word boundaries).
use alloc::vec::Vec;
use icu_properties::props::{GeneralCategory, Script};
use parley_data::Properties;
/// Appends to `out` the word boundaries strictly inside `text`, as ascending byte offsets, for a
/// `text` all in one dictionary language: `language` is `th`, `lo`, `km`, `my` or `ja` (Han,
/// hiragana and katakana, whose dictionary Chinese and Japanese share).
pub type DictionarySegmenter = fn(text: &str, language: &str, out: &mut Vec<usize>);
#[cfg(feature = "std")]
static SEGMENTER: std::sync::OnceLock<DictionarySegmenter> = std::sync::OnceLock::new();
/// Gives Parley the host's dictionary word boundaries, once (a second call changes nothing).
/// Without `complex-scripts` and without this, a Thai phrase has no break opportunity and a
/// Chinese sentence's words are its characters. Needs `std`.
pub fn set_dictionary_segmenter(segmenter: DictionarySegmenter) {
#[cfg(feature = "std")]
let _ = SEGMENTER.set(segmenter);
#[cfg(not(feature = "std"))]
let _ = segmenter;
}
fn segmenter() -> Option<DictionarySegmenter> {
#[cfg(all(feature = "std", not(feature = "complex-scripts")))]
return SEGMENTER.get().copied();
#[cfg(not(all(feature = "std", not(feature = "complex-scripts"))))]
None
}
/// The dictionary language a character's script asks for, and whether its words are its line
/// break opportunities (class SA).
fn language(script: Script) -> Option<(&'static str, bool)> {
Some(match script {
Script::Thai => ("th", true),
Script::Lao => ("lo", true),
Script::Khmer => ("km", true),
Script::Myanmar => ("my", true),
Script::Han | Script::Hiragana | Script::Katakana => ("ja", false),
_ => return None,
})
}
/// A mark, a joiner or a length mark (ー) carries on the run before it.
fn continues(properties: Properties, ch: char) -> bool {
matches!(properties.script(), Script::Inherited)
|| matches!(
properties.general_category(),
GeneralCategory::NonspacingMark | GeneralCategory::SpacingMark | GeneralCategory::EnclosingMark
)
|| matches!(ch, '\u{200C}' | '\u{200D}' | '\u{30FC}')
}
/// The text's dictionary runs and the host's word boundaries inside them.
#[derive(Default)]
pub(crate) struct Words {
/// `(start, end, sa)` byte ranges, ascending.
runs: Vec<(usize, usize, bool)>,
/// Boundaries strictly inside the runs, ascending.
bounds: Vec<usize>,
run: usize,
bound: usize,
}
impl Words {
pub(crate) fn of(text: &str, properties: impl Fn(char) -> Properties) -> Self {
let Some(segment) = segmenter() else { return Self::default() };
let mut words = Self::default();
let mut open: Option<(usize, &'static str, bool)> = None;
let close = |words: &mut Self, start: usize, end: usize, lang: &'static str, sa: bool| {
let run = &text[start..end];
// A single character has no boundary inside it.
if run.chars().nth(1).is_none() {
return;
}
let mut found = Vec::new();
segment(run, lang, &mut found);
words.bounds.extend(found.into_iter().filter(|&b| b > 0 && b < run.len() && run.is_char_boundary(b)).map(|b| b + start));
words.runs.push((start, end, sa));
};
for (at, ch) in text.char_indices() {
let props = properties(ch);
if let Some((start, lang, sa)) = open {
if continues(props, ch) || language(props.script()).is_some_and(|(l, _)| l == lang) {
continue;
}
close(&mut words, start, at, lang, sa);
}
open = language(props.script()).map(|(lang, sa)| (at, lang, sa));
}
if let Some((start, lang, sa)) = open {
close(&mut words, start, text.len(), lang, sa);
}
words
}
/// The boundaries inside Thai, Lao, Khmer and Burmese runs: their line break opportunities.
/// None with `line-dictionaries`, whose line segmenter finds them itself.
pub(crate) fn line_breaks(&self) -> impl Iterator<Item = usize> + '_ {
let mut run = if cfg!(feature = "line-dictionaries") { self.runs.len() } else { 0 };
self.bounds.iter().copied().filter(move |&b| {
while self.runs.get(run).is_some_and(|r| r.1 <= b) {
run += 1;
}
self.runs.get(run).is_some_and(|r| r.0 < b && r.2)
})
}
/// Inside a run (past its first character), whether `at` is a word boundary; `None` outside
/// one, where the rule-based segmenter decides. Asked in ascending order.
pub(crate) fn word_at(&mut self, at: usize) -> Option<bool> {
while self.runs.get(self.run).is_some_and(|r| r.1 <= at) {
self.run += 1;
}
let run = self.runs.get(self.run)?;
if at <= run.0 {
return None;
}
while self.bounds.get(self.bound).is_some_and(|&b| b < at) {
self.bound += 1;
}
Some(self.bounds.get(self.bound) == Some(&at))
}
}
+12
View File
@@ -0,0 +1,12 @@
// Copyright 2025 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
/// Glyph with an offset and advance.
#[derive(Copy, Clone, Default, Debug, PartialEq)]
#[expect(missing_docs, reason = "Deferred")]
pub struct Glyph {
pub id: u32,
pub x: f32,
pub y: f32,
pub advance: f32,
}
+331
View File
@@ -0,0 +1,331 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Itemization breaks text into individually-shapeable items.
use core::{ops::Range, str::CharIndices};
use icu_properties::props::Script as IcuScript;
use parlance::{BidiLevel, Script};
use crate::{Analysis, CharInfo, ShapeOptions};
/// A range of text.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextRange {
/// The range of byte offsets.
pub byte_range: Range<usize>,
/// The range of character indices.
pub char_range: Range<usize>,
}
/// A span of text inside an [`Item`] with constant script and bidirectional embedding level.
#[derive(Clone, Debug)]
pub struct Segment {
/// The text range of this item.
pub range: TextRange,
/// The bidi level of characters in this item.
pub bidi_level: BidiLevel,
/// The script of characters in this item.
///
/// Characters in the source text that do not have a particular script (i.e., they are one of
/// [`Script::COMMON`], [`Script::UNKNOWN`] or [`Script::INHERITED`]) get their script from
/// surrounding context. Currently, these just inherit the script of the preceding characters.
/// Leading characters without a particular script inherit the script of the first character
/// *with* a particular script. These heuristics may change in the future. For more, see UAX 24
/// (<https://www.unicode.org/reports/tr24/>) Section 5.
pub script: Script,
}
/// A span of text shaped with specific [`ShapeOptions`].
///
/// An [`Item`] represents a sequence of constant [`ShapeOptions`], but cannot always be passed to
/// the shaper as a single unit. Within an item, the script or bidirectional text embedding level
/// may change, which requires further splitting the item into segments of constant script and bidi
/// level (see [`Segment`]).
#[derive(Debug)]
pub struct Item<'a> {
/// The character offset in the source text which this item ends.
///
/// This must be strictly greater than the previous item's end. For the first item, it must be
/// greater than 0.
pub char_end: u32,
/// The options to shape this item with.
//
// TODO: should users instead be allowed to build `options` at the `Segment` level (i.e.,
// through some callback)? The motivation is for users to have access to the segment's `Script`
// and be able to set font features based on that. If the entirety of `ShapeOptions` moves
// there, it would allow users to set, e.g., a font size per segment, even though it's not
// necessarily an item boundary; and note an item then doesn't mean a whole lot anymore. We
// could also allow only some options to be per-segment. In any case, we're probably moving
// towards a future where items reset grapheme segmentation, but segments do not (note Gecko and
// Blink also reset grapheme segmentation when something like font size changes, but not when
// the script changes).
pub options: ShapeOptions<'a>,
// TODO: we probably should allow users to pass in some data (like we allow passing
// style_indices elsewhere), which we copy onto `ShapedRun`. That allows users to easily
// correlate `ShapedRun`s with some data they themselves hold.
//
// This is potentially important for better correctness in `parley`: it itemizes based on
// `nearly_eq` of shaping-relevant styles like font size, i.e., it should then read that item's
// style to know the font size, even though it may be different for the run.
// /// Opaque data copied onto every `ShapedRun` produced from this item.
// pub user_data: u16,
}
/// Produces the items in a text via [`Self::next`]; created by [`Analysis::itemize`].
#[derive(Debug)]
pub(crate) struct Itemizer<'a> {
/// Our underlying iterator over the input text.
char_indices: CharIndices<'a>,
/// The per-char info, parallel to [`Self::char_indices`].
char_info: &'a [CharInfo],
/// The per-char bidi level, parallel to [`Self::char_indices`].
bidi_levels: &'a [BidiLevel],
/// The paragraph's base bidi level.
///
/// If [`Self::bidi_levels`] is empty as a special case, this is the bidi level of each
/// character.
paragraph_bidi_level: BidiLevel,
/// The running character offset of the last-processed item.
current_char_offset: usize,
/// The running script of the last-processed item.
current_script: IcuScript,
}
impl Analysis {
/// Divide the `text` into individually-shapeable segments.
///
/// The `text` passed in must be the same as used for producing the `self` analysis.
///
/// The text is divided into items produced by a predicate passed to [`Itemizer::next`] and
/// further divided into segments of constant bidi level and script.
///
/// Characters that don't have a particular script have their script resolved based on
/// surrounding context (see [`Segment::script`]).
pub(crate) fn itemize<'a>(&'a self, text: &'a str) -> Itemizer<'a> {
let first_real_script = self
.char_info()
.iter()
.map(|x| x.script)
.find(|&script| real_script(script))
.unwrap_or(IcuScript::Latin);
Itemizer {
char_indices: text.char_indices(),
char_info: self.char_info(),
bidi_levels: self.bidi_levels(),
paragraph_bidi_level: self.paragraph_level(),
current_char_offset: 0,
current_script: first_real_script,
}
}
}
impl Itemizer<'_> {
/// Produce the next segment, if any.
///
/// For consecutive characters where the bidi level and script are unchanging, the `split_after`
/// predicate is called with the growing item range, and can be used to split on additional
/// properties like shaping-relevant style changes (e.g., font size) or properties like
/// language.
///
/// The predicate is given a range encoding the current item and considers whether to split
/// after that item based on the next character. Iff the predicate returns `true`, the text is
/// split after that item; i.e., given a range of `start..end`, the predicate controls whether
/// that item is now finished, or whether it is extended to include the character at `end` (at
/// which point the item spans `start..end+1`).
//
// TODO: currently the items from `split_after` have the same effect as a change in bidi or
// script. This is not how browsers handle things. In particular, `split_after` should reset
// grapheme segmentation, whereas bidi and script should produce separately-shaped segments.
#[inline]
pub(crate) fn next(
&mut self,
mut split_after: impl FnMut(TextRange) -> bool,
) -> Option<Segment> {
if self.char_info.is_empty() {
// We're already finished.
debug_assert!(
self.char_indices.next().is_none() && self.bidi_levels.is_empty(),
"`char_info`, `bidi_levels`, and `char_indices` should now all be empty \
(though note `bidi_levels` may already have been empty as a special-case)"
);
return None;
}
let mut item_bidi_level = BidiLevel::new(0); // Initialized in the loop.
let start_byte_offset = self.char_indices.offset();
let mut item_char_len = 0;
loop {
let byte_offset = self.char_indices.offset();
let bidi_level = if self.bidi_levels.is_empty() {
self.paragraph_bidi_level
} else {
self.bidi_levels[0]
};
let mut script = self.char_info[0].script;
if !real_script(script) {
// This is a very simple heuristic, where if a character does not have a "real
// script," it inherits the script of the preceding character. UAX 24 paragraph
// 5.1 says this "works well in many cases", but also suggests performing, e.g.,
// bracket matching (for example, the parentheses in `hello (αβγ)` should ideally
// both be marked as being `Latin`). At that point, `Itemizer` would probably like
// to have reusable scratch for the bracket stack.
script = self.current_script;
}
// First iteration of the loop, initialize item properties.
if item_char_len == 0 {
item_bidi_level = bidi_level;
self.current_script = script;
}
if bidi_level != item_bidi_level || script != self.current_script {
break;
}
if item_char_len > 0
&& split_after(TextRange {
byte_range: start_byte_offset..byte_offset,
char_range: self.current_char_offset..self.current_char_offset + item_char_len,
})
{
break;
}
self.char_indices.next().expect("The passed in `text` was not of the same length as the text used to generate `Analysis`");
self.char_info = &self.char_info[1..];
if !self.bidi_levels.is_empty() {
self.bidi_levels = &self.bidi_levels[1..];
}
item_char_len += 1;
if self.char_info.is_empty() {
// The text is now empty, so we're finished.
break;
}
}
let start_char_offset = self.current_char_offset;
self.current_char_offset += item_char_len;
Some(Segment {
range: TextRange {
byte_range: start_byte_offset..self.char_indices.offset(),
char_range: start_char_offset..self.current_char_offset,
},
script: icu_script_to_parlance_script(self.current_script),
bidi_level: item_bidi_level,
})
}
}
fn real_script(script: IcuScript) -> bool {
script != IcuScript::Common && script != IcuScript::Unknown && script != IcuScript::Inherited
}
/// Convert an ICU script into a [`Script`].
#[inline]
fn icu_script_to_parlance_script(script: IcuScript) -> Script {
static SHORT_NAMES: icu_properties::PropertyNamesShortBorrowed<'static, IcuScript> =
icu_properties::PropertyNamesShort::new();
SHORT_NAMES
.get(script)
.and_then(|name| Script::parse(name).ok())
.unwrap_or(Script::UNKNOWN)
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use parlance::Script;
use crate::{Analysis, AnalysisOptions, Analyzer};
use super::Segment;
const LATN: Script = Script::from_bytes(*b"Latn");
const GREK: Script = Script::from_bytes(*b"Grek");
const ARAB: Script = Script::from_bytes(*b"Arab");
fn analyze(text: &str) -> Analysis {
let mut analyzer = Analyzer::new();
let mut analysis = Analysis::new();
let options = AnalysisOptions::default();
analyzer.analyze(text, &options, &mut analysis);
analysis
}
fn items(text: &str) -> Vec<Segment> {
let analysis = analyze(text);
let mut itemizer = analysis.itemize(text);
core::iter::from_fn(|| itemizer.next(|_| false)).collect()
}
#[test]
fn empty() {
assert!(items("").is_empty());
}
#[test]
fn mixed_direction() {
let text = "hello مرحبا";
let items = items(text);
assert!(items.len() >= 2);
assert_eq!(items[0].script, LATN);
assert!(items[0].bidi_level.is_ltr());
assert!(
items
.iter()
.any(|item| item.script == ARAB && item.bidi_level.is_rtl())
);
// Items tile the text contiguously.
let mut cursor = 0;
for item in &items {
assert_eq!(item.range.byte_range.start, cursor);
cursor = item.range.byte_range.end;
}
assert_eq!(cursor, text.len());
}
#[test]
fn predicate() {
let text = "abcdef";
let analysis = analyze(text);
let mut itemizer = analysis.itemize(text);
let items: Vec<_> =
core::iter::from_fn(|| itemizer.next(|range| range.char_range.end == 3)).collect();
assert_eq!(items.len(), 2);
assert_eq!(items[0].range.byte_range, 0..3);
assert_eq!(items[0].range.char_range, 0..3);
assert_eq!(items[1].range.byte_range, 3..6);
assert_eq!(items[1].range.char_range, 3..6);
}
#[test]
fn neutral_backward() {
// Latin, a space (`Common`), then Greek.
let text = "abc αβγ";
let items = items(text);
assert_eq!(items.len(), 2);
// The space attaches to the Latin run.
assert_eq!(&text[items[0].range.byte_range.clone()], "abc ");
assert_eq!(items[0].script, LATN);
assert_eq!(&text[items[1].range.byte_range.clone()], "αβγ");
assert_eq!(items[1].script, GREK);
}
}
+128
View File
@@ -0,0 +1,128 @@
// Copyright 2025 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Parley Engine provides low level APIs for shaping paragraphs of text.
//!
//! ## Usage
//!
//! Use [`Analyzer`], [`Analysis`], [`Shaper`] and [`ShapedText`] to shape a paragraph of text into
//! glyphs. Correct reshaping of lines is in progress; in the meantime you can break text at
//! [`Atom`] or [`ShapedCluster`][crate::shape::ShapedCluster] boundaries.
//!
//! Text analysis is performed before shaping, and the same source string must be passed to each
//! stage.
//!
//! Higher-level users may prefer using [`parley`][parley], which uses this crate and implements
//! layout and styling.
//!
//! ```rust,no_run
//! # // We only compile this doctest because we don't have a font available.
//! # use parley_engine::{Analysis, AnalysisOptions, Analyzer, FontInstanceRef, FontSelector, ShapedText, ShapeOptions, Shaper};
//! # use parley_engine::shape::CharCluster;
//! # use parley_engine::itemize::{Item, Segment};
//! #
//! # struct NoFont;
//! # impl FontSelector for NoFont {
//! # fn select_font(
//! # &mut self,
//! # _segment: &Segment,
//! # _options: &ShapeOptions<'_>,
//! # _cluster: &mut CharCluster,
//! # ) -> Option<FontInstanceRef<'_>> {
//! # unimplemented!()
//! # }
//! # }
//! #
//! # let select_font = NoFont;
//! let mut analysis = Analysis::default();
//! let mut analyzer = Analyzer::default();
//! let mut shaped_text = ShapedText::default();
//! let mut shaper = Shaper::default();
//!
//! let text = "The quick brown ثعلب jumps over the lazy dog.";
//! let char_count = text.chars().count();
//! let char_style_indices = vec![0; char_count];
//!
//! analyzer.analyze(text, &AnalysisOptions::default(), &mut analysis);
//! shaper.shape_text(
//! text,
//! &analysis,
//! &char_style_indices,
//! [Item {
//! char_end: char_count.try_into().unwrap(),
//! options: ShapeOptions {
//! font_size: 16.0,
//! language: None,
//! features: &[],
//! variations: &[],
//! },
//! }],
//! select_font, // Selects fonts covering each cluster.
//! &mut shaped_text,
//! );
//!
//! for (run_idx, run) in shaped_text.runs().iter().enumerate() {
//! let slice = shaped_text.run_slice(run_idx as u32);
//! // You can, for example, measure grapheme advances for hit-testing or
//! // placing carets.
//! for atom in slice.atoms_start() {
//! for grapheme in atom.graphemes_start() {
//! std::dbg!(grapheme);
//! }
//! }
//!
//! // Or get glyphs for rendering (for simplicity, this iterates clusters in
//! // logical order, but for rendering you'd want to reorder runs and clusters
//! // according to their `run.bidi_level`).
//! for cluster in slice.shaped_clusters_range() {
//! for glyph in slice.shaped_cluster_glyphs(cluster) {
//! std::dbg!(glyph);
//! }
//! }
//! }
//! ```
//!
//! ## Features
//!
//! - `std` (enabled by default): This is currently unused and is provided for forward compatibility.
//! - `bytemuck`: Forwarded to [`parlance`], which then implements traits from `bytemuck` on its
//! types.
//!
//! [parley]: https://docs.rs/parley
// LINEBENDER LINT SET - lib.rs - v3
// See https://linebender.org/wiki/canonical-lints/
// These lints shouldn't apply to examples or tests.
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
// These lints shouldn't apply to examples.
#![warn(clippy::print_stdout, clippy::print_stderr)]
// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit.
#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))]
// END LINEBENDER LINT SET
#![cfg_attr(docsrs, feature(doc_cfg))]
#![no_std]
#[cfg(feature = "std")]
extern crate std;
extern crate alloc;
mod analysis;
mod analyzer;
mod bidi;
pub mod break_overrides;
pub mod dictionary;
pub mod platform;
mod glyph;
pub mod itemize;
mod lru_cache;
pub mod shape;
pub use linebender_resource_handle::FontData;
pub use parlance::{BaseDirection, NormalizedCoord};
pub use analysis::{Analysis, AnalysisDataSources, CharInfo};
pub use analyzer::{AnalysisOptions, Analyzer, LineBreakConfig};
pub use glyph::Glyph;
pub use shape::atom::{Atom, Atoms, Grapheme, Graphemes, ShapedClusterGlyphs, ShapedSlice};
pub use shape::shaped_text::{FontMetrics, ShapedRun, ShapedText};
pub use shape::shaper::{FontInstance, FontInstanceRef, FontSelector, ShapeOptions, Shaper};
+208
View File
@@ -0,0 +1,208 @@
// Copyright 2025 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use alloc::vec::Vec;
use hashbrown::Equivalent;
/// An entry in the cache.
pub(crate) struct Entry<ID, T> {
pub epoch: u64,
pub id: ID,
pub data: T,
}
/// A least-recently-used cache. This cache uses a linear scan of its entries
/// to find a given entry - it is optimised for a low number of entries. Preferably
/// keep `max_entries` low - in the order of tens.
pub(crate) struct LruCache<ID, T> {
entries: Vec<Entry<ID, T>>,
epoch: u64,
max_entries: usize,
}
impl<ID, T> LruCache<ID, T> {
pub(crate) fn new(max_entries: usize) -> Self {
Self {
entries: Vec::default(),
epoch: 0,
max_entries,
}
}
/// Returns a reference to the entry with the given ID. If the entry is not
/// found, it is created and returned using `make_data`.
///
/// The lookup key must be `Equivalent` to ID for lookups and convertible `Into<ID>`
/// for creating new entries.
pub(crate) fn entry<K>(&mut self, id: K, make_data: impl FnOnce() -> T) -> &T
where
K: Equivalent<ID> + Into<ID>,
{
let index = self.find_entry(id, make_data);
self.epoch += 1;
let entry = &mut self.entries[index];
entry.epoch = self.epoch;
&entry.data
}
fn find_entry<K>(&mut self, id: K, make_data: impl FnOnce() -> T) -> usize
where
K: Equivalent<ID> + Into<ID>,
{
let epoch = self.epoch;
let mut lowest_serial = epoch;
let mut lowest_index = 0;
for (i, entry) in self.entries.iter().enumerate() {
if id.equivalent(&entry.id) {
return i;
}
if entry.epoch < lowest_serial {
lowest_serial = entry.epoch;
lowest_index = i;
}
}
if self.entries.len() < self.max_entries {
lowest_index = self.entries.len();
self.entries.push(Entry {
epoch,
id: id.into(),
data: make_data(),
});
} else {
let entry = &mut self.entries[lowest_index];
entry.epoch = epoch;
entry.id = id.into();
entry.data = make_data();
}
lowest_index
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::{String, ToString};
#[derive(Debug, Clone, PartialEq)]
struct TestId(String);
struct TestLookupKey<'a>(&'a str);
impl<'a> Equivalent<TestId> for TestLookupKey<'a> {
fn equivalent(&self, key: &TestId) -> bool {
self.0 == key.0.as_str()
}
}
impl<'a> From<TestLookupKey<'a>> for TestId {
fn from(key: TestLookupKey<'a>) -> Self {
Self(key.0.to_string())
}
}
impl Equivalent<Self> for TestId {
fn equivalent(&self, key: &Self) -> bool {
self.0 == key.0
}
}
#[test]
fn test_retrieve_existing_entry() {
let mut cache = LruCache::new(3);
// Insert an entry
let value1 = cache.entry(TestLookupKey("key1"), || 42);
assert_eq!(*value1, 42);
// Retrieve the same entry - make_data should not be called
let value2 = cache.entry(TestLookupKey("key1"), || {
panic!("Should not create new data")
});
assert_eq!(*value2, 42);
assert_eq!(cache.entries.len(), 1);
}
#[test]
fn test_multiple_entries() {
let mut cache = LruCache::new(3);
let value1 = cache.entry(TestLookupKey("key1"), || 1);
assert_eq!(*value1, 1);
let value2 = cache.entry(TestLookupKey("key2"), || 2);
assert_eq!(*value2, 2);
let value3 = cache.entry(TestLookupKey("key3"), || 3);
assert_eq!(*value3, 3);
assert_eq!(cache.entries.len(), 3);
assert_eq!(cache.epoch, 3);
}
#[test]
fn test_lru_eviction() {
let mut cache = LruCache::new(3);
// Add three entries
cache.entry(TestLookupKey("key1"), || 1);
cache.entry(TestLookupKey("key2"), || 2);
cache.entry(TestLookupKey("key3"), || 3);
// Access key1 to update its epoch
cache.entry(TestLookupKey("key1"), || panic!("Should not create"));
// Add key4 - should evict key2 (oldest untouched)
cache.entry(TestLookupKey("key4"), || 4);
// Verify key1 is still present
let value1 = cache.entry(TestLookupKey("key1"), || {
panic!("key1 should still be present")
});
assert_eq!(*value1, 1);
// Verify key2 was evicted
let mut was_created = false;
cache.entry(TestLookupKey("key2"), || {
was_created = true;
20
});
assert!(was_created, "key2 should have been evicted");
}
#[test]
fn test_lru_eviction_after_multiple_hits() {
let mut cache = LruCache::new(3);
cache.entry(TestLookupKey("key1"), || 1);
cache.entry(TestLookupKey("key2"), || 2);
cache.entry(TestLookupKey("key3"), || 3);
// Hit all three in order: key3 first (making it LRU among hits),
// then key1, then key2 (most recently used).
cache.entry(TestLookupKey("key3"), || panic!("Should not create"));
cache.entry(TestLookupKey("key1"), || panic!("Should not create"));
cache.entry(TestLookupKey("key2"), || panic!("Should not create"));
// Insert key4 — should evict key3 (least recently accessed)
cache.entry(TestLookupKey("key4"), || 4);
// key1 and key2 should still be present with original values
// (check these first since verifying key3 eviction will trigger another eviction)
let v1 = cache.entry(TestLookupKey("key1"), || {
panic!("key1 should still be present")
});
assert_eq!(*v1, 1);
let v2 = cache.entry(TestLookupKey("key2"), || {
panic!("key2 should still be present")
});
assert_eq!(*v2, 2);
// key3 should have been evicted
let mut key3_recreated = false;
cache.entry(TestLookupKey("key3"), || {
key3_recreated = true;
30
});
assert!(key3_recreated, "key3 should have been evicted as the LRU");
}
}
+70
View File
@@ -0,0 +1,70 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! A face of last resort that the platform draws (Rune: vendor/parley_engine.patch). A host that
//! can shape and draw text itself (a browser's canvas, with the system's fonts, shaping and
//! colour emoji) registers a font that covers every character and gives its runs a shaper here.
//! A run in that font isn't shaped by HarfRust: the host gives one glyph per grapheme, its
//! advance measured as the platform lays the run out, and the glyph ids are the host's own, for
//! it to draw them.
use alloc::vec::Vec;
/// A run in the platform's face, for its shaper.
#[derive(Debug)]
pub struct PlatformText<'a> {
/// The run's text.
pub text: &'a str,
/// Byte offsets into `text` where each grapheme starts, ascending, the first 0.
pub graphemes: &'a [u32],
/// Byte offsets where each unit the platform draws whole starts (at grapheme starts, between
/// break opportunities), ascending, the first 0. A line never breaks inside one.
pub units: &'a [u32],
/// The font size, in the layout's units.
pub size: f32,
/// The weight asked for (`wght`, 100 to 900).
pub weight: f32,
/// Italic asked for.
pub italic: bool,
/// The run is right to left.
pub rtl: bool,
/// The run's language tag, if it has one.
pub language: Option<&'a str>,
}
/// One glyph per grapheme of a [`PlatformText`], in logical order.
#[derive(Clone, Copy, Debug, Default)]
pub struct PlatformGlyph {
/// The host's id for what this glyph draws.
pub id: u32,
/// The grapheme's advance, in the layout's units.
pub advance: f32,
/// How far right of its pen the glyph draws, in the layout's units.
pub x_offset: f32,
}
/// Fills `out` with one glyph per grapheme of the run, in logical order.
pub type PlatformShaper = fn(run: &PlatformText<'_>, out: &mut Vec<PlatformGlyph>);
#[cfg(feature = "std")]
static PLATFORM: std::sync::OnceLock<(u64, PlatformShaper)> = std::sync::OnceLock::new();
/// Makes the font whose data has id `font` (`Blob::id`) the platform's face, shaped by `shaper`,
/// once (a second call changes nothing). Needs `std`.
pub fn set_platform_face(font: u64, shaper: PlatformShaper) {
#[cfg(feature = "std")]
let _ = PLATFORM.set((font, shaper));
#[cfg(not(feature = "std"))]
let _ = (font, shaper);
}
/// The shaper for the font with data id `font`, if it's the platform's face.
pub(crate) fn shaper(font: u64) -> Option<PlatformShaper> {
#[cfg(feature = "std")]
return PLATFORM.get().filter(|(id, _)| *id == font).map(|(_, shaper)| *shaper);
#[cfg(not(feature = "std"))]
{
let _ = font;
None
}
}
File diff suppressed because it is too large. Load diff
+215
View File
@@ -0,0 +1,215 @@
// Copyright 2025 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use alloc::boxed::Box;
use hashbrown::Equivalent;
use parlance::FontVariation;
#[derive(PartialEq, Copy, Clone)]
pub(crate) struct ShapeDataKey {
/// The font collection's blob ID.
font_blob_id: u64,
/// The font's index in the font collection.
font_index: u32,
}
impl ShapeDataKey {
pub(crate) const fn new(font_blob_id: u64, font_index: u32) -> Self {
Self {
font_blob_id,
font_index,
}
}
}
impl Equivalent<Self> for ShapeDataKey {
#[inline(always)]
fn equivalent(&self, key: &Self) -> bool {
self == key
}
}
impl From<&Self> for ShapeDataKey {
#[inline(always)]
fn from(key: &Self) -> Self {
*key
}
}
pub(crate) struct ShapeInstanceId {
/// The font collection's blob ID.
font_blob_id: u64,
/// The font's index in the font collection.
font_index: u32,
synthesis: fontique::Synthesis,
variations: Option<Box<[FontVariation]>>,
}
pub(crate) struct ShapeInstanceKey<'a> {
/// The font collection's blob ID.
font_blob_id: u64,
/// The font's index in the font collection.
font_index: u32,
synthesis: &'a fontique::Synthesis,
variations: Option<&'a [FontVariation]>,
}
impl<'a> ShapeInstanceKey<'a> {
pub(crate) const fn new(
font_blob_id: u64,
font_index: u32,
synthesis: &'a fontique::Synthesis,
variations: Option<&'a [FontVariation]>,
) -> Self {
Self {
font_blob_id,
font_index,
synthesis,
variations,
}
}
}
impl<'a> Equivalent<ShapeInstanceId> for ShapeInstanceKey<'a> {
#[inline(always)]
fn equivalent(&self, key: &ShapeInstanceId) -> bool {
self.font_blob_id == key.font_blob_id
&& self.font_index == key.font_index
&& *self.synthesis == key.synthesis
&& self.variations == key.variations.as_deref()
}
}
impl<'a> From<ShapeInstanceKey<'a>> for ShapeInstanceId {
#[inline(always)]
fn from(key: ShapeInstanceKey<'a>) -> Self {
Self {
font_blob_id: key.font_blob_id,
font_index: key.font_index,
synthesis: *key.synthesis,
variations: key.variations.map(|v| v.to_vec().into()),
}
}
}
/// A shaped run's font metrics: its font instance at a size (Rune: vendor/parley_engine.patch).
pub(crate) struct RunMetricsId {
instance: ShapeInstanceId,
font_size: u32,
}
pub(crate) struct RunMetricsKey<'a> {
instance: ShapeInstanceKey<'a>,
font_size: f32,
}
impl<'a> RunMetricsKey<'a> {
pub(crate) const fn new(instance: ShapeInstanceKey<'a>, font_size: f32) -> Self {
Self {
instance,
font_size,
}
}
}
impl<'a> Equivalent<RunMetricsId> for RunMetricsKey<'a> {
#[inline(always)]
fn equivalent(&self, key: &RunMetricsId) -> bool {
self.font_size.to_bits() == key.font_size && self.instance.equivalent(&key.instance)
}
}
impl<'a> From<RunMetricsKey<'a>> for RunMetricsId {
#[inline(always)]
fn from(key: RunMetricsKey<'a>) -> Self {
Self {
instance: key.instance.into(),
font_size: key.font_size.to_bits(),
}
}
}
pub(crate) struct ShapePlanId {
/// The font collection's blob ID.
font_blob_id: u64,
/// The font's index in the font collection.
font_index: u32,
synthesis: fontique::Synthesis,
direction: harfrust::Direction,
script: harfrust::Script,
language: Option<harfrust::Language>,
features: Box<[harfrust::Feature]>,
variations: Option<Box<[FontVariation]>>,
}
pub(crate) struct ShapePlanKey<'a> {
/// The font collection's blob ID.
font_blob_id: u64,
/// The font's index in the font collection.
font_index: u32,
synthesis: &'a fontique::Synthesis,
direction: harfrust::Direction,
script: harfrust::Script,
language: Option<harfrust::Language>,
features: &'a [harfrust::Feature],
variations: Option<&'a [FontVariation]>,
}
impl<'a> ShapePlanKey<'a> {
pub(crate) const fn new(
font_blob_id: u64,
font_index: u32,
synthesis: &'a fontique::Synthesis,
direction: harfrust::Direction,
script: harfrust::Script,
language: Option<harfrust::Language>,
features: &'a [harfrust::Feature],
variations: Option<&'a [FontVariation]>,
) -> Self {
Self {
font_blob_id,
font_index,
synthesis,
direction,
script,
language,
features,
variations,
}
}
}
impl<'a> Equivalent<ShapePlanId> for ShapePlanKey<'a> {
#[inline(always)]
fn equivalent(&self, key: &ShapePlanId) -> bool {
self.font_blob_id == key.font_blob_id
&& self.font_index == key.font_index
&& *self.synthesis == key.synthesis
&& self.direction == key.direction
&& self.script == key.script
&& self.language == key.language
&& self.features.len() == key.features.len()
&& self.variations == key.variations.as_deref()
&& self
.features
.iter()
.zip(key.features.iter())
.all(|(a, b)| a == b)
}
}
impl<'a> From<ShapePlanKey<'a>> for ShapePlanId {
#[inline(always)]
fn from(key: ShapePlanKey<'a>) -> Self {
Self {
font_blob_id: key.font_blob_id,
font_index: key.font_index,
synthesis: *key.synthesis,
direction: key.direction,
script: key.script,
language: key.language,
features: key.features.to_vec().into(),
variations: key.variations.map(|v| v.to_vec().into()),
}
}
}
+638
View File
@@ -0,0 +1,638 @@
// Copyright 2025 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
#![expect(missing_docs, reason = "Deferred")]
#![expect(missing_debug_implementations, reason = "Deferred")]
use core::cmp::Ordering;
use alloc::vec::Vec;
use icu_normalizer::properties::Decomposed;
use parley_emoji::{EmojiDFA, EmojiPresentationStyle, EmojiSegmentationCategory};
use crate::{CharInfo, analysis::AnalysisDataSources};
#[derive(Debug, Default)]
pub struct CharCluster {
chars: Vec<Char>,
map_len: u8,
start: u32,
end: u32,
force_normalize: bool,
comp: Form,
decomp: Form,
emoji_presentation_style: EmojiPresentationStyle,
}
impl CharCluster {
#[inline]
pub fn range(&self) -> SourceRange {
SourceRange {
start: self.start,
end: self.end,
}
}
#[inline(always)]
pub fn chars(&self) -> &[Char] {
&self.chars
}
#[inline(always)]
pub fn is_emoji(&self) -> bool {
self.emoji_presentation_style.is_emoji()
}
}
/// Source range of a cluster in code units.
#[derive(Copy, Clone)]
pub struct SourceRange {
pub start: u32,
pub end: u32,
}
#[derive(Copy, Clone, Debug, Default)]
pub struct Char {
/// The character.
pub ch: char,
/// Whether the character
pub is_control_character: bool,
/// True if the character should be considered when mapping glyphs.
pub contributes_to_shaping: bool,
/// Indexes into the list of styles for the containing text run, to find the style applicable
/// to this character.
pub style_index: u16,
}
/// Whitespace class of a character.
///
/// All white space characters as defined
/// [by Unicode](https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt) map to a variant of
/// this enum. The variants are based on the various sets of white space as in
/// [CSS Text 4][css-text-4].
///
/// A character maps to [`Whitespace::None`] if and only if that character's [`char::is_whitespace`]
/// is `false`.
///
/// [css-text-4]: https://www.w3.org/TR/css-text-4/
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Whitespace {
/// Not white space.
None = 0,
/// Standard space.
Space = 1,
/// Non-breaking space (U+00A0).
NoBreakSpace = 2,
/// Ideographic space (U+3000).
///
/// Note CSS Text 4 doesn't treat this space any differently from [`Self::OtherSpaceSeparator`],
/// but some applications do.
IdeographicSpace = 3,
/// The Unicode "space separators" (category `Zs`), except for the standard space, non-breaking
/// space and ideographic space.
///
/// Applications may want to treat those three space separators differently from the general
/// class of space separators.
OtherSpaceSeparator = 4,
/// Horizontal tab.
Tab = 5,
/// Newline (CR, LF, CRLF, LS, or PS).
Newline = 6,
/// Vertical tab, form feed and next line.
///
/// These are Unicode `White_Space`, but CSS Text 4 § 4 says to treat them as visible glyphs.
///
/// Note [`Self::Tab`] and some of [`Self::Newline`] are also in the Unicode `Cc` category.
/// There are also `Cc` characters that aren't `White_Space` (those would be
/// [`Whitespace::None`]).
ControlWhitespace = 7,
// NOTE: if you grow these variants more than eight, ensure you also update the encoding in
// `GraphemeFlags`.
}
impl Whitespace {
#[inline]
pub(crate) const fn from_char(c: char) -> Self {
// See https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt.
match c {
' ' => Self::Space,
'\u{00A0}' => Self::NoBreakSpace,
'\u{3000}' => Self::IdeographicSpace,
// Ogham space mark, en quad through hair space, narrow no-break space, medium
// mathematical space.
'\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}' => {
Self::OtherSpaceSeparator
}
'\t' => Self::Tab,
// Newline, carriage return, line separator, paragraph separator.
'\n' | '\r' | '\u{2028}' | '\u{2029}' => Self::Newline,
// Vertical tab, form feed, next line. These are `White_Space` that CSS says to render
// as control characters.
'\u{000b}' | '\u{000c}' | '\u{0085}' => Self::ControlWhitespace,
_ => Self::None,
}
}
/// Returns true for space or no break space.
#[inline]
pub fn is_space_or_nbsp(self) -> bool {
matches!(self, Self::Space | Self::NoBreakSpace)
}
}
/// A font's coverage of a character cluster.
///
/// This is the fraction `covered / total` of characters covered by a font. Coverages are ordered by
/// the value of the fraction (with `0 / 0` considered to be completely covered). Use, e.g.,
/// [`Self::cmp`] to compare coverages.
///
/// In the unlikely event there are more characters than this in the character cluster, the counts
/// are saturated to [`u8::MAX`].
#[derive(Copy, Clone, Eq, Debug)]
pub struct Coverage {
/// The number of characters covered by the font.
pub covered: u8,
/// The number of characters counting towards coverage.
pub total: u8,
}
impl Coverage {
/// Zero coverage.
///
/// Useful, for example, as a starting "best coverage," in case you're searching for a
/// best-covering font.
pub const NONE: Self = Self {
covered: 0,
total: u8::MAX,
};
/// Complete coverage, meaning all characters contributing to shaping are covered.
///
/// A coverage compares equal to `COMPLETE` exactly when it is complete, see also
/// [`Self::is_complete`].
pub const COMPLETE: Self = Self {
covered: u8::MAX,
total: u8::MAX,
};
/// Returns `true` iff all characters are covered.
#[inline(always)]
#[must_use]
pub fn is_complete(self) -> bool {
self.covered >= self.total
}
}
impl PartialEq for Coverage {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl PartialOrd for Coverage {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Coverage {
/// Coverages are ordered by the value of the fraction `covered / total`.
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
// We check `is_complete` explicitly, such that fractions of `x / 0`, which are considered
// complete, are ordered identically to other complete fractions. Cases other than those
// with a denominator of 0 would have already been correctly ordered by value through the
// cross-multiplication in the `(false, false)` arm, but note we now order all complete
// fractions as `Ordering::Equal`.
match (self.is_complete(), other.is_complete()) {
(true, true) => Ordering::Equal,
(true, false) => Ordering::Greater,
(false, true) => Ordering::Less,
(false, false) => (u16::from(self.covered) * u16::from(other.total))
.cmp(&(u16::from(other.covered) * u16::from(self.total))),
}
}
}
impl CharCluster {
#[inline]
pub(crate) fn clear(&mut self) {
self.chars.clear();
self.map_len = 0;
self.start = 0;
self.end = 0;
self.force_normalize = false;
self.comp.clear();
self.decomp.clear();
self.emoji_presentation_style = EmojiPresentationStyle::Default;
}
#[inline(always)]
fn len(&self) -> usize {
self.chars.len()
}
/// Returns the primary style index for the cluster.
#[inline(always)]
pub fn style_index(&self) -> u16 {
self.chars[0].style_index
}
#[inline(always)]
fn contributes_to_shaping(ch: char, analysis_data_sources: &AnalysisDataSources) -> bool {
let props = analysis_data_sources.properties(ch);
crate::analysis::contributes_to_shaping(props.general_category(), props.script())
}
fn decomposed(&mut self, analysis_data_sources: &AnalysisDataSources) -> Option<&[Char]> {
match self.decomp.state {
FormState::Invalid => None,
FormState::None => {
self.decomp.state = FormState::Invalid;
// Only attempt pairwise normalization (1 <-> 2 characters)
if self.chars.len() != 1 {
return None;
}
let decomposer = analysis_data_sources.decomposing_normalizer();
let decomp = decomposer.decompose(self.chars[0].ch);
match decomp {
Decomposed::Default | Decomposed::Singleton(_) => {
return None;
}
Decomposed::Expansion(a, b) => {
let mut copy = self.chars[0];
copy.ch = a;
copy.contributes_to_shaping =
Self::contributes_to_shaping(a, analysis_data_sources);
self.decomp.chars[0] = copy;
copy.ch = b;
copy.contributes_to_shaping =
Self::contributes_to_shaping(b, analysis_data_sources);
self.decomp.chars[1] = copy;
self.decomp.len = 2;
}
}
self.decomp.state = FormState::Valid;
self.decomp.setup();
Some(self.decomp.chars())
}
FormState::Valid => Some(self.decomp.chars()),
}
}
fn composed(&mut self, analysis_data_sources: &AnalysisDataSources) -> Option<&[Char]> {
match self.comp.state {
FormState::Invalid => None,
FormState::None => {
self.comp.state = FormState::Invalid;
// Only attempt pairwise normalization (1 <-> 2 characters)
if self.chars.len() != 2 {
return None;
}
let composer = analysis_data_sources.composing_normalizer();
let ch = composer.compose(self.chars[0].ch, self.chars[1].ch)?;
let mut copy = self.chars[0];
copy.ch = ch;
copy.contributes_to_shaping =
Self::contributes_to_shaping(ch, analysis_data_sources);
self.comp.chars[0] = copy;
self.comp.len = 1;
self.comp.state = FormState::Valid;
self.comp.setup();
Some(self.comp.chars())
}
FormState::Valid => Some(self.comp.chars()),
}
}
/// Calculate a candidate font's coverage of this character cluster.
///
/// The callback `covers` should return whether the character is covered by the font under
/// consideration. The coverage returned is the best coverage of the character cluster's
/// characters, or the characters of its normalized forms (see
/// <https://www.unicode.org/reports/tr15/>).
///
/// Coverages are ordered by how much of the cluster they cover, see [`Coverage`]. Note
/// [`Coverage::total`] may be different from the count of [`Self::chars`], and may also differ
/// between subsequent calls due to returning the best coverage of either the original
/// characters or one of the normalized forms.
pub fn calculate_coverage(
&mut self,
covers: impl Fn(char) -> bool,
analysis_data_sources: &AnalysisDataSources,
) -> Coverage {
let len = self.len();
let mut best_coverage = Mapper {
chars: &self.chars[..len],
map_len: self.map_len,
}
.coverage(&covers);
if best_coverage.is_complete() {
return best_coverage;
}
if self.force_normalize && self.composed(analysis_data_sources).is_some() {
let coverage = self.comp.coverage(&covers);
if coverage > best_coverage {
best_coverage = coverage;
if coverage.is_complete() {
return best_coverage;
}
}
}
if self.decomposed(analysis_data_sources).is_some() {
let coverage = self.decomp.coverage(&covers);
if coverage > best_coverage {
best_coverage = coverage;
if coverage.is_complete() {
return best_coverage;
}
}
if !self.force_normalize && self.composed(analysis_data_sources).is_some() {
let coverage = self.comp.coverage(&covers);
if coverage > best_coverage {
best_coverage = coverage;
if coverage.is_complete() {
return best_coverage;
}
}
}
}
best_coverage
}
/// Rebuilds `self` in-place using the existing allocation for the given grapheme.
///
/// `chars` must yield the grapheme's characters with associated analysis info, and style index.
///
/// `code_unit_offset_in_string` must be the byte offset of the grapheme's first character in the
/// source string. When this method returns, its value is the byte offset just past the end of
/// the grapheme in the source string.
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
#[inline]
pub(crate) fn fill(
&mut self,
chars: impl Iterator<Item = (char, CharInfo, u16)>,
code_unit_offset_in_string: &mut usize,
) {
// Reset cluster but keep allocation
self.clear();
let mut force_normalize = false;
let mut is_emoji = false;
let mut map_len: u8 = 0;
let mut emoji_dfa = EmojiDFA::new();
let mut leading_is_emoji_presentation = false;
let start = *code_unit_offset_in_string as u32;
for (i, (ch, info, style_index)) in chars.enumerate() {
*code_unit_offset_in_string += ch.len_utf8();
force_normalize |= info.force_normalize();
is_emoji |= info.is_emoji_or_pictograph();
let mut is_emoji_presentation_selector = false;
if is_emoji {
if i == 0 {
leading_is_emoji_presentation = info.is_emoji_presentation();
}
let category = EmojiSegmentationCategory::from_codepoint(
ch as u32,
info.is_emoji(),
info.is_emoji_presentation(),
info.is_emoji_modifier(),
info.is_emoji_modifier_base(),
info.is_region_indicator(),
);
is_emoji_presentation_selector = category.is_presentation_selector();
emoji_dfa.step_record(category);
}
// Variation selectors don't impact font coverage, and are default ignorable.
// TODO: Is there a default ignorable flag we should be using instead?
let contributes_to_shaping =
info.contributes_to_shaping() && !is_emoji_presentation_selector;
if contributes_to_shaping {
map_len = map_len.saturating_add(1);
}
self.chars.push(Char {
ch,
contributes_to_shaping,
style_index,
is_control_character: info.is_control(),
});
}
// Finalize cluster metadata
let end = *code_unit_offset_in_string as u32;
self.map_len = map_len;
self.start = start;
self.end = end;
self.force_normalize = force_normalize;
if is_emoji {
self.emoji_presentation_style =
emoji_dfa.presentation_style(leading_is_emoji_presentation);
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum FormState {
None,
Valid,
Invalid,
}
#[derive(Clone, Debug)]
pub(crate) struct Form {
chars: [Char; 2],
len: u8,
map_len: u8,
state: FormState,
}
impl Default for Form {
fn default() -> Self {
Self::new()
}
}
impl Form {
fn new() -> Self {
Self {
chars: [Char::default(), Char::default()],
len: 0,
map_len: 0,
state: FormState::None,
}
}
fn clear(&mut self) {
self.chars = [Char::default(), Char::default()];
self.len = 0;
self.map_len = 0;
self.state = FormState::None;
}
#[inline(always)]
fn chars(&self) -> &[Char] {
&self.chars[..self.len as usize]
}
#[inline(always)]
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
fn setup(&mut self) {
self.map_len = self
.chars()
.iter()
.filter(|c| !c.is_control_character)
.count() as u8;
}
#[inline(always)]
fn coverage(&self, covers: &impl Fn(char) -> bool) -> Coverage {
Mapper {
chars: &self.chars[..self.len as usize],
map_len: self.map_len,
}
.coverage(covers)
}
}
struct Mapper<'a> {
chars: &'a [Char],
map_len: u8,
}
impl<'a> Mapper<'a> {
/// Returns the coverage of characters contributing to shaping.
fn coverage(&self, covers: &impl Fn(char) -> bool) -> Coverage {
let mut mapped: u8 = 0;
for c in self.chars.iter() {
if c.contributes_to_shaping && covers(c.ch) {
mapped = mapped.saturating_add(1);
}
}
// If this assert is hit, some bookkeeping is wrong somewhere, but the returned coverage is
// then simply considered to be complete.
debug_assert!(
mapped <= self.map_len,
"Counted more covered characters than the number of characters we consider to be contributing."
);
Coverage {
covered: mapped,
total: self.map_len,
}
}
}
#[cfg(test)]
mod tests {
use crate::shape::Whitespace;
use super::Coverage;
#[test]
fn ordering() {
assert!(Coverage::NONE < Coverage::COMPLETE);
assert_eq!(
Coverage {
covered: 0,
total: 0,
},
Coverage::COMPLETE
);
assert_eq!(
Coverage {
covered: 5,
total: 5,
},
Coverage::COMPLETE
);
assert_eq!(
Coverage {
// `covered` is greater than `total`, which shouldn't be produced by us, but is
// possible because `Coverage`'s fields are `pub`.
covered: 3,
total: 2,
},
Coverage::COMPLETE
);
assert_eq!(
Coverage {
covered: 255,
total: 255,
},
Coverage::COMPLETE
);
assert!(
Coverage {
covered: 4,
total: 5,
} > Coverage::NONE
);
assert!(
Coverage {
covered: 4,
total: 5,
} < Coverage::COMPLETE
);
assert!(
Coverage {
covered: 254,
total: 255,
} > Coverage::NONE
);
assert!(
Coverage {
covered: 254,
total: 255,
} < Coverage::COMPLETE
);
}
#[test]
fn whitespace() {
// Test all code points from `NUL` up to the last `White_Space` character as defined in
// https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt.
for c in '\u{0000}'..='\u{3000}' {
let ws = Whitespace::from_char(c);
assert!(
c.is_whitespace() && ws != Whitespace::None
|| !c.is_whitespace() && ws == Whitespace::None,
"`Whitespace` should encode exactly all of Unicode's `White_Space` characters."
);
}
}
}
+393
View File
@@ -0,0 +1,393 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
#![expect(missing_docs, reason = "Deferred")]
use core::ops::Range;
use crate::shape::Whitespace;
/// Data for a single character of the source text.
///
/// This is a character in the Unicode scalar value sense, i.e., it corresponds to a single `char`
/// of the source text.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Character {
pub text_byte_start: u32,
/// Style index for this character.
pub style_index: u16,
/// The whitespace class of this character.
pub whitespace: Whitespace,
/// Properties of this character.
pub flags: CharacterFlags,
/// Whether this character begins a grapheme cluster.
pub grapheme_start: bool,
}
impl Character {
/// The byte range of this character in the source text.
#[inline(always)]
pub fn text_byte_range(&self) -> Range<usize> {
self.text_byte_start as usize..self.text_byte_start as usize + self.flags.len_utf8()
}
/// Returns if this character is any whitespace.
#[inline(always)]
pub fn is_whitespace(self) -> bool {
self.whitespace != Whitespace::None
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) struct ShapedClusterFlags(u16);
impl ShapedClusterFlags {
const GLYPH_LEN_MASK: u16 = 0x00FF;
const INLINE_GLYPH: u16 = 1 << 8;
const GRAPHEME_START: u16 = 1 << 9;
const SAFE_TO_BREAK_BEFORE: u16 = 1 << 10;
/// Whether a soft wrap opportunity exists before the cluster's first character.
const SOFT_WRAP_BEFORE: u16 = 1 << 11;
/// [`Whitespace`] class of the cluster's first character (3 bits).
const WHITESPACE_SHIFT: u16 = 12;
const WHITESPACE_MASK: u16 = 0b111 << Self::WHITESPACE_SHIFT;
#[inline(always)]
pub(crate) const fn new(glyph_len: u8) -> Self {
Self(glyph_len as u16)
}
#[inline(always)]
pub(crate) const fn with_inline_glyph(mut self, set: bool) -> Self {
self.0 = self.0 & !Self::INLINE_GLYPH | if set { Self::INLINE_GLYPH } else { 0 };
self
}
#[inline(always)]
pub(crate) const fn with_grapheme_start(mut self, set: bool) -> Self {
self.0 = self.0 & !Self::GRAPHEME_START | if set { Self::GRAPHEME_START } else { 0 };
self
}
#[inline(always)]
pub(crate) const fn with_safe_to_break_before(mut self, set: bool) -> Self {
self.0 =
self.0 & !Self::SAFE_TO_BREAK_BEFORE | if set { Self::SAFE_TO_BREAK_BEFORE } else { 0 };
self
}
#[inline(always)]
pub(crate) const fn with_first_char(
mut self,
soft_wrap_opportunity: bool,
whitespace: Whitespace,
) -> Self {
self.0 = self.0 & !(Self::SOFT_WRAP_BEFORE | Self::WHITESPACE_MASK)
| if soft_wrap_opportunity {
Self::SOFT_WRAP_BEFORE
} else {
0
}
| ((whitespace as u16) << Self::WHITESPACE_SHIFT);
self
}
#[inline(always)]
const fn is_soft_wrap_opportunity_before(self) -> bool {
self.0 & Self::SOFT_WRAP_BEFORE != 0
}
#[inline(always)]
const fn whitespace(self) -> Whitespace {
match (self.0 & Self::WHITESPACE_MASK) >> Self::WHITESPACE_SHIFT {
1 => Whitespace::Space,
2 => Whitespace::NoBreakSpace,
3 => Whitespace::IdeographicSpace,
4 => Whitespace::OtherSpaceSeparator,
5 => Whitespace::Tab,
6 => Whitespace::Newline,
7 => Whitespace::ControlWhitespace,
_ => Whitespace::None,
}
}
#[inline(always)]
const fn glyph_len(self) -> u8 {
(self.0 & Self::GLYPH_LEN_MASK) as u8
}
#[inline(always)]
const fn has_inline_glyph(self) -> bool {
self.0 & Self::INLINE_GLYPH != 0
}
#[inline(always)]
const fn is_grapheme_start(self) -> bool {
self.0 & Self::GRAPHEME_START != 0
}
#[inline(always)]
const fn is_safe_to_break_before(self) -> bool {
self.0 & Self::SAFE_TO_BREAK_BEFORE != 0
}
}
/// A span of characters and the glyphs they shaped into.
///
/// Shaping may reorder, compose, decompose, etc.; there is no finer-grained correspondence between
/// characters and glyphs. For example, a base letter with a combining mark may shape into a single
/// glyph, a single character may shape into multiple glyphs, and a ligature may combine multiple
/// characters into shared glyphs.
///
/// Shaped cluster boundaries are not necessarily [`Grapheme`][crate::Grapheme] boundaries. The
/// shared boundaries are encoded by [`Atom`][crate::Atom]s.
///
/// For more information about clusters, see [HarfBuzz's documentation][harfbuzz].
///
/// [harfbuzz]: https://harfbuzz.github.io/working-with-harfbuzz-clusters.html
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct ShapedCluster {
/// The characters of this cluster, as a range into
/// [`ShapedText::characters`](crate::ShapedText::characters).
//
// TODO: this currently stores the full range, but perhaps we could store only the start index.
// See <https://github.com/linebender/parley/pull/715#discussion_r3693794119>.
pub(crate) chars_range: (u32, u32),
/// Style index for this cluster.
pub style_index: u16,
/// The index into the glyph array where this cluster's glyphs start.
///
/// If [`Self::has_inline_glyph`] is `true`, this is a glyph identifier instead. For more, see
/// the documentation on that method.
pub glyph_offset: u32,
// /// Number of glyphs in this cluster (0xFF = single glyph stored inline)
// pub glyph_len: u8,
pub(crate) flags: ShapedClusterFlags,
/// Advance width for this cluster
pub advance: f32,
}
impl ShapedCluster {
/// The characters of this cluster, as a range into [`ShapedText::characters`](crate::ShapedText::characters).
///
/// This is also the range of character positions in the source text (in the Unicode scalar
/// value sense).
#[inline(always)]
pub fn chars_range(&self) -> Range<u32> {
self.chars_range.0..self.chars_range.1
}
/// The number of glyphs of this cluster.
#[inline(always)]
pub fn glyph_len(self) -> u8 {
if self.has_inline_glyph() {
1
} else {
self.flags.glyph_len()
}
}
/// Whether this cluster's glyph is stored inline in [`Self::glyph_offset`].
///
/// This is only possible if [`Self::glyph_len`] is one, and the glyph has no offset.
/// [`Self::glyph_offset`] then encodes the glyph identifier rather than an index into the glyph
/// array. The glyph's advance then is this cluster's advance.
#[inline(always)]
pub fn has_inline_glyph(self) -> bool {
self.flags.has_inline_glyph()
}
/// Whether this shaped cluster's logical start also starts a grapheme.
#[inline(always)]
pub fn is_grapheme_start(self) -> bool {
self.flags.is_grapheme_start()
}
/// Whether breaking logically before this shaped cluster requires reshaping.
///
/// Note that if this shaped cluster does not start a grapheme (see
/// [`Self::is_grapheme_start`]), you have to reshape regardless of this value.
#[inline(always)]
pub fn is_safe_to_break_before(self) -> bool {
self.flags.is_safe_to_break_before()
}
/// Whether a soft wrap opportunity exists before this cluster's first character.
///
/// This is [`Character::flags`]' soft-wrap bit of the first character of [`Self::chars_range`],
/// cached here so that measuring text does not need to touch the character array.
#[inline(always)]
pub fn is_soft_wrap_opportunity_before(self) -> bool {
self.flags.is_soft_wrap_opportunity_before()
}
/// The [`Whitespace`] class of this cluster's first character.
///
/// See [`Self::is_soft_wrap_opportunity_before`].
#[inline(always)]
pub fn whitespace(self) -> Whitespace {
self.flags.whitespace()
}
/// The number of characters in this cluster.
#[inline(always)]
pub fn char_len(self) -> u32 {
self.chars_range.1 - self.chars_range.0
}
/// The number of graphemes this cluster overlaps.
pub(crate) fn graphemes_overlapped(&self, characters: &[Character]) -> u32 {
let start = self.chars_range().start as usize + 1;
let end = self.chars_range().end as usize;
let mut graphemes = 1;
for character in &characters[start..end] {
graphemes += u32::from(character.grapheme_start);
}
graphemes
}
}
/// Properties of a [`Character`].
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct CharacterFlags(u8);
impl CharacterFlags {
/// Bits 0..2: the UTF-8 length of the source character minus one.
///
/// (Note the UTF-8 length of any character is between 1 and 4 inclusive.)
const LEN_UTF8_MASK: u8 = 0b11;
/// Whether the source character is an emoji.
const EMOJI: u8 = 1 << 2;
/// Whether there is a word boundary before the character.
const WORD_BOUNDARY: u8 = 1 << 3;
/// Whether there is a soft wrap opportunity before the character.
const SOFT_WRAP_OPPORTUNITY: u8 = 1 << 4;
#[inline(always)]
pub fn new(source_char: char, is_word_boundary: bool, is_soft_wrap_opportunity: bool) -> Self {
// TODO: Defer to ICU4X properties (see: https://docs.rs/icu/latest/icu/properties/props/struct.Emoji.html).
let is_emoji = matches!(source_char as u32, 0x1F600..=0x1F64F | 0x1F300..=0x1F5FF | 0x1F680..=0x1F6FF | 0x2600..=0x26FF | 0x2700..=0x27BF);
#[expect(
clippy::cast_possible_truncation,
reason = "`len_utf8` is between 1 and 4 inclusive"
)]
let len_utf8 = source_char.len_utf8() as u8;
Self(
(len_utf8 - 1)
| if is_emoji { Self::EMOJI } else { 0 }
| if is_word_boundary {
Self::WORD_BOUNDARY
} else {
0
}
| if is_soft_wrap_opportunity {
Self::SOFT_WRAP_OPPORTUNITY
} else {
0
},
)
}
/// Whether there is a soft wrap opportunity before this character ([UAX #14][line-breaking]).
///
/// Note mandatory breaks (like `\n`) are encoded as [`Whitespace`].
///
/// [line-breaking]: https://www.unicode.org/reports/tr14/
#[inline(always)]
pub fn is_soft_wrap_opportunity(self) -> bool {
self.0 & Self::SOFT_WRAP_OPPORTUNITY != 0
}
/// Returns if there is a word boundary before the character.
#[inline(always)]
pub fn is_word_boundary(self) -> bool {
self.0 & Self::WORD_BOUNDARY != 0
}
/// Returns if the character is an emoji.
#[inline(always)]
pub fn is_emoji(self) -> bool {
self.0 & Self::EMOJI != 0
}
/// Returns the number of bytes the source character would need if encoded in UTF-8.
///
/// That number of bytes is always between 1 and 4, inclusive.
#[inline(always)]
pub fn len_utf8(self) -> usize {
(self.0 & Self::LEN_UTF8_MASK) as usize + 1
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn character_flags() {
for (ch, len, emoji) in [
('a', 1, false),
(' ', 1, false),
('\t', 1, false),
('\r', 1, false),
('\n', 1, false),
('\u{00e9}', 2, false),
('\u{2028}', 3, false),
('\u{2600}', 3, true),
('\u{1F600}', 4, true),
] {
for (is_word_boundary, is_soft_wrap_opportunity) in
[(false, false), (true, false), (false, true), (true, true)]
{
let flags = CharacterFlags::new(ch, is_word_boundary, is_soft_wrap_opportunity);
assert_eq!(flags.len_utf8(), len, "{ch:?}");
assert_eq!(flags.is_emoji(), emoji, "{ch:?}");
assert_eq!(flags.is_word_boundary(), is_word_boundary, "{ch:?}");
assert_eq!(
flags.is_soft_wrap_opportunity(),
is_soft_wrap_opportunity,
"{ch:?}"
);
}
let character = Character {
text_byte_start: 3,
style_index: 7,
whitespace: Whitespace::from_char(ch),
flags: CharacterFlags::new(ch, false, false),
grapheme_start: true,
};
assert_eq!(character.text_byte_range(), 3..3 + len, "{ch:?}");
}
}
#[test]
fn first_char_flags_round_trip() {
let soft_wraps = [false, true];
let whitespaces = [
Whitespace::None,
Whitespace::Space,
Whitespace::NoBreakSpace,
Whitespace::IdeographicSpace,
Whitespace::OtherSpaceSeparator,
Whitespace::Tab,
Whitespace::Newline,
Whitespace::ControlWhitespace,
];
for soft_wrap in soft_wraps {
for whitespace in whitespaces {
let flags = ShapedClusterFlags::new(3)
.with_grapheme_start(true)
.with_first_char(soft_wrap, whitespace);
assert_eq!(flags.is_soft_wrap_opportunity_before(), soft_wrap);
assert_eq!(flags.whitespace(), whitespace);
assert_eq!(flags.glyph_len(), 3);
assert!(flags.is_grapheme_start());
}
}
}
}
+16
View File
@@ -0,0 +1,16 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Text shaping utilities.
pub(crate) mod atom;
mod cache;
mod cluster;
mod data;
pub(crate) mod shaped_text;
pub(crate) mod shaper;
pub use cluster::{Char, CharCluster, Coverage, SourceRange, Whitespace};
pub use data::{Character, CharacterFlags, ShapedCluster};
pub(crate) use data::ShapedClusterFlags;
+859
View File
@@ -0,0 +1,859 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Data structures to store the result of shaping.
use core::ops::Range;
use alloc::vec::Vec;
use parlance::{BidiLevel, NormalizedCoord};
use skrifa::MetadataProvider;
use crate::{
CharInfo, FontInstance, Glyph,
itemize::{Segment, TextRange},
};
use super::{
Character, CharacterFlags, ShapedCluster, ShapedClusterFlags, Whitespace, atom::ShapedSlice,
shaper::ShapeOptions,
};
/// Metrics that apply to the glyphs of a font.
///
/// These metrics are scaled by the font size.
///
/// The `underline_*` and `strikethrough_*` fields are derived if not set by the font.
///
// TODO: Perhaps it'd be nicer if we exposed unscaled metrics (design units) instead. This currently
// just follows what `parley` used to do in its `RunMetrics`. If we go unscaled, we should then
// either also store units per em, or em-normalize the values like CSS does.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FontMetrics {
/// Distance from the baseline to the top of the alignment box.
pub ascent: f32,
/// Distance from the baseline to the bottom of the alignment box.
pub descent: f32,
/// Recommended additional spacing between lines.
pub leading: f32,
/// Offset of the top of underline decoration from the baseline.
pub underline_offset: f32,
/// Thickness of the underline decoration.
pub underline_size: f32,
/// Offset of the top of strikethrough decoration from the baseline.
pub strikethrough_offset: f32,
/// Thickness of the strikethrough decoration.
pub strikethrough_size: f32,
/// Distance from the baseline to the top of a typical English capital.
pub cap_height: Option<f32>,
/// Distance from the baseline to the top of the lowercase "x" or
/// similar character.
pub x_height: Option<f32>,
}
impl FontMetrics {
/// Metrics to use when no font is available at all.
///
/// These roughly match common Latin fonts, so that a layout without fonts still has plausible
/// line heights.
pub const fn fallback(font_size: f32) -> Self {
Self {
ascent: font_size * 0.8,
descent: font_size * 0.2,
leading: 0.,
underline_offset: 0.,
underline_size: 0.,
strikethrough_offset: 0.,
strikethrough_size: 0.,
cap_height: None,
x_height: None,
}
}
/// Compute the metrics of `font` at `font_size`, positioned at the variable font location
/// given by the `synthesis` and `variations` axis settings.
///
/// Returns `None` if the font data cannot be parsed.
pub fn from_font_instance(
font: &FontInstance,
font_size: f32,
variations: &[parlance::FontVariation],
) -> Option<Self> {
// A style's metrics depend on its font instance, size and variations alone; a style
// table asks for the same few again in every layout (Rune: vendor/parley_engine.patch).
#[cfg(feature = "std")]
{
type Memo = Vec<(u64, u32, fontique::Synthesis, u32, Vec<parlance::FontVariation>, Option<FontMetrics>)>;
std::thread_local! {
static MEMO: core::cell::RefCell<Memo> = const { core::cell::RefCell::new(Vec::new()) };
}
let (id, index, size) = (font.font.data.id(), font.font.index, font_size.to_bits());
let found = MEMO.with_borrow(|memo| {
memo.iter()
.find(|m| m.0 == id && m.1 == index && m.2 == font.synthesis && m.3 == size && m.4 == variations)
.map(|m| m.5)
});
if let Some(metrics) = found {
return metrics;
}
let metrics = Self::compute_from_font_instance(font, font_size, variations);
MEMO.with_borrow_mut(|memo| {
if memo.len() >= 64 {
memo.remove(0);
}
memo.push((id, index, font.synthesis, size, variations.to_vec(), metrics));
});
return metrics;
}
Self::compute_from_font_instance(font, font_size, variations)
}
fn compute_from_font_instance(
font: &FontInstance,
font_size: f32,
variations: &[parlance::FontVariation],
) -> Option<Self> {
let font_ref =
skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).ok()?;
let location = font_ref.axes().location(
font.synthesis
.variation_settings()
.iter()
.map(|(tag, value)| (skrifa::Tag::new(&tag.to_be_bytes()), *value))
.chain(
variations
.iter()
.map(|v| (skrifa::Tag::new(&v.tag.to_bytes()), v.value)),
),
);
Some(Self::from_skrifa_metrics(
&skrifa::metrics::Metrics::new(
&font_ref,
skrifa::prelude::Size::new(font_size),
&location,
),
font_size,
))
}
pub(crate) fn from_skrifa_metrics(metrics: &skrifa::metrics::Metrics, font_size: f32) -> Self {
// Default values from HarfBuzz: https://github.com/harfbuzz/harfbuzz/blob/12ee77ee00514c442bcd28f9aa9d56b708c37382/src/hb-ot-metrics.cc#L355-L372
let fallback_decoration_size = font_size / 18.0;
let (underline_offset, underline_size) = if let Some(underline) = metrics.underline {
(underline.offset, underline.thickness)
} else {
(-fallback_decoration_size, fallback_decoration_size)
};
let (strikethrough_offset, strikethrough_size) = if let Some(strikeout) = metrics.strikeout
{
(strikeout.offset, strikeout.thickness)
} else {
(metrics.ascent / 2.0, fallback_decoration_size)
};
Self {
ascent: metrics.ascent,
descent: -metrics.descent,
leading: metrics.leading,
underline_offset,
underline_size,
strikethrough_offset,
strikethrough_size,
x_height: metrics.x_height,
cap_height: metrics.cap_height,
}
}
}
/// The result of shaping.
///
/// After [analyzing][crate::Analysis] your text, [shape the text][crate::Shaper::shape_text],
/// writing the result into this [`ShapedText`]. This then holds your shaped paragraph of text.
///
/// This shaped text holds spans of the source text's characters that were shaped into
/// [`ShapedCluster`]s. Note that the boundaries of shaped clusters and graphemes need not coincide;
/// see [`ShapedCluster`]s documentation for more information.
///
/// Use [`Self::run_slice`] to get a run's [`ShapedSlice`]. From there, you can interact with slices
/// of shaped text, such as walking [atoms](crate::Atom) (e.g., [`ShapedSlice::atoms_start`]) and
/// [graphemes](crate::Grapheme) (e.g., [`ShapedSlice::graphemes_start`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ShapedText {
runs: Vec<ShapedRun>,
characters: Vec<Character>,
shaped_clusters: Vec<ShapedCluster>,
glyphs: Vec<Glyph>,
fonts: Vec<FontInstance>,
normalized_coords: Vec<NormalizedCoord>,
}
impl ShapedText {
/// Create a reusable [`ShapedText`].
pub fn new() -> Self {
Self::default()
}
/// Reserve capacity for at least `additional_chars` more characters.
///
/// This speculatively reserves capacity for `additional_chars` more clusters and glyphs.
#[inline]
pub(crate) fn reserve(&mut self, additional_chars: usize) {
self.characters.reserve(additional_chars);
self.shaped_clusters.reserve(additional_chars);
self.glyphs.reserve(additional_chars);
}
/// Clear the result while retaining capacity.
#[inline]
pub fn clear(&mut self) {
self.runs.clear();
self.characters.clear();
self.shaped_clusters.clear();
self.glyphs.clear();
self.fonts.clear();
self.normalized_coords.clear();
}
/// Get a [`ShapedSlice`] of the run at `run_index`.
pub fn run_slice(&self, run_index: u32) -> ShapedSlice<'_> {
let run = &self.runs[run_index as usize];
ShapedSlice {
characters: &self.characters,
shaped_clusters: &self.shaped_clusters,
glyphs: &self.glyphs,
clusters: (
run.shaped_clusters_range.start,
run.shaped_clusters_range.end,
),
}
}
/// The shaped runs.
///
/// Each run contains glyphs that can be rendered with a single font.
#[inline(always)]
pub fn runs(&self) -> &[ShapedRun] {
&self.runs
}
/// Escape hatch for `parley` tests that remap style indices to check whether layouts are
/// otherwise identical. This is not for public consumption!
#[doc(hidden)]
#[inline(always)]
pub fn remap_styles(&mut self, remap: &[u16]) {
for character in self.characters.iter_mut() {
character.style_index = remap[character.style_index as usize];
}
for shaped_cluster in self.shaped_clusters.iter_mut() {
shaped_cluster.style_index = remap[shaped_cluster.style_index as usize];
}
}
/// The character data of the text, in logical order.
///
/// [`ShapedRun::characters_range`] indexes into this. The nth [`Character`] corresponds exactly
/// to the nth character of the source text (in the Unicode scalar value sense). This contains
/// every character of the source text unless shaping was aborted due to
/// [`FontSelector::select_font`][crate::FontSelector::select_font] failing to return a font.
#[inline(always)]
pub fn characters(&self) -> &[Character] {
&self.characters
}
/// The shaped clusters.
///
/// [`ShapedRun::shaped_clusters_range`] indexes into this.
#[inline(always)]
pub fn shaped_clusters(&self) -> &[ShapedCluster] {
&self.shaped_clusters
}
/// The shaped glyphs.
///
/// [`ShapedRun::glyphs_range`] indexes into this.
#[inline(always)]
pub fn glyphs(&self) -> &[Glyph] {
&self.glyphs
}
/// The fonts.
///
/// [`ShapedRun::font_index`] indexes into this.
#[inline(always)]
pub fn fonts(&self) -> &[FontInstance] {
&self.fonts
}
/// The normalized font coordinates used by runs in this shaped text.
///
/// [`ShapedRun::normalized_coords_range`] splits this into per-run slices.
#[inline(always)]
pub fn normalized_coords(&self) -> &[NormalizedCoord] {
&self.normalized_coords
}
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
pub(crate) fn push_run(
&mut self,
text: &str,
range: TextRange,
segment: &Segment,
options: &ShapeOptions<'_>,
char_info: &[CharInfo],
char_style_indices: &[u16],
font: &FontInstance,
glyph_infos: &[harfrust::GlyphInfo],
glyph_positions: &[harfrust::GlyphPosition],
normalized_coords: &[harfrust::NormalizedCoord],
(font_metrics, units_per_em): (FontMetrics, f32),
) {
debug_assert_eq!(
range.char_range.len(),
text[range.byte_range.clone()].chars().count(),
"The claimed character range and the text's covered byte range should agree"
);
let normalized_coords_range = {
let start = self.normalized_coords.len();
self.normalized_coords.extend(
normalized_coords
.iter()
.map(|c| NormalizedCoord::from_bits(c.to_bits())),
);
start..self.normalized_coords.len()
};
let font_index = self
.fonts
.iter()
.position(|f| f == font)
.unwrap_or_else(|| {
let index = self.fonts.len();
self.fonts.push(font.clone());
index
});
// `HarfRust` returns glyphs in visual order, so we need to process them as such while
// maintaining logical ordering of clusters.
let scale_factor = options.font_size / units_per_em;
let shaped_clusters_start = self.shaped_clusters.len();
// Push all characters.
let characters_start = self.characters.len();
for (((byte_offset, ch), info), style_index) in text[range.byte_range.clone()]
.char_indices()
.zip(&char_info[range.char_range.clone()])
.zip(&char_style_indices[range.char_range.clone()])
{
self.characters.push(Character {
text_byte_start: (range.byte_range.start + byte_offset) as u32,
style_index: *style_index,
whitespace: Whitespace::from_char(ch),
flags: CharacterFlags::new(
ch,
info.is_word_boundary(),
info.is_soft_wrap_opportunity(),
),
grapheme_start: info.is_grapheme_start(),
});
}
// TODO: we force a grapheme break at the start of the run, as itemization could have split
// a grapheme into two. Ideally, grapheme segmentation should be performed after
// itemization, at which case this will always be true.
self.characters[characters_start].grapheme_start = true;
let glyphs_start = self.glyphs.len();
if segment.bidi_level.is_ltr() {
process_shaped_clusters(
&mut self.shaped_clusters,
&mut self.glyphs,
scale_factor,
glyph_infos.iter(),
glyph_positions.iter(),
&self.characters,
characters_start,
);
} else {
process_shaped_clusters(
&mut self.shaped_clusters,
&mut self.glyphs,
scale_factor,
glyph_infos.iter().rev(),
glyph_positions.iter().rev(),
&self.characters,
characters_start,
);
// Reverse each cluster's glyphs, such that they are in paint order.
//
// TODO: could this become a single `reverse` over the range?
for cluster in &self.shaped_clusters[shaped_clusters_start..] {
if !cluster.has_inline_glyph() && cluster.glyph_len() > 1 {
let start = cluster.glyph_offset as usize;
self.glyphs[start..start + cluster.glyph_len() as usize].reverse();
}
}
}
let shaped_clusters_range = shaped_clusters_start as u32..self.shaped_clusters.len() as u32;
let run_advance = self.shaped_clusters[shaped_clusters_start..]
.iter()
.map(|cluster| cluster.advance)
.sum();
self.runs.push(ShapedRun {
range,
font_size: options.font_size,
font_index,
characters_range: characters_start as u32..self.characters.len() as u32,
shaped_clusters_range,
glyphs_range: glyphs_start..self.glyphs.len(),
normalized_coords_range,
bidi_level: segment.bidi_level,
advance: run_advance,
font_metrics,
});
}
}
/// One shaped run, belonging to a [`ShapedText`].
#[derive(Clone, Debug, PartialEq)]
pub struct ShapedRun {
/// The range of text this run corresponds to.
pub range: TextRange,
/// Font size.
pub font_size: f32,
/// This run's font, as an index into [`ShapedText::fonts`].
//
// Note: We carry the font index instead of having `ShapedRun` carry `Arc<FontInstance>`,
// meaning `ShapedRun` could become `Copy` once we have access to `core::range::Range`.
pub font_index: usize,
/// This run's characters, as a range into [`ShapedText::characters`].
pub characters_range: Range<u32>,
/// This run's shaped clusters, as a range into [`ShapedText::shaped_clusters`].
pub shaped_clusters_range: Range<u32>,
/// This run's glyphs, as a range into [`ShapedText::glyphs`].
pub glyphs_range: Range<usize>,
/// The normalized variation coords of this run, as a range into [`ShapedText::normalized_coords`].
pub normalized_coords_range: Range<usize>,
/// The bidi level of the run.
pub bidi_level: BidiLevel,
/// Total advance of the run.
pub advance: f32,
/// The font metrics of this run.
pub font_metrics: FontMetrics,
}
/// Processes shaped glyphs from `HarfRust` and converts them into `ShapedCluster` and `Glyph`.
///
/// # Parameters
///
/// ## Output Parameters (mutated by this function):
/// * `shaped_clusters` - Vector where new `ShapedCluster` entries will be pushed.
/// * `glyphs` - Vector where new `Glyph` entries will be pushed. Note: single-glyph clusters
/// with zero offsets are inlined directly into `ShapedCluster`.
///
/// ## Input Parameters:
/// * `scale_factor` - Scaling factor used to convert font units to the target size.
/// * `glyph_infos` - `HarfRust` glyph information in logical order (i.e., reversed for RTL runs).
/// * `glyph_positions` - `HarfRust` glyph positioning data in logical order (i.e., reversed for RTL
/// runs).
/// * `characters` must contain the shaped characters whose clusters we're now processing, starting at
/// index `characters_start`.
/// * `characters_start` - See `characters`.
fn process_shaped_clusters<'a>(
shaped_clusters: &mut Vec<ShapedCluster>,
glyphs: &mut Vec<Glyph>,
scale_factor: f32,
glyph_infos: impl Iterator<Item = &'a harfrust::GlyphInfo>,
glyph_positions: impl Iterator<Item = &'a harfrust::GlyphPosition>,
characters: &[Character],
characters_start: usize,
) {
struct Cluster {
id: u32,
characters_start: usize,
glyphs_start: usize,
glyphs: u32,
inline_glyph: Option<Glyph>,
advance: f32,
}
/// Flush `cluster`, whose characters end at `char_end`, onto `shaped_clusters`.
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
fn flush(
cluster: &mut Cluster,
char_end: usize,
characters: &[Character],
shaped_clusters: &mut Vec<ShapedCluster>,
) {
let first_character = &characters[cluster.characters_start];
let is_newline = first_character.whitespace == Whitespace::Newline;
let (glyph_offset, glyph_len, inline_glyph, advance) = if is_newline {
// Elide glyphs of newlines.
(cluster.glyphs_start as u32, 0, false, 0.)
} else if let Some(inline_glyph) = cluster.inline_glyph.take() {
(inline_glyph.id, 1, true, cluster.advance)
} else {
(
cluster.glyphs_start as u32,
cluster.glyphs as u8,
false,
cluster.advance,
)
};
shaped_clusters.push(ShapedCluster {
chars_range: (cluster.characters_start as u32, char_end as u32),
style_index: first_character.style_index,
flags: ShapedClusterFlags::new(glyph_len)
.with_grapheme_start(first_character.grapheme_start)
// TODO: fill with actual shaping data (`parley` currently just ignores this)
.with_safe_to_break_before(false)
.with_inline_glyph(inline_glyph)
.with_first_char(
first_character.flags.is_soft_wrap_opportunity(),
first_character.whitespace,
),
glyph_offset,
advance,
});
}
let mut cluster = Cluster {
id: 0,
characters_start,
glyphs_start: glyphs.len(),
glyphs: 0,
inline_glyph: None,
advance: 0.,
};
for (glyph_info, glyph_pos) in glyph_infos.zip(glyph_positions) {
if glyph_info.cluster != cluster.id {
let char_end = characters_start + glyph_info.cluster as usize;
flush(&mut cluster, char_end, characters, shaped_clusters);
cluster = Cluster {
id: glyph_info.cluster,
characters_start: char_end,
glyphs_start: glyphs.len(),
glyphs: 0,
inline_glyph: None,
advance: 0.,
};
}
let glyph = Glyph {
id: glyph_info.glyph_id,
x: (glyph_pos.x_offset as f32) * scale_factor,
// Convert from font space (Y-up) to layout space (Y-down)
y: -(glyph_pos.y_offset as f32) * scale_factor,
advance: (glyph_pos.x_advance as f32) * scale_factor,
};
if cluster.glyphs == 0 && glyph.x == 0. && glyph.y == 0. {
// Defer this potential zero-offset, single glyph cluster
cluster.inline_glyph = Some(glyph);
} else {
if let Some(pending_glyph) = cluster.inline_glyph.take() {
glyphs.push(pending_glyph);
}
glyphs.push(glyph);
}
cluster.advance += glyph.advance;
cluster.glyphs += 1;
}
// Flush the final cluster.
flush(&mut cluster, characters.len(), characters, shaped_clusters);
}
#[cfg(test)]
mod tests {
use alloc::{sync::Arc, vec, vec::Vec};
use fontique::Synthesis;
use linebender_resource_handle::{Blob, FontData};
use crate::{
Analysis, AnalysisOptions, Analyzer, FontInstance, FontInstanceRef, FontSelector,
ShapeOptions, Shaper,
itemize::{Item, Segment},
shape::CharCluster,
};
use super::ShapedText;
const ROBOTO: &[u8] =
include_bytes!("../../../parley_dev/assets/fonts/roboto_fonts/Roboto-Regular.ttf");
const NOTO_KUFI_ARABIC: &[u8] =
include_bytes!("../../../parley_dev/assets/fonts/noto_fonts/NotoKufiArabic-Regular.otf");
const NOTO_COLOR_EMOJI: &[u8] = include_bytes!(
"../../../parley_dev/assets/fonts/noto_color_emoji/NotoColorEmoji-Subset.ttf"
);
/// A [`FontSelector`] shaping everything with a single font.
struct SingleFont(FontInstance);
impl FontSelector for SingleFont {
fn select_font(
&mut self,
_item: &Segment,
_options: &ShapeOptions<'_>,
_cluster: &mut CharCluster,
) -> Option<FontInstanceRef<'_>> {
Some(self.0.as_ref())
}
}
/// A [`FontSelector`] shaping clusters starting with a particular character with one font, and
/// all other clusters with another, to split the text into runs at that character.
struct FontForChar {
ch: char,
font: FontInstance,
other_font: FontInstance,
}
impl FontSelector for FontForChar {
fn select_font(
&mut self,
_segment: &Segment,
_options: &ShapeOptions<'_>,
cluster: &mut CharCluster,
) -> Option<FontInstanceRef<'_>> {
if cluster.chars()[0].ch == self.ch {
Some(self.font.as_ref())
} else {
Some(self.other_font.as_ref())
}
}
}
fn analyze(text: &str) -> Analysis {
let mut analysis = Analysis::new();
Analyzer::new().analyze(
text,
&AnalysisOptions {
line_break: &[],
line_break_override: None,
..AnalysisOptions::default()
},
&mut analysis,
);
analysis
}
fn font_instance(font_data: &'static [u8]) -> FontInstance {
FontInstance {
font: FontData::new(Blob::new(Arc::new(font_data)), 0),
synthesis: Synthesis::default(),
}
}
fn shape_with_font(text: &str, font_data: &'static [u8]) -> ShapedText {
shape_with_font_selector(text, SingleFont(font_instance(font_data)))
}
fn shape_with_font_selector(text: &str, select_font: impl FontSelector) -> ShapedText {
let analysis = analyze(text);
let mut shaper = Shaper::default();
let mut shaped = ShapedText::new();
let char_style_indices = vec![0; text.chars().count()];
let items = [Item {
char_end: text.chars().count().try_into().unwrap(),
options: ShapeOptions {
font_size: 32.0,
language: None,
features: &[],
variations: &[],
},
}];
shaper.shape_text(
text,
&analysis,
&char_style_indices,
items,
select_font,
&mut shaped,
);
shaped
}
/// A run can shape into no glyphs at all: `HarfRust` normally shapes `default-ignorable`
/// characters (like a soft-hyphen) into a space glyph with zero advance, but if the space glyph
/// is not available, it just deletes the character.
///
/// This checks whether we handle that.
#[test]
fn run_without_glyphs_is_kept() {
// The soft hyphen is `default-ignorable`, and is a grapheme of its own, so font selection
// gives it a run of its own.
let shaped = shape_with_font_selector(
"a\u{00AD}b",
FontForChar {
ch: '\u{00AD}',
// Our Noto Color Emoji subset has no space character.
font: font_instance(NOTO_COLOR_EMOJI),
other_font: font_instance(ROBOTO),
},
);
assert_eq!(
shaped.characters().iter().count(),
3,
"the characters of a run without glyphs are shaped"
);
let [a, soft_hyphen, b] = shaped.runs() else {
panic!("expected three runs, got {}", shaped.runs().len());
};
assert_eq!(a.characters_range, 0..1);
assert_eq!(soft_hyphen.characters_range, 1..2);
assert_eq!(b.characters_range, 2..3);
assert!(soft_hyphen.glyphs_range.is_empty());
assert_eq!(soft_hyphen.advance, 0.);
// The soft-hyphen's run should have a single cluster, and it must be without glyphs.
let clusters = shaped.run_slice(1).shaped_clusters();
assert_eq!(clusters.len(), 1);
assert_eq!(clusters[0].glyph_len(), 0);
assert_eq!(clusters[0].chars_range(), 1..2);
}
#[test]
fn single_cluster_run_advance_matches_its_cluster() {
let shaped = shape_with_font("A", ROBOTO);
let run = &shaped.runs()[0];
let cluster = &shaped.shaped_clusters()[run.shaped_clusters_range.start as usize];
assert!(cluster.advance > 0.0);
assert_eq!(run.advance, cluster.advance);
}
/// [U+0600 U+0623 U+064F] is a single grapheme in text-wide segmentation, but U+0600 has
/// bidi class AN while the following characters resolve to a different bidi level, so
/// itemization splits the grapheme into the items [U+0600] [U+0623 U+064F]. The item
/// boundary forces a grapheme start on U+0623.
#[test]
fn one_grapheme_split_across_items() {
let shaped = shape_with_font("\u{0600}\u{0623}\u{064F}", NOTO_KUFI_ARABIC);
let grapheme_starts: Vec<bool> =
shaped.characters.iter().map(|c| c.grapheme_start).collect();
assert_eq!(grapheme_starts, [true, true, false]);
let clusters: Vec<(u32, u32, bool)> = shaped
.shaped_clusters
.iter()
.map(|c| {
(
c.chars_range().start,
c.chars_range().end,
c.is_grapheme_start(),
)
})
.collect();
assert_eq!(clusters, [(0, 1, true), (1, 3, true)]);
}
/// "ffi" is three graphemes but shapes into one cluster.
#[test]
fn three_graphemes_one_cluster() {
let shaped = shape_with_font("ffi", ROBOTO);
let grapheme_starts: Vec<bool> =
shaped.characters.iter().map(|c| c.grapheme_start).collect();
assert_eq!(grapheme_starts, [true, true, true]);
let clusters: Vec<(u32, u32, bool)> = shaped
.shaped_clusters
.iter()
.map(|c| {
(
c.chars_range().start,
c.chars_range().end,
c.is_grapheme_start(),
)
})
.collect();
assert_eq!(clusters, [(0, 3, true)]);
}
#[test]
fn newlines_removed() {
for newline in ["\n", "\r", "\u{2028}", "\u{2029}"] {
let shaped = shape_with_font(&alloc::format!("a{newline}b"), ROBOTO);
let index = shaped
.shaped_clusters
.iter()
.position(|cluster| cluster.chars_range().start == 1)
.unwrap();
let newline_cluster = &shaped.shaped_clusters[index];
assert_eq!(newline_cluster.glyph_len(), 0, "newline glyphs are removed");
assert_eq!(newline_cluster.advance, 0., "newline advance is set to 0");
}
}
/// An itemization boundary forces a cluster break in shaping, and must force a grapheme start.
#[test]
fn item_boundaries_force_grapheme_start() {
// Two regional indicators forming a single flag grapheme...
let text = "\u{1F1E6}\u{1F1E7}";
let char_style_indices = vec![0; text.chars().count()];
let analysis = analyze(text);
assert_eq!(
analysis
.char_info()
.iter()
.map(|info| info.is_grapheme_start())
.collect::<Vec<_>>(),
[true, false]
);
let font = font_instance(ROBOTO);
let mut shaper = Shaper::default();
let mut shaped = ShapedText::new();
// ...split over two items.
let items = [
Item {
char_end: 1,
options: ShapeOptions {
font_size: 32.0,
language: None,
features: &[],
variations: &[],
},
},
Item {
char_end: text.chars().count().try_into().unwrap(),
options: ShapeOptions {
font_size: 32.0,
language: None,
features: &[],
variations: &[],
},
},
];
shaper.shape_text(
text,
&analysis,
&char_style_indices,
items,
SingleFont(font),
&mut shaped,
);
let grapheme_starts: Vec<bool> =
shaped.characters.iter().map(|c| c.grapheme_start).collect();
assert_eq!(grapheme_starts, [true, true]);
// But note that, had we had three regional indicator symbols, like `[R0 R1 R2]` itemized as
// `[R0] [R1 R2]`, the last pair should form a single grapheme. We don't do that currently.
}
}
+605
View File
@@ -0,0 +1,605 @@
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Shaping of text.
use alloc::vec::Vec;
use core::mem;
use harfrust::ShapeOptions as HarfShapeOptions;
use linebender_resource_handle::{Blob, FontData};
use parlance::{FontFeature, FontVariation, Language};
use crate::shape::shaped_text::FontMetrics;
use crate::{
Analysis, CharInfo, ShapedText,
itemize::{Item, Segment, TextRange},
lru_cache::LruCache,
shape::{CharCluster, cache},
};
/// Shaping options for one item.
///
/// These are styling options relevant for shaping. They're styling, in that they're not derived
/// from the underlying text. When you [shape the text][`Shaper::shape_text`], you should split the
/// text into [`Item`]s at the points where these options change.
#[derive(Debug)]
pub struct ShapeOptions<'a> {
/// The font size to shape the item with.
pub font_size: f32,
/// The language to shape the item with.
pub language: Option<Language>,
/// The font features to shape the item with.
///
/// If there are font features with duplicate [tags][`FontFeature::tag`], later values override
/// earlier values.
pub features: &'a [FontFeature],
/// The font variations that are constant over an item.
pub variations: &'a [FontVariation],
}
/// The font instance to shape an item with.
#[derive(Clone, Debug, PartialEq)]
pub struct FontInstance {
/// The font.
pub font: FontData,
/// Font synthesis suggestions.
// TODO: Synthesis carries more than we need, and ties us to `fontique`. We can likely change
// this to opaque user data.
pub synthesis: fontique::Synthesis,
}
impl FontInstance {
/// Borrow this font instance.
#[inline]
pub fn as_ref(&self) -> FontInstanceRef<'_> {
FontInstanceRef {
data: &self.font.data,
index: self.font.index,
synthesis: &self.synthesis,
}
}
}
/// A borrowed [`FontInstance`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FontInstanceRef<'a> {
/// Blob containing the content of the font file.
pub data: &'a Blob<u8>,
/// Index of the font in a collection, or 0 for a single font.
pub index: u32,
/// Font synthesis suggestions.
pub synthesis: &'a fontique::Synthesis,
}
impl From<FontInstanceRef<'_>> for FontInstance {
#[inline]
fn from(font: FontInstanceRef<'_>) -> Self {
Self {
font: FontData {
data: font.data.clone(),
index: font.index,
},
synthesis: *font.synthesis,
}
}
}
/// Reusable scratch to shape text using [`Self::shape_text`].
pub struct Shaper {
shape_data_cache: LruCache<cache::ShapeDataKey, harfrust::ShaperData>,
shape_instance_cache: LruCache<cache::ShapeInstanceId, harfrust::ShaperInstance>,
shape_plan_cache: LruCache<cache::ShapePlanId, harfrust::ShapePlan>,
/// Each run's font metrics and units per em (Rune: vendor/parley_engine.patch).
run_metrics_cache: LruCache<cache::RunMetricsId, (FontMetrics, f32)>,
unicode_buffer: Option<harfrust::UnicodeBuffer>,
features: Vec<harfrust::Feature>,
char_cluster: CharCluster,
}
impl Default for Shaper {
fn default() -> Self {
const MAX_ENTRIES: usize = 16;
Self {
shape_data_cache: LruCache::new(MAX_ENTRIES),
shape_instance_cache: LruCache::new(MAX_ENTRIES),
shape_plan_cache: LruCache::new(MAX_ENTRIES),
run_metrics_cache: LruCache::new(MAX_ENTRIES),
unicode_buffer: Some(harfrust::UnicodeBuffer::new()),
features: Vec::new(),
char_cluster: CharCluster::default(),
}
}
}
impl core::fmt::Debug for Shaper {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Shaper").finish_non_exhaustive()
}
}
impl Shaper {
/// Shape text into glyphs, overwriting `shaped_text`.
///
/// The `text` passed in must be the same as used for producing `analysis`.
///
/// This uses the items returned by `items`, and further itemizes the text into
/// individually-shapeable segments of constant bidi level and script. `items` should be used to
/// split on properties like shaping-relevant style changes (e.g., font size) or properties like
/// language.
///
/// `char_style_indices` holds per-character style indices; these are copied onto
/// [`Character`][super::Character`] and [`ShapedCluster`][super::ShapedCluster]. A shaped
/// cluster's style index is that of its logically first constituent character.
///
/// Characters that don't have a particular script have their script resolved based on
/// surrounding context (see [`Segment::script`]).
///
/// Each segment is then broken into runs of maximal sequences of character clusters for which
/// `select_font` returns the same font.
///
/// # Panics
///
/// Panics if `items` does not cover the entire source text, or the font returned by
/// `select_font` is malformed.
pub fn shape_text<'options>(
&mut self,
text: &str,
analysis: &Analysis,
// TODO: rename to something like `user_data` (s.t. we don't assume it's a style per se).
char_style_indices: &[u16],
items: impl IntoIterator<Item = Item<'options>>,
mut select_font: impl FontSelector,
shaped_text: &mut ShapedText,
) {
shaped_text.clear();
shaped_text.reserve(text.len());
let char_count = analysis.char_info().len();
debug_assert_eq!(
char_style_indices.len(),
char_count,
"The number of character style indices must be equal to the character count"
);
let mut previous_item_end = 0;
let mut itemizer = analysis.itemize(text);
for item in items {
assert!(
item.char_end > previous_item_end,
"item ends must be strictly increasing"
);
assert!(
item.char_end as usize <= char_count,
"items must not span past the text"
);
loop {
let segment = itemizer
.next(
#[inline(always)]
|text_range| text_range.char_range.end == item.char_end as usize,
)
.expect("A segment must be yielded, given items tile the full text exactly");
if shape_segment(
self,
text,
&segment,
&item.options,
&mut select_font,
analysis.char_info(),
char_style_indices,
shaped_text,
)
.is_err()
{
// Abort on error. This happens iff `FontSelector::select_font` failed to return a
// font. By aborting we ensure `ShapedText` covers the source text contiguously (as
// we need a font to construct `ShapedRun`).
return;
};
debug_assert!(
segment.range.char_range.end <= item.char_end as usize,
"Segments must not span past the item."
);
if segment.range.char_range.end == item.char_end as usize {
break;
}
}
previous_item_end = item.char_end;
}
assert_eq!(
previous_item_end as usize, char_count,
"`items` does not cover the entire source text"
);
debug_assert_eq!(
shaped_text.characters().len(),
char_count,
"All characters must have been processed"
);
}
}
/// Shape one segment.
///
/// Returns `Err(())` if shaping should be aborted, which happens iff [`FontSelector::select_font`]
/// returned `None`.
fn shape_segment(
scx: &mut Shaper,
text: &str,
segment: &Segment,
options: &ShapeOptions<'_>,
select_font: &mut impl FontSelector,
char_info: &[CharInfo],
char_style_indices: &[u16],
shaped_text: &mut ShapedText,
) -> Result<(), ()> {
select_font.begin_segment(segment, options);
let text_range = &segment.range.byte_range;
let char_range = &segment.range.char_range;
let segment_text = &text[text_range.clone()];
// Only process current segment
let segment_char_info = &char_info[char_range.start..char_range.end];
let segment_char_style_indices = &char_style_indices[char_range.start..char_range.end];
if segment_text.is_empty() {
return Ok(()); // No clusters
}
let char_cluster = &mut scx.char_cluster;
// Shaping inputs that are constant over the segment.
let direction = if segment.bidi_level.is_rtl() {
harfrust::Direction::RightToLeft
} else {
harfrust::Direction::LeftToRight
};
let hb_script = script_to_harfrust(segment.script);
let language = options
.language
.as_ref()
.and_then(|lang| lang.as_str().parse::<harfrust::Language>().ok());
scx.features.clear();
scx.features.extend(options.features.iter().map(|feature| {
harfrust::Feature::new(
harfrust::Tag::new(&feature.tag.to_bytes()),
feature.value as u32,
..,
)
}));
// Shape a run of the segment with a single font, appending it to `shaped_text`.
let mut shape_run = |font: &FontInstance, range: TextRange| {
// The platform's face: its host measures the run and draws it (`platform`).
if let Some(platform) = crate::platform::shaper(font.font.data.id()) {
shape_platform_run(platform, text, range, segment, options, char_info, char_style_indices, font, shaped_text);
return;
}
// TODO: How do we want to handle errors like this?
let font_ref =
harfrust::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
// Create harfrust shaper
let shaper_data = scx.shape_data_cache.entry(
cache::ShapeDataKey::new(font.font.data.id(), font.font.index),
|| harfrust::ShaperData::new(&font_ref),
);
let instance = scx.shape_instance_cache.entry(
cache::ShapeInstanceKey::new(
font.font.data.id(),
font.font.index,
&font.synthesis,
Some(options.variations),
),
|| {
harfrust::ShaperInstance::from_variations(
&font_ref,
variations_iter(&font.synthesis, options.variations),
)
},
);
let harf_shaper = shaper_data
.shaper(&font_ref)
.instance(Some(instance))
.build();
let shaper_plan = scx.shape_plan_cache.entry(
cache::ShapePlanKey::new(
font.font.data.id(),
font.font.index,
&font.synthesis,
direction,
hb_script,
language.clone(),
&scx.features,
Some(options.variations),
),
|| {
harfrust::ShapePlan::new(
&harf_shaper,
direction,
Some(hb_script),
language.as_ref(),
&scx.features,
)
},
);
// Prepare harfrust buffer
let mut buffer = mem::take(&mut scx.unicode_buffer).unwrap();
buffer.clear();
buffer.set_cluster_level(harfrust::BufferClusterLevel::MonotoneCharacters);
// Use the entire run text including newlines.
let run_text = &text[range.byte_range.clone()];
buffer.reserve(run_text.len());
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
for (i, ch) in run_text.chars().enumerate() {
// Ensure that each cluster's index matches the index into `infos`. This is required
// for efficient cluster lookup within `data.rs`.
//
// In other words, instead of using `buffer.push_str`, which iterates `run_text`
// with `char_indices`, push each char individually via `.chars` with a cluster index
// that matches its `infos` counterpart. This allows us to lookup `infos` via cluster
// index in `data.rs`.
buffer.add(ch, i as u32);
}
buffer.set_pre_context(&text[..range.byte_range.start]);
buffer.set_post_context(&text[range.byte_range.end..]);
buffer.set_direction(direction);
buffer.set_script(hb_script);
if let Some(lang) = &language {
buffer.set_language(lang.clone());
}
let glyph_buffer = harf_shaper.shape(
buffer,
HarfShapeOptions::new()
.plan(Some(shaper_plan))
.features(&scx.features)
.point_size(Some(options.font_size)),
);
// A run's metrics depend on its font instance and size alone: made once for each.
let metrics = *scx.run_metrics_cache.entry(
cache::RunMetricsKey::new(
cache::ShapeInstanceKey::new(
font.font.data.id(),
font.font.index,
&font.synthesis,
Some(options.variations),
),
options.font_size,
),
|| {
let font_ref =
skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
let metrics = skrifa::metrics::Metrics::new(
&font_ref,
skrifa::prelude::Size::new(options.font_size),
harf_shaper.coords(),
);
(
FontMetrics::from_skrifa_metrics(&metrics, options.font_size),
metrics.units_per_em as f32,
)
},
);
shaped_text.push_run(
text,
range,
segment,
options,
char_info,
char_style_indices,
font,
glyph_buffer.glyph_infos(),
glyph_buffer.glyph_positions(),
harf_shaper.coords(),
metrics,
);
// Replace buffer to reuse allocation in the next run.
scx.unicode_buffer = Some(glyph_buffer.clear());
};
// This is the run being accumulated, i.e., consecutive graphemes for which `select_font`
// returns the same font.
let mut run: Option<(FontInstance, TextRange)> = None;
// The segment's characters with their analysis data and style indices.
let mut chars = segment_text
.chars()
.zip(segment_char_info)
.zip(segment_char_style_indices)
.map(|((ch, &info), &style_index)| (ch, info, style_index));
// The lengths of the segment's graphemes in characters.
let grapheme_lengths = segment_char_info
.chunk_by(|_, info| !info.is_grapheme_start())
.map(<[_]>::len);
// The end of the previous grapheme.
let mut byte_end = text_range.start;
let mut char_end = char_range.start;
for grapheme_length in grapheme_lengths {
let (byte_start, char_start) = (byte_end, char_end);
char_cluster.fill(chars.by_ref().take(grapheme_length), &mut byte_end);
char_end += grapheme_length;
let grapheme = TextRange {
byte_range: byte_start..byte_end,
char_range: char_start..char_end,
};
let font = select_font
.select_font(segment, options, char_cluster)
.ok_or(())?;
if let Some((run_font, run_range)) = &mut run
&& run_font.as_ref() == font
{
run_range.byte_range.end = byte_end;
run_range.char_range.end = char_end;
} else {
if let Some((run_font, run_range)) = run.take() {
// The font changed: shape the previous run.
shape_run(&run_font, run_range);
}
run = Some((font.into(), grapheme));
}
}
if let Some((run_font, run_range)) = run {
shape_run(&run_font, run_range);
}
Ok(())
}
#[inline]
fn variations_iter<'a>(
synthesis: &'a fontique::Synthesis,
item: &'a [FontVariation],
) -> impl Iterator<Item = harfrust::Variation> + 'a {
synthesis
.variation_settings()
.iter()
.map(|(tag, value)| harfrust::Variation {
tag: *tag,
value: *value,
})
.chain(item.iter().map(|variation| harfrust::Variation {
tag: harfrust::Tag::new(&variation.tag.to_bytes()),
value: variation.value,
}))
}
/// A run in the platform's face (`platform`), appended to `shaped_text`: its host gives a glyph
/// per grapheme, with units it draws whole between the run's break opportunities.
#[expect(clippy::too_many_arguments, reason = "the shape_run closure's inputs")]
fn shape_platform_run(
shaper: crate::platform::PlatformShaper,
text: &str,
range: TextRange,
segment: &Segment,
options: &ShapeOptions<'_>,
char_info: &[CharInfo],
char_style_indices: &[u16],
font: &FontInstance,
shaped_text: &mut ShapedText,
) {
let run_text = &text[range.byte_range.clone()];
let (mut graphemes, mut units, mut clusters) = (Vec::new(), Vec::new(), Vec::new());
let mut after_newline = false;
for (i, ((at, ch), info)) in run_text.char_indices().zip(&char_info[range.char_range.clone()]).enumerate() {
let newline = matches!(ch, '\n' | '\r' | '\u{0B}' | '\u{0C}' | '\u{85}' | '\u{2028}' | '\u{2029}');
let grapheme = i == 0 || info.is_grapheme_start() || newline || after_newline;
if grapheme {
#[expect(clippy::cast_possible_truncation, reason = "a run is under 4 GiB")]
{
if i == 0 || info.is_soft_wrap_opportunity() || newline || after_newline {
units.push(at as u32);
}
graphemes.push(at as u32);
clusters.push(i as u32);
}
}
after_newline = newline;
}
let wght = harfrust::Tag::new(b"wght");
let weight = variations_iter(&font.synthesis, options.variations)
.filter(|v| v.tag == wght)
.last()
.map_or(if font.synthesis.embolden() { 700. } else { 400. }, |v| v.value);
let rtl = segment.bidi_level.is_rtl();
let mut glyphs = Vec::with_capacity(graphemes.len());
shaper(
&crate::platform::PlatformText {
text: run_text,
graphemes: &graphemes,
units: &units,
size: options.font_size,
weight,
italic: font.synthesis.skew().is_some(),
rtl,
language: options.language.as_ref().map(|l| l.as_str()),
},
&mut glyphs,
);
glyphs.resize(graphemes.len(), crate::platform::PlatformGlyph::default());
let font_ref = skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
let metrics = skrifa::metrics::Metrics::new(
&font_ref,
skrifa::prelude::Size::new(options.font_size),
skrifa::instance::LocationRef::default(),
);
let upem = metrics.units_per_em as f32;
let units_of = |px: f32| (px * upem / options.font_size.max(1e-3)).round() as i32;
let mut infos: Vec<harfrust::GlyphInfo> = Vec::with_capacity(glyphs.len());
let mut positions: Vec<harfrust::GlyphPosition> = Vec::with_capacity(glyphs.len());
for (glyph, &cluster) in glyphs.iter().zip(&clusters) {
let mut info = harfrust::GlyphInfo::default();
info.glyph_id = glyph.id;
info.cluster = cluster;
infos.push(info);
let mut position = harfrust::GlyphPosition::default();
position.x_advance = units_of(glyph.advance);
position.x_offset = units_of(glyph.x_offset);
positions.push(position);
}
// In visual order, as HarfRust gives them.
if rtl {
infos.reverse();
positions.reverse();
}
shaped_text.push_run(
text,
range,
segment,
options,
char_info,
char_style_indices,
font,
&infos,
&positions,
&[],
(FontMetrics::from_skrifa_metrics(&metrics, options.font_size), upem),
);
}
pub(crate) fn script_to_harfrust(script: fontique::Script) -> harfrust::Script {
harfrust::Script::from_iso15924_tag(harfrust::Tag::new(&script.to_bytes()))
.unwrap_or(harfrust::script::UNKNOWN)
}
/// Implements font selection for shaping.
pub trait FontSelector {
/// Called when a new segment starts.
///
/// This can be useful to inspect, e.g., the segment's script.
fn begin_segment(&mut self, segment: &Segment, options: &ShapeOptions<'_>) {
let _ = (segment, options);
}
/// Called once per character cluster within the current segment.
///
/// A character cluster will usually be a grapheme, though if text direction or script changes
/// mid-grapheme, it will be split over segments.
///
/// Shaping is aborted if this returns `None`; [`ShapedText`] then contains a partial result.
fn select_font(
&mut self,
segment: &Segment,
options: &ShapeOptions<'_>,
cluster: &mut CharCluster,
) -> Option<FontInstanceRef<'_>>;
}