Repository navigation
Bidirectional text: shape RTL runs, place rows in visual order, keep one glyph per char - #8577
abdu-benayad wants to merge 2 commits into
Conversation
…l order Text with right-to-left characters is now laid out per UAX emilk#9: * `layout` resolves bidi embedding levels once per job (`unicode-bidi`), skipped entirely for ASCII text and for text with no RTL character. * `segment_into_runs` also splits where the level changes, and `shape_text` sets the harfrust direction from the level instead of guessing it, so digits inside Arabic or Hebrew shape left-to-right and read `123`. * `layout_shaped_run` walks a right-to-left run's clusters backwards, so the glyph vector stays in logical order with increasing x. This restores the `glyphs.len() == char_count` invariant for RTL text (a 13-char Arabic string produced 20 glyphs before, which left the `TextEdit` caret in phantom slots past the end of the string) and keeps line breaking unchanged. * After line breaking, `reorder_row_visually` applies rule L2 per row by rewriting x positions only; a glyph's index is still its char index. * `Glyph` carries its `bidi_level`; `Row::char_at` and `Row::x_offset` use it to put the caret on the correct side of a glyph, and the background, underline and selection painters walk glyphs by x. Paragraph direction is taken from the first strong character (P2/P3), as `dir="auto"` does in a browser. No new `LayoutJob` field. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Some fonts compose a letter from a base glyph and mark glyphs (Hack's `ǻ`, Noto Naskh Arabic's `ب`), so one character shapes to two or more glyphs. `layout_shaped_run` emitted one `Glyph` per shaped glyph, which broke the `glyphs.len() == char_count` invariant the cursor and selection code rely on: in a `TextEdit`, every such letter shifted the caret one slot. Such a cluster is now rendered into one atlas entry, the outlines of all its glyphs filled together at their shaped offsets, and carried by the cluster's first character with the cluster's whole advance. The entry is cached and sub-pixel binned like a single glyph, keyed by every glyph and offset in it. Clusters with a `.notdef` or a color glyph keep the old per-glyph path. Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Preview is being built... Preview will be available at https://egui-pr-preview.github.io/pr/8577-bidi-runs View snapshot changes at kitdiff |
|
I tested this branch (c93e886) with Arabic: Noto Sans Arabic as a fallback face, the layout checked directly, plus a real
On my checks, failures went from 492 on 1. Arabic marks (harakat) on undotted letters are drawn away from their letter
Cause:
Fix: put the base first within the cluster after emitting it. The positions are already final, so only the order changes: @@ fn emit_cluster_glyphs(
let mut emitted = 0;
+ let first_glyph = paragraph.glyphs.len();
for idx in glyph_range.clone() {
@@
emitted += 1;
}
+ // A right-to-left shaper puts a cluster's marks before its base. Put the base first,
+ // so it carries the cluster's first char and the marks move with it in
+ // `reorder_row_visually`. Positions are already final, so only the order changes.
+ if run.bidi_level % 2 == 1
+ && let Some(cluster) = paragraph.glyphs.get_mut(first_glyph..)
+ && let Some(base) = cluster.iter().position(|glyph| 0.0 < glyph.advance_width)
+ {
+ cluster.rotate_left(base);
+ }
+
emitted
}With this change the marks sit on their letters, and the caret walks x = 2, 7, 11, 18, 21, 21.5. 2. End caret of a right-to-left line that ends in left-to-right text sits at the line startType Cause: past the last glyph, Fix: None => match self.glyphs.last() {
Some(last) if last.is_rtl() => last.pos.x,
+ // A right-to-left row can end in left-to-right text, placed anywhere on it:
+ Some(last) if self.glyphs.iter().any(Glyph::is_rtl) => last.max_x(),
_ => self.size.x,
},With both changes, 3. A selection that crosses a direction change paints the wrong glyphsIn A selection that is contiguous in logical order can be split into separate pieces on screen. Out of scope, for a follow-up
Thanks for working on this! It's the piece we're waiting on to show right-to-left text properly in PdfCraft. |
|
Thanks for this. We carry an earlier, smaller version of the same idea in a fork (bidi levels per run, each run shaped in its resolved direction), and this PR covers all of it, so I'd rather help land it than open a competing one. One case from our users worth a test: Arabic-Indic digits outside right-to-left text. They belong to the Arabic script, so on main the shaper guesses right to left and "٤٥" is drawn as "٥٤" (crmne/zapfast#184). Setting the direction for every run, as this PR does, fixes it. Here is a test that fails on main and passes on c93e886, in case you want to cherry-pick it: crmne@b33eff0 |
- **reported from use:** double-clicking the Persian replacement in Search & Replace closed the program with `attempt to subtract with overflow` from `epaint/src/text/index.rs:134` (a `CharIndex` subtraction) - root cause: egui 0.36 lays a right-to-left run out with more glyphs than characters (upstream emilk/egui#8576), so a click maps to a cursor past the last character, and word selection's `num_chars - cursor` is unsigned. A bare `\r` reaches the same place another way: line-start search only knows `\n`, while line-end search treats `\r` as a break as well, leaving the cursor beyond the line handed to the word code - `text_fields` defuses the input on a field whose text is risky: the one frame carrying a double/triple click, or a word-wise key (Alt/Ctrl + ←/→, Alt/Ctrl + Backspace/Delete, Ctrl+W), draws it in a disabled scope, so `Response::double_clicked()` is false and the arithmetic never runs; single clicks, typing, drag selection and every LTR field are unchanged - every `TextEdit` goes through it — command box, run/field/new-text editors, and the ten panel fields — because document text and file names can be right-to-left - **egui's selectable labels run the same word selection**, so labels are no longer selectable (`theme::apply` turns off `selectable_labels` and `multi_widget_text_select`): labels here are chrome, page text is selected on the canvas, and the one setting covers labels added later - tests: a regression test double-clicks a Persian and a `\r` replacement and word-lefts through the panel; without the guard it reproduces the reported panic exactly - shell 766/0, app 969 at the known 12 (run with XDG_CONFIG_HOME pointed at a scratch dir — `clearhistory…` otherwise deletes the real `~/.config/Pagify/recent.json`, which this sandbox holds read-only) - upstream fix is emilk/egui#8577; `text_fields` goes when the app moves past egui 0.36
egui 0.36 shapes each font run with HarfRust, so an Arabic, Hebrew or Kurdish word draws right to left with its letters joined, but it places a line's runs left to right in logical order: a layer named "سلام عليكم" shows "عليكم سلام". bidi_label::for_egui puts the runs in visual order with the Unicode bidi algorithm and leaves the letters of every stretch egui reverses by itself in logical order (a right-to-left run is reversed, then each right-to-left-script stretch in it is turned back; Arabic-Indic digits in a left-to-right run are pre-reversed). Reordering characters too (reorder_line) mirrors every word and loses the lam-alef ligature. layer_row_ui::truncated, which draws layer names in the Layers panel rows, uses it for names with right-to-left characters. A long name is cut in logical order first, so it keeps its beginning and the "…" sits at its reading end; other names lay out exactly as before. Tests cover the string rules, and, where an Arabic or Hebrew system font is installed, the drawn glyph positions (first word rightmost, the لا ligature intact) and eliding. unicode-bidi 0.3 is already in the tree through usvg/resvg. A stopgap until egui orders runs by bidi level (emilk/egui#8577). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…l order Port of emilk#8577 (draft, commits c55da03 and c93e886) to 0.37.0. `layout` resolves UAX emilk#9 embedding levels per paragraph with `unicode-bidi` (first strong character sets the direction, like `dir="auto"`; ASCII text takes no new path). Runs split on level as well as face, right-to-left runs are shaped as such, and `Row::glyphs` stays in logical order with one `Glyph` per char (`Glyph::bidi_level` is new). After line breaking, each row with right-to-left text is placed in visual order (rule L2). `Row::char_at`, `Row::x_offset` and the selection rects are direction-aware, and row backgrounds, underline and strikethrough walk glyphs in visual order. A cluster with more glyphs than characters (a letter the font composes from a base and marks, as in Noto Naskh Arabic or Hack's `ǻ`) is drawn as one atlas bitmap carried by its first char, so the caret no longer breaks on it. 0.37.0's fontless-cluster runs get a bidi level too. Co-authored-by: Abdu Benayad <[email protected]>
Fixes from the review of emilk#8577 (fares111111122, crmne): * A right-to-left shaper puts a cluster's marks before its base. The base now carries the cluster's char index and moves with its marks when the row is reordered, and a `.notdef` base is no longer dropped in favour of its mark. * The end cursor of a right-to-left row that ends in left-to-right text ("ملف PDF") sits after that text, not at the row's right edge. * `Row::x_ranges` gives one x range per visual stretch of a char range. Selections and IME underlines are painted per stretch, so selecting a Hebrew word inside Latin text, or "abc א" across the boundary, highlights the right glyphs. * Left-to-right rows keep the plain hit-test scan, so clicks resolve exactly as before. Tests: Arabic with digits and mirrored brackets, Arabic-Indic digits outside right-to-left text, Hebrew and Latin in one paragraph (also wrapped), hit tests and selection across a direction boundary, mark order, the end caret, and a snapshot of left-to-right layout taken from 0.37.0. Co-authored-by: Carmine Paolino <[email protected]>
…orkarounds Apply emilk/egui#8577 (bidi runs) to epaint via [patch.crates-io]. Arabic words now keep their order and the cursor follows the text with the stock TextEdit and the normal fonts, so the hand-written rtl module and the Arabic font family are removed. The Windows fallback font and the dimmed no-glyph preview stay. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Two commits in
epaint, no public API removed.1. Shape right-to-left text in bidi runs and place rows in visual order.
layoutresolves UAX #9 embedding levels per paragraph withunicode-bidi(first-strong direction, likedir="auto"; ASCII text takes no new path). Runs split on level as well as face, RTL runs are shaped withDirection::RightToLeft, andRow::glyphsstays in logical order with oneGlyphper char (Glyph::bidi_levelis new). After line breaking each row with an RTL glyph is reordered visually (L2).Row::char_at/x_offsetand the selection rects become direction-aware, and the row painters (backgrounds, underline, strikethrough) walk glyphs in visual order.2. Draw a cluster with more glyphs than characters as one bitmap. Fonts that compose a letter from a base plus marks (Noto Naskh Arabic
ب, Hackǻ) shaped to twoGlyphs for one char, which broke the caret with or without bidi. Such a cluster now fills all its outlines into one atlas entry, keyed by every glyph and offset, carried by the first char with the whole advance. Clusters with a.notdefor a color glyph keep the per-glyph path.Before (0.36.2) / after, same probe, Inter + Noto Naskh Arabic, 26pt:
TextEditwithعدد 123 مرحبا: End, ArrowLeft ×3, typex→مرxحبا(wasمرحباx).Tests: four new in
epaint::text::text_layout(logical order and glyph count for Hebrew/Arabic/mixed, visual placement, cursor side and round-trip, the composed letter).cargo test -p epaint -p egui, clippy-D warnings,--no-default-featurescheck pass. The demo/kittest snapshot suites show the same set of llvmpipe-vs-reference mismatches on this branch as onmain, nothing new.Not in this PR: L1 (trailing whitespace at paragraph level), an explicit paragraph-direction override on
LayoutJob, and a wasm size measurement for theunicode-biditables (#8328).🤖 Generated with Claude Code