PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: Arabic in added text (shaping, bidi order, searchable Type 3 glyphs) (#403)
fares11111112221a96245854c
diff --git a/Cargo.lock b/Cargo.lockindex d43c0e0b6..e4a8c9110 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3568,6 +3568,7 @@ dependencies = ["pdfcraft-fonts","pdfcraft-model","thiserror 2.0.21",+ "unicode-bidi",][[package]]@@ -3626,6 +3627,7 @@ dependencies = [name = "pdfcraft-fonts"version = "0.4.0"dependencies = [+ "harfrust","pdfcraft-cos","skrifa 0.44.0",]diff --git a/ROADMAP.md b/ROADMAP.mdindex cad37c682..101b8eed5 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -139,6 +139,7 @@ M0 → M1 → M2 → M3 → M4 must happen in order. After M4, M5–M12 can runNewest first. One line per session: the date, what moved, and the new overall percentage.+- **2026-10-09 (community, M7, Arabic added text):** Add text writes Arabic into the PDF instead of `?`. The text is shaped with the craft-fonts `Arab` face through harfrust (already in the tree via egui): joining forms, ligatures and mark positions. Each line is laid out in display order by the Unicode bidirectional algorithm, so Arabic mixed with Latin words, European or Arabic-Indic digits and brackets reads correctly; justified right-to-left paragraphs end at the right edge. Each cluster (a letter with its dots or marks) becomes one glyph of a Type 3 font built from the face's outlines, with a ToUnicode entry, so `text_extract`, copy and search get every letter once and no font file is embedded. Wrapping measures shaped words. Each item has its own fonts under names free on the page (a full save renumbers objects but not resource names); updating or deleting the item removes them. Without the face, adding Arabic text returns a clear error and changes nothing, while an existing item holding Arabic still moves and retypes, drawn as `?` as before. Tests cover shaping, display order, ToUnicode, font names and clean-up on one page, and odd input (empty lines, direction controls, lone marks, 18,000 characters). Not yet: bold/italic Arabic, Hebrew, right-to-left typing in the box (misc.rtl-ui), editing existing Arabic text (edit.rtl-cjk-editing). The craft-fonts revision pinned for releases predates its Arabic face, so release builds report the missing font until the pin moves. Overall estimate unchanged (about 30–35%).- **2026-10-09 (M2, predictor hardening):** Empty PNG predictor frames return without row buffers. Packed TIFF Predictor 2 rows reject overflowing dimensions and size per-component scratch to the samples present in the input, aligned with upstream lopdf#589. Synthetic regressions cover malformed dimensions, partial rows, 1/2/4-bit decoding and padding. Overall estimate unchanged (about 30–35%).- **2026-10-09 (community, document inspection):** Annotation dates preserve non-date Unicode text instead of panicking while opening; failed auxiliary structure inspection keeps renderer page geometry and reports a warning. Synthetic UTF16BE annotation, UTF8-boundary and independent panic regressions cover the fix. Overall estimate unchanged (about 30–35%).diff --git a/crates/edit/Cargo.toml b/crates/edit/Cargo.tomlindex 1aadd6338..427337809 100644--- a/crates/edit/Cargo.toml+++ b/crates/edit/Cargo.toml@@ -14,6 +14,8 @@ pdfcraft-content = { workspace = true }pdfcraft-fonts = { workspace = true }pdfcraft-model = { workspace = true }thiserror = { workspace = true }+# Display order of right-to-left lines in added text; already in the tree via the interface.+unicode-bidi = "0.3"[dev-dependencies]hayro-syntax = { workspace = true }diff --git a/crates/edit/src/added.rs b/crates/edit/src/added.rsindex d189dedf8..6537f92df 100644--- a/crates/edit/src/added.rs+++ b/crates/edit/src/added.rs@@ -7,8 +7,11 @@//! content. Boxes are in display space (origin at the bottom-left of the page as shown, after//! `/Rotate`), so items stay upright on rotated pages.+use std::collections::HashMap;+use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString, Stream};-use pdfcraft_fonts::{helvetica_width, literal, win_ansi};+use pdfcraft_fonts::{GlyphError, GlyphOutline, ShapedCluster, arabic_glyph, helvetica_width, literal, shape_arabic, win_ansi};+use unicode_bidi::{Level, ParagraphBidiInfo};use crate::{EditError, check, contents, n, page_list, place_tagged};@@ -195,24 +198,139 @@ fn norm(r: [f64; 4]) -> [f64; 4] {/// The lines of a text item after wrapping to its box width.pub fn lines(t: &AddedText) -> Vec<String> {+ wrapped(t).into_iter().map(|(line, _)| line).collect()+}++/// [`lines`], each with whether its paragraph runs right to left (its first strong character+/// does).+fn wrapped(t: &AddedText) -> Vec<(String, bool)> {let width = (t.rect[2] - t.rect[0]).max(t.size);let mut out = Vec::new();for para in t.text.split('\n') {- let mut line = String::new();+ let arabic = para.chars().any(is_arabic);+ let rtl = arabic && unicode_bidi::get_base_direction(para) == unicode_bidi::Direction::Rtl;+ // Arabic words are shaped one by one (joining stops at spaces), so a line's width is the+ // sum of its words' and shaping stays linear in the paragraph's length. The space is the+ // paragraph's; a space between Latin words is drawn in the item's font, a few hundredths+ // of an em apart.+ let measure = |s: &str| if arabic { arabic_width(t, s, rtl) } else { t.family.width(s, t.size, t.bold) };+ let space = measure(" ");+ let (mut line, mut line_w) = (String::new(), 0.0);for word in para.split(' ') {let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };- if !line.is_empty() && t.family.width(&candidate, t.size, t.bold) > width {- out.push(std::mem::take(&mut line));+ let candidate_w = if arabic { if line.is_empty() { measure(word) } else { line_w + space + measure(word) } } else { measure(&candidate) };+ if !line.is_empty() && candidate_w > width {+ out.push((std::mem::take(&mut line), rtl));line = word.to_string();+ line_w = measure(word);} else {line = candidate;+ line_w = candidate_w;}}- out.push(line);+ out.push((line, rtl));}out}+/// Arabic letters, marks, digits and punctuation: an item with any of them is shaped with the+/// craft-fonts Arabic face.+fn is_arabic(c: char) -> bool {+ matches!(u32::from(c), 0x0600..=0x06FF | 0x0750..=0x077F | 0x0870..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFC)+}++/// Direction marks, embeddings, overrides and isolates: they steer the order and are not drawn.+fn is_bidi_control(c: char) -> bool {+ matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')+}++fn mirrored(c: char) -> char {+ match c {+ '(' => ')',+ ')' => '(',+ '[' => ']',+ ']' => '[',+ '{' => '}',+ '}' => '{',+ '<' => '>',+ '>' => '<',+ '«' => '»',+ '»' => '«',+ other => other,+ }+}++/// A piece of a line with Arabic text, in drawing order.+enum Piece {+ /// Shown in the item's own standard font.+ Latin(String),+ Arabic(Vec<ShapedCluster>),+}++/// A line of an Arabic item in drawing order (the Unicode bidirectional algorithm, UAX #9), and+/// its width at the item's size. `rtl` is its paragraph's direction.+fn arabic_layout(t: &AddedText, line: &str, rtl: bool) -> Result<(Vec<Piece>, f64), EditError> {+ // unicode-bidi indexes the first level of a line, so an empty one would panic.+ if line.is_empty() {+ return Ok((Vec::new(), 0.0));+ }+ let base = if rtl { Level::rtl() } else { Level::ltr() };+ let info = ParagraphBidiInfo::new(line, Some(base));+ let (levels, runs) = info.visual_runs(0..line.len());+ let mut pieces = Vec::new();+ for run in runs {+ let run_rtl = levels.get(run.start).is_some_and(Level::is_rtl);+ // Runs lie on character boundaries; a missing slice is skipped, never a panic.+ let Some(text) = line.get(run) else { continue };+ // Arabic letters take the Arabic face; so do spaces and punctuation between them, which the+ // shaper then mirrors. Latin text (and what the face lacks) keeps the item's font.+ let mut segments: Vec<(bool, String)> = Vec::new();+ for c in text.chars().filter(|c| !is_bidi_control(*c)) {+ let arabic = is_arabic(c) || (run_rtl && !c.is_alphanumeric() && pdfcraft_fonts::arabic_has(c));+ match segments.last_mut() {+ Some((kind, s)) if *kind == arabic => s.push(c),+ _ => segments.push((arabic, c.to_string())),+ }+ }+ if run_rtl {+ segments.reverse();+ }+ for (arabic, s) in segments {+ pieces.push(if arabic {+ Piece::Arabic(shape_arabic(&s, run_rtl).map_err(|e| arabic_error(e, &s))?)+ } else if run_rtl {+ Piece::Latin(s.chars().rev().map(mirrored).collect())+ } else {+ Piece::Latin(s)+ });+ }+ }+ let width = pieces+ .iter()+ .map(|p| match p {+ Piece::Latin(s) => t.family.width(s, t.size, t.bold),+ Piece::Arabic(clusters) => clusters.iter().map(|c| c.advance).sum::<f64>() * t.size,+ })+ .sum();+ Ok((pieces, width))+}++/// The width of `s` in an Arabic item; the item's font's estimate if it can't be shaped (drawing+/// then reports why).+fn arabic_width(t: &AddedText, s: &str, rtl: bool) -> f64 {+ arabic_layout(t, s, rtl).map(|(_, w)| w).unwrap_or_else(|_| t.family.width(s, t.size, t.bold))+}++fn arabic_error(e: GlyphError, text: &str) -> EditError {+ EditError::Invalid(match e {+ GlyphError::NoFont => "Arabic text needs PdfCraft's Arabic font, which this build doesn't include \+ (to build it in, set CRAFT_FONTS_DIR to a craft-fonts checkout that has an Arab face)"+ .into(),+ GlyphError::Missing => format!("the Arabic font can't show \"{text}\""),+ GlyphError::TooComplex => format!("the Arabic font's glyphs for \"{text}\" are too complex"),+ })+}+/// The box a text item occupies (height from its lines).pub fn text_rect(t: &AddedText) -> [f64; 4] {let r = norm(t.rect);@@ -224,8 +342,196 @@ fn font_name(base: &str) -> String {format!("PCF{}", base.replace('-', ""))}-/// Content and resources for an item; `view` maps display space to user space.-fn draw(doc: &Document, c: &Content, view: [f64; 6]) -> Result<(Vec<u8>, Dict), EditError> {+/// Most glyphs in one Type 3 font: its codes are single bytes, 1–240.+const GLYPHS_PER_FONT: usize = 240;+/// Most Type 3 fonts one item may use, which bounds the objects it adds (ordinary text needs one+/// or two).+const MAX_ARABIC_FONTS: usize = 16;++/// Draw a text item that has Arabic in it. Each line is laid out in display order; Arabic glyphs+/// come from Type 3 fonts drawn from the craft-fonts face's outlines (no font file is embedded),+/// with a ToUnicode map for copy and search. Other text uses the item's standard font `latin`.+fn draw_arabic(doc: &mut Document, t: &AddedText, latin: &str, taken: &Dict, fonts: &mut Dict, out: &mut Vec<u8>) -> Result<(), EditError> {+ let r = text_rect(t);+ let lines = wrapped(t);+ let laid = lines.iter().map(|(line, rtl)| arabic_layout(t, line, *rtl)).collect::<Result<Vec<_>, _>>()?;+ // Every distinct cluster (a letter with its dots and the text it stands for) is one glyph of+ // one of the fonts, so copy and search get each character exactly once.+ let mut keys: Vec<&ShapedCluster> = Vec::new();+ let mut index: HashMap<ClusterKey, usize> = HashMap::new();+ for c in laid.iter().flat_map(|(pieces, _)| pieces).flat_map(|p| match p {+ Piece::Arabic(clusters) => clusters.as_slice(),+ Piece::Latin(_) => &[],+ }) {+ index.entry(cluster_key(c)).or_insert_with(|| {+ keys.push(c);+ keys.len() - 1+ });+ }+ if keys.len() > GLYPHS_PER_FONT * MAX_ARABIC_FONTS {+ return Err(EditError::Invalid("the text uses too many different Arabic glyphs; split it into several boxes".into()));+ }+ // Every outline is read before anything is written, so a failure leaves the document as it was.+ let mut outlines = HashMap::new();+ for c in &keys {+ for (id, _) in &c.glyphs {+ if !outlines.contains_key(id) {+ outlines.insert(*id, arabic_glyph(*id).map_err(|e| arabic_error(e, &c.text))?);+ }+ }+ }+ let mut names = Vec::new();+ for chunk in keys.chunks(GLYPHS_PER_FONT) {+ let font = type3_arabic(doc, chunk, &outlines);+ // A name no font on the page has, so items never replace each other's fonts (object+ // numbers alone don't do: a full save renumbers objects but keeps resource names).+ let mut name = format!("PCAr{}", font.num);+ let mut suffix = 0usize;+ while taken.contains(name.as_bytes()) || fonts.contains(name.as_bytes()) {+ suffix = suffix.saturating_add(1);+ name = format!("PCAr{}_{suffix}", font.num);+ }+ fonts.set(name.clone().into_bytes(), Object::Ref(font));+ names.push(name);+ }+ let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));+ out.extend(format!("BT {} {} {} rg\n", n(cr), n(cg), n(cb)).bytes());+ for (i, ((line, rtl), (pieces, w))) in lines.iter().zip(&laid).enumerate() {+ let spaces = line.matches(' ').count();+ // Justified: the spaces of every line but the last stretch to fill the box.+ let tw = if t.align == Align::Justify && i + 1 < lines.len() && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };+ let x = match t.align {+ // A right-to-left paragraph's unstretched last line ends at the right edge.+ Align::Justify if *rtl => r[2] - w - tw * spaces as f64,+ Align::Left | Align::Justify => r[0],+ Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,+ Align::Right => r[2] - w,+ };+ let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;+ let mut pen = x;+ let mut current: Option<&str> = None;+ for piece in pieces {+ match piece {+ Piece::Latin(s) => {+ out.extend(format!("/{latin} {} Tf {} Tw 1 0 0 1 {} {} Tm ", n(t.size), n(tw), n(pen), n(y)).bytes());+ out.extend(literal(&win_ansi(s)));+ out.extend_from_slice(b" Tj\n");+ current = Some(latin);+ pen += t.family.width(s, t.size, t.bold) + tw * s.matches(' ').count() as f64;+ }+ Piece::Arabic(clusters) => {+ for c in clusters {+ let Some(&k) = index.get(&cluster_key(c)) else { continue };+ let Some(name) = names.get(k / GLYPHS_PER_FONT) else { continue };+ // Codes start at 1; k % 240 + 1 is at most 240.+ let code = u8::try_from(k % GLYPHS_PER_FONT + 1).unwrap_or(1);+ if current != Some(name.as_str()) {+ out.extend(format!("/{name} {} Tf ", n(t.size)).bytes());+ current = Some(name.as_str());+ }+ out.extend(format!("1 0 0 1 {} {} Tm ", n(pen), n(y)).bytes());+ out.extend(literal(&[code]));+ out.extend_from_slice(b" Tj\n");+ pen += c.advance * t.size + if c.text == " " { tw } else { 0.0 };+ }+ }+ }+ }+ }+ out.extend_from_slice(b"ET\n");+ Ok(())+}++/// What makes two clusters the same Type 3 glyph: text, glyphs, offsets and advance (bit for bit;+/// equal clusters come from the same font units).+type ClusterKey<'a> = (&'a str, Vec<(u32, u64, u64)>, u64);++fn cluster_key(c: &ShapedCluster) -> ClusterKey<'_> {+ (c.text.as_str(), c.glyphs.iter().map(|(id, [x, y])| (*id, x.to_bits(), y.to_bits())).collect(), c.advance.to_bits())+}++/// A Type 3 font with `clusters` as codes 1…, each drawn from the Arabic face's glyph `outlines`.+fn type3_arabic(doc: &mut Document, clusters: &[&ShapedCluster], outlines: &HashMap<u32, GlyphOutline>) -> ObjRef {+ let mut charprocs = Dict::new();+ let mut differences = vec![Object::Int(1)];+ let mut widths = Vec::with_capacity(clusters.len());+ let mut bbox = [0.0f64; 4];+ let mut to_unicode = Vec::new();+ for (i, c) in clusters.iter().enumerate() {+ let code = i + 1;+ // Glyph space is 1000 units per em.+ let mut paths = Vec::new();+ let mut ink: Option<[f64; 4]> = None;+ for (id, [dx, dy]) in &c.glyphs {+ let Some(g) = outlines.get(id) else { continue };+ for contour in &g.contours {+ for (j, p) in contour.iter().enumerate() {+ paths.extend(format!("{} {} {}\n", n((p[0] + dx) * 1000.0), n((p[1] + dy) * 1000.0), if j == 0 { "m" } else { "l" }).bytes());+ }+ paths.extend_from_slice(b"h\n");+ let b = [g.bbox[0] + dx, g.bbox[1] + dy, g.bbox[2] + dx, g.bbox[3] + dy];+ ink = Some(ink.map_or(b, |a| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]));+ }+ }+ // Rounded outwards so no ink is clipped.+ let [x0, y0, x1, y1] =+ ink.map_or([0.0; 4], |b| [(b[0] * 1000.0).floor(), (b[1] * 1000.0).floor(), (b[2] * 1000.0).ceil(), (b[3] * 1000.0).ceil()]);+ bbox = [bbox[0].min(x0), bbox[1].min(y0), bbox[2].max(x1), bbox[3].max(y1)];+ let mut proc = format!("{} 0 {} {} {} {} d1\n", n(c.advance * 1000.0), n(x0), n(y0), n(x1), n(y1)).into_bytes();+ if !paths.is_empty() {+ proc.extend(paths);+ proc.extend_from_slice(b"f\n");+ }+ let glyph = format!("g{code:02X}");+ charprocs.set(glyph.clone().into_bytes(), Object::Ref(doc.add(Object::Stream(Stream::flate(Dict::new(), &proc)))));+ differences.push(Object::name(&glyph));+ widths.push(Object::Real((c.advance * 1000.0).round()));+ if !c.text.is_empty() {+ let hex: String = c.text.encode_utf16().map(|u| format!("{u:04X}")).collect();+ to_unicode.push(format!("<{code:02X}> <{hex}>\n"));+ }+ }+ let mut cmap = String::from(+ "/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n/CMapType 2 def\n1 begincodespacerange\n<01> <FF>\nendcodespacerange\n",+ );+ // A CMap block holds at most 100 entries.+ for block in to_unicode.chunks(100) {+ cmap.push_str(&format!("{} beginbfchar\n{}endbfchar\n", block.len(), block.concat()));+ }+ cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");+ let cmap = doc.add(Object::Stream(Stream::flate(Dict::new(), cmap.as_bytes())));+ let family = pdfcraft_fonts::document_arabic_font().map_or("Arabic", |f| f.family);+ let mut descriptor = Dict::new();+ descriptor.set(b"Type".to_vec(), Object::name("FontDescriptor"));+ descriptor.set(b"FontName".to_vec(), Object::name(&family.replace(' ', "")));+ descriptor.set(b"FontFamily".to_vec(), Object::String(PdfString::literal(family.as_bytes().to_vec())));+ descriptor.set(b"Flags".to_vec(), Object::Int(4));+ descriptor.set(b"ItalicAngle".to_vec(), Object::Int(0));+ let mut encoding = Dict::new();+ encoding.set(b"Type".to_vec(), Object::name("Encoding"));+ encoding.set(b"Differences".to_vec(), Object::Array(differences));+ let mut font = Dict::new();+ font.set(b"Type".to_vec(), Object::name("Font"));+ font.set(b"Subtype".to_vec(), Object::name("Type3"));+ font.set(b"FontDescriptor".to_vec(), Object::Ref(doc.add(Object::Dict(descriptor))));+ font.set(b"FontBBox".to_vec(), Object::Array(bbox.iter().map(|v| Object::Real(*v)).collect()));+ font.set(+ b"FontMatrix".to_vec(),+ Object::Array(vec![Object::Real(0.001), Object::Int(0), Object::Int(0), Object::Real(0.001), Object::Int(0), Object::Int(0)]),+ );+ font.set(b"FirstChar".to_vec(), Object::Int(1));+ font.set(b"LastChar".to_vec(), Object::Int(clusters.len() as i64));+ font.set(b"Widths".to_vec(), Object::Array(widths));+ font.set(b"Encoding".to_vec(), Object::Dict(encoding));+ font.set(b"CharProcs".to_vec(), Object::Dict(charprocs));+ font.set(b"ToUnicode".to_vec(), Object::Ref(cmap));+ doc.add(Object::Dict(font))+}++/// Content and resources for an item; `view` maps display space to user space. `taken` holds the+/// page's font names. `existing`: the item is being replaced, so a build without the Arabic face+/// keeps drawing its Arabic as `?`, as before Arabic was supported, rather than refusing to move it.+fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing: bool) -> Result<(Vec<u8>, Dict), EditError> {let mut res = Dict::new();let mut out = format!("q {} {} {} {} {} {} cm\n", n(view[0]), n(view[1]), n(view[2]), n(view[3]), n(view[4]), n(view[5])).into_bytes();match c {@@ -241,6 +547,12 @@ fn draw(doc: &Document, c: &Content, view: [f64; 6]) -> Result<(Vec<u8>, Dict),}let mut fonts = Dict::new();fonts.set(name.clone().into_bytes(), Object::Dict(font));+ if t.text.chars().any(is_arabic) && (pdfcraft_fonts::document_arabic_font().is_some() || !existing) {+ draw_arabic(doc, t, &name, taken, &mut fonts, &mut out)?;+ res.set(b"Font".to_vec(), Object::Dict(fonts));+ out.extend_from_slice(b"Q\n");+ return Ok((out, res));+ }res.set(b"Font".to_vec(), Object::Dict(fonts));let r = text_rect(t);let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));@@ -410,9 +722,15 @@ fn write(doc: &mut Document, page: usize, c: &Content, obj: Option<ObjRef>) -> Rlet all = page_list(doc);check(&[page], all.len())?;let p = &all[page];- let (content, res) = draw(doc, c, p.view_matrix(doc))?;- // The page gets its own copy of its resources with the item's fonts and images added.+ let view = p.view_matrix(doc);+ // The page gets its own copy of its resources with the item's fonts and images added, and+ // without the Arabic fonts of the version it replaces.let mut pres = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();+ if let Some(r) = obj {+ drop_fonts(doc, &mut pres, &own_fonts(doc, r));+ }+ let taken = pres.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();+ let (content, res) = draw(doc, c, view, &taken, obj.is_some())?;for (k, v) in res.iter() {let mut sub = pres.get(k).map(|s| doc.resolve(s)).and_then(|s| s.as_dict().cloned()).unwrap_or_default();for (n2, o) in v.as_dict().into_iter().flat_map(|d| d.iter()) {@@ -497,6 +815,40 @@ pub fn delete_content(doc: &mut Document, page: usize, index: usize) -> Result<(let a = find(doc, page, index)?;let p = page_list(doc).swap_remove(page);let list: Vec<Object> = contents(doc, &p)?.into_iter().filter(|o| o.as_ref() != Some(a.obj)).collect();- doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), Object::Array(list)))?;+ let fonts = own_fonts(doc, a.obj);+ // Only the page's own resources carry an item's fonts (`write` gives the page a copy).+ let res = match p.dict.get(b"Resources") {+ Some(Object::Dict(d)) if !fonts.is_empty() => Some(d.clone()),+ _ => None,+ };+ let res = res.map(|mut r| {+ drop_fonts(doc, &mut r, &fonts);+ r+ });+ doc.update_dict(p.obj, |d| {+ d.set(b"Contents".to_vec(), Object::Array(list));+ if let Some(r) = res {+ d.set(b"Resources".to_vec(), Object::Dict(r));+ }+ })?;Ok(())}++/// The Type 3 fonts an Arabic item's stream shows text with. Each item has its own (`draw_arabic`+/// names them so), so they go when the item is replaced or deleted.+fn own_fonts(doc: &Document, obj: ObjRef) -> Vec<Vec<u8>> {+ let Object::Stream(s) = &*doc.get(obj) else { return Vec::new() };+ let Ok(data) = s.decoded() else { return Vec::new() };+ data.split(u8::is_ascii_whitespace).filter_map(|w| w.strip_prefix(b"/")).filter(|w| w.starts_with(b"PCAr")).map(<[u8]>::to_vec).collect()+}++fn drop_fonts(doc: &Document, res: &mut Dict, names: &[Vec<u8>]) {+ if names.is_empty() {+ return;+ }+ let Some(mut fonts) = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()) else { return };+ for name in names {+ fonts.remove(name);+ }+ res.set(b"Font".to_vec(), Object::Dict(fonts));+}diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex 6711ba4a1..edba41fc6 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -227,6 +227,132 @@ fn added_text_and_images_are_page_content_that_stays_editable() {assert!(marks_present(&doc).is_empty());}+#[test]+fn added_arabic_text_is_shaped_in_display_order_and_stays_searchable() {+ let mut doc = fixture();+ let text =+ AddedText { rect: [72.0, 600.0, 400.0, 700.0], text: "مرحبا World".into(), size: 14.0, align: Align::Right, ..AddedText::default() };+ if pdfcraft_fonts::document_arabic_font().is_none() {+ eprintln!("skipping the Arabic drawing checks: built without a craft-fonts Arab face (set CRAFT_FONTS_DIR)");+ let err = add_content(&mut doc, 0, &Content::Text(text)).unwrap_err();+ assert!(matches!(&err, EditError::Invalid(m) if m.contains("CRAFT_FONTS_DIR")), "{err:?}");+ assert!(!doc.is_modified(), "nothing is written when the font is missing");+ return;+ }+ add_content(&mut doc, 0, &Content::Text(text.clone())).unwrap();+ // A second Arabic item on the same page keeps its own fonts.+ add_content(&mut doc, 0, &Content::Text(AddedText { text: "شكرا".into(), rect: [72.0, 500.0, 400.0, 520.0], ..text.clone() })).unwrap();+ let doc = reopen(&doc);+ let added = list_added(&doc);+ let Content::Text(t) = &added[0].content else { panic!() };+ assert_eq!(t.text, "مرحبا World", "the logical text is kept for editing");+ let s = streams(&doc, 0);+ let item = s.iter().find(|s| s.contains("(World) Tj")).unwrap();+ // A right-to-left paragraph: "World" is drawn left of the Arabic word.+ let x_before = |s: &str, at: usize| -> f64 {+ let tm = s[..at].rfind("1 0 0 1 ").unwrap() + 8;+ s[tm..].split(' ').next().unwrap().parse().unwrap()+ };+ let latin_x = x_before(item, item.find("(World) Tj").unwrap());+ let arabic_at = item.find("/PCAr").unwrap();+ let arabic_x = x_before(item, item[arabic_at..].find(" Tj").unwrap() + arabic_at);+ assert!(latin_x < arabic_x, "{item}");+ // The Arabic glyphs come from Type 3 fonts whose ToUnicode maps give back each letter.+ let p = &pdfcraft_model::pages(&doc)[0];+ let res = doc.resolve(p.dict.get(b"Resources").unwrap());+ let fonts = doc.resolve(res.as_dict().unwrap().get(b"Font").unwrap()).as_dict().unwrap().clone();+ let arabic: Vec<_> = fonts.iter().filter(|(k, _)| k.starts_with(b"PCAr")).map(|(_, v)| doc.resolve(v).as_dict().unwrap().clone()).collect();+ assert_eq!(arabic.len(), 2, "one font per item");+ let mut mapped = String::new();+ for f in &arabic {+ assert_eq!(f.name(b"Subtype"), Some(&b"Type3"[..]));+ mapped += &String::from_utf8_lossy(&stream_bytes(&doc, f.get(b"ToUnicode").unwrap()).unwrap());+ }+ for letter in ["0645", "0631", "062D", "0628", "0627", "0634", "0643"] {+ assert!(mapped.contains(&format!("<{letter}>")), "{letter} in {mapped}");+ }+}++/// The `PCAr` font names in page `page`'s resources.+fn arabic_font_names(doc: &Document, page: usize) -> Vec<String> {+ let p = &pdfcraft_model::pages(doc)[page];+ let Some(res) = p.dict.get(b"Resources").map(|r| doc.resolve(r)) else { return vec![] };+ let Some(fonts) = res.as_dict().and_then(|r| r.get(b"Font")).map(|f| doc.resolve(f)) else { return vec![] };+ fonts.as_dict().unwrap().iter().map(|(k, _)| String::from_utf8_lossy(k).into_owned()).filter(|k| k.starts_with("PCAr")).collect()+}++#[test]+fn arabic_items_keep_their_own_fonts_through_saves_updates_and_deletes() {+ let mut doc = fixture();+ let text = AddedText { rect: [72.0, 600.0, 400.0, 700.0], text: "مرحبا".into(), size: 14.0, ..AddedText::default() };+ if pdfcraft_fonts::document_arabic_font().is_none() {+ // An item that already holds Arabic (stored by an older version, drawn as "?") can still+ // be moved and retyped without the face.+ add_content(&mut doc, 0, &Content::Text(AddedText { text: "x".into(), ..text.clone() })).unwrap();+ update_content(&mut doc, 0, 0, &Content::Text(text)).unwrap();+ assert!(streams(&doc, 0).join("").contains("(?????) Tj"));+ return;+ }+ // A full save renumbers objects but keeps resource names, so a font named after its object+ // number may meet a name already on the page: here, every name it could take.+ let mut taken = Dict::new();+ for num in 1..2_000 {+ taken.set(format!("PCAr{num}").into_bytes(), Object::name("Taken"));+ }+ let mut res = Dict::new();+ res.set(b"Font".to_vec(), Object::Dict(taken));+ let page = pdfcraft_model::pages(&doc)[0].obj;+ doc.update_dict(page, |d| d.set(b"Resources".to_vec(), Object::Dict(res))).unwrap();+ add_content(&mut doc, 0, &Content::Text(text.clone())).unwrap();+ add_content(&mut doc, 0, &Content::Text(AddedText { text: "شكرا".into(), rect: [72.0, 500.0, 400.0, 520.0], ..text.clone() })).unwrap();+ let names = arabic_font_names(&doc, 0);+ assert_eq!(names.len(), 1_999 + 2, "nothing replaced");+ let p = &pdfcraft_model::pages(&doc)[0];+ let fonts = doc.resolve(p.dict.get(b"Resources").unwrap()).as_dict().unwrap().get(b"Font").cloned().unwrap();+ let fonts = doc.resolve(&fonts).as_dict().unwrap().clone();+ assert_eq!(fonts.iter().filter(|(_, v)| v.as_name() == Some(&b"Taken"[..])).count(), 1_999);+ let first = own(&doc, 0);+ assert!(first.len() == 1 && first[0].contains('_'), "a free name, not a taken one: {first:?}");+ // Updating an item swaps its fonts; deleting it removes them.+ update_content(&mut doc, 0, 0, &Content::Text(AddedText { text: "أهلا".into(), ..text })).unwrap();+ let names = arabic_font_names(&doc, 0);+ assert!(names.len() == 2_001 && !names.contains(&first[0]), "the replaced item's font is gone");+ delete_content(&mut doc, 0, 0).unwrap();+ delete_content(&mut doc, 0, 0).unwrap();+ assert_eq!(arabic_font_names(&doc, 0).len(), 1_999, "only the page's own names are left");+ reopen(&doc);+}++/// The `PCAr` fonts the stream of added item `index` on page 0 shows text with.+fn own(doc: &Document, index: usize) -> Vec<String> {+ let s = String::from_utf8_lossy(&stream_bytes(doc, &Object::Ref(list_added(doc)[index].obj)).unwrap()).into_owned();+ let mut names: Vec<String> =+ s.split_whitespace().filter_map(|w| w.strip_prefix('/')).filter(|w| w.starts_with("PCAr")).map(String::from).collect();+ names.dedup();+ names+}++#[test]+fn odd_arabic_text_never_panics() {+ let mut doc = fixture();+ let long = "بسم الله ".repeat(2_000);+ for s in+ ["\u{202E}ب\u{064B}\u{064B} (]", "\u{064B}", "ا\u{200F}\u{2067}b\u{2069}", "ا\n\nب\tc", "ا\u{2029}ب\rc\u{85}د\n", "ﷺ ١٢٣ 456", long.as_str()]+ {+ let r = add_content(&mut doc, 0, &Content::Text(AddedText { rect: [0.0, 800.0, 300.0, 780.0], text: s.into(), ..AddedText::default() }));+ assert_eq!(r.is_ok(), pdfcraft_fonts::document_arabic_font().is_some(), "{:?}: {r:?}", s.chars().take(12).collect::<String>());+ }+ // A character the face lacks is an error that names it, not a box or a crash.+ if pdfcraft_fonts::document_arabic_font().is_some() && !pdfcraft_fonts::arabic_has('\u{FDFD}') {+ let r = add_content(+ &mut doc,+ 0,+ &Content::Text(AddedText { rect: [0.0, 800.0, 300.0, 780.0], text: "ب \u{FDFD}".into(), ..AddedText::default() }),+ );+ assert!(matches!(&r, Err(EditError::Invalid(m)) if m.contains('\u{FDFD}')), "{r:?}");+ }+}+/// One page with Helvetica (WinAnsi) and a subset font that has only the glyphs it uses.fn text_page(content: &str) -> Document {let objs: Vec<String> = vec![diff --git a/crates/fonts/Cargo.toml b/crates/fonts/Cargo.tomlindex e2b388010..2e863845b 100644--- a/crates/fonts/Cargo.toml+++ b/crates/fonts/Cargo.toml@@ -12,3 +12,5 @@ workspace = truepdfcraft-cos = { workspace = true }# Glyph outlines of the bundled script font (typed signatures); already in the tree via egui.skrifa = "0.44"+# Arabic shaping for text written into PDFs; already in the tree via egui, on the same read-fonts.+harfrust = "0.12"diff --git a/crates/fonts/README.md b/crates/fonts/README.mdindex 0f59dd6b4..aa7174493 100644--- a/crates/fonts/README.md+++ b/crates/fonts/README.md@@ -33,6 +33,10 @@ set). Without that variable `CRAFT_FONTS` is empty and everything below copes:keep Mincho. Type 3 paths and advances both come from that selected face. Missing weightsfall back to a real Regular face, never synthetic bold; no italic face is supplied. Thedefault `document_japanese_font` / `japanese_glyph` APIs still use regular document Mincho.+- `document_arabic_font` / `shape_arabic` / `arabic_glyph`: the first `Arab` face, shaped with+ harfrust (joining forms, ligatures, mark positions) into clusters for Arabic text written into+ PDFs; the editor draws each cluster as one Type 3 glyph with a ToUnicode entry. Without the face+ they return `GlyphError::NoFont` and the editor reports a clear error.- `document_japanese_fonts_for_style`: every `Jpan` face in that order of preference, so theeditor can use the first one that has all of the replacement's glyphs (the faces differ incoverage, e.g. of Cyrillic).diff --git a/crates/fonts/src/arabic.rs b/crates/fonts/src/arabic.rsnew file mode 100644index 000000000..6a4a53a6a--- /dev/null+++ b/crates/fonts/src/arabic.rs@@ -0,0 +1,171 @@+//! Arabic text written into PDFs: shaping (joining forms, lam-alef ligatures, mark placement) with+//! the craft-fonts `Arab` face, and that face's glyph outlines.++use std::sync::OnceLock;++use harfrust::{BufferClusterLevel, Direction, ShapeOptions, ShaperData, UnicodeBuffer, script};+use skrifa::instance::{LocationRef, Size};+use skrifa::raw::TableProvider;+use skrifa::{FontRef, GlyphId, MetadataProvider};++use crate::{GlyphError, GlyphOutline};++/// One cluster of shaped Arabic text: the glyphs that show one character (a letter's body and+/// dots, say), or several characters for a ligature. Em units.+#[derive(Clone, Debug, PartialEq)]+pub struct ShapedCluster {+ /// Glyph ids, each with its offset from the cluster's pen position (marks sit above or below).+ pub glyphs: Vec<(u32, [f64; 2])>,+ pub advance: f64,+ /// The characters it shows, in logical order.+ pub text: String,+}++fn face() -> Option<&'static (FontRef<'static>, ShaperData)> {+ static FACE: OnceLock<Option<(FontRef<'static>, ShaperData)>> = OnceLock::new();+ FACE.get_or_init(|| {+ let font = FontRef::new(crate::document_arabic_font()?.bytes).ok()?;+ let data = ShaperData::new(&font);+ Some((font, data))+ })+ .as_ref()+}++/// Whether the Arabic document face has a glyph for `c` (false without the face).+pub fn arabic_has(c: char) -> bool {+ face().is_some_and(|(font, _)| font.charmap().map(c).is_some())+}++/// Shape one directional run of `text` with the Arabic document face. The clusters come in+/// drawing order, left to right. [`GlyphError::NoFont`] without the face;+/// [`GlyphError::Missing`] when it lacks a character.+pub fn shape_arabic(text: &str, rtl: bool) -> Result<Vec<ShapedCluster>, GlyphError> {+ let (font, data) = face().ok_or(GlyphError::NoFont)?;+ let shaper = data.shaper(font).build();+ let scale = 1.0 / f64::from(shaper.units_per_em().max(1));+ let mut buffer = UnicodeBuffer::new();+ buffer.push_str(text);+ buffer.set_direction(if rtl { Direction::RightToLeft } else { Direction::LeftToRight });+ buffer.set_script(script::ARABIC);+ // One cluster per character, so marks keep their own text for copy and search.+ buffer.set_cluster_level(BufferClusterLevel::Characters);+ let shaped = shaper.shape(buffer, ShapeOptions::new());+ // Clusters are byte offsets into `text`; a cluster shows the characters up to the next one.+ let mut starts: Vec<usize> = shaped.glyph_infos().iter().map(|g| g.cluster as usize).collect();+ starts.sort_unstable();+ starts.dedup();+ let mut out: Vec<(usize, ShapedCluster)> = Vec::new();+ for (info, pos) in shaped.glyph_infos().iter().zip(shaped.glyph_positions()) {+ if info.glyph_id == 0 {+ return Err(GlyphError::Missing);+ }+ let start = info.cluster as usize;+ // A cluster's glyphs are adjacent in the shaped run.+ let cluster = match out.last_mut() {+ Some((s, c)) if *s == start => c,+ _ => {+ let end = starts.get(starts.partition_point(|s| *s <= start)).copied().unwrap_or(text.len());+ let text = text.get(start..end).unwrap_or_default().to_string();+ out.push((start, ShapedCluster { glyphs: Vec::new(), advance: 0.0, text }));+ // Just pushed.+ let Some((_, c)) = out.last_mut() else { continue };+ c+ }+ };+ let at = [cluster.advance + f64::from(pos.x_offset) * scale, f64::from(pos.y_offset) * scale];+ cluster.glyphs.push((info.glyph_id, at));+ cluster.advance += f64::from(pos.x_advance) * scale;+ }+ Ok(out.into_iter().map(|(_, c)| c).collect())+}++/// Glyph `id` of the Arabic document face, bounded like [`crate::japanese_glyph`]. Glyphs without+/// outlines (spaces) come back empty.+pub fn arabic_glyph(id: u32) -> Result<GlyphOutline, GlyphError> {+ let (font, _) = face().ok_or(GlyphError::NoFont)?;+ if font.maxp().map_or(true, |m| id >= u32::from(m.num_glyphs())) {+ return Err(GlyphError::Missing);+ }+ let gid = GlyphId::new(id);+ let loc = LocationRef::default();+ let scale = 1.0 / font.metrics(Size::unscaled(), loc).units_per_em.max(1) as f64;+ let width = font.glyph_metrics(Size::unscaled(), loc).advance_width(gid).unwrap_or(0.0) as f64 * scale;+ // Marks have no advance; the widest ligatures (U+FDFD) span a few em.+ if !width.is_finite() || !(0.0..=8.0).contains(&width) {+ return Err(GlyphError::Missing);+ }+ if font.outline_glyphs().get(gid).is_none() {+ return Ok(GlyphOutline { contours: Vec::new(), width, bbox: [0.0, 0.0, width, 0.0] });+ }+ crate::script::bounded_outline(font, gid, width)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn face_or_skip() -> bool {+ if crate::document_arabic_font().is_none() {+ eprintln!("skipping the Arabic shaping checks: built without a craft-fonts Arab face (set CRAFT_FONTS_DIR)");+ assert_eq!(shape_arabic("ب", true), Err(GlyphError::NoFont));+ assert_eq!(arabic_glyph(1).map(|_| ()), Err(GlyphError::NoFont));+ assert!(!arabic_has('ب'));+ return false;+ }+ true+ }++ #[test]+ fn letters_take_their_joining_forms() {+ if !face_or_skip() {+ return;+ }+ let ids =+ |s: &str| shape_arabic(s, true).unwrap().iter().flat_map(|c| c.glyphs.iter().map(|g| g.0)).collect::<std::collections::BTreeSet<_>>();+ let (isolated, joined) = (ids("ب"), ids("ببب"));+ // Initial, medial and final forms are glyphs the isolated letter doesn't use.+ assert!(joined.difference(&isolated).count() >= 2, "{isolated:?} {joined:?}");+ // One cluster per letter, however many glyphs the face draws it with (Noto Sans Arabic:+ // body and dots).+ let c = shape_arabic("ببب", true).unwrap();+ assert!(c.len() == 3 && c.iter().all(|c| c.text == "ب" && c.advance > 0.0 && !c.glyphs.is_empty()), "{c:?}");+ }++ #[test]+ fn right_to_left_runs_are_drawn_from_their_last_letter() {+ if !face_or_skip() {+ return;+ }+ let g = shape_arabic("سلام", true).unwrap();+ let drawn: String = g.iter().map(|g| g.text.as_str()).collect();+ assert_eq!(drawn.chars().rev().collect::<String>(), "سلام");+ assert!(shape_arabic("سلام", false).unwrap().iter().map(|g| g.text.as_str()).collect::<String>() == "سلام");+ }++ #[test]+ fn marks_keep_their_own_text_and_no_advance() {+ if !face_or_skip() {+ return;+ }+ let c = shape_arabic("بَ", true).unwrap();+ assert_eq!(c.len(), 2, "{c:?}");+ let mark = c.iter().find(|c| c.text == "\u{064E}").unwrap();+ assert_eq!(mark.advance, 0.0);+ let outline = arabic_glyph(mark.glyphs[0].0).unwrap();+ assert!(!outline.contours.is_empty() && outline.bbox[1] > 0.0, "the fatha sits above the baseline");+ }++ #[test]+ fn spaces_and_missing_characters() {+ if !face_or_skip() {+ return;+ }+ let space = shape_arabic(" ", true).unwrap();+ assert!(space[0].advance > 0.0);+ assert!(arabic_glyph(space[0].glyphs[0].0).unwrap().contours.is_empty());+ assert!(arabic_has('ب') && !arabic_has('日'));+ assert_eq!(shape_arabic("日", true), Err(GlyphError::Missing));+ assert_eq!(arabic_glyph(u32::MAX).map(|_| ()), Err(GlyphError::Missing));+ assert!(shape_arabic("", true).unwrap().is_empty());+ }+}diff --git a/crates/fonts/src/craft.rs b/crates/fonts/src/craft.rsindex 84bc0d04c..36d45002d 100644--- a/crates/fonts/src/craft.rs+++ b/crates/fonts/src/craft.rs@@ -49,6 +49,12 @@ pub fn ui_arabic_fonts() -> Vec<&'static CraftFont> {arabic(CRAFT_FONTS.iter())}+/// The face for Arabic text written into PDFs: the first `Arab` face. `None` when built without+/// craft-fonts or when its revision has no Arabic face.+pub fn document_arabic_font() -> Option<&'static CraftFont> {+ ui_arabic_fonts().into_iter().next()+}+fn arabic<'a>(faces: impl IntoIterator<Item = &'a CraftFont>) -> Vec<&'a CraftFont> {faces.into_iter().filter(|f| f.covers("Arab")).collect()}diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rsindex 1dc6ced27..749ef53a0 100644--- a/crates/fonts/src/lib.rs+++ b/crates/fonts/src/lib.rs@@ -5,13 +5,15 @@#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]+mod arabic;mod craft;mod encodings;pub mod pdf;mod script;+pub use arabic::{ShapedCluster, arabic_glyph, arabic_has, shape_arabic};pub use craft::{- CRAFT_FONTS, CraftFont, SHIPPORI_MINCHO, document_japanese_font, document_japanese_font_for_style, document_japanese_fonts_for_style,- ui_arabic_fonts, ui_chinese_fonts, ui_cjk_fonts, ui_japanese_fonts, ui_telugu_fonts,+ CRAFT_FONTS, CraftFont, SHIPPORI_MINCHO, document_arabic_font, document_japanese_font, document_japanese_font_for_style,+ document_japanese_fonts_for_style, ui_arabic_fonts, ui_chinese_fonts, ui_cjk_fonts, ui_japanese_fonts, ui_telugu_fonts,};pub use script::{GlyphError, GlyphOutline, MAX_SIGNATURE_CHARS, ScriptOutline, japanese_glyph, japanese_glyph_from, script_outline};diff --git a/crates/fonts/src/script.rs b/crates/fonts/src/script.rsindex 1247ca25a..04695ebea 100644--- a/crates/fonts/src/script.rs+++ b/crates/fonts/src/script.rs@@ -2,7 +2,7 @@use skrifa::instance::{LocationRef, Size};use skrifa::outline::{DrawSettings, OutlinePen};-use skrifa::{FontRef, MetadataProvider};+use skrifa::{FontRef, GlyphId, MetadataProvider};static FONT: &[u8] = include_bytes!("../../../assets/fonts/DancingScript.ttf");@@ -145,6 +145,13 @@ pub fn japanese_glyph_from(face: &crate::CraftFont, ch: char) -> Result<GlyphOutif !width.is_finite() || width <= 0.0 || width > 2.0 {return Err(GlyphError::Missing);}+ bounded_outline(&font, gid, width)+}++/// Glyph `gid` of `font` in em units with advance `width`, bounded like [`japanese_glyph`].+pub(crate) fn bounded_outline(font: &FontRef, gid: GlyphId, width: f64) -> Result<GlyphOutline, GlyphError> {+ let loc = LocationRef::default();+ let scale = 1.0 / font.metrics(Size::unscaled(), loc).units_per_em.max(1) as f64;let Some(glyph) = font.outline_glyphs().get(gid) else { return Err(GlyphError::Missing) };let mut pen = Flatten::new(scale);let _ = glyph.draw(DrawSettings::unhinted(Size::unscaled(), loc), &mut pen);diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 19698c151..21ab60ae6 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -1950,8 +1950,8 @@ milestone = "M7"status = "shipped"commands = ["edit.text"]tools = ["page_add_text", "content_update"]-evidence = ["crates/ui-egui/tests/content.rs::typing_moving_styling_and_deleting_added_content", "crates/ui-egui/tests/content.rs::clicking_elsewhere_keeps_the_text_and_starts_a_new_box", "crates/automation/tests/automation.rs::adding_content_through_tools", "crates/edit/src/tests.rs::added_text_and_images_are_page_content_that_stays_editable", "crates/engine/src/tests.rs::added_text_and_images_render_and_stay_editable"]-notes = "page content, editable later (retype, move, restyle); standard fonts, Windows-1252 text. Each click on the page keeps the box being typed and starts a new one; Done and Discard beside the box"+evidence = ["crates/ui-egui/tests/content.rs::typing_moving_styling_and_deleting_added_content", "crates/ui-egui/tests/content.rs::clicking_elsewhere_keeps_the_text_and_starts_a_new_box", "crates/automation/tests/automation.rs::adding_content_through_tools", "crates/edit/src/tests.rs::added_text_and_images_are_page_content_that_stays_editable", "crates/engine/src/tests.rs::added_text_and_images_render_and_stay_editable", "crates/edit/src/tests.rs::added_arabic_text_is_shaped_in_display_order_and_stays_searchable"]+notes = "page content, editable later (retype, move, restyle); standard fonts, Windows-1252 text. Arabic text is shaped with the craft-fonts Arab face (Type 3 outlines with ToUnicode) and laid out in bidirectional display order; it is drawn regular whatever the bold/italic setting, Hebrew and other right-to-left scripts are not covered, and typing in the box is still left to right (misc.rtl-ui). Each click on the page keeps the box being typed and starts a new one; Done and Discard beside the box"[[feature]]id = "edit.find-replace"