PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: grow text boxes and edit existing text (#1539)
Yousef Mojahidd1bc2001156c
diff --git a/ROADMAP.md b/ROADMAP.mdindex 9b67d4ec6..c2cd0f881 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -164,6 +164,7 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md- **2026-10-15 (M14, gap 24):** `misc.localization` and `misc.installers` move from planned to partial. Localization: 22 catalogs ship, but Chinese shows tofu in releases, Telugu has no release font and Arabic is not mirrored. Installers: macOS and Windows releases are signed, Linux packages are not. The Acrobat menu diff itself remains open. Estimates unchanged.- **2026-10-13 (G14, Vietnamese localization):** Added Vietnamese (`vi`, Tiếng Việt) as an interface and date language with a 2,591-entry catalog (`plural_none`) covering 100% of the current localizable key union (plus `theme`/`Appearance`). Locale tags `vi` / `vi-VN` / `vi_VN.UTF-8` resolve; calendar months use numeric `Tháng 1`…`12` / `tháng 1`…`12`. Native-speaker community review recorded. The twelve-language localization mean moves from ≈59% to ≈68%; weighted readiness ≈49% → ≈50%. Status stays `partial`: engine/OS details, document contents, filenames, CLI/MCP and external help stay outside the catalog by design.+- **2026-10-12 (M7, local text-box candidate):** Add Text opens source text for editing and both text tools retype added items on one click. Draft boxes grow toward the page edge and downwards, with the grown width saved. Single visual rows grow across style boundaries, while multi-row paragraph widths stay fixed. Added-text previews remove only the selected item on a clone, with UI and read-only tool regressions. Arabic shaping, ordering and alignment are outside this candidate. Estimates unchanged.- **2026-10-12 (M14, #1395):** XDG desktops use the configuration base for app.ron, safely copying existing preferences without overwriting a destination. Original preferences, logs, recovery and digital IDs are retained; failed migration falls back to the original location. Portable and non-XDG locations remain unchanged; estimates unchanged.- **2026-10-12 (M10, Windows print progress, follow-up to #944):** While a job spools, the progress card counts its sheets ("Sending sheet 2 of 3 to Office…") as craft-print reports them (`submit_with_progress`, storytold/craft-libs#27), and steps aside for another long job's card. Pins craft-libs 666c358. Estimates unchanged.diff --git a/crates/automation/README.md b/crates/automation/README.mdindex cb1d85c1f..4e27702a3 100644--- a/crates/automation/README.md+++ b/crates/automation/README.md@@ -157,6 +157,10 @@ For inline editor previews, `page_render` accepts `hide_text_block` (a 1-based i`text_paragraphs`). It renders the page without that paragraph’s source glyphs and leaves theworking document unchanged.+`page_render.hide_added_text` does the same for an added text item's 1-based index from+`content_list` or `object_list`. It removes only that item in a read-only preview and is+mutually exclusive with `hide_text_block`.+## Existing text and document fontsdiff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsindex 1933c7d0d..ad18f7112 100644--- a/crates/automation/src/lib.rs+++ b/crates/automation/src/lib.rs@@ -1798,12 +1798,23 @@ impl Automation {return Err(ToolError::InvalidArgs(format!("dpi must be between 1 and {MAX_DPI}")));}let scale = (dpi / 72.0) as f32;- let out = if let Some(block) = a.opt_int("hide_text_block")? {+ let block = a.opt_int("hide_text_block")?;+ let added = a.opt_int("hide_added_text")?;+ if block.is_some() && added.is_some() {+ return Err(ToolError::InvalidArgs("choose only one of hide_text_block and hide_added_text".into()));+ }+ let out = if let Some(block) = block {let index = usize::try_from(block).ok().and_then(|n| n.checked_sub(1)).ok_or_else(|| ToolError::InvalidArgs("hide_text_block must be a positive paragraph index from text_paragraphs".into()))?;self.doc(a)?.text_edit_preview(page, index).map_err(failed)?.render_background(scale).map_err(failed)?+ } else if let Some(added) = added {+ let index = usize::try_from(added)+ .ok()+ .and_then(|n| n.checked_sub(1))+ .ok_or_else(|| ToolError::InvalidArgs("hide_added_text must be a positive added text index from object_list".into()))?;+ self.doc(a)?.added_text_preview(page, index).map_err(failed)?.render_background(scale).map_err(failed)?} else {self.renderer(id)?.render(RenderRequest { page, kind: RequestKind::Pixels, tile: None, scale, tag: 0, preview: false })};diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex cd83fd5b4..5e89aef78 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -161,7 +161,8 @@ pub fn tools() -> Vec<ToolDef> {t("page_render", "Render a page", "Render one page to a PNG image (default 96 dpi, at most 600).").ro().with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "dpi": { "type": "number", "minimum": 1, "maximum": 600 },- "hide_text_block": { "type": "integer", "minimum": 1, "description": "Render an inline editor background without this paragraph (index from text_paragraphs). Does not modify the document." }+ "hide_text_block": { "type": "integer", "minimum": 1, "description": "Render an inline editor background without this paragraph (index from text_paragraphs). Does not modify the document." },+ "hide_added_text": { "type": "integer", "minimum": 1, "description": "Render a retyping background without this added text item (added index from object_list). Mutually exclusive with hide_text_block. Does not modify the document." }}), &["doc", "page"])),t("object_list", "List editable objects", "List existing paragraphs, Image/Form artwork and added content once, with source kind/index references, displayed rectangles and document generation. Indexes change when content changes; use generation in object_move to reject stale references.").ro().with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1}}), &["doc","page"])),diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rsindex 58f4a5272..f45aec3f5 100644--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@ -621,6 +621,29 @@ fn text_editor_background_is_read_only_and_removes_source_glyphs() {}}+#[test]+fn added_text_editor_background_hides_only_the_item_without_editing() {+ let dir = workdir("added-text-preview");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ let render = json!({"doc":doc,"page":1,"dpi":72});+ let before = a.call("page_render", &render).unwrap();+ ok(&mut a, "page_add_text", json!({"doc":doc,"page":1,"text":"Retype this label","at":[20,20],"width":160}));+ let drawn = a.call("page_render", &render).unwrap();+ assert_ne!(drawn, before);+ let state = ok(&mut a, "doc_info", json!({"doc":doc}));+ let items = ok(&mut a, "content_list", json!({"doc":doc}));+ let preview = a.call("page_render", &json!({"doc":doc,"page":1,"dpi":72,"hide_added_text":1})).unwrap();+ assert_eq!(preview, before, "native text and the page background stay intact");+ assert_eq!(a.call("page_render", &render).unwrap(), drawn);+ assert_eq!(ok(&mut a, "doc_info", json!({"doc":doc})), state);+ assert_eq!(ok(&mut a, "content_list", json!({"doc":doc})), items);+ for index in [-1, 0, 2, i64::MAX] {+ assert!(a.call("page_render", &json!({"doc":doc,"page":1,"hide_added_text":index})).is_err());+ }+ assert!(a.call("page_render", &json!({"doc":doc,"page":1,"hide_added_text":1,"hide_text_block":1})).is_err());+}+#[test]fn edit_undo_redo_and_save_round_trip() {let dir = workdir("edit");diff --git a/crates/edit/src/added.rs b/crates/edit/src/added.rsindex 2b6c9d13a..d246df725 100644--- a/crates/edit/src/added.rs+++ b/crates/edit/src/added.rs@@ -501,6 +501,11 @@ pub fn text_rect(t: &AddedText) -> [f64; 4] {[r[0], r[3] - h, r[2], r[3]]}+/// The widest explicit line before wrapping, measured with the PDF writing fonts.+pub fn text_width(t: &AddedText) -> f64 {+ t.text.split('\n').map(|line| shaped_width(t, line, unicode_bidi::get_base_direction(line) == unicode_bidi::Direction::Rtl)).fold(0.0, f64::max)+}+fn font_name(base: &str) -> String {format!("PCF{}", base.replace('-', ""))}diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex aab8134bb..b542142df 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -3431,6 +3431,30 @@ fn mixed_styles_and_matrix_sizes_form_visual_regions_without_merging_columns() {assert_eq!(blocks[2].text, "Other column");}+#[test]+fn a_single_row_with_mixed_styles_grows_before_wrapping() {+ let mut doc = text_page("BT /F1 10 Tf 72 582 Td (Plain ) Tj /F2 10 Tf (bold) Tj /F1 10 Tf ( text.) Tj ET");+ doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |f| {+ *f = Dict::new();+ f.set(b"Type".to_vec(), Object::name("Font"));+ f.set(b"Subtype".to_vec(), Object::name("Type1"));+ f.set(b"BaseFont".to_vec(), Object::name("Helvetica-Bold"));+ })+ .unwrap();+ let blocks = text::text_blocks(&doc, 0).unwrap();+ let index = blocks.iter().position(|b| b.editor_text == "Plain bold text.").unwrap();+ let source = &blocks[index];+ assert_eq!(source.rows.len(), 1);+ assert!(source.lines.len() > 1);+ let draft = "Plain bold text. More words on the same line";+ text::replace_block(&mut doc, 0, index, draft).unwrap();+ let edited = text::text_blocks(&reopen(&doc), 0).unwrap();+ let block = edited.iter().find(|b| b.text == draft).unwrap();+ assert_eq!(block.rows.len(), 1, "a style boundary must not pin a single row to its original width");+ assert!((block.rect[0] - source.rect[0]).abs() < 0.1);+ assert!(block.rect[2] > source.rect[2] + 20.0);+}+#[test]fn explicit_editor_rows_survive_single_run_edit_and_reopen() {let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Original heading) Tj ET");diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rsindex 0f6a25161..2d7baf519 100644--- a/crates/edit/src/text_regions.rs+++ b/crates/edit/src/text_regions.rs@@ -379,8 +379,9 @@ pub(super) fn rewrite_styled_block(if !dx.is_finite() || !dy.is_finite() || style.width.is_some_and(|w| !w.is_finite()) {return Err(EditError::Invalid("the paragraph's position and width must be finite".into()));}- // A rewritten OCR line grows to the right rather than wrapping onto the scanned line below.- let natural = if block.invisible {+ // A visual row grows even when it contains several source/font runs. Multi-row+ // paragraphs retain their container width; an explicit width always wins.+ let natural = if block.invisible || block.rows.len() == 1 {(p.crop(doc)[2] - 36.0 - (block.rect[0] + dx)).max(block.rect[2] - block.rect[0])} else {block.rect[2] - block.rect[0]diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex c85556c23..eb0a11825 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -52,6 +52,7 @@ pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnificpub use pdfcraft_cos::Algorithm;pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, SourceKind, decode_text, source_kind};+pub use pdfcraft_edit::added::{text_rect as added_text_rect, text_width as added_text_width};pub use pdfcraft_edit::{Added, AddedImage, AddedText, Align as TextAlign, Background, Content as AddedContent, Family as FontFamily, HeaderFooter, MarkKind, Watermark,};diff --git a/crates/engine/src/text_preview.rs b/crates/engine/src/text_preview.rsindex d18016967..d533faf7e 100644--- a/crates/engine/src/text_preview.rs+++ b/crates/engine/src/text_preview.rs@@ -33,6 +33,20 @@ impl TextEditPreview {}impl Document {+ /// Background for retyping an added text item, without changing its saved content.+ pub fn added_text_preview(&self, page: usize, index: usize) -> Result<TextEditPreview, String> {+ guard(|| {+ if !self.added().iter().filter(|a| a.page == page).nth(index).is_some_and(|a| matches!(a.content, crate::AddedContent::Text(_))) {+ return Err("the selected added item is not text".into());+ }+ let editor = self.editor.as_ref().ok_or("the document can't be read")?;+ let mut cos = editor.cos.clone();+ pdfcraft_edit::delete_content(&mut cos, page, index).map_err(|e| e.to_string())?;+ let bytes = Arc::new(pdfcraft_cos::write_incremental(&cos, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())?);+ Ok(TextEditPreview { page, bytes, config: self.config.clone() })+ })?+ }+/// Measure a draft without changing bytes, dirty state, or undo history.pub fn text_edit_layout(&self,diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex c2e6e8201..8bc3a5c7a 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -2557,7 +2557,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {view.prepare.selected = None;}view.objects.prepare(doc, tool == QuickTool::EditText && can_modify, ui.ctx());- view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), scale);+ view.text_background.prepare(ui.ctx(), doc, view.line_editor.as_ref(), view.content.draft.as_ref(), scale);let added = if editing_content { doc.added().to_vec() } else { Vec::new() };let doc_links = if tool == QuickTool::Link { doc.links().to_vec() } else { Vec::new() };if editing_content {@@ -2777,7 +2777,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {}}}- view.text_background.paint(painter, &xf, i, view.line_editor.as_ref());+ view.text_background.paint(painter, &xf, i, view.line_editor.as_ref(), view.content.draft.as_ref());if editing_content {let page_tex = view.pages.get(&i).map(|p| p.tex.id());view.move_background.paint(ui, painter, &xf, i, info, &view.content, page_tex);@@ -2915,9 +2915,46 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {let image_owns_pointer = tool == QuickTool::EditText && crate::edit_text_ui::image_owns_pointer(ui, &xf, i, info, view);let on_objects =!image_owns_pointer && tool == QuickTool::EditText && can_modify && crate::object_ui::page_input(ui, &resp, &xf, i, doc, view);+ let lines = if matches!(tool, QuickTool::AddText | QuickTool::EditText) && can_modify {+ let generation = doc.edit_generation();+ match view.edit_lines.get(&i) {+ Some((g, l)) if *g == generation => l.clone(),+ _ => {+ let l = doc.text_blocks(i);+ view.edit_lines.insert(i, (generation, l.clone()));+ l+ }+ }+ } else {+ Vec::new()+ };+ let over_source = tool == QuickTool::AddText+ && pointer.is_some_and(|p| {+ !crate::content_ui::hits_added(&xf, info, i, &added, p)+ && lines.iter().any(|line| xf.user_rect(info, i, line.rect.map(|v| v as f32)).expand(2.0).contains(p))+ });+ let source_blocked = over_source && view.content.hold_blocked();+ if over_source && resp.clicked() && !source_blocked {+ if let Some(edit) = view.content.finish_draft(&added) {+ view.pending_edit = Some(edit);+ }+ view.content.selected = None;+ }let on_content = !on_objects && editing_content && can_modify && {- crate::content_ui::page_input(ui, &resp, &xf, i, info, &added, tool == QuickTool::AddText, &text_style, view)- || tool == QuickTool::AddText+ source_blocked+ || crate::content_ui::page_input(+ ui,+ &resp,+ &xf,+ i,+ info,+ &added,+ tool == QuickTool::AddText && !over_source,+ matches!(tool, QuickTool::AddText | QuickTool::EditText),+ &text_style,+ view,+ )+ || tool == QuickTool::AddText && !over_source};// Added content owns its gesture; its source text must not queue a second edit.// Edit text & images boxes every paragraph and image whenever the tool is on. Only the@@ -2925,16 +2962,8 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) {// input is blocked (another tab, a dialog, the window unfocused): the boxes stay drawn// instead of vanishing until the pointer comes back.let others_own_pointer = on_objects || on_content;- let on_edit_text = tool == QuickTool::EditText && can_modify && {+ let on_edit_text = (tool == QuickTool::EditText || over_source) && can_modify && {let generation = doc.edit_generation();- let lines = match view.edit_lines.get(&i) {- Some((g, l)) if *g == generation => l.clone(),- _ => {- let l = doc.text_blocks(i);- view.edit_lines.insert(i, (generation, l.clone()));- l- }- };let images = match view.edit_images.get(&i) {Some((g, l)) if *g == generation => l.clone(),_ => {diff --git a/crates/ui-egui/src/content_ui.rs b/crates/ui-egui/src/content_ui.rsindex 52f8e3cb4..5f5ef32f7 100644--- a/crates/ui-egui/src/content_ui.rs+++ b/crates/ui-egui/src/content_ui.rs@@ -86,9 +86,13 @@ pub struct ContentView {pub select_added: Option<(usize, usize)>,grab: Option<(usize, Grab, Pos2)>,undrawable: UndrawableMemo,+ layout: Option<(AddedText, f32, f64, [f64; 4])>,}impl ContentView {+ pub(crate) fn finish_draft(&mut self, added: &[Added]) -> Option<Edit> {+ self.draft.take().and_then(|d| finish(self, d, added))+ }/// The draft's first character the standard fonts can't draw. Such a draft is kept open, and/// counts as unsaved work, until it is corrected or discarded.pub(crate) fn blocked(&self) -> Option<char> {@@ -248,6 +252,10 @@ fn on_page(added: &[Added], page: usize) -> Vec<(usize, &Added)> {added.iter().filter(|a| a.page == page).enumerate().collect()}+pub(crate) fn hits_added(xf: &PageXform, info: &DocInfo, page: usize, added: &[Added], point: Pos2) -> bool {+ on_page(added, page).iter().any(|(_, a)| screen_rect(xf, info, page, a.content.rect()).expand(2.0).contains(point))+}+fn handles(r: Rect) -> [(Pos2, bool, bool); 4] {[(r.left_top(), true, true), (r.right_top(), false, true), (r.left_bottom(), true, false), (r.right_bottom(), false, false)]}@@ -306,6 +314,7 @@ pub(crate) fn page_input(info: &DocInfo,added: &[Added],adding_text: bool,+ edit_on_click: bool,style: &AddedText,view: &mut DocView,) -> bool {@@ -363,14 +372,10 @@ pub(crate) fn page_input(let at = to_display(xf, info, page, p);let mut style = style.clone();style.text.clear();- cv.draft = Some(TextDraft {- page,- index: None,- rect: [at[0], at[1] - style.size * 1.2, at[0] + 200.0, at[1]],- text: String::new(),- style,- focus: true,- });+ let page_width = info.pages.get(page).map_or(f64::INFINITY, |p| p.width as f64);+ let rect = [at[0], at[1] - style.size * 1.2, (at[0] + 200.0).min(page_width), at[1]];+ style.rect = rect;+ cv.draft = Some(TextDraft { page, index: None, rect, text: String::new(), style, focus: true });consumed = true;if typed.is_some() {view.pending_edit = typed;@@ -395,13 +400,19 @@ pub(crate) fn page_input(}return consumed;}- if resp.double_clicked()+ if (resp.double_clicked() || edit_on_click && resp.clicked() && corner.is_none())&& let Some((i, a)) = hit&& let AddedContent::Text(t) = &a.content{if cv.hold_blocked() {return true;}+ if cv.draft.as_ref().is_some_and(|d| d.page == page && d.index == Some(i)) {+ return true;+ }+ if let Some(edit) = cv.finish_draft(added) {+ view.pending_edit = Some(edit);+ }cv.draft = Some(TextDraft { page, index: Some(i), rect: t.rect, text: t.text.clone(), style: t.clone(), focus: true });cv.selected = Some((page, i));consumed = true;@@ -478,16 +489,46 @@ pub(crate) fn after_refresh(view: &mut DocView, added: &[Added]) {/// committed (a click away, or Done), and whether Done finished adding text. Discard or Escape/// throws the draft away.pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, added: &[Added]) -> (Option<Edit>, bool) {- let Some((page, rect)) = view.content.draft.as_ref().map(|d| (d.page, d.rect)) else { return (None, false) };+ let Some(page) = view.content.draft.as_ref().map(|d| d.page) else { return (None, false) };let Some(xf) = view.page_xform(page) else { return (None, false) };- let r = screen_rect(&xf, info, page, rect);let zoom = xf.rect.width() / xf.pw.max(1.0);+ let Some(draft) = view.content.draft.as_mut() else { return (None, false) };+ let font = crate::edit_text_ui::editor_font(&draft.style, (draft.style.size as f32 * zoom).clamp(1.0, 300.0));+ let text = AddedText { text: draft.text.clone(), ..draft.style.clone() };+ let Some(page_width) = info.pages.get(page).map(|p| p.width as f64) else { return (None, false) };+ if let Some((key, z, width, rect)) = &view.content.layout+ && *key == text+ && *z == zoom+ && *width == page_width+ {+ draft.rect = *rect;+ } else {+ let source = draft.style.rect;+ if draft.index.is_some() && draft.text == draft.style.text {+ draft.rect = source;+ } else {+ let natural = ctx.fonts_mut(|f| f.layout_no_wrap(draft.text.clone(), font.clone(), Color32::BLACK).size().x) as f64 / zoom as f64;+ let width = natural.max(pdfcraft_engine::added_text_width(&text)) + 2.0;+ let available = page_width - source[0];+ let width = width.max(source[2] - source[0]).min(available.max(1.0));+ draft.rect = [source[0], source[1], source[0] + width, source[3]];+ draft.rect = pdfcraft_engine::added_text_rect(&AddedText { rect: draft.rect, ..text.clone() });+ }+ view.content.layout = Some((text, zoom, page_width, draft.rect));+ }+ let r = screen_rect(&xf, info, page, draft.rect);+ let source_rect = draft.index.map(|_| screen_rect(&xf, info, page, draft.style.rect));+ let background_ready = draft.index.is_some_and(|index| view.text_background.ready_added(page, index));let tokens = Tokens::get(ctx);let (mut commit, mut cancel, mut done) = (false, false, false);let mut undrawable = None;let memo = &view.content.undrawable;- egui::Area::new(egui::Id::new(("added-text", view.id.0))).order(egui::Order::Foreground).fixed_pos(r.min).show(ctx, |ui| {+ egui::Area::new(egui::Id::new(("added-text", view.id.0))).order(egui::Order::Foreground).fixed_pos(r.min).constrain(false).show(ctx, |ui| {let Some(t) = view.content.draft.as_mut() else { return };+ ui.set_width(r.width() + 64.0);+ if let Some(source_rect) = source_rect.filter(|_| !background_ready) {+ ui.painter().rect_filled(source_rect.union(r).expand(1.0), CornerRadius::ZERO, Color32::WHITE);+ }// The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655).ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE);let [cr, cg, cb] = t.style.color.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8);@@ -495,10 +536,10 @@ pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, adui.spacing_mut().item_spacing.x = 4.0;let resp = ui.add(egui::TextEdit::multiline(&mut t.text)- .font(egui::FontId::proportional((t.style.size as f32 * zoom).max(8.0)))+ .font(font).desired_width(r.width().max(60.0)).desired_rows(1)- .background_color(Color32::from_rgba_unmultiplied(255, 255, 255, 235))+ .background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE }).text_color(Color32::from_rgb(cr, cg, cb)).hint_text(tl!("Type text")).id_salt("added-text-edit"),@@ -558,7 +599,8 @@ fn finish(cv: &mut ContentView, d: TextDraft, added: &[Added]) -> Option<Edit> {Some(i) => {let (_, a) = on_page(added, d.page).into_iter().find(|(k, _)| *k == i)?;let AddedContent::Text(old) = &a.content else { return None };- (old.text != text).then(|| Edit::UpdateContent { page: d.page, index: i, content: AddedContent::Text(AddedText { text, ..old.clone() }) })+ let updated = AddedText { text, rect: d.rect, ..d.style };+ (*old != updated).then_some(Edit::UpdateContent { page: d.page, index: i, content: AddedContent::Text(updated) })}}}diff --git a/crates/ui-egui/src/edit_text_ui.rs b/crates/ui-egui/src/edit_text_ui.rsindex 3c0c18a5e..d8881ba47 100644--- a/crates/ui-egui/src/edit_text_ui.rs+++ b/crates/ui-egui/src/edit_text_ui.rs@@ -15,11 +15,17 @@ use crate::canvas::{DocView, PageXform};const ACCENT: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);+#[derive(Clone, Copy, PartialEq)]+enum TextTarget {+ Block(usize),+ Added(usize),+}+/// A cached, read-only page background. The source glyphs are removed before rasterization;/// colour, pictures and unselected text beneath the editor remain visible.#[derive(Default)]pub(crate) struct TextBackground {- key: Option<(u64, usize, usize)>,+ key: Option<(u64, usize, TextTarget)>,renderer: Option<pdfcraft_render::RenderPool>,texture: Option<egui::TextureHandle>,tag: Option<u64>,@@ -33,12 +39,26 @@ impl TextBackground {self.renderer.is_some() && self.received != self.tag}- pub fn prepare(&mut self, ctx: &egui::Context, doc: &pdfcraft_engine::Document, editor: Option<&LineEditor>, scale: f32) {- let key = editor.map(|ed| (doc.edit_generation(), ed.page, ed.block));+ pub fn prepare(+ &mut self,+ ctx: &egui::Context,+ doc: &pdfcraft_engine::Document,+ editor: Option<&LineEditor>,+ draft: Option<&crate::content_ui::TextDraft>,+ scale: f32,+ ) {+ let key = editor+ .map(|ed| (doc.edit_generation(), ed.page, TextTarget::Block(ed.block)))+ .or_else(|| draft.and_then(|d| d.index.map(|index| (doc.edit_generation(), d.page, TextTarget::Added(index)))));if self.key != key {*self = Self { key, ..Default::default() };- if let Some((_, page, block)) = key {- self.renderer = doc.text_edit_preview(page, block).ok().map(|p| p.renderer());+ if let Some((_, page, target)) = key {+ self.renderer = match target {+ TextTarget::Block(block) => doc.text_edit_preview(page, block),+ TextTarget::Added(index) => doc.added_text_preview(page, index),+ }+ .ok()+ .map(|p| p.renderer());}}if let Some(ed) = editor {@@ -82,11 +102,26 @@ impl TextBackground {}pub fn ready(&self, page: usize, block: usize) -> bool {- self.key.is_some_and(|(_, p, b)| (p, b) == (page, block)) && self.texture.is_some()+ self.key.is_some_and(|(_, p, target)| (p, target) == (page, TextTarget::Block(block))) && self.texture.is_some()}- pub fn paint(&self, painter: &egui::Painter, xf: &PageXform, page: usize, editor: Option<&LineEditor>) {- let Some(_) = editor.filter(|ed| ed.page == page && self.ready(page, ed.block)) else { return };+ pub fn ready_added(&self, page: usize, index: usize) -> bool {+ self.key.is_some_and(|(_, p, target)| (p, target) == (page, TextTarget::Added(index))) && self.texture.is_some()+ }++ pub fn paint(+ &self,+ painter: &egui::Painter,+ xf: &PageXform,+ page: usize,+ editor: Option<&LineEditor>,+ draft: Option<&crate::content_ui::TextDraft>,+ ) {+ let ready = editor.is_some_and(|ed| ed.page == page && self.ready(page, ed.block))+ || draft.is_some_and(|d| d.page == page && d.index.is_some_and(|index| self.ready_added(page, index)));+ if !ready {+ return;+ }let Some(tex) = &self.texture else { return };// Font metrics can underestimate the actual glyph ink. Paint the complete textless// page so overhanging glyphs cannot remain outside the estimated source rectangle.@@ -273,7 +308,7 @@ fn look_of(b: &pdfcraft_engine::TextBlock) -> pdfcraft_engine::AddedText {source_look(&b.base_font, b.size, b.color, b.bold, b.italic)}-fn editor_font(look: &pdfcraft_engine::AddedText, size: f32) -> FontId {+pub(crate) fn editor_font(look: &pdfcraft_engine::AddedText, size: f32) -> FontId {let family = match (look.family, look.bold) {(pdfcraft_engine::FontFamily::Courier, _) => FontFamily::Monospace,(_, true) => FontFamily::Name("semibold".into()),@@ -1304,7 +1339,7 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -// extent: single rows grow toward the page edge, paragraphs rewrap at their// source width, and the visible frame grows/shrinks vertically with their rows.// An OCR phrase (several stretched words on one scanned line) also grows rightwards.- let single_run = ed.source.as_ref().is_some_and(|(block, _)| block.lines.len() == 1 || block.invisible);+ let single_run = ed.source.as_ref().is_some_and(|(block, _)| block.rows.len() == 1 || block.invisible);let width = if !ed.multiline && single_run && !ed.text.contains('\n') && ed.has_changes() {let job = editor_job(ui, ed, &ed.text, scale, f32::INFINITY);let natural = ui.fonts_mut(|f| f.layout_job(job)).size().x;@@ -1449,7 +1484,7 @@ mod tests {let ctx = egui::Context::default();let mut background = TextBackground::default();for _ in 0..100 {- background.prepare(&ctx, doc, Some(&ed), 1.0);+ background.prepare(&ctx, doc, Some(&ed), None, 1.0);if background.ready(0, 0) {break;}@@ -1458,12 +1493,12 @@ mod tests {assert!(background.ready(0, 0));assert!(!background.pending());let texture = background.texture.as_ref().unwrap().id();- background.prepare(&ctx, doc, Some(&ed), 1.0);+ background.prepare(&ctx, doc, Some(&ed), None, 1.0);assert_eq!(background.texture.as_ref().unwrap().id(), texture);assert_eq!(doc.bytes, source);assert_eq!(doc.edit_generation(), generation);assert!(!doc.dirty && doc.can_undo().is_none());- background.prepare(&ctx, doc, None, 1.0);+ background.prepare(&ctx, doc, None, None, 1.0);assert!(background.texture.is_none() && background.renderer.is_none());}@@ -1478,7 +1513,7 @@ mod tests {let ctx = egui::Context::default();ctx.begin_pass(egui::RawInput { max_texture_side: Some(16384), ..Default::default() });let mut background = TextBackground::default();- background.prepare(&ctx, doc, Some(&ed), 8.0);+ background.prepare(&ctx, doc, Some(&ed), None, 8.0);let expected = 8.0f32.min(crate::canvas::TILE_THRESHOLD / page.width.max(page.height));assert!(expected > crate::canvas::BASE_SIDE / page.width.max(page.height), "the test page needs the larger side");assert_eq!(background.tag, Some((expected * 1000.0) as u64));@@ -1486,7 +1521,7 @@ mod tests {ctx.end_pass().textures_delta.clear();ctx.begin_pass(egui::RawInput { max_texture_side: Some(2048), ..Default::default() });let mut small = TextBackground::default();- small.prepare(&ctx, doc, Some(&ed), 8.0);+ small.prepare(&ctx, doc, Some(&ed), None, 8.0);assert_eq!(small.tag, Some(((2048.0 / page.width.max(page.height)) * 1000.0) as u64));ctx.end_pass().textures_delta.clear();}diff --git a/crates/ui-egui/tests/content.rs b/crates/ui-egui/tests/content.rsindex b656593c4..dd2c032ef 100644--- a/crates/ui-egui/tests/content.rs+++ b/crates/ui-egui/tests/content.rs@@ -76,6 +76,113 @@ fn texts(h: &Harness<'static, PdfCraftApp>) -> Vec<String> {.collect()}+#[test]+fn text_tool_drafts_grow_for_latin_and_arabic() {+ for text in ["Wide words ".repeat(8), "سلام عليكم ".repeat(8)] {+ let mut h = harness();+ assert!(h.state_mut().execute("edit.text"));+ h.run_steps(2);+ let point = at(&h, 40.0, 300.0);+ click(&mut h, point);+ let before = h.state().views[0].content.draft.as_ref().unwrap().rect;+ h.event(egui::Event::Text(text.clone()));+ h.run_steps(4);+ let draft = h.state().views[0].content.draft.as_ref().unwrap();+ assert!(draft.rect[2] - draft.rect[0] > before[2] - before[0] + 10.0, "the editor grows before wrapping: {}", text);+ assert!(draft.rect[2] <= 300.0 && draft.rect[1] < before[1], "the frame stays on the page and grows vertically");+ if let Ok(dir) = std::env::var("PDFCRAFT_SHOTS") {+ let language = if text.starts_with("Wide") { "latin" } else { "arabic" };+ h.render().unwrap().save(format!("{dir}/growing-{language}-text.png")).unwrap();+ }+ h.get_by_label("Done adding text").click();+ h.run_steps(3);+ if text.starts_with("سلام") && pdfcraft_fonts::document_arabic_font().is_none() {+ assert!(h.state().views[0].content.draft.is_some(), "without a document font the draft remains available");+ assert!(added(&h).is_empty());+ continue;+ }+ let pdfcraft_engine::AddedContent::Text(saved) = &added(&h)[0].content else { panic!() };+ assert_eq!(saved.text, text.trim_end());+ assert!(saved.rect[2] - saved.rect[0] > before[2] - before[0] + 10.0, "Save uses the grown width");+ }+}++#[test]+fn text_tool_single_click_retypes_added_text_without_another_item() {+ for command in ["edit.text", "edit.edit_text"] {+ for (original, replacement) in [("Original", "Replacement"), ("سلام", "سلام عليكم ورحمة الله")] {+ if original == "سلام" && pdfcraft_fonts::document_arabic_font().is_none() {+ continue;+ }+ let mut h = harness();+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText {+ page: 0,+ text: pdfcraft_engine::AddedText { rect: [40.0, 195.0, 140.0, 210.0], text: original.into(), ..Default::default() },+ }));+ assert!(h.state_mut().execute(command));+ h.run_steps(3);+ let point = at(&h, 45.0, 195.0);+ click(&mut h, point);+ let draft = h.state().views[0].content.draft.as_ref().expect("one click edits the existing item");+ assert_eq!(draft.index, Some(0));+ assert_eq!(draft.text, original);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.event(egui::Event::Text(replacement.into()));+ h.run_steps(3);+ h.get_by_label("Done adding text").click();+ h.run_steps(3);+ assert_eq!(texts(&h), [replacement]);+ let state = h.state();+ let bytes = state.session.save_bytes(state.views[0].id).unwrap();+ let mut reopened = pdfcraft_engine::Session::new();+ let id = reopened.open("again.pdf", None, bytes, None).unwrap();+ assert_eq!(reopened.get(id).unwrap().added().len(), 1);+ let pdfcraft_engine::AddedContent::Text(text) = &reopened.get(id).unwrap().added()[0].content else { panic!() };+ assert_eq!(text.text, replacement);+ }+ }+}++#[test]+fn text_tool_deleting_a_draft_hides_the_old_added_glyphs_and_cancel_restores_them() {+ let mut h = harness();+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText {+ page: 0,+ text: pdfcraft_engine::AddedText { rect: [40.0, 195.0, 240.0, 220.0], text: "Original glyphs".into(), size: 18.0, ..Default::default() },+ }));+ let bytes = h.state().session.get(h.state().views[0].id).unwrap().bytes.clone();+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(3);+ let point = at(&h, 45.0, 185.0);+ click(&mut h, point);+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);+ h.key_press(egui::Key::Backspace);+ for _ in 0..100 {+ h.run_steps(2);+ if !h.state().render_pending() {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ assert!(h.state().views[0].content.draft.as_ref().unwrap().text.is_empty());+ let shot = h.render().unwrap();+ for x in 105..140 {+ for y in 185..197 {+ let pixel = at(&h, x as f32, y as f32);+ let [r, g, b, a] = shot.get_pixel(pixel.x as u32, pixel.y as u32).0;+ assert!(r > 200 && g > 200 && b > 200 && a == 255, "old glyph ink remains at {x},{y}: {r},{g},{b},{a}");+ }+ }+ if let Ok(dir) = std::env::var("PDFCRAFT_SHOTS") {+ shot.save(format!("{dir}/cleared-added-text.png")).unwrap();+ }+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().bytes, bytes, "previewing does not edit the document");+ h.key_press(egui::Key::Escape);+ h.run_steps(3);+ assert_eq!(texts(&h), ["Original glyphs"]);+ assert!(h.state().views[0].content.draft.is_none());+}+#[test]fn clicking_elsewhere_keeps_the_text_and_starts_a_new_box() {// #74: a click elsewhere on the page threw away the text being typed and opened a new box.diff --git a/crates/ui-egui/tests/editing.rs b/crates/ui-egui/tests/editing.rsindex 883c36722..65b90dad5 100644--- a/crates/ui-egui/tests/editing.rs+++ b/crates/ui-egui/tests/editing.rs@@ -2626,6 +2626,89 @@ fn editing_existing_text_in_place() {assert_eq!(texts_of(s, 0), ["Chapter One"], "the page shows it");}+#[test]+fn text_tool_clicking_source_text_edits_instead_of_adding_a_copy() {+ let mut h = harness(1, |_| {});+ assert!(h.state_mut().execute("edit.text"));+ h.run_steps(2);+ let page = h.state().views[0].page_screen_rect(0).unwrap();+ let blank = egui::pos2(page.left() + 0.2 * page.width(), page.top() + 0.1 * page.height());+ h.hover_at(blank);+ h.run_steps(1);+ h.drag_at(blank);+ h.run_steps(1);+ h.drop_at(blank);+ h.run_steps(3);+ h.event(egui::Event::Text("Keep this note".into()));+ h.run_steps(3);+ let point = egui::pos2(page.left() + 40.0 / 200.0 * page.width(), page.top() + 142.0 / 300.0 * page.height());+ h.hover_at(point);+ h.run_steps(1);+ h.drag_at(point);+ h.run_steps(1);+ h.drop_at(point);+ h.run_steps(4);+ assert!(h.state().views[0].content.draft.is_none(), "clicking source text must not start an added layer");+ assert_eq!(h.state().views[0].line_editor.as_ref().unwrap().text, "Page 1");+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().added().len(), 1, "the previous draft is kept");+ h.key_press_modifiers(Modifiers::COMMAND, Key::A);+ h.event(egui::Event::Text("Replacement".into()));+ h.run_steps(3);+ h.key_press_modifiers(Modifiers::COMMAND, Key::Enter);+ h.run_steps(3);+ assert_eq!(page_texts(h.state()), ["Keep this note\nReplacement"]);+ assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().added().len(), 1, "editing the source adds no second layer");+}++#[test]+fn text_tool_mixed_style_row_grows_in_the_editor_and_saved_pdf() {+ let bytes = source_font_fixture_with_text("BT /F1 12 Tf 20 220 Td (Small ) Tj /F2 12 Tf (row) Tj ET");+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| {+ let mut app = PdfCraftApp::new();+ app.set_option("language", "en").unwrap();+ app.open_bytes("mixed-row.pdf", None, bytes).unwrap();+ app+ });+ h.run_steps(4);+ assert!(h.state_mut().execute("edit.edit_text"));+ h.run_steps(2);+ let page = h.state().views[0].page_screen_rect(0).unwrap();+ let point = egui::pos2(page.left() + 25.0 / 300.0 * page.width(), page.top() + 75.0 / 300.0 * page.height());+ h.hover_at(point);+ h.run_steps(1);+ h.drag_at(point);+ h.run_steps(1);+ h.drop_at(point);+ h.run_steps(4);+ let replacement = "Small row with more words";+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+ h.event(egui::Event::Text(" with more words".into()));+ h.run_steps(4);+ let galley = h+ .output()+ .shapes+ .iter()+ .find_map(|s| match &s.shape {+ egui::Shape::Text(t) if t.galley.text() == replacement => Some(&t.galley),+ _ => None,+ })+ .expect("the draft is painted");+ assert_eq!(galley.rows.len(), 1, "mixed source runs grow as one visual row");+ if let Ok(path) = std::env::var("PDFCRAFT_MIXED_ROW_SHOT") {+ h.render().unwrap().save(path).unwrap();+ }+ h.key_press_modifiers(Modifiers::COMMAND, Key::Enter);+ h.run_steps(3);+ let state = h.state();+ let doc = state.session.get(state.views[0].id).unwrap();+ assert_eq!(doc.text_blocks(0)[0].editor_text, replacement);+ assert_eq!(doc.text_blocks(0)[0].rows.len(), 1);+ let bytes = state.session.save_bytes(state.views[0].id).unwrap();+ let mut reopened = pdfcraft_engine::Session::new();+ let id = reopened.open("again.pdf", None, bytes, None).unwrap();+ assert_eq!(reopened.get(id).unwrap().text_blocks(0)[0].rows.len(), 1);+}+/// One page whose only line is drawn twice at the same spot (fake bold, as many generated/// documents do).fn double_drawn() -> Vec<u8> {diff --git a/docs/editing-existing-text.md b/docs/editing-existing-text.mdindex 50b9261c9..e8bb03b9a 100644--- a/docs/editing-existing-text.md+++ b/docs/editing-existing-text.md@@ -10,6 +10,12 @@ moved because an earlier row wrapped, are rewritten, and formatting a selectiononly the rows it covers. Changing the whole paragraph's formatting, width or position rewritesevery row.+Add Text also opens existing text when it is clicked; a blank-space click starts a new item.+Both text tools retype an added text item with one click. Draft boxes grow to the page edge+before wrapping, and the saved item uses that width. A single visual source row grows across font/style boundaries;+multi-row paragraphs retain their existing wrap width. Retyping uses a preview with only+that added item's old drawing removed, so deleted draft characters do not show underneath.+A subset font contains only some of the original face's glyphs. A new character cannot bereconstructed from a glyph the PDF does not contain. **Load font…** imports an openly licensed,embeddable standalone `.ttf` or `.otf` face. **Installed fonts…** discovers eligible user-installeddiff --git a/docs/roadmap.md b/docs/roadmap.mdindex 0316ccf22..e6a5ce039 100644--- a/docs/roadmap.md+++ b/docs/roadmap.md@@ -178,6 +178,7 @@ M2 (renderer), M7 (content editing), M10 (OCR and Office), M11 (Preflight and st| Date | Change | Summary ||---|---|---|+| 2026-10-12 | minor | M7 local candidate: text drafts grow and save their width; single visual rows grow across style boundaries; both text tools retype added items and Add Text edits source text. Added-item textless previews are read-only and covered by UI/tool regressions. Estimates unchanged. || 2026-10-12 | minor | M14/#1395: XDG configuration preferences, safe migration and fallback; logs/recovery retain data locations, portable/non-XDG unchanged. Estimates unchanged. || 2026-10-12 | minor | M6: XFDF field import and data extraction preserve all text around XML comments and processing instructions; synthetic save/reopen regressions. Estimates unchanged. || 2026-10-12 | minor | M2: preserve whitespace-bounded EI bytes in known unfiltered inline images; row padding, masks and aliases tested, with independent saved-PDF pixel checks. Estimates unchanged. |