Skip to content

Bidirectional text: shape RTL runs, place rows in visual order, keep one glyph per char - #8577

Draft
abdu-benayad wants to merge 2 commits into
emilk:mainfrom
abdu-benayad:bidi-runs
Draft

abdu-benayad wants to merge 2 commits into
emilk:mainfrom
abdu-benayad:bidi-runs

Conversation

@abdu-benayad

Copy link
Copy Markdown

Two commits in epaint, no public API removed.

1. Shape right-to-left text in bidi runs and place rows in visual order. layout resolves UAX #9 embedding levels per paragraph with unicode-bidi (first-strong direction, like dir="auto"; ASCII text takes no new path). Runs split on level as well as face, RTL runs are shaped with Direction::RightToLeft, and Row::glyphs stays in logical order with one Glyph per char (Glyph::bidi_level is new). After line breaking each row with an RTL glyph is reordered visually (L2). Row::char_at / x_offset and 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 two Glyphs 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 .notdef or a color glyph keep the per-glyph path.

Before (0.36.2) / after, same probe, Inter + Noto Naskh Arabic, 26pt:

before
after

TextEdit with عدد 123 مرحبا: End, ArrowLeft ×3, type x → مر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-features check pass. The demo/kittest snapshot suites show the same set of llvmpipe-vs-reference mismatches on this branch as on main, 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 the unicode-bidi tables (#8328).

🤖 Generated with Claude Code

abdu-benayad and others added 2 commits September 17, 2026 03:06
…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]>
@github-actions

Copy link
Copy Markdown

Preview is being built...

Preview will be available at https://egui-pr-preview.github.io/pr/8577-bidi-runs

View snapshot changes at kitdiff

@fares111111122

Copy link
Copy Markdown

I tested this branch (c93e886) with Arabic: Noto Sans Arabic as a fallback face, the layout checked directly, plus a real TextEdit driven with text and key events. Compared with main, this is a big step forward:

  • word order, numbers inside Arabic, mirrored brackets, wrapping and per-paragraph direction are all right;
  • Home/End, Backspace/Delete and inserting at the start work;
  • lam-alef and ﷺ are fine;
  • 3000 random mixed Arabic/Latin/digits/marks/bidi-control strings produced no panics.

On my checks, failures went from 492 on main to 93 here. I found three issues, and have tested fixes for two of them.

1. Arabic marks (harakat) on undotted letters are drawn away from their letter

بِسْمِ: the sukun over س is drawn to the right of the whole word, and the kasra under م lands under ب/س. With the arrow keys the caret jumps back and forth: x = 7, 20, 18, 25, 21 instead of a steady walk.

Cause:

  • In a right-to-left run, harfrust outputs a cluster's mark glyphs before its base.
  • reorder_row_visually attaches each zero-width glyph to the advancing glyph before it, so the mark travels with the previous letter.
  • emit_cluster_glyphs gives every glyph of a cluster the cluster's first char, so the base char's index points at the mark glyph.
  • Dotted letters (ب) are not affected: they have more glyphs than chars and go through emit_cluster_bitmap.

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 start

Type ملف and then PDF into a TextEdit. The caret ends up at the right edge, on top of the start-of-text caret, instead of after PDF. The same happens with صفحة 12 من 340.

Cause: past the last glyph, Row::x_offset returns size.x whenever the last glyph is left-to-right.

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, cargo test -p epaint --lib (72 tests) and cargo test -p egui --lib (57 tests) pass, and cargo clippy -p epaint -- -D warnings is clean.

3. A selection that crosses a direction change paints the wrong glyphs

In Open ملف now, selecting Open (chars 0..5) also highlights ملف. The same happens in صفحة 12 من 340.

A selection that is contiguous in logical order can be split into separate pieces on screen. paint_text_selection, however, draws one rectangle from the smaller to the larger x. One rectangle per visual stretch of selected glyphs would fix it. I haven't written that fix.

Out of scope, for a follow-up

  • Arrow keys move logically. Inside Arabic text, ← therefore moves the caret to the right. macOS and Windows move it visually.
  • On main too, every glyph of a multi-glyph cluster carries the cluster's first char, so Row::text() returns اا for اّ.

Thanks for working on this! It's the piece we're waiting on to show right-to-left text properly in PdfCraft.

@crmne

crmne commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

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

farzadbekran added a commit to HSI-Lighting/Pagify that referenced this pull request Oct 18, 2026
- **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
FredApps pushed a commit to FredApps/photocraft that referenced this pull request Oct 29, 2026
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]>
richerfu pushed a commit to richerfu/egui that referenced this pull request Nov 2, 2026
…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]>
richerfu pushed a commit to richerfu/egui that referenced this pull request Nov 2, 2026
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]>
mohseenjamall added a commit to mohseenjamall/FontCraft that referenced this pull request Nov 21, 2026
…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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TextEdit caret is lost in Arabic/Hebrew text since 0.35: rows hold more glyphs than characters

3 participants