From d3b46e7cabefebd04ce18f1d8ad3031e23359e1d Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sat, 7 Nov 2026 10:31:35 +0300 Subject: [PATCH 1/9] fix(text): text that mixes directions reads the right way round A paragraph was shaped as one run in the direction of its first letter, so a number or a Latin word inside Arabic came out reversed ("2026" as "6202", "AniCraft" as "tfarCinA"), and a wrapped Arabic paragraph was broken from its visual left, which put its last words on the first line. Layout now follows the Unicode bidi algorithm (UAX #9, the unicode-bidi crate, MIT OR Apache-2.0): each paragraph's level runs are shaped in their own direction to measure it, lines are found in reading order, and each line's runs are shaped and placed in visual order. Text that reads one way is laid out as before. A test pins the line breaks and, where the font has Arabic letters, the number's order and the wrapped paragraph's first line. --- Cargo.lock | 7 ++ crates/text/Cargo.toml | 2 + crates/text/src/lib.rs | 156 +++++++++++++++++++++++++++-------------- docs/adr/0012-text.md | 4 ++ docs/roadmap.md | 2 +- 5 files changed, 119 insertions(+), 52 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d7b4d91a..77042232 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -268,6 +268,7 @@ dependencies = [ "fontdb", "harfrust", "skrifa", + "unicode-bidi", ] [[package]] @@ -3147,6 +3148,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-general-category" version = "1.1.0" diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 6214daf1..79dfffa5 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -14,6 +14,8 @@ fontdb.workspace = true # Shaping (a HarfBuzz port) and outlines/metrics: both already in the tree through egui. harfrust = "0.12" skrifa = { version = "0.44", default-features = false, features = ["std"] } +# The Unicode bidi algorithm (UAX #9), for text that mixes right-to-left and left-to-right runs. +unicode-bidi = "0.3" [lints] workspace = true diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 950dfa6d..530030cf 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -199,64 +199,45 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let charmap = font.charmap(); let missing = text.chars().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(*c).is_none()).count(); - // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. + // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. Text + // that mixes directions follows the Unicode bidi algorithm (UAX #9): a paragraph's lines are + // found in reading order, then each line's runs are shaped in their own direction and placed + // in visual order, so a number or a Latin word inside Arabic reads the right way round, and a + // wrapped Arabic paragraph starts on the first line. let mut lines: Vec<(f32, Vec<(Glyph, f32)>)> = Vec::new(); for para in text.split('\n') { let para = para.strip_suffix('\r').unwrap_or(para); - let mut buffer = harfrust::UnicodeBuffer::new(); - buffer.push_str(para); - buffer.guess_segment_properties(); - let shaped = shaper.shape(buffer, harfrust::ShapeOptions::new()); - let run: Vec = shaped - .glyph_infos() - .iter() - .zip(shaped.glyph_positions()) - .map(|(info, pos)| Glyph { - id: skrifa::GlyphId::new(info.glyph_id), - cluster: info.cluster as usize, - x_offset: pos.x_offset as f32 * scale, - y_offset: pos.y_offset as f32 * scale, - advance: pos.x_advance as f32 * scale + style.letter_spacing, - }) - .collect(); - let is_space = |g: &Glyph| para.get(g.cluster..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace); - let mut line: Vec<(Glyph, f32)> = Vec::new(); - let mut x = 0.0f32; - // Where the current line could break: after its last space. - let mut break_at: Option = None; - for g in run { - let space = is_space(&g); - if let Some(w) = style.width - && !space - && x + g.advance > w - && !line.is_empty() - { - // Wrap: at the last space if there is one (dropping trailing spaces), else here. - let rest = match break_at { - Some(b) => line.split_off(b), - None => Vec::new(), - }; - while line.last().is_some_and(|(g, _)| is_space(g)) { - line.pop(); + let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); + let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); + // Each byte's share of the width (a cluster's advance on its first byte), run by run. + let mut advance = vec![0.0f32; para.len()]; + let mut start = 0; + while start < para.len() { + let level = bidi.levels.get(start).copied(); + let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); + for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { + if let Some(a) = advance.get_mut(start + g.cluster) { + *a += g.advance; } - let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push((width, std::mem::take(&mut line))); - let shift = rest.first().map_or(0.0, |(_, gx)| *gx); - line = rest.into_iter().map(|(g, gx)| (g, gx - shift)).collect(); - x = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - break_at = None; } - line.push((g, x)); - x += line.last().map_or(0.0, |(g, _)| g.advance); - if space { - break_at = Some(line.len()); + start = end; + } + for range in break_lines(para, &advance, style.width) { + let mut line: Vec<(Glyph, f32)> = Vec::new(); + let mut x = 0.0f32; + if !range.is_empty() { + let (levels, runs) = bidi.visual_runs(range); + for run in runs { + let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl()); + for g in shape_run(run, rtl) { + let a = g.advance; + line.push((g, x)); + x += a; + } + } } + lines.push((x, line)); } - while line.last().is_some_and(|(g, _)| is_space(g)) { - line.pop(); - } - let width = line.last().map_or(0.0, |(g, gx)| gx + g.advance); - lines.push((width, line)); } let box_width = style.width.unwrap_or_else(|| lines.iter().map(|(w, _)| *w).fold(0.0, f32::max)); @@ -279,6 +260,58 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing }) } +/// Shapes `text` in one direction. Glyphs come back in visual order (left to right), clusters +/// counted in bytes from the start of `text`. +fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { + let mut buffer = harfrust::UnicodeBuffer::new(); + buffer.push_str(text); + buffer.set_direction(if rtl { harfrust::Direction::RightToLeft } else { harfrust::Direction::LeftToRight }); + buffer.guess_segment_properties(); + let shaped = shaper.shape(buffer, harfrust::ShapeOptions::new()); + shaped + .glyph_infos() + .iter() + .zip(shaped.glyph_positions()) + .map(|(info, pos)| Glyph { + id: skrifa::GlyphId::new(info.glyph_id), + cluster: info.cluster as usize, + x_offset: pos.x_offset as f32 * scale, + y_offset: pos.y_offset as f32 * scale, + advance: pos.x_advance as f32 * scale + letter_spacing, + }) + .collect() +} + +/// A paragraph's lines as byte ranges in reading order, given each byte's share of the width: +/// wrapped after the last space before `width` is passed (or within a word wider than the line), +/// with the spaces at a line's end left out. +fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec> { + let trimmed = |start: usize, end: usize| start..para.get(start..end).map_or(start, |s| start + s.trim_end().len()); + let mut lines = Vec::new(); + let (mut start, mut x, mut break_at) = (0usize, 0.0f32, None::); + for (i, c) in para.char_indices() { + let a = advance.get(i).copied().unwrap_or(0.0); + let space = c.is_whitespace(); + if let Some(w) = width + && !space + && x + a > w + && i > start + { + let end = break_at.unwrap_or(i); + lines.push(trimmed(start, end)); + start = end; + x = advance.get(start..i).map_or(0.0, |s| s.iter().sum()); + break_at = None; + } + x += a; + if space { + break_at = Some(i + c.len_utf8()); + } + } + lines.push(trimmed(start, para.len())); + lines +} + /// Draws glyph outlines (font space, y up) into a path (pixels, y down) at a pen position. struct Pen<'a> { cmds: &'a mut Vec, @@ -371,6 +404,27 @@ mod tests { assert!(boxed(Align::Right).min.x > 280.0); } + #[test] + fn mixed_directions_read_the_right_way_round() { + // Lines are found in reading order: after the last space that fits, or within a word. + assert_eq!(break_lines("ab cd ef", &[1.0; 8], Some(5.0)), vec![0..5, 6..8]); + assert_eq!(break_lines("abcdefgh", &[1.0; 8], Some(3.0)), vec![0..3, 3..6, 6..8]); + let Some(fonts) = fonts() else { return }; + let lay = |t: &str, width| fonts.layout(t, &Style { width, ..style(40.0) }).unwrap(); + let arabic = lay("مرحبا 2026", None); + if arabic.missing > 0 { + eprintln!("{} has no Arabic letters: right-to-left layout test skipped", arabic.family); + return; + } + // A number inside Arabic keeps its digits in order, at the line's left end ... + assert!(arabic.outline.cmds.starts_with(&lay("2026", None).outline.cmds)); + // ... and a wrapped Arabic paragraph starts with its first word, on the first line. + let first = lay("بيت", None); + let wrapped = lay("بيت جديد", Some(first.width + 1.0)); + assert!(wrapped.height > first.height * 1.8, "two lines: {}", wrapped.height); + assert!(wrapped.outline.cmds.starts_with(&first.outline.cmds)); + } + #[test] fn families_resolve_and_styles_are_clamped() { let Some(fonts) = fonts() else { return }; diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index 751dfa77..ff42d48c 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -34,6 +34,10 @@ so neither may depend on which fonts happen to be installed. embedded Inter), shapes with `harfrust` (a HarfBuzz port), reads outlines and metrics with `skrifa`, and breaks lines (paragraphs at line breaks; with a width, greedily at spaces). These crates are already in the dependency tree through egui, so no new licences. + Text that mixes directions (Arabic or Hebrew with numbers or Latin words) follows the + Unicode bidi algorithm through `unicode-bidi` (MIT OR Apache-2.0): lines are found in + reading order, then each line's runs are shaped in their own direction and placed in + visual order. Bold and italic pick the matching face of the family; there is no synthetic styling. 5. **Break Apart** turns a text element into a shape with the same outlines, as Animate's second Break Apart does. diff --git a/docs/roadmap.md b/docs/roadmap.md index f3a35188..3d3a9c7d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,7 +29,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters); frame scripts on the same sandbox; HTML canvas runtime export; button states in test-movie preview; command macros. | | **M7** | Advanced animation | Bone/IK tool; camera layer with depth; variable-width strokes and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | Installers and signing for Windows/macOS/Linux; web build (wasm) of the editor; localisation; accessibility audit; crash-recovery autosave; documentation book. | From e90f3854a4e3fc2a88959e08df9d4a76b04e7342 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sat, 7 Nov 2026 10:41:40 +0300 Subject: [PATCH 2/9] fix(text): letters the chosen font lacks come from a fallback face Text was drawn with one face, so letters it doesn't have showed as boxes, and nothing said so: Arabic in Inter, the default family where the app embeds it, or in Consolas. Now each character the chosen face lacks comes from the first of FALLBACK_FAMILIES that has it (faces with wide coverage that come with Windows, macOS and common Linux desktops, then Noto's script families), character by character: the rest of the block keeps its face, and a letter's marks stay with it. The block's line metrics still come from the chosen face. Characters no face has are counted, and text.create and text.edit now say they show as boxes. --- crates/engine/src/cmds_text.rs | 12 ++- crates/text/src/lib.rs | 140 ++++++++++++++++++++++++++++----- docs/adr/0012-text.md | 4 +- docs/roadmap.md | 2 +- 4 files changed, 136 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 354e3c97..c46e5f45 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -105,7 +105,17 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu }, ) .map_err(|e| EngineError::State(format!("can't lay out text: {e}")))?; - let note = (!style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim())).then(|| format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + let mut notes = Vec::new(); + if !style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim()) { + notes.push(format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); + } + // Letters no installed font has (after the fallbacks) would otherwise show as boxes unsaid. + match layout.missing { + 0 => {} + 1 => notes.push("1 character isn't in any font on this computer and shows as a box".to_string()), + n => notes.push(format!("{n} characters aren't in any font on this computer and show as boxes")), + } + let note = (!notes.is_empty()).then(|| notes.join("; ")); let block = TextBlock { text: text.to_string(), font: layout.family, diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 530030cf..0c9b8814 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -158,11 +158,55 @@ impl Fonts { style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, }; let id = self.db.query(&q).ok_or(TextError::NoFonts)?; - let laid = self.db.with_face_data(id, |data, index| lay_out(data, index, text, style)).flatten().ok_or(TextError::NoFonts)?; + let face = |id| self.db.with_face_data(id, |data, index| (data.to_vec(), index)); + let mut faces = vec![face(id).ok_or(TextError::NoFonts)?]; + // Characters the face doesn't have (Arabic in Inter, say) come from the first fallback + // family that has them; everything else stays in the chosen face. + let charmap_lacks = |f: &(Vec, u32), c: char| skrifa::FontRef::from_index(&f.0, f.1).ok().is_none_or(|font| font.charmap().map(c).is_none()); + let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); + missing.sort_unstable(); + missing.dedup(); + missing.retain(|c| faces.first().is_none_or(|f| charmap_lacks(f, *c))); + for fallback in FALLBACK_FAMILIES { + if missing.is_empty() || faces.len() >= MAX_FACES { + break; + } + let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; + let Some(f) = face(fid) else { continue }; + let before = missing.len(); + missing.retain(|c| charmap_lacks(&f, *c)); + if missing.len() < before { + faces.push(f); + } + } + let laid = lay_out(&faces, text, style).ok_or(TextError::NoFonts)?; Ok(Layout { family, ..laid }) } } +/// Families tried, in order, for characters the chosen face doesn't have: faces with wide +/// coverage that come with Windows, macOS and common Linux desktops, then Noto's script families. +pub const FALLBACK_FAMILIES: &[&str] = &[ + "Segoe UI", + "Arial", + "Tahoma", + "Geeza Pro", + "Arial Unicode MS", + "DejaVu Sans", + "Noto Sans", + "Noto Sans Arabic", + "Noto Naskh Arabic", + "Noto Sans Hebrew", +]; + +/// Most faces one text block draws with (the chosen face and its fallbacks). +const MAX_FACES: usize = 6; + +/// A character that is drawn (not a space, a line break or another control). +fn needs_glyph(c: char) -> bool { + !c.is_control() && !c.is_whitespace() +} + /// Clamps a style to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px). pub fn sanitize(style: &Style) -> Style { let fin = |v: f32, d: f32| if v.is_finite() { v } else { d }; @@ -175,8 +219,10 @@ pub fn sanitize(style: &Style) -> Style { } } -/// One shaped glyph: id, where its pen position starts, its offsets and advance (pixels). +/// One shaped glyph: the face it comes from, its id, the byte it starts at in its paragraph, its +/// offsets and advance (pixels). struct Glyph { + face: usize, id: skrifa::GlyphId, cluster: usize, x_offset: f32, @@ -184,20 +230,22 @@ struct Glyph { advance: f32, } -fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option { +/// Lays `text` out with `faces`: the chosen face first (its metrics set the lines), then the +/// fallbacks for characters it doesn't have. +fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option { let style = sanitize(style); - let font = skrifa::FontRef::from_index(data, index).ok()?; + let fonts: Vec = faces.iter().filter_map(|(data, index)| skrifa::FontRef::from_index(data, *index).ok()).collect(); let size = skrifa::instance::Size::new(style.size); - let metrics = font.metrics(size, skrifa::instance::LocationRef::default()); - let upem = f32::from(metrics.units_per_em.max(1)); - let scale = style.size / upem; + let metrics = fonts.first()?.metrics(size, skrifa::instance::LocationRef::default()); let ascent = metrics.ascent; let line_height = (metrics.ascent - metrics.descent + metrics.leading).max(style.size * 0.5) + style.line_spacing; - let shaper_data = harfrust::ShaperData::new(&font); - let shaper = shaper_data.shaper(&font).build(); - let glyphs = font.outline_glyphs(); - let charmap = font.charmap(); - let missing = text.chars().filter(|c| !c.is_control() && !c.is_whitespace() && charmap.map(*c).is_none()).count(); + let shaper_data: Vec = fonts.iter().map(harfrust::ShaperData::new).collect(); + let shapers: Vec = fonts.iter().zip(&shaper_data).map(|(f, d)| d.shaper(f).build()).collect(); + let scales: Vec = fonts.iter().map(|f| style.size / f32::from(f.metrics(size, skrifa::instance::LocationRef::default()).units_per_em.max(1))).collect(); + let outlines: Vec<_> = fonts.iter().map(|f| f.outline_glyphs()).collect(); + let charmaps: Vec<_> = fonts.iter().map(|f| f.charmap()).collect(); + let has = |face: usize, c: char| charmaps.get(face).is_some_and(|m| m.map(c).is_some()); + let missing = text.chars().filter(|c| needs_glyph(*c) && !(0..fonts.len()).any(|f| has(f, *c))).count(); // Lines: paragraphs at line breaks, each wrapped at spaces to the width if there is one. Text // that mixes directions follows the Unicode bidi algorithm (UAX #9): a paragraph's lines are @@ -208,7 +256,35 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option for para in text.split('\n') { let para = para.strip_suffix('\r').unwrap_or(para); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); - let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); + // The face drawing each byte: the chosen one where it has the character, else the first + // fallback that does. Spaces and marks stay with what comes before them, so a letter and + // its harakat are shaped together. + let mut face_of = vec![0usize; para.len()]; + let mut current = 0; + for (i, c) in para.char_indices() { + let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); + if !joins || !has(current, c) { + current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(if joins { current } else { 0 }); + } + face_of.iter_mut().skip(i).take(c.len_utf8()).for_each(|f| *f = current); + } + // A run shaped in one direction, split where the face changes; glyphs in visual order. + let shape_run = |run: std::ops::Range, rtl: bool| { + let mut parts: Vec> = Vec::new(); + let mut start = run.start; + while start < run.end { + let face = face_of.get(start).copied().unwrap_or(0); + let end = (start..run.end).find(|i| face_of.get(*i).copied().unwrap_or(0) != face).unwrap_or(run.end); + if let (Some(s), Some(shaper)) = (para.get(start..end), shapers.get(face)) { + parts.push(shape(shaper, face, s, start, rtl, scales.get(face).copied().unwrap_or(1.0), style.letter_spacing)); + } + start = end; + } + if rtl { + parts.reverse(); + } + parts.into_iter().flatten().collect::>() + }; // Each byte's share of the width (a cluster's advance on its first byte), run by run. let mut advance = vec![0.0f32; para.len()]; let mut start = 0; @@ -216,7 +292,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { - if let Some(a) = advance.get_mut(start + g.cluster) { + if let Some(a) = advance.get_mut(g.cluster) { *a += g.advance; } } @@ -250,7 +326,7 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option }; let baseline = ascent + row as f32 * line_height; for (g, gx) in line { - let Some(glyph) = glyphs.get(g.id) else { continue }; + let Some(glyph) = outlines.get(g.face).and_then(|o| o.get(g.id)) else { continue }; let mut pen = Pen { cmds: &mut outline.cmds, x: shift + gx + g.x_offset, y: baseline - g.y_offset }; let settings = skrifa::outline::DrawSettings::unhinted(size, skrifa::instance::LocationRef::default()); let _ = glyph.draw(settings, &mut pen); @@ -260,9 +336,9 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option Some(Layout { outline, width: box_width.max(0.0), height: height.max(0.0), family: String::new(), missing }) } -/// Shapes `text` in one direction. Glyphs come back in visual order (left to right), clusters -/// counted in bytes from the start of `text`. -fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { +/// Shapes `text` (which starts at byte `at` of its paragraph) with one face in one direction. +/// Glyphs come back in visual order (left to right), clusters counted from the paragraph's start. +fn shape(shaper: &harfrust::Shaper<'_>, face: usize, text: &str, at: usize, rtl: bool, scale: f32, letter_spacing: f32) -> Vec { let mut buffer = harfrust::UnicodeBuffer::new(); buffer.push_str(text); buffer.set_direction(if rtl { harfrust::Direction::RightToLeft } else { harfrust::Direction::LeftToRight }); @@ -273,8 +349,9 @@ fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, lette .iter() .zip(shaped.glyph_positions()) .map(|(info, pos)| Glyph { + face, id: skrifa::GlyphId::new(info.glyph_id), - cluster: info.cluster as usize, + cluster: at + info.cluster as usize, x_offset: pos.x_offset as f32 * scale, y_offset: pos.y_offset as f32 * scale, advance: pos.x_advance as f32 * scale + letter_spacing, @@ -425,6 +502,31 @@ mod tests { assert!(wrapped.outline.cmds.starts_with(&first.outline.cmds)); } + #[test] + fn letters_the_font_lacks_come_from_a_fallback_face() { + let Some(fonts) = fonts() else { return }; + let has = |family: &str, c: char| { + let q = fontdb::Query { families: &[fontdb::Family::Name(family)], ..fontdb::Query::default() }; + fonts.db.query(&q).and_then(|id| fonts.db.with_face_data(id, |d, i| skrifa::FontRef::from_index(d, i).is_ok_and(|f| f.charmap().map(c).is_some()))).unwrap_or(false) + }; + // A family with Latin letters and no Arabic ones, and a fallback that has Arabic. + let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { return }; + if !FALLBACK_FAMILIES.iter().any(|f| has(f, 'ب')) { + eprintln!("no fallback family with Arabic letters here: fallback test skipped"); + return; + } + let lay = |t: &str| fonts.layout(t, &Style { family: latin.clone(), ..style(40.0) }).unwrap(); + let arabic = lay("بيت"); + assert_eq!((arabic.missing, arabic.family.as_str()), (0, latin.as_str()), "the block keeps its family"); + assert!(!arabic.outline.cmds.is_empty()); + // The Latin letters are still drawn in the chosen face, the Arabic ones after them. + let mixed = lay("ab بيت"); + assert!(mixed.outline.cmds.starts_with(&lay("ab").outline.cmds)); + assert!(mixed.outline.cmds.len() > lay("ab").outline.cmds.len()); + // A character no font has is counted, so the command can say so. + assert_eq!(lay("a\u{10FFFD}").missing, 1); + } + #[test] fn families_resolve_and_styles_are_clamped() { let Some(fonts) = fonts() else { return }; diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index ff42d48c..cc7138c7 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -37,7 +37,9 @@ so neither may depend on which fonts happen to be installed. Text that mixes directions (Arabic or Hebrew with numbers or Latin words) follows the Unicode bidi algorithm through `unicode-bidi` (MIT OR Apache-2.0): lines are found in reading order, then each line's runs are shaped in their own direction and placed in - visual order. + visual order. Characters the chosen face doesn't have (Arabic in Inter, say) come from the + first of `FALLBACK_FAMILIES` that has them, character by character, so the rest of the block + keeps its face; any that no face has are counted, and the command says they show as boxes. Bold and italic pick the matching face of the family; there is no synthetic styling. 5. **Break Apart** turns a text element into a shape with the same outlines, as Animate's second Break Apart does. diff --git a/docs/roadmap.md b/docs/roadmap.md index 3d3a9c7d..164e9328 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,7 +29,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a | **M2** | Model at scale | ~~`Arc` structural sharing (O(changed) undo)~~ done early (ADR 0001); ~~scenes~~ ✅ (ADR 0011); ~~layer folders~~ ✅, ~~guide and motion-guide layers~~ ✅; ~~mask layers~~ ✅; ~~Movie Clip and Button behaviours~~ ✅ (playback; button states and scripting come with M6); ~~group alpha / offscreen compositing~~ ✅; ~~shape tween~~ ✅ (shape hints still to do); motion tween + Motion Editor curves; ~~MCP server~~ ✅; perf budgets ✅ (machine-independent ones gate every PR; timing via `bench --check` on a known machine, CI once a benchmark runner exists); ~~layering check~~ ✅ (`src/architecture_tests.rs`, runs with `cargo test`). | | **M3** | GPU stage | wgpu renderer (sparse-strip coverage, tile binning, gradient ramps in a texture atlas) behind a feature flag; per-pixel parity tests vs the CPU oracle; becomes the default stage renderer once parity ≤ 1/255 mean error; 4K playback at 60 fps for 1,000 shapes. | | **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. | -| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | +| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, mixed directions through the Unicode bidi algorithm, fallback faces for letters the chosen font lacks, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; audio layers (symphonia + cpal), waveform display, stream sync; filters (blur, drop shadow, glow, colour matrix) and ~~blend modes~~ ✅ on Movie Clips. | | **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters); frame scripts on the same sandbox; HTML canvas runtime export; button states in test-movie preview; command macros. | | **M7** | Advanced animation | Bone/IK tool; camera layer with depth; variable-width strokes and brush library; asset warp; graph-based easing presets library. | | **M8** | Release quality | Installers and signing for Windows/macOS/Linux; web build (wasm) of the editor; localisation; accessibility audit; crash-recovery autosave; documentation book. | From 5fb4c75d732101bbf70b0c5ab4b74876a7bda3f1 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Sun, 8 Nov 2026 07:18:28 +0300 Subject: [PATCH 3/9] perf(text): read the chosen face in place and each fallback's charmap once Fallback faces had every face copied out of the memory-mapped font on each layout, the chosen one included, and a font parsed for every character checked against it. Now the chosen face is read in place, only fallback faces the text needs are copied, and each candidate's charmap is read once. The fallback test says when it skips, and checks the Arabic letters are the fallback face's (as wide as in that family) rather than boxes from the chosen face. --- crates/text/src/lib.rs | 80 +++++++++++++++++++++++++++--------------- 1 file changed, 52 insertions(+), 28 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 0c9b8814..cb5675d8 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -158,28 +158,37 @@ impl Fonts { style: if style.italic { fontdb::Style::Italic } else { fontdb::Style::Normal }, }; let id = self.db.query(&q).ok_or(TextError::NoFonts)?; - let face = |id| self.db.with_face_data(id, |data, index| (data.to_vec(), index)); - let mut faces = vec![face(id).ok_or(TextError::NoFonts)?]; - // Characters the face doesn't have (Arabic in Inter, say) come from the first fallback - // family that has them; everything else stays in the chosen face. - let charmap_lacks = |f: &(Vec, u32), c: char| skrifa::FontRef::from_index(&f.0, f.1).ok().is_none_or(|font| font.charmap().map(c).is_none()); - let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); - missing.sort_unstable(); - missing.dedup(); - missing.retain(|c| faces.first().is_none_or(|f| charmap_lacks(f, *c))); - for fallback in FALLBACK_FAMILIES { - if missing.is_empty() || faces.len() >= MAX_FACES { - break; - } - let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; - let Some(f) = face(fid) else { continue }; - let before = missing.len(); - missing.retain(|c| charmap_lacks(&f, *c)); - if missing.len() < before { - faces.push(f); - } - } - let laid = lay_out(&faces, text, style).ok_or(TextError::NoFonts)?; + // The chosen face is read in place (memory-mapped); only fallback faces the text needs are + // copied, so text in one script costs what it did before fallbacks. + let laid = self + .db + .with_face_data(id, |data, index| { + // Characters the face doesn't have (Arabic in Inter, say) come from the first + // fallback family that has them; everything else stays in the chosen face. + let mut missing: Vec = text.chars().filter(|c| needs_glyph(*c)).collect(); + missing.sort_unstable(); + missing.dedup(); + keep_lacking(&mut missing, data, index); + let mut fallbacks: Vec<(Vec, u32)> = Vec::new(); + for fallback in FALLBACK_FAMILIES { + if missing.is_empty() || fallbacks.len() + 1 >= MAX_FACES { + break; + } + let Some(fid) = self.db.query(&fontdb::Query { families: &[fontdb::Family::Name(fallback)], ..q }).filter(|f| *f != id) else { continue }; + let helps = |d: &[u8], i: u32| { + let before = missing.len(); + keep_lacking(&mut missing, d, i); + (missing.len() < before).then(|| (d.to_vec(), i)) + }; + if let Some(face) = self.db.with_face_data(fid, helps).flatten() { + fallbacks.push(face); + } + } + let faces: Vec<(&[u8], u32)> = std::iter::once((data, index)).chain(fallbacks.iter().map(|(d, i)| (d.as_slice(), *i))).collect(); + lay_out(&faces, text, style) + }) + .flatten() + .ok_or(TextError::NoFonts)?; Ok(Layout { family, ..laid }) } } @@ -207,6 +216,14 @@ fn needs_glyph(c: char) -> bool { !c.is_control() && !c.is_whitespace() } +/// Drops from `chars` those the face in `data` has (its charmap read once). +fn keep_lacking(chars: &mut Vec, data: &[u8], index: u32) { + if let Ok(font) = skrifa::FontRef::from_index(data, index) { + let charmap = font.charmap(); + chars.retain(|c| charmap.map(*c).is_none()); + } +} + /// Clamps a style to sane ranges (sizes from 1 to 2000 px, spacing within ±1000 px). pub fn sanitize(style: &Style) -> Style { let fin = |v: f32, d: f32| if v.is_finite() { v } else { d }; @@ -232,7 +249,7 @@ struct Glyph { /// Lays `text` out with `faces`: the chosen face first (its metrics set the lines), then the /// fallbacks for characters it doesn't have. -fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option { +fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style) -> Option { let style = sanitize(style); let fonts: Vec = faces.iter().filter_map(|(data, index)| skrifa::FontRef::from_index(data, *index).ok()).collect(); let size = skrifa::instance::Size::new(style.size); @@ -266,7 +283,9 @@ fn lay_out(faces: &[(Vec, u32)], text: &str, style: &Style) -> Option, rtl: bool| { @@ -510,15 +529,20 @@ mod tests { fonts.db.query(&q).and_then(|id| fonts.db.with_face_data(id, |d, i| skrifa::FontRef::from_index(d, i).is_ok_and(|f| f.charmap().map(c).is_some()))).unwrap_or(false) }; // A family with Latin letters and no Arabic ones, and a fallback that has Arabic. - let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { return }; - if !FALLBACK_FAMILIES.iter().any(|f| has(f, 'ب')) { + let Some(latin) = fonts.families().iter().find(|f| has(f, 'a') && !has(f, 'ب')) else { + eprintln!("no family with Latin letters and no Arabic ones here: fallback test skipped"); + return; + }; + let Some(fallback) = FALLBACK_FAMILIES.iter().find(|f| has(f, 'ب')) else { eprintln!("no fallback family with Arabic letters here: fallback test skipped"); return; - } + }; let lay = |t: &str| fonts.layout(t, &Style { family: latin.clone(), ..style(40.0) }).unwrap(); let arabic = lay("بيت"); assert_eq!((arabic.missing, arabic.family.as_str()), (0, latin.as_str()), "the block keeps its family"); - assert!(!arabic.outline.cmds.is_empty()); + // The letters are the fallback face's (as wide as in that family), not the chosen face's boxes. + let direct = fonts.layout("بيت", &Style { family: fallback.to_string(), ..style(40.0) }).unwrap(); + assert!((arabic.width - direct.width).abs() < 0.01, "{} vs {} in {fallback}", arabic.width, direct.width); // The Latin letters are still drawn in the chosen face, the Arabic ones after them. let mixed = lay("ab بيت"); assert!(mixed.outline.cmds.starts_with(&lay("ab").outline.cmds)); From c9dd3163d1077ce6fd9e733d5f7a7bf4d25dc471 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 01:05:24 +0300 Subject: [PATCH 4/9] perf(text): skip bidi reordering for a paragraph with no right-to-left text (M5) --- crates/text/src/lib.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 6e4ca3fd..c4037a55 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -318,7 +318,14 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option for range in break_lines(para, &advance, style.width) { let mut line: Vec<(Glyph, f32)> = Vec::new(); let mut x = 0.0f32; - if !range.is_empty() { + if !bidi.has_rtl() { + // All left to right: nothing to reorder (visual_runs copies the paragraph's levels per line). + for g in shape_run(range, false) { + let a = g.advance; + line.push((g, x)); + x += a; + } + } else if !range.is_empty() { let (levels, runs) = bidi.visual_runs(range); for run in runs { let rtl = levels.get(run.start).is_some_and(|l| l.is_rtl()); From 912ceba1916d8c950675201983968b6fe94892a1 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 09:26:04 +0300 Subject: [PATCH 5/9] fix(text): invisible format characters aren't missing glyphs; the notice names the fonts it checked (M5) --- crates/engine/src/cmds_text.rs | 6 +++--- crates/text/src/lib.rs | 8 +++++++- docs/adr/0012-text.md | 5 +++-- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index 9f1396e1..ededa328 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -109,11 +109,11 @@ pub(crate) fn lay_out(text: &str, style: &TextStyle, width: Option) -> Resu if !style.font.trim().is_empty() && !layout.family.eq_ignore_ascii_case(style.font.trim()) { notes.push(format!("“{}” isn't installed on this computer; used {}", style.font.trim(), layout.family)); } - // Letters no installed font has (after the fallbacks) would otherwise show as boxes unsaid. + // Letters neither the font nor the fallback fonts have would otherwise show as boxes unsaid. match layout.missing { 0 => {} - 1 => notes.push("1 character isn't in any font on this computer and shows as a box".to_string()), - n => notes.push(format!("{n} characters aren't in any font on this computer and show as boxes")), + 1 => notes.push(format!("1 character isn't in {} or the fallback fonts and shows as a box", layout.family)), + n => notes.push(format!("{n} characters aren't in {} or the fallback fonts and show as boxes", layout.family)), } let note = (!notes.is_empty()).then(|| notes.join("; ")); let block = TextBlock { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 7355a31a..6e35b879 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -280,7 +280,11 @@ const MAX_FACES: usize = 6; /// A character that is drawn (not a space, a line break or another control). fn needs_glyph(c: char) -> bool { - !c.is_control() && !c.is_whitespace() + // Invisible format characters (ZWNJ, ZWJ, direction marks and embeddings, variation + // selectors, the BOM) draw as nothing, and fonts often don't map them. + let invisible = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::BN + || matches!(c, '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}'); + !c.is_control() && !c.is_whitespace() && !invisible } /// Drops from `chars` those the face in `data` has (its charmap read once). @@ -649,6 +653,8 @@ mod tests { assert!(mixed.outline.cmds.len() > lay("ab").outline.cmds.len()); // A character no font has is counted, so the command can say so. assert_eq!(lay("a\u{10FFFD}").missing, 1); + // Invisible format characters aren't boxes, so they aren't missing either. + assert_eq!(lay("a\u{200C}b\u{200D}\u{200F}\u{FE0F}").missing, 0); } #[test] diff --git a/docs/adr/0012-text.md b/docs/adr/0012-text.md index 7e06e2fc..1ca8e1b6 100644 --- a/docs/adr/0012-text.md +++ b/docs/adr/0012-text.md @@ -52,5 +52,6 @@ so neither may depend on which fonts happen to be installed. edited, and the user is told. * Text in Animate documents imports onto this model (ADR 0014). * Not yet: per-character styles in one block, vertical text, text along a path, input and - dynamic text fields (with scripting, M6), font embedding for export, glyph fallback across - fonts for missing characters (missing glyphs draw as the font's "notdef" box). + dynamic text fields (with scripting, M6), font embedding for export, fallback to installed + fonts outside the fallback list (a character none of the loaded faces has draws as the + font's "notdef" box, and the command says so). From c80f2c47e3ac4c33950caf10bf8c8f4f6bcd2898 Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Tue, 10 Nov 2026 10:54:49 +0300 Subject: [PATCH 6/9] perf(text): a block without a width skips the measuring pass that only line wrapping reads (M5) --- crates/text/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 44f64a56..d5a7efa5 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -307,9 +307,10 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style) -> Option let para = para.strip_suffix('\r').unwrap_or(para); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); let shape_run = |run: std::ops::Range, rtl: bool| para.get(run).map_or_else(Vec::new, |s| shape(&shaper, s, rtl, scale, style.letter_spacing)); - // Each byte's share of the width (a cluster's advance on its first byte), run by run. + // Each byte's share of the width (a cluster's advance on its first byte), run by run. Only wrapping + // reads it, so a block without a width skips this pass (it would shape every paragraph twice). let mut advance = vec![0.0f32; para.len()]; - let mut start = 0; + let mut start = if style.width.is_some() { 0 } else { para.len() }; while start < para.len() { let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); From a9c6fc0d3232086a8afa53332d715da7b41479ed Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Wed, 11 Nov 2026 09:23:55 +0300 Subject: [PATCH 7/9] fix(text): a combining mark the letter's face lacks takes the letter to a face with both (M5) Before, the mark alone went to the fallback face and was shaped apart from its letter, so it couldn't attach. Now the letter moves with it when one face has both; a mark no face pairs with still comes from the first face that has it. --- crates/text/src/lib.rs | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 86c3de5b..7e57000c 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -377,13 +377,26 @@ fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style) -> Option let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); // The face drawing each byte: the chosen one where it has the character, else the first // fallback that does. Spaces and marks stay with what comes before them, so a letter and - // its harakat are shaped together. + // its harakat are shaped together; a mark its letter's face lacks takes the letter to a + // face that has both, if there is one. let mut face_of = vec![0usize; para.len()]; let mut current = 0; + let mut base = (0, '\0'); // the last letter: its byte offset and character for (i, c) in para.char_indices() { let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); - if !joins || !has(current, c) { - current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(if joins { current } else { 0 }); + if !joins { + current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(0); + base = (i, c); + } else if !has(current, c) { + let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; + if let Some(both) = (0..fonts.len()).find(|f| mark && has(*f, base.1) && has(*f, c)) { + current = both; + if let Some(bytes) = face_of.get_mut(base.0..i) { + bytes.fill(both); + } + } else if let Some(f) = (0..fonts.len()).find(|f| has(*f, c)) { + current = f; + } } if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { bytes.fill(current); @@ -661,6 +674,21 @@ mod tests { assert_eq!(lay("a\u{10FFFD}").missing, 1); // Invisible format characters aren't boxes, so they aren't missing either. assert_eq!(lay("a\u{200C}b\u{200D}\u{200F}\u{FE0F}").missing, 0); + // A combining mark the chosen face lacks takes its letter along to a face with both, so + // the two are shaped together (the mark attaches) instead of in two faces. + let mark = '\u{0301}'; + if let (Some(latin), Some(both)) = ( + fonts.families().iter().find(|f| has(f, 'e') && !has(f, mark)), + FALLBACK_FAMILIES.iter().find(|f| has(f, mark)).filter(|f| has(f, 'e')), + ) { + let lay_in = |family: &str| fonts.layout("e\u{0301}", &Style { family: family.to_string(), ..style(40.0) }).unwrap(); + let (mixed, direct) = (lay_in(latin), lay_in(both)); + assert_eq!(mixed.missing, 0); + assert!((mixed.width - direct.width).abs() < 0.01, "{} vs {} in {both}", mixed.width, direct.width); + assert_eq!(mixed.outline.cmds.len(), direct.outline.cmds.len()); + } else { + eprintln!("no family with e and without U+0301 here: combining mark check skipped"); + } } #[test] From da342a3d11b8c4f9a002f28970865c9713d38d0e Mon Sep 17 00:00:00 2001 From: SoldierPePe Date: Fri, 13 Nov 2026 10:55:15 +0300 Subject: [PATCH 8/9] fix(text): wrap narrow lines between shaped clusters, never inside one break_lines walked every scalar, but advances sit only on a cluster's first byte, so a cluster wider than the line was split after its first scalar: a combining mark landed on the next line, away from its letter, and a ligature was reshaped in pieces. Advances are now None inside a cluster and lines break only where one starts; an overwide cluster stays whole on its own line. Regressions for a combining mark and a ligature at a narrow width. --- crates/text/src/lib.rs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 6afcd84f..8adcb4a8 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -510,16 +510,17 @@ fn lay_out(data: &[u8], index: u32, text: &str, style: &Style, want_glyphs: bool run }) }; - // Each byte's share of the width (a cluster's advance on its first byte), run by run. Only wrapping - // reads it, so a block without a width skips this pass (it would shape every paragraph twice). - let mut advance = vec![0.0f32; para.len()]; + // Each cluster's advance on its first byte, run by run (`None` inside a cluster, where a + // line can't break). Only wrapping reads it, so a block without a width skips this pass + // (it would shape every paragraph twice). + let mut advance: Vec> = vec![None; para.len()]; let mut start = if style.width.is_some() { 0 } else { para.len() }; while start < para.len() { let level = bidi.levels.get(start).copied(); let end = (start..para.len()).find(|i| bidi.levels.get(*i).copied() != level).unwrap_or(para.len()); for g in shape_run(start..end, level.is_some_and(|l| l.is_rtl())) { if let Some(a) = advance.get_mut(g.cluster) { - *a += g.advance; + *a.get_or_insert(0.0) += g.advance; } } start = end; @@ -654,15 +655,16 @@ fn shape(shaper: &harfrust::Shaper<'_>, text: &str, rtl: bool, scale: f32, lette .collect() } -/// A paragraph's lines as byte ranges in reading order, given each byte's share of the width: -/// wrapped after the last space before `width` is passed (or within a word wider than the line), -/// with the spaces at a line's end left out. -fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec> { +/// A paragraph's lines as byte ranges in reading order, given each cluster's advance on its first +/// byte (`None` inside a cluster): wrapped after the last space before `width` is passed (or +/// between the clusters of a word wider than the line, never inside one), with the spaces at a +/// line's end left out. +fn break_lines(para: &str, advance: &[Option], width: Option) -> Vec> { let trimmed = |start: usize, end: usize| start..para.get(start..end).map_or(start, |s| start + s.trim_end().len()); let mut lines = Vec::new(); let (mut start, mut x, mut break_at) = (0usize, 0.0f32, None::); for (i, c) in para.char_indices() { - let a = advance.get(i).copied().unwrap_or(0.0); + let Some(a) = advance.get(i).copied().flatten() else { continue }; let space = c.is_whitespace(); if let Some(w) = width && !space @@ -672,7 +674,7 @@ fn break_lines(para: &str, advance: &[f32], width: Option) -> Vec Date: Fri, 13 Nov 2026 11:11:13 +0300 Subject: [PATCH 9/9] fix(text): a mark its letter's face lacks moves the whole cluster to a face with all of it (M5) Fallback looked only at the letter and the new mark, then moved the letter and every earlier mark to that face, so a mark the original face had could land in a face without it and draw as notdef while the missing count stayed zero. The face is now chosen for the whole cluster; when no face has all of it, the new mark comes from a face that has it and the rest stay where they were. Invisible joiners the face doesn't map no longer move the run to another face, which would break joining across a ZWJ. The face choice is a pure function, choose_faces, with regressions for complementary coverage. --- crates/text/src/lib.rs | 74 +++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 27 deletions(-) diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 2ca50820..1d07fffb 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -514,6 +514,40 @@ pub fn sanitize(style: &Style) -> Style { } } +/// The face drawing each byte of a paragraph, given how many faces there are and which has which +/// character: the chosen one (0) where it has the character, else the first fallback that does. +/// Spaces and marks stay with what comes before them, so a letter and its harakat are shaped +/// together; a mark its letter's face lacks takes the whole cluster (the letter and every mark +/// after it) to a face that has all of them, if there is one, and otherwise draws from a face +/// that has the mark, leaving the letter and the earlier marks where they were. +fn choose_faces(para: &str, faces: usize, has: impl Fn(usize, char) -> bool) -> Vec { + let mut face_of = vec![0usize; para.len()]; + let mut current = 0; + let mut base = 0; // the byte offset of the last letter + for (i, c) in para.char_indices() { + let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); + if !joins { + current = (0..faces).find(|f| has(*f, c)).unwrap_or(0); + base = i; + } else if needs_glyph(c) && !has(current, c) { + let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; + let cluster = para.get(base..i + c.len_utf8()).unwrap_or_default(); + if let Some(all) = (0..faces).find(|f| mark && cluster.chars().filter(|ch| needs_glyph(*ch)).all(|ch| has(*f, ch))) { + current = all; + if let Some(bytes) = face_of.get_mut(base..i) { + bytes.fill(all); + } + } else if let Some(f) = (0..faces).find(|f| has(*f, c)) { + current = f; + } + } + if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { + bytes.fill(current); + } + } + face_of +} + /// One shaped glyph: the face it comes from, its id, the byte it starts at in its paragraph, its /// offsets and advance (pixels). struct Glyph { @@ -568,33 +602,7 @@ fn lay_out(faces: &[(&[u8], u32)], text: &str, style: &Style, want_glyphs: bool) let to_char = Arc::new(to_char); let lines_before = lines.len(); let bidi = unicode_bidi::ParagraphBidiInfo::new(para, None); - // The face drawing each byte: the chosen one where it has the character, else the first - // fallback that does. Spaces and marks stay with what comes before them, so a letter and - // its harakat are shaped together; a mark its letter's face lacks takes the letter to a - // face that has both, if there is one. - let mut face_of = vec![0usize; para.len()]; - let mut current = 0; - let mut base = (0, '\0'); // the last letter: its byte offset and character - for (i, c) in para.char_indices() { - let joins = !needs_glyph(c) || matches!(unicode_bidi::bidi_class(c), unicode_bidi::BidiClass::NSM | unicode_bidi::BidiClass::BN); - if !joins { - current = (0..fonts.len()).find(|f| has(*f, c)).unwrap_or(0); - base = (i, c); - } else if !has(current, c) { - let mark = unicode_bidi::bidi_class(c) == unicode_bidi::BidiClass::NSM; - if let Some(both) = (0..fonts.len()).find(|f| mark && has(*f, base.1) && has(*f, c)) { - current = both; - if let Some(bytes) = face_of.get_mut(base.0..i) { - bytes.fill(both); - } - } else if let Some(f) = (0..fonts.len()).find(|f| has(*f, c)) { - current = f; - } - } - if let Some(bytes) = face_of.get_mut(i..i + c.len_utf8()) { - bytes.fill(current); - } - } + let face_of = choose_faces(para, fonts.len(), has); // A run shaped in one direction, split where the face changes; glyphs in visual order. let shape_run = |run: std::ops::Range, rtl: bool| { let mut parts: Vec> = Vec::new(); @@ -881,6 +889,18 @@ mod tests { assert!(boxed(Align::Right).min.x > 280.0); } + #[test] + fn a_mark_takes_its_whole_cluster_to_a_face_with_all_of_it() { + let covers = |sets: &'static [&'static str]| move |f: usize, c: char| sets.get(f).is_some_and(|s| s.contains(c)); + // Face 1 has the letter and the second mark but not the first; face 2 has all three. + assert_eq!(choose_faces("e\u{0301}\u{0323}", 3, covers(&["e\u{0301}", "e\u{0323}", "e\u{0301}\u{0323}"])), vec![2; 5]); + // No face has all three: the letter and its first mark stay together, and the second + // mark comes from a face that has it. + assert_eq!(choose_faces("q\u{0301}\u{0323}", 2, covers(&["q\u{0323}", "q\u{0301}"])), vec![1, 1, 1, 0, 0]); + // An invisible joiner the face doesn't map doesn't move the run to another face. + assert_eq!(choose_faces("ب\u{200D}ب", 2, covers(&["ب", "\u{200D}"])), vec![0; 7]); + } + #[test] fn mixed_directions_read_the_right_way_round() { // Lines are found in reading order: after the last space that fits, or within a word.