diff --git a/crates/font-catalog/src/lib.rs b/crates/font-catalog/src/lib.rs index 043667ee4..21b51ba1a 100644 --- a/crates/font-catalog/src/lib.rs +++ b/crates/font-catalog/src/lib.rs @@ -27,6 +27,7 @@ mod fontconfig; mod outline; mod registry; mod scan; +mod segments; mod shape; mod suitcase; pub mod system; @@ -37,6 +38,7 @@ pub use fallback::{cluster_face, drawable_characters}; pub use fontconfig::fontconfig_dirs; pub use outline::{FontOutline, GlyphPen, OutlineError}; pub use scan::{FaceInfo, LocalizedName, Source, is_font_file, style_italic, style_weight, style_width}; +pub use segments::SegmentBoundary; pub use shape::{RunGlyph, RunInput, ShapeRunError, shape_run}; #[cfg(test)] diff --git a/crates/font-catalog/src/segments.rs b/crates/font-catalog/src/segments.rs new file mode 100644 index 000000000..e36a05144 --- /dev/null +++ b/crates/font-catalog/src/segments.rs @@ -0,0 +1,55 @@ +//! Boundaries between runs that need separate shaping. + +/// Tracks the properties of the current shaping segment while walking grapheme clusters. +/// The caller resolves font faces, bidi levels and script classification; marks stay with the +/// preceding segment even when their face, level or case differs. +pub struct SegmentBoundary { + face: F, + level: L, + small_caps: bool, + strong_script: Option, +} + +impl SegmentBoundary { + /// Begin at the first segment's face and bidi level. + pub fn new(face: F, level: L) -> Self { + Self { face, level, small_caps: false, strong_script: None } + } + + /// Observe a cluster and return whether it begins a new shaping segment. Pass `None` for + /// common or inherited script and `true` for marks, joiners and variation selectors. + pub fn advance(&mut self, face: F, level: L, small_caps: bool, strong_script: Option, mark: bool) -> bool { + let script_change = matches!((self.strong_script, strong_script), (Some(a), Some(b)) if a != b); + let split = (self.face != face || self.level != level || self.small_caps != small_caps || script_change) && !mark; + if split { + self.face = face; + self.level = level; + self.small_caps = small_caps; + } + if let Some(script) = strong_script { + self.strong_script = Some(script); + } + split + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn preserves_marks_and_splits_on_face_direction_case_and_script() { + let mut state = SegmentBoundary::::new(1, 0); + assert!(!state.advance(1, 0, false, Some(1), false)); + assert!(!state.advance(2, 1, true, None, true)); + assert!(state.advance(2, 1, true, Some(2), false)); + assert!(!state.advance(2, 1, true, None, false)); + assert!(state.advance(2, 1, true, Some(1), false)); + } + #[test] + fn strong_script_on_a_mark_updates_the_following_boundary() { + let mut state = SegmentBoundary::::new(1, 0); + assert!(!state.advance(1, 0, false, Some(1), false)); + assert!(!state.advance(1, 0, false, Some(2), true)); + assert!(!state.advance(1, 0, false, Some(2), false)); + } +}