PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M7: align the selected lines of a paragraph or text box on their own
RiceDee5c1c3462eb42
diff --git a/crates/automation/src/content.rs b/crates/automation/src/content.rsindex 8926a1368..c162e739d 100644--- a/crates/automation/src/content.rs+++ b/crates/automation/src/content.rs@@ -53,17 +53,48 @@ fn style(a: &Args, t: &mut AddedText) -> Result<()> {t.color = parse_color(c)?;}if let Some(al) = a.opt_str("align")? {- t.align = match al {- "left" => TextAlign::Left,- "center" | "centre" => TextAlign::Center,- "right" => TextAlign::Right,- "justify" => TextAlign::Justify,- other => return Err(bad(format!("unknown align {other:?}"))),- };+ t.align = parse_align(al)?;+ // The whole box: no paragraph keeps an alignment of its own unless `aligns` gives it one.+ t.aligns.clear();+ }+ if let Some(aligns) = opt_aligns(a)? {+ let count = pdfcraft_engine::paragraph_align::count(&t.text);+ t.aligns = pdfcraft_engine::paragraph_align::tidy(aligns.into_iter().take(count).collect(), t.align);}Ok(())}+pub(crate) fn parse_align(al: &str) -> Result<TextAlign> {+ Ok(match al {+ "left" => TextAlign::Left,+ "center" | "centre" => TextAlign::Center,+ "right" => TextAlign::Right,+ "justify" => TextAlign::Justify,+ other => return Err(bad(format!("unknown align {other:?}"))),+ })+}++/// Most entries `aligns` takes: one per paragraph, and no text has this many.+const MAX_ALIGNS: usize = 4096;++/// `aligns`: each paragraph's (line's) own alignment, or null where it follows `align`.+pub(crate) fn opt_aligns(a: &Args) -> Result<Option<Vec<Option<TextAlign>>>> {+ let Some(v) = a.get("aligns") else { return Ok(None) };+ let items = v.as_array().ok_or_else(|| bad("aligns must be an array of left, center, right, justify or null"))?;+ if items.len() > MAX_ALIGNS {+ return Err(bad(format!("aligns takes at most {MAX_ALIGNS} entries")));+ }+ items+ .iter()+ .map(|v| match v {+ Value::Null => Ok(None),+ Value::String(s) => parse_align(s).map(Some),+ _ => Err(bad("each entry of aligns is left, center, right, justify or null")),+ })+ .collect::<Result<Vec<_>>>()+ .map(Some)+}+impl Automation {pub(crate) fn content_list(&self, a: &Args) -> Result<Value> {let doc = self.doc(a)?;@@ -153,6 +184,8 @@ impl Automation {match &mut content {AddedContent::Text(t) => {if let Some(s) = a.opt_str("text")? {+ // Each paragraph keeps its own alignment through the retyping.+ t.aligns = pdfcraft_engine::paragraph_align::remap(&t.text, s, &t.aligns);t.text = s.to_string();}style(a, t)?;@@ -164,8 +197,8 @@ impl Automation {if a.get("text").is_some() {return Err(bad("images have no text"));}- if ["font", "size", "bold", "italic", "color", "align"].iter().any(|k| a.get(k).is_some()) {- return Err(bad("font, size, bold, italic, color and align apply to text"));+ if ["font", "size", "bold", "italic", "color", "align", "aligns"].iter().any(|k| a.get(k).is_some()) {+ return Err(bad("font, size, bold, italic, color, align and aligns apply to text"));}if let Some(deg) = a.opt_int("rotate")? {if deg.rem_euclid(90) != 0 {diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rsindex 1dae412e4..8c5ae96bc 100644--- a/crates/automation/src/lib.rs+++ b/crates/automation/src/lib.rs@@ -726,13 +726,10 @@ impl Automation {style.color = Some(comments::parse_color(c)?);}if let Some(al) = a.opt_str("align")? {- style.align = Some(match al {- "left" => pdfcraft_engine::TextAlign::Left,- "center" => pdfcraft_engine::TextAlign::Center,- "right" => pdfcraft_engine::TextAlign::Right,- "justify" => pdfcraft_engine::TextAlign::Justify,- other => return Err(ToolError::InvalidArgs(format!("unknown align {other:?}"))),- });+ style.align = Some(content::parse_align(al)?);+ }+ if let Some(aligns) = content::opt_aligns(&a)? {+ style.aligns = aligns;}// Where the paragraph is drawn after the edit: moved by dx, dy (up is +dy).let [dx, dy] = style.offset.unwrap_or([0.0, 0.0]);diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex 1e009c117..db521074d 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -594,6 +594,7 @@ pub fn tools() -> Vec<ToolDef> {"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },+ "aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },}),&["doc", "page", "text"],)),@@ -615,6 +616,7 @@ pub fn tools() -> Vec<ToolDef> {"font": { "type": "string", "enum": ["helvetica", "times", "courier"] }, "size": { "type": "number", "minimum": 1, "maximum": 500 },"bold": { "type": "boolean" }, "italic": { "type": "boolean" }, "color": { "type": "string" },"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },+ "aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },"rotate": { "type": "integer" }, "flip_h": { "type": "boolean" }, "flip_v": { "type": "boolean" },"crop": { "type": "array", "items": { "type": "number", "minimum": 0, "maximum": 0.49 }, "minItems": 4, "maxItems": 4 },"image": { "type": "string", "description": "Replace the picture with this file." },@@ -1362,6 +1364,7 @@ pub fn tools() -> Vec<ToolDef> {"size": { "type": "number", "exclusiveMinimum": 0 },"color": { "type": "string", "description": "#rrggbb" },"align": { "type": "string", "enum": ["left", "center", "right", "justify"] },+ "aligns": { "type": "array", "maxItems": 4096, "items": { "enum": ["left", "center", "right", "justify", null] }, "description": "Each paragraph's (line's) own alignment, by index; null follows align." },"underline": { "type": "boolean" },"line_spacing": { "type": "number", "description": "Multiple of the font size (1.2 is ordinary)." },"dx": { "type": "number", "description": "Paragraph only: move right by this many points (negative: left)." },diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rsindex 9fd5c4269..5b8931c6a 100644--- a/crates/automation/tests/it/automation.rs+++ b/crates/automation/tests/it/automation.rs@@ -8424,3 +8424,26 @@ fn bookmark_list_reports_colour_and_style() {let re = ok(&mut b, "doc_open", json!({ "path": "restyled.pdf" }))["doc"].as_u64().unwrap();assert_eq!(style(&ok(&mut b, "bookmark_list", json!({ "doc": re }))["bookmarks"]), style(&set), "saved");}++/// `aligns` gives each line of added text an alignment of its own; `align` alone is the whole box+/// again. Text edits take `aligns` for a paragraph's rows the same way.+#[test]+fn added_text_lines_take_their_own_alignments() {+ let dir = workdir("paragraph-aligns");+ let mut a = auto(&dir);+ let id = ok(&mut a, "doc_create", json!({"from":"blank","width":600,"height":400}))["doc"].as_u64().unwrap();+ ok(&mut a, "page_add_text", json!({"doc":id,"page":1,"text":"Left line\nRight line","at":[40,50],"width":500,"size":12,"aligns":[null,"right"]}));+ let rect = |a: &mut Automation, text: &str| -> Vec<f64> {+ let lines = ok(a, "text_lines", json!({"doc":id,"page":1}));+ let line = lines["lines"].as_array().unwrap().iter().find(|l| l["text"] == text).cloned().unwrap();+ line["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect()+ };+ assert!((rect(&mut a, "Left line")[0] - 40.0).abs() < 1.0);+ assert!((rect(&mut a, "Right line")[2] - 540.0).abs() < 1.0, "{:?}", rect(&mut a, "Right line"));+ // The whole box centred: the right-aligned line goes with it.+ ok(&mut a, "content_update", json!({"doc":id,"page":1,"index":1,"align":"center"}));+ let right = rect(&mut a, "Right line");+ assert!(((right[0] + right[2]) / 2.0 - 290.0).abs() < 1.0, "{right:?}");+ assert!(a.call("content_update", &json!({"doc":id,"page":1,"index":1,"aligns":["sideways"]})).is_err());+ assert!(a.call("content_update", &json!({"doc":id,"page":1,"index":1,"aligns":"right"})).is_err());+}diff --git a/crates/edit/src/added.rs b/crates/edit/src/added.rsindex d39bb0fa9..29ccc4e8c 100644--- a/crates/edit/src/added.rs+++ b/crates/edit/src/added.rs@@ -116,6 +116,16 @@ pub struct AddedText {pub size: f64,pub color: [f64; 3],pub align: Align,+ /// Paragraphs (lines typed with Enter) aligned other than [`AddedText::align`], by index;+ /// `None` and paragraphs past the end follow `align` ([`crate::paragraph_align`]).+ pub aligns: Vec<Option<Align>>,+}++impl AddedText {+ /// Paragraph `i`'s alignment.+ pub fn paragraph_align(&self, i: usize) -> Align {+ crate::paragraph_align::align_of(&self.aligns, i, self.align)+ }}impl Default for AddedText {@@ -129,6 +139,7 @@ impl Default for AddedText {size: 12.0,color: [0.0; 3],align: Align::Left,+ aligns: Vec::new(),}}}@@ -232,7 +243,7 @@ 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()+ wrapped(t).into_iter().map(|(line, ..)| line).collect()}#[cfg(test)]@@ -242,13 +253,13 @@ thread_local! {}/// [`lines`], each with whether its paragraph runs right to left (its first strong character-/// does).-fn wrapped(t: &AddedText) -> Vec<(String, bool)> {+/// does) and which paragraph it is in.+fn wrapped(t: &AddedText) -> Vec<(String, bool, usize)> {#[cfg(test)]WRAP_CALLS.with(|c| c.set(c.get().saturating_add(1)));let width = (t.rect[2] - t.rect[0]).max(t.size);let mut out = Vec::new();- for para in t.text.split('\n') {+ for (index, para) in t.text.split('\n').enumerate() {// Arabic or Hebrew: laid out with the bidirectional algorithm and shaped.let rtl_script = para.chars().any(|c| is_arabic(c) || is_hebrew(c));let thai = para.chars().any(is_thai);@@ -256,7 +267,7 @@ fn wrapped(t: &AddedText) -> Vec<(String, bool)> {&& !rtl_script&& let Ok(lines) = thai_lines(t, para, width){- out.extend(lines.into_iter().map(|line| (line, false)));+ out.extend(lines.into_iter().map(|line| (line, false, index)));continue;}let rtl = rtl_script && unicode_bidi::get_base_direction(para) == unicode_bidi::Direction::Rtl;@@ -272,7 +283,7 @@ fn wrapped(t: &AddedText) -> Vec<(String, bool)> {let candidate_w =if rtl_script || thai { 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));+ out.push((std::mem::take(&mut line), rtl, index));line = word.to_string();line_w = measure(word);} else {@@ -280,7 +291,7 @@ fn wrapped(t: &AddedText) -> Vec<(String, bool)> {line_w = candidate_w;}}- out.push((line, rtl));+ out.push((line, rtl, index));}out}@@ -354,7 +365,7 @@ pub fn first_undrawable(t: &AddedText) -> Option<char> {return t.text.split('\n').find_map(pdfcraft_fonts::first_non_win_ansi);}// What `shaped_layout` leaves to the standard font, exactly as `draw_shaped` splits it.- wrapped(t).into_iter().find_map(|(line, rtl)| {+ wrapped(t).into_iter().find_map(|(line, rtl, _)| {let (pieces, _) = shaped_layout(t, &line, rtl).ok()?;pieces.iter().find_map(|p| match p {Piece::Latin(s) => pdfcraft_fonts::first_non_win_ansi(s),@@ -523,8 +534,26 @@ fn font_name(base: &str) -> String {const GLYPHS_PER_FONT: usize = 240;/// A line of a shaped-text item after layout: its text, whether its paragraph runs right to left,-/// its pieces in drawing order and its width at the item's size.-type LaidLine = (String, bool, Vec<Piece>, f64);+/// its paragraph, its pieces in drawing order and its width at the item's size.+type LaidLine = (String, bool, usize, Vec<Piece>, f64);++/// Where line `i` (`w` wide unstretched, with `spaces` spaces) starts in the box `r`, and its word+/// spacing. `paragraphs` holds each line's paragraph: a line takes its paragraph's alignment, and+/// every line of a justified paragraph but its last is stretched to the box's width.+fn placed(t: &AddedText, r: [f64; 4], paragraphs: &[usize], i: usize, w: f64, spaces: usize, rtl: bool) -> (f64, f64) {+ let paragraph = paragraphs.get(i).copied().unwrap_or(0);+ let align = t.paragraph_align(paragraph);+ let ends_paragraph = paragraphs.get(i + 1) != Some(¶graph);+ let tw = if align == Align::Justify && !ends_paragraph && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };+ let x = match 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,+ };+ (x, tw)+}/// Draw a text item that has Arabic, Hebrew or Thai in it. Each line is laid out in display order; their glyphs/// come from Type 3 fonts drawn from the craft-fonts face's outlines (no font file is embedded),@@ -532,7 +561,7 @@ type LaidLine = (String, bool, Vec<Piece>, f64);fn draw_shaped(doc: &mut Document, t: &AddedText, taken: &Dict, fonts: &mut Dict, out: &mut Vec<u8>) -> Result<(), EditError> {let laid = wrapped(t).into_iter()- .map(|(line, rtl)| shaped_layout(t, &line, rtl).map(|(pieces, w)| (line, rtl, pieces, w)))+ .map(|(line, rtl, paragraph)| shaped_layout(t, &line, rtl).map(|(pieces, w)| (line, rtl, paragraph, pieces, w))).collect::<Result<Vec<_>, _>>()?;draw_laid_shaped(doc, t, &laid, taken, fonts, out, shaped_glyph)}@@ -554,7 +583,7 @@ fn draw_laid_shaped(// 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 {+ for c in laid.iter().flat_map(|(_, _, _, pieces, _)| pieces).flat_map(|p| match p {Piece::Shaped(clusters) => clusters.as_slice(),Piece::Latin(_) => &[],}) {@@ -596,21 +625,14 @@ fn draw_laid_shaped(}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 laid.iter().enumerate() {+ let paragraphs: Vec<usize> = laid.iter().map(|(_, _, p, ..)| *p).collect();+ for (i, (line, rtl, _, pieces, w)) in laid.iter().enumerate() {// Shaped glyphs are painted in visual order. Keep the original line's typing order// explicitly, including marks, ligatures, digits and mixed-script punctuation.let logical: String = line.encode_utf16().map(|u| format!("{u:04X}")).collect();out.extend(format!("/Span <</ActualText <FEFF{logical}>>> BDC\n").bytes());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 < laid.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 (x, tw) = placed(t, r, ¶graphs, i, *w, spaces, *rtl);let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;let mut pen = x;let mut current: Option<&str> = None;@@ -788,20 +810,14 @@ fn draw(doc: &mut Document, c: &Content, view: [f64; 6], taken: &Dict, existing:let r = text_rect(t);let [cr, cg, cb] = t.color.map(|v| v.clamp(0.0, 1.0));out.extend(format!("BT /{name} {} Tf {} {} {} rg\n", n(t.size), n(cr), n(cg), n(cb)).bytes());- let all = lines(t);- for (i, line) in all.iter().enumerate() {+ let all = wrapped(t);+ let paragraphs: Vec<usize> = all.iter().map(|(_, _, p)| *p).collect();+ for (i, (line, ..)) in all.iter().enumerate() {let w = t.family.width(line, t.size, t.bold, t.italic);- let x = match t.align {- Align::Left | Align::Justify => r[0],- Align::Center => r[0] + ((r[2] - r[0]) - w) / 2.0,- Align::Right => r[2] - w,- };// Baseline: 0.8 em below the line top.let y = r[3] - (i as f64 * 1.2 + 0.95) * t.size;- // Justified: word spacing makes every line but the last fill the box.- let spaces = line.matches(' ').count();- let tw =- if t.align == Align::Justify && i + 1 < all.len() && spaces > 0 { ((r[2] - r[0]) - w).max(0.0) / spaces as f64 } else { 0.0 };+ // Justified: word spacing makes every line of a paragraph but its last fill the box.+ let (x, tw) = placed(t, r, ¶graphs, i, w, line.matches(' ').count(), false);out.extend(format!("1 0 0 1 {} {} Tm {} Tw ", n(x), n(y), n(tw)).bytes());out.extend(literal(&win_ansi(line)));out.extend_from_slice(b" Tj\n");@@ -851,15 +867,12 @@ fn params(c: &Content) -> Dict {d.set(b"Font".to_vec(), Object::name(t.family.base_font(t.bold, t.italic)));d.set(b"Size".to_vec(), Object::Real(t.size));d.set(b"Color".to_vec(), arr(&t.color));- d.set(- b"Align".to_vec(),- Object::Int(match t.align {- Align::Left => 0,- Align::Center => 1,- Align::Right => 2,- Align::Justify => 3,- }),- );+ d.set(b"Align".to_vec(), Object::Int(align_code(t.align)));+ // Each paragraph's own alignment, or null where it follows /Align.+ let aligns = crate::paragraph_align::tidy(t.aligns.clone(), t.align);+ if !aligns.is_empty() {+ d.set(b"Aligns".to_vec(), Object::Array(aligns.iter().map(|a| a.map_or(Object::Null, |a| Object::Int(align_code(a)))).collect()));+ }d.set(b"Rect".to_vec(), arr(&text_rect(t)));}Content::Image(i) => {@@ -883,6 +896,24 @@ fn params(c: &Content) -> Dict {d}+fn align_code(a: Align) -> i64 {+ match a {+ Align::Left => 0,+ Align::Center => 1,+ Align::Right => 2,+ Align::Justify => 3,+ }+}++fn align_from(code: Option<i64>) -> Align {+ match code {+ Some(1) => Align::Center,+ Some(2) => Align::Right,+ Some(3) => Align::Justify,+ _ => Align::Left,+ }+}+fn parse(doc: &Document, d: &Dict) -> Option<Content> {let r = nums(doc, d.get(b"Rect"));let rect: [f64; 4] = r.try_into().ok()?;@@ -890,20 +921,27 @@ fn parse(doc: &Document, d: &Dict) -> Option<Content> {b"Text" => {let (family, bold, italic) = Family::from_base(d.name(b"Font").unwrap_or(b"Helvetica"));let c = nums(doc, d.get(b"Color"));+ let text = d.get(b"Text").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default();+ let align = align_from(d.int(b"Align"));+ // At most one entry per paragraph, whatever the file says.+ let aligns = d+ .get(b"Aligns")+ .and_then(|a| {+ doc.resolve(a)+ .as_array()+ .map(|a| a.iter().take(crate::paragraph_align::count(&text)).map(|v| v.as_int().map(|c| align_from(Some(c)))).collect())+ })+ .unwrap_or_default();Some(Content::Text(AddedText {rect,- text: d.get(b"Text").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default(),+ text,family,bold,italic,size: d.get(b"Size").and_then(Object::as_f64).unwrap_or(12.0),color: if c.len() == 3 { [c[0], c[1], c[2]] } else { [0.0; 3] },- align: match d.int(b"Align") {- Some(1) => Align::Center,- Some(2) => Align::Right,- Some(3) => Align::Justify,- _ => Align::Left,- },+ align,+ aligns: crate::paragraph_align::tidy(aligns, align),}))}b"Image" => {diff --git a/crates/edit/src/added/arabic_tests.rs b/crates/edit/src/added/arabic_tests.rsindex d4ebb73e4..0671e3ce3 100644--- a/crates/edit/src/added/arabic_tests.rs+++ b/crates/edit/src/added/arabic_tests.rs@@ -24,7 +24,7 @@ fn cluster(id: u32, advance: f64) -> ShapedCluster {fn line(clusters: Vec<ShapedCluster>, rtl: bool) -> LaidLine {let text = clusters.iter().map(|c| c.text.as_str()).collect();let width = clusters.iter().map(|c| c.advance).sum::<f64>() * item().size;- (text, rtl, vec![Piece::Shaped(clusters)], width)+ (text, rtl, 0, vec![Piece::Shaped(clusters)], width)}/// A glyph outline: a box on the baseline, `advance` em wide.@@ -147,7 +147,7 @@ fn an_item_below_the_old_limit_is_drawn_exactly_as_before() {let space = ShapedCluster { script: ShapedScript::Arabic, glyphs: vec![(6, [0.0, 0.0])], advance: 0.25, text: " ".into() };let ligature = ShapedCluster { script: ShapedScript::Arabic, glyphs: vec![(4, [0.0, 0.0]), (5, [-0.1, 0.2])], advance: 0.6, text: "لا".into() };let mixed: LaidLine =- ("Hi ب".into(), false, vec![Piece::Latin("Hi ".into()), Piece::Shaped(vec![cluster(1, 0.5), cluster(2, 0.5), space, ligature])], 4.0);+ ("Hi ب".into(), false, 0, vec![Piece::Latin("Hi ".into()), Piece::Shaped(vec![cluster(1, 0.5), cluster(2, 0.5), space, ligature])], 4.0);let rtl = line(vec![cluster(2, 0.5), cluster(9, 0.75)], true);let laid = vec![mixed, rtl];let mut doc = Document::new_empty();diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rsindex 630f12550..f367b39d8 100644--- a/crates/edit/src/lib.rs+++ b/crates/edit/src/lib.rs@@ -1031,6 +1031,7 @@ pub use images::{ImageChange, PageImage, change_image, page_images, reading_imagpub mod bidi;pub mod indic;mod linebreak;+pub mod paragraph_align;pub mod text;pub use text::{BlockKey, BlockStyle, LineEdit, MAX_FORM_DEPTH, MAX_FORM_VISITS, RangeStyle, ReadingBlocks, TextBlock, TextLine, TextSession, block_overlapping,diff --git a/crates/edit/src/paragraph_align.rs b/crates/edit/src/paragraph_align.rsnew file mode 100644index 000000000..cf2023e61--- /dev/null+++ b/crates/edit/src/paragraph_align.rs@@ -0,0 +1,135 @@+//! Alignment paragraph by paragraph. A paragraph is the text between two hard line breaks+//! (`\n`): a line typed with Enter in added text, or a source row of an edited paragraph. Each can+//! have an alignment of its own; `None` (or no entry) follows the box's or paragraph's alignment.++use std::ops::RangeInclusive;++use crate::added::Align;++/// How many paragraphs `text` has (an empty text has one).+pub fn count(text: &str) -> usize {+ text.bytes().filter(|b| *b == b'\n').count().saturating_add(1)+}++/// The paragraph the byte position `at` of `text` is in.+fn paragraph_at(text: &str, at: usize) -> usize {+ let bytes = text.as_bytes();+ bytes.get(..at.min(bytes.len())).unwrap_or_default().iter().filter(|b| **b == b'\n').count()+}++/// The paragraphs a selection (byte range) of `text` touches. An empty selection is the caret's+/// paragraph; a selection ending just after a line break doesn't reach the next paragraph.+pub fn selected(text: &str, range: std::ops::Range<usize>) -> RangeInclusive<usize> {+ let first = paragraph_at(text, range.start);+ let last = if range.end > range.start { paragraph_at(text, range.end - 1) } else { first };+ first..=last.max(first)+}++/// Paragraph `i`'s alignment: its own, or `base`.+pub fn align_of(aligns: &[Option<Align>], i: usize, base: Align) -> Align {+ aligns.get(i).copied().flatten().unwrap_or(base)+}++/// Give paragraphs `which` of a text with `count` paragraphs the alignment `align`; the others+/// keep theirs. With a `base`, entries equal to it become `None` ([`tidy`]), so equal alignments+/// compare equal however they were set; without one (the base is only guessed, as for an edited+/// paragraph's own rows) every entry set stays. Trailing `None`s are dropped either way.+pub fn set(aligns: &[Option<Align>], count: usize, which: RangeInclusive<usize>, align: Align, base: Option<Align>) -> Vec<Option<Align>> {+ let mut out: Vec<Option<Align>> = (0..count).map(|i| aligns.get(i).copied().flatten()).collect();+ for i in which {+ if let Some(a) = out.get_mut(i) {+ *a = Some(align);+ }+ }+ match base {+ Some(base) => tidy(out, base),+ None => trimmed(out),+ }+}++/// `aligns` without entries that only repeat `base`, and without trailing `None`s.+pub fn tidy(mut aligns: Vec<Option<Align>>, base: Align) -> Vec<Option<Align>> {+ for a in &mut aligns {+ if *a == Some(base) {+ *a = None;+ }+ }+ trimmed(aligns)+}++fn trimmed(mut aligns: Vec<Option<Align>>) -> Vec<Option<Align>> {+ while aligns.last() == Some(&None) {+ aligns.pop();+ }+ aligns+}++/// Carry the alignments of `old`'s paragraphs over to `new`: the paragraphs before and after+/// the change keep theirs, and the paragraphs the change made take the alignment of the first+/// paragraph it changed, or for lines only inserted, of the paragraph before them (so Enter in or+/// after a centred paragraph makes centred ones).+pub fn remap(old: &str, new: &str, aligns: &[Option<Align>]) -> Vec<Option<Align>> {+ if aligns.is_empty() || old == new {+ return aligns.to_vec();+ }+ let (o, n): (Vec<&str>, Vec<&str>) = (old.split('\n').collect(), new.split('\n').collect());+ let shortest = o.len().min(n.len());+ let prefix = o.iter().zip(&n).take_while(|(a, b)| a == b).count().min(shortest);+ let suffix = o.iter().rev().zip(n.iter().rev()).take_while(|(a, b)| a == b).count().min(shortest - prefix);+ let at = |i: usize| aligns.get(i).copied().flatten();+ let inserted_only = o.len() - prefix - suffix == 0;+ let changed = if inserted_only && prefix > 0 { at(prefix - 1) } else { at(prefix) };+ let mut out: Vec<Option<Align>> = (0..prefix).map(at).collect();+ out.extend(std::iter::repeat_n(changed, n.len() - prefix - suffix));+ out.extend((o.len() - suffix..o.len()).map(at));+ trimmed(out)+}++#[cfg(test)]+mod tests {+ use super::*;+ use Align::*;++ #[test]+ fn a_selection_names_the_paragraphs_it_touches() {+ let text = "One\nTwo\nThree";+ assert_eq!(count(text), 3);+ assert_eq!(count(""), 1);+ assert_eq!(selected(text, 0..0), 0..=0, "the caret's paragraph");+ assert_eq!(selected(text, 5..6), 1..=1);+ assert_eq!(selected(text, 2..9), 0..=2);+ assert_eq!(selected(text, 4..8), 1..=1, "a whole line with its break stays on that line");+ assert_eq!(selected(text, 0..999), 0..=2, "past the end is clamped");+ // Not a character boundary: still counted by bytes, never a panic.+ assert_eq!(selected("é\nb", 1..1), 0..=0);+ }++ #[test]+ fn setting_one_paragraph_keeps_the_others_and_tidies() {+ let one = set(&[], 3, 1..=1, Center, Some(Left));+ assert_eq!(one, [None, Some(Center)]);+ assert_eq!(align_of(&one, 0, Left), Left);+ assert_eq!(align_of(&one, 1, Left), Center);+ assert_eq!(align_of(&one, 9, Right), Right);+ assert_eq!(set(&one, 3, 1..=1, Left, Some(Left)), [], "back to the box's alignment is no entry at all");+ assert_eq!(set(&one, 3, 2..=7, Right, Some(Left)), [None, Some(Center), Some(Right)], "paragraphs past the end are ignored");+ assert_eq!(set(&[Some(Right); 9], 2, 0..=0, Center, Some(Left)), [Some(Center), Some(Right)], "entries past the text are dropped");+ assert_eq!(set(&[], 3, 0..=0, Left, None), [Some(Left)], "without a base, an explicit entry stays");+ }++ #[test]+ fn alignments_follow_their_paragraphs_through_an_edit() {+ let aligns = [Some(Center), None, Some(Right)];+ assert_eq!(remap("A\nB\nC", "A\nB\nC", &aligns), aligns);+ // A line inserted before the last keeps the last right-aligned.+ assert_eq!(remap("A\nB\nC", "A\nB\nnew\nC", &aligns), [Some(Center), None, None, Some(Right)]);+ // Enter inside the centred first paragraph: both halves are centred.+ assert_eq!(remap("Ab\nB\nC", "A\nb\nB\nC", &aligns), [Some(Center), Some(Center), None, Some(Right)]);+ // The middle paragraph deleted.+ assert_eq!(remap("A\nB\nC", "A\nC", &aligns), [Some(Center), Some(Right)]);+ // Everything replaced takes the first changed paragraph's alignment.+ assert_eq!(remap("A\nB", "x", &[None, Some(Right)]), []);+ assert_eq!(remap("A\nA", "A", &[Some(Center), Some(Right)]), [Some(Center)]);+ assert_eq!(remap("A", "A\nA", &[Some(Center)]), [Some(Center), Some(Center)]);+ }+}diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex 0549906db..692a21c8c 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -6638,3 +6638,74 @@ fn a_flatten_refused_on_a_later_page_changes_nothing() {assert!(matches!(flatten(&mut doc, &[0, 1], true, false), Err(EditError::Invalid(_))));assert_eq!((*doc.get(first)).clone(), before, "the first page keeps its comment and content");}++/// One row of an edited paragraph aligned on its own (#A: highlighting a line and aligning it):+/// the other rows stay where they were.+#[test]+fn one_row_of_a_paragraph_takes_its_own_alignment() {+ let mut doc = text_page("BT /F1 10 Tf 12 TL 100 700 Td (One two three four five six seven) Tj T* (eight nine ten eleven twelve) Tj ET");+ let block = text::text_blocks(&doc, 0).unwrap()[0].clone();+ assert_eq!(block.editor_text, "One two three four five six seven\neight nine ten eleven twelve");+ let style = text::BlockStyle { aligns: vec![None, Some(added::Align::Right)], ..Default::default() };+ text::rewrite_block(&mut doc, 0, 0, Some(&block.editor_text), &style).unwrap();+ let lines = text::text_lines(&doc, 0).unwrap();+ let row = |t: &str| lines.iter().find(|l| l.text.starts_with(t)).unwrap().rect;+ assert!((row("One")[0] - block.rect[0]).abs() < 0.5, "the first row stays at the left: {:?}", row("One"));+ assert!((row("eight")[2] - block.rect[2]).abs() < 1.0, "the second row ends at the right edge: {:?} vs {}", row("eight"), block.rect[2]);+}++/// The same in a region of several styles: only the short first row is centred.+#[test]+fn one_row_of_a_styled_region_takes_its_own_alignment() {+ let mut doc = mixed_region_page();+ let block = text::text_blocks(&doc, 0).unwrap()[1].clone();+ assert_eq!(+ block.editor_text,+ "About+Plain bold text.+Italic footer"+ );+ let row = |lines: &[text::TextLine], t: &str| lines.iter().find(|l| l.text.starts_with(t)).unwrap().rect;+ let before = text::text_lines(&doc, 0).unwrap();+ let style = text::BlockStyle { aligns: vec![Some(added::Align::Center)], ..Default::default() };+ text::rewrite_block(&mut doc, 0, 1, Some(&block.editor_text), &style).unwrap();+ let lines = text::text_lines(&doc, 0).unwrap();+ assert!((row(&lines, "Italic")[0] - row(&before, "Italic")[0]).abs() < 0.5, "the last row stays put");+ assert!((row(&lines, "Plain")[0] - row(&before, "Plain")[0]).abs() < 0.5, "the middle row stays put");+ let about = row(&lines, "About");+ let (mid, centre) = ((about[0] + about[2]) / 2.0, (block.rect[0] + block.rect[2]) / 2.0);+ assert!(about[0] > row(&before, "About")[0] + 5.0 && (mid - centre).abs() < 1.5, "the first row is centred: {mid} vs {centre}");+}++/// Added text: each paragraph is laid out with its own alignment, a justified paragraph's last+/// line isn't stretched, and the alignments survive saving and reopening.+#[test]+fn added_text_paragraphs_keep_their_own_alignments() {+ let mut doc = fixture();+ let text = AddedText {+ rect: [72.0, 600.0, 372.0, 700.0],+ text: "Left line\nRight line\nCentred line".into(),+ size: 12.0,+ aligns: vec![None, Some(Align::Right), Some(Align::Center)],+ ..AddedText::default()+ };+ assert_eq!(text.paragraph_align(1), Align::Right);+ add_content(&mut doc, 0, &Content::Text(text.clone())).unwrap();+ let doc = reopen(&doc);+ let Content::Text(t) = &list_added(&doc)[0].content else { panic!() };+ assert_eq!(t.aligns, text.aligns, "saved with the item");+ let page = streams(&doc, 0).join("\n");+ let x_of = |s: &str| -> f64 {+ let at = page.find(&format!("({s}) Tj")).unwrap();+ let tm = page[..at].rfind(" Tm").unwrap();+ let nums: Vec<f64> = page[..tm].rsplit("1 0 0 1 ").next().unwrap().split_whitespace().filter_map(|v| v.parse().ok()).collect();+ nums[0]+ };+ let w = |s: &str| Family::Helvetica.width(s, 12.0, false, false);+ assert!((x_of("Left line") - 72.0).abs() < 0.01);+ assert!((x_of("Right line") - (372.0 - w("Right line"))).abs() < 0.01);+ assert!((x_of("Centred line") - (72.0 + (300.0 - w("Centred line")) / 2.0)).abs() < 0.01);+ // A paragraph's own alignment the same as the box's is no entry at all.+ let tidy = paragraph_align::tidy(vec![Some(Align::Left), Some(Align::Right)], Align::Left);+ assert_eq!(tidy, [None, Some(Align::Right)]);+}diff --git a/crates/edit/src/text.rs b/crates/edit/src/text.rsindex d00393531..3ce185a98 100644--- a/crates/edit/src/text.rs+++ b/crates/edit/src/text.rs@@ -2565,10 +2565,10 @@ fn paragraph_separator(c: char) -> bool {/// Greedy word wrapping to `width` with `advance` giving a string's width. Each `\n` starts a/// new line. A row may also end inside a word of Chinese or Japanese text ([`crate::linebreak`]);-/// those pieces join without a space.-fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {+/// those pieces join without a space. Each line comes with the `\n`-separated row it is from.+fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<(String, usize)> {let mut out = Vec::new();- for row in text.split('\n') {+ for (index, row) in text.split('\n').enumerate() {let mut line = String::new();let start = out.len();for word in row.split(paragraph_separator).filter(|word| !word.is_empty()) {@@ -2579,7 +2579,7 @@ fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {(false, _) => format!("{line}{piece}"),};if !line.is_empty() && advance(&candidate) > width {- out.push(std::mem::take(&mut line));+ out.push((std::mem::take(&mut line), index));line = piece.to_string();} else {line = candidate;@@ -2587,7 +2587,7 @@ fn wrap(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Vec<String> {}}if !line.is_empty() || out.len() == start {- out.push(line);+ out.push((line, index));}}out@@ -2616,6 +2616,9 @@ pub struct BlockStyle {/// Fill colour (RGB 0–1).pub color: Option<[f64; 3]>,pub align: Option<crate::added::Align>,+ /// Rows (the text's lines between `\n`s) aligned other than the paragraph, by index; `None`+ /// and rows past the end follow `align` ([`crate::paragraph_align`]).+ pub aligns: Vec<Option<crate::added::Align>>,/// Draw a line under each line of text.pub underline: Option<bool>,/// Line spacing as a multiple of the font size (1.2 is ordinary).@@ -2926,8 +2929,10 @@ fn rewrite_block_from(}block_ops.extend(state.ops());block_ops.push(Op::new("Tm", tm.iter().map(|v| n(*v)).collect()));+ // Each row's alignment: its own, or the paragraph's.+ let align_of = |row: usize| style.aligns.get(row).copied().flatten().or(align);// Alignment: each line's offset from the left edge, in text space.- let offset = |line: &str| -> f64 {+ let offset = |line: &str, align: Option<crate::added::Align>| -> f64 {let free = (width - advance(line)).max(0.0) / k;match align {Some(crate::added::Align::Center) => free / 2.0,@@ -2943,7 +2948,6 @@ fn rewrite_block_from(// (ISO 32000-1 §9.3.3), so where a space is shown with another code (a composite font, a// generated Type 3 font, a subset without a space) the extra space follows each space as a// TJ adjustment instead, and code 32, which may then be a letter, gets none.- let justify = align == Some(crate::added::Align::Justify);let word_spacing_reaches_spaces = match metrics.as_ref().filter(|_| reuse) {Some(m) => m.encode(" ").is_some_and(|b| m.codes(&b).iter().all(|(c, len)| m.is_space(*c, *len))),None => type3.is_none(),@@ -2951,12 +2955,14 @@ fn rewrite_block_from(let mut x = 0.0;let mut tw_set = 0.0;let mut underlines: Vec<(f64, f64, f64)> = Vec::new(); // (x0, x1, y) in text space- for (i, line) in wrapped.iter().enumerate() {+ for (i, (line, row)) in wrapped.iter().enumerate() {+ let line_align = align_of(*row);+ let justify = line_align == Some(crate::added::Align::Justify);let spaces = line.matches(' ').count();let tw =if justify && i + 1 < wrapped.len() && spaces > 0 { (width - advance(line)).max(0.0) / k / o_state.scale / spaces as f64 } else { 0.0 };// A stretched line fills the width from the left edge.- let dx = if tw > 0.0 { 0.0 } else { offset(line) };+ let dx = if tw > 0.0 { 0.0 } else { offset(line, line_align) };if i > 0 || dx != 0.0 {block_ops.push(Op::new("Td", vec![n(dx - x), n(if i > 0 { -lead } else { 0.0 })]));}@@ -3349,24 +3355,28 @@ mod tests {assert!(!same_base_font("Arial", ""));}+ fn rows(lines: Vec<(String, usize)>) -> Vec<String> {+ lines.into_iter().map(|(line, _)| line).collect()+ }+#[test]fn paragraph_wrapping_keeps_ideographic_spaces() {let width = |s: &str| s.chars().count() as f64;- assert_eq!(wrap("A B C", 4.0, width), ["A B", "C"]);- assert_eq!(wrap("A\u{a0}B C", 3.0, width), ["A B", "C"]);- assert_eq!(wrap("A\u{2028}B C", 3.0, width), ["A B", "C"]);- assert_eq!(wrap(" \tA B\r\nC ", 3.0, width), ["A B", "C"]);+ assert_eq!(rows(wrap("A B C", 4.0, width)), ["A B", "C"]);+ assert_eq!(rows(wrap("A\u{a0}B C", 3.0, width)), ["A B", "C"]);+ assert_eq!(rows(wrap("A\u{2028}B C", 3.0, width)), ["A B", "C"]);+ assert_eq!(rows(wrap(" \tA B\r\nC ", 3.0, width)), ["A B", "C"]);}#[test]fn japanese_text_wraps_between_characters_but_not_before_closing_marks() {let width = |s: &str| s.chars().count() as f64;- assert_eq!(wrap("日本語の文章です。", 3.0, width), ["日本語", "の文章", "です。"]);+ assert_eq!(rows(wrap("日本語の文章です。", 3.0, width)), ["日本語", "の文章", "です。"]);// The comma can't begin a row, so the character before it moves down with it.- assert_eq!(wrap("あいう、えお", 3.0, width), ["あい", "う、え", "お"]);+ assert_eq!(rows(wrap("あいう、えお", 3.0, width)), ["あい", "う、え", "お"]);// Pieces of one word join without a space; separate words keep theirs.- assert_eq!(wrap("Edit PDFを編集", 6.0, width), ["Edit", "PDFを編集"]);- assert_eq!(wrap("一行目 二行目", 4.0, width), ["一行目 ", "二行目"]);+ assert_eq!(rows(wrap("Edit PDFを編集", 6.0, width)), ["Edit", "PDFを編集"]);+ assert_eq!(rows(wrap("一行目 二行目", 4.0, width)), ["一行目 ", "二行目"]);}#[test]diff --git a/crates/edit/src/text_regions.rs b/crates/edit/src/text_regions.rsindex a77559494..11ae6c5a2 100644--- a/crates/edit/src/text_regions.rs+++ b/crates/edit/src/text_regions.rs@@ -728,6 +728,9 @@ pub(super) fn rewrite_styled_block(let mut rows: Vec<Vec<(char, usize, String)>> = Vec::new();// Each row's characters, as indexes into the draft's characters (`chars` holds all of them).let mut row_ranges = Vec::new();+ // Each row's line in the draft (its `\n`-separated part), which [`BlockStyle::aligns`] counts.+ let mut row_lines: Vec<usize> = Vec::new();+ let mut draft_line = 0usize;let mut row_start = 0;let mut row = Vec::new();let mut row_width = 0.0;@@ -737,6 +740,8 @@ pub(super) fn rewrite_styled_block(let Some(item) = chars.get(at) else { break };if item.0 == '\n' {row_ranges.push(row_start..row_start + row.len());+ row_lines.push(draft_line);+ draft_line = draft_line.saturating_add(1);rows.push(std::mem::take(&mut row));row_width = 0.0;at += 1;@@ -760,6 +765,7 @@ pub(super) fn rewrite_styled_block(row.pop();}row_ranges.push(row_start..row_start + row.len());+ row_lines.push(draft_line);rows.push(std::mem::take(&mut row));row_width = 0.0;row_start = at;@@ -770,6 +776,7 @@ pub(super) fn rewrite_styled_block(}if !row.is_empty() {row_ranges.push(row_start..row_start + row.len());+ row_lines.push(draft_line);rows.push(row);}let streams = content_streams(doc, &p.dict)?;@@ -869,10 +876,12 @@ pub(super) fn rewrite_styled_block(continue;}let w = measured.get(row_index).copied().unwrap_or(0.0);- let align = style.align.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });+ // The row's own alignment, or the paragraph's.+ let asked = row_lines.get(row_index).and_then(|l| style.aligns.get(*l)).copied().flatten().or(style.align);+ let align = asked.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });let original_rect = block.rows.get(row_index).and_then(|row| row_rect(row, lines)).unwrap_or(block.rect);- let left = if style.width.is_none() && style.align.is_none() { original_rect[0] } else { block.rect[0] };- let available = if style.width.is_none() && style.align.is_none() { original_rect[2] - original_rect[0] } else { width };+ let left = if style.width.is_none() && asked.is_none() { original_rect[0] } else { block.rect[0] };+ let available = if style.width.is_none() && asked.is_none() { original_rect[2] - original_rect[0] } else { width };let mut x = left+ match align {crate::added::Align::Center => (available - w) / 2.0,diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 68fc076b9..caeddb02a 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -56,6 +56,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::paragraph_align;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/tests.rs b/crates/engine/src/tests.rsindex ed4e6efa1..7e2542c5d 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -6369,6 +6369,7 @@ fn content_edit_keeps_pages_annotations_fields_and_links() {size: 12.0,color: [0.0, 0.0, 0.0],align: TextAlign::Left,+ aligns: Vec::new(),};session.apply(id, Edit::AddText { page: 1, text }).unwrap();let after = session.get(id).unwrap();@@ -6408,6 +6409,7 @@ fn content_refresh_lists_match_the_storages_an_edit_touches() {size: 12.0,color: [0.0, 0.0, 0.0],align: TextAlign::Left,+ aligns: Vec::new(),},},Edit::MoveObjects { page: 0, objects: vec![target(crate::ObjectKind::Added)], offset: [1.0, 0.0] },diff --git a/crates/ui-egui/src/content_ui.rs b/crates/ui-egui/src/content_ui.rsindex c99c2cd78..c9d2c33ab 100644--- a/crates/ui-egui/src/content_ui.rs+++ b/crates/ui-egui/src/content_ui.rs@@ -66,9 +66,12 @@ pub struct TextDraft {/// Display space.pub rect: [f64; 4],pub text: String,- /// The box's formatting; its `text` is what the page has (empty for new text).+ /// The box's formatting; its `text` and `rect` are what the page has (empty for new text), and+ /// its `aligns` follow `text` as it is typed.pub style: AddedText,pub focus: bool,+ /// The selected bytes of `text` (empty: the caret), for aligning the lines it touches.+ pub selection: Option<std::ops::Range<usize>>,/// The text the box's own Undo history starts from ([`crate::edit_text_ui::forget_typing_before`]).pub typing_from: Option<String>,}@@ -404,7 +407,7 @@ pub(crate) fn page_input(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, typing_from: None });+ cv.draft = Some(TextDraft { page, index: None, rect, text: String::new(), style, focus: true, selection: None, typing_from: None });consumed = true;if typed.is_some() {view.pending_edit = typed;@@ -442,7 +445,16 @@ pub(crate) fn page_input(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, typing_from: None });+ cv.draft = Some(TextDraft {+ page,+ index: Some(i),+ rect: t.rect,+ text: t.text.clone(),+ style: t.clone(),+ focus: true,+ selection: None,+ typing_from: None,+ });cv.selected = Some((page, i));consumed = true;return consumed;@@ -552,6 +564,11 @@ pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, adlet (mut commit, mut cancel, mut done) = (false, false, false);let mut undrawable = None;let memo = &view.content.undrawable;+ // Clicks outside the document (the Format text panel) keep the text open, as they keep a+ // paragraph being edited open.+ // Where the click that took the focus was: the pointer itself may be gone by then (a touch, a+ // pen lifted away).+ let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));// Shown at once, like the paragraph editor: a fade-in shows the page's copy through it. Over// the page, so only where the document shows: text scrolled under the mode bar or a side// panel must leave them their pointer (#2755).@@ -570,28 +587,38 @@ pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, ad// 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);- // Laid out as the page draws it, so opening the box doesn't show it realigned.- // shortcut: justified text is shown left-aligned here (TextEdit can't justify), until the editor gets its own layouter.- let halign = match t.style.align {- pdfcraft_engine::TextAlign::Center => egui::Align::Center,- pdfcraft_engine::TextAlign::Right => egui::Align::Max,- pdfcraft_engine::TextAlign::Left | pdfcraft_engine::TextAlign::Justify => egui::Align::Min,- };+ let color = Color32::from_rgb(cr, cg, cb);+ // Laid out as the page draws it, each paragraph with its own alignment, so opening the+ // box doesn't show it realigned.+ let style = t.style.clone();+ let line_font = font.clone();+ let mut layouter =+ |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| aligned_galley(ui, text.as_str(), &style, &line_font, color, wrap);+ let before = t.text.clone();let input = input_id();crate::edit_text_ui::forget_typing_before(ui.ctx(), input, &mut t.typing_from, &t.style.text);ui.horizontal_top(|ui| {ui.spacing_mut().item_spacing.x = 4.0;- let resp = ui.add(- egui::TextEdit::multiline(&mut t.text)- .font(font)- .desired_width(r.width().max(60.0))- .desired_rows(1)- .horizontal_align(halign)- .background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE })- .text_color(Color32::from_rgb(cr, cg, cb))- .hint_text(tl!("Type text"))- .id(input),- );+ let output = egui::TextEdit::multiline(&mut t.text)+ .font(font)+ .desired_width(r.width().max(60.0))+ .desired_rows(1)+ .layouter(&mut layouter)+ .background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE })+ .text_color(color)+ .hint_text(tl!("Type text"))+ .id(input)+ .show(ui);+ let resp = output.response;+ if let Some(cursor) = output.cursor_range {+ let chars = cursor.as_sorted_char_range();+ let byte = |index: usize| t.text.char_indices().nth(index).map_or(t.text.len(), |(at, _)| at);+ t.selection = Some(byte(chars.start.into())..byte(chars.end.into()));+ }+ // Each paragraph keeps its own alignment through the typing.+ if t.text != before {+ t.style.aligns = pdfcraft_engine::paragraph_align::remap(&before, &t.text, &t.style.aligns);+ }if t.focus {resp.request_focus();t.focus = false;@@ -613,7 +640,7 @@ pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, ad// Pressing a button takes the focus from the text: that is not a click away.let on_buttons = ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| buttons.contains(p));cancel |= ui.input(|i| i.key_pressed(egui::Key::Escape));- commit = done || resp.lost_focus() && !on_buttons && !view.objects.hold_editor;+ commit = done || resp.lost_focus() && !on_buttons && !outside && !view.objects.hold_editor;});// Page text is drawn with the standard fonts; anything else would be saved as `?` (#125).undrawable = self::undrawable(t, memo);@@ -637,6 +664,8 @@ pub(crate) fn editor(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, ad/// updated, and text emptied by retyping removed. Empty new text adds nothing.fn finish(cv: &mut ContentView, d: TextDraft, added: &[Added]) -> Option<Edit> {let text = d.text.trim_end().to_string();+ let aligns = pdfcraft_engine::paragraph_align::remap(&d.text, &text, &d.style.aligns);+ let d = TextDraft { style: AddedText { aligns, ..d.style }, ..d };match d.index {None if text.trim().is_empty() => None,None => {@@ -658,6 +687,50 @@ pub(crate) fn input_id() -> egui::Id {egui::Id::new("added-text-input")}+/// `text` laid out as added text with `style` is drawn: each paragraph (line typed with Enter) wrapped+/// to `wrap` and placed by its own alignment, a justified one with every row but its last+/// stretched.+fn aligned_galley(ui: &egui::Ui, text: &str, style: &AddedText, font: &egui::FontId, color: Color32, wrap: f32) -> std::sync::Arc<egui::Galley> {+ use pdfcraft_engine::TextAlign;+ let job = |text: &str, align: TextAlign| {+ let mut job = egui::text::LayoutJob::simple(text.to_owned(), font.clone(), color, wrap);+ job.justify = align == TextAlign::Justify;+ job+ };+ let uniform = text.split('\n').enumerate().all(|(i, _)| style.paragraph_align(i) == style.align);+ if uniform && style.align != TextAlign::Center && style.align != TextAlign::Right {+ return ui.fonts_mut(|f| f.layout_job(job(text, style.align)));+ }+ // Each paragraph on its own (egui aligns a whole job one way), its rows moved within the+ // box's width, then joined in order: the caret and selection see one text.+ let mut galleys = Vec::new();+ let mut start = 0;+ for (i, paragraph) in text.split('\n').enumerate() {+ let end = start + paragraph.len();+ // The last paragraph keeps a trailing break, as egui's own split does.+ let last = end + 1 == text.len();+ let piece = if last { text.get(start..).unwrap_or_default() } else { paragraph };+ let mut galley = ui.fonts_mut(|f| f.layout_job(job(piece, style.paragraph_align(i))));+ let g = std::sync::Arc::make_mut(&mut galley);+ for placed in &mut g.rows {+ let free = (wrap - placed.row.size.x).max(0.0);+ placed.pos.x = match style.paragraph_align(i) {+ TextAlign::Center => free / 2.0,+ TextAlign::Right => free,+ TextAlign::Left | TextAlign::Justify => 0.0,+ };+ }+ g.rect = Rect::from_min_max(Pos2::ZERO, Pos2::new(g.rect.width().max(wrap), g.rect.height()));+ galleys.push(galley);+ if last {+ break;+ }+ start = end + 1;+ }+ let whole = std::sync::Arc::new(egui::text::LayoutJob::simple(text.to_owned(), font.clone(), color, wrap));+ std::sync::Arc::new(egui::Galley::concat(whole, &galleys, ui.ctx().pixels_per_point()))+}+/// How to use the tools, under the Add content list.pub(crate) fn hint(ui: &mut egui::Ui, t: &Tokens) {ui.label(diff --git a/crates/ui-egui/src/edit_text_ui.rs b/crates/ui-egui/src/edit_text_ui.rsindex f2c5c5515..f9074af30 100644--- a/crates/ui-egui/src/edit_text_ui.rs+++ b/crates/ui-egui/src/edit_text_ui.rs@@ -356,7 +356,12 @@ impl LineEditor {family: (l.family != o.family || self.family_chosen || l.bold != o.bold || l.italic != o.italic).then_some((l.family, l.bold, l.italic)),size: (l.size != o.size).then_some(l.size),color: (l.color != o.color).then_some(l.color),- align: (l.align != o.align).then_some(l.align),+ // The whole paragraph's alignment when it was picked, or when the rows' own were+ // dropped for it (the rows are where those put them, so leaving it out keeps them there).+ align: (l.align != o.align || l.aligns.is_empty() && !o.aligns.is_empty()).then_some(l.align),+ // Rows aligned on their own, sent with every rewrite of the paragraph while it is open:+ // nothing in the page records them, so a rewrite without them would undo them.+ aligns: if l.aligns != o.aligns || self.text != self.original { l.aligns.clone() } else { Vec::new() },underline: (self.extras.underline != self.extras0.underline).then_some(self.extras.underline),line_spacing: (self.extras.line_spacing != self.extras0.line_spacing && self.extras.line_spacing > 0.0).then_some(self.extras.line_spacing),@@ -403,9 +408,17 @@ impl LineEditor {self.source_rect = block.rect.map(|v| v as f32);self.multiline = block.rows.len() > 1;self.source = Some((block.clone(), lines));- self.text = block.editor_text.clone();+ let before = std::mem::replace(&mut self.text, block.editor_text.clone());+ self.follow_rows(&before);self.original = self.text.clone();}++ /// The text changed from `before`: rows aligned on their own keep their alignment.+ pub(crate) fn follow_rows(&mut self, before: &str) {+ for look in [&mut self.look, &mut self.look0] {+ look.aligns = pdfcraft_engine::paragraph_align::remap(before, &self.text, &look.aligns);+ }+ }}/// The look shown for a paragraph: the family and weight guessed from its PDF font name.@@ -1539,7 +1552,14 @@ fn editor_galley(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width:let g = Arc::make_mut(&mut galley);let mut bounds = Rect::NOTHING;let mut meshes = Rect::NOTHING;+ // Which line of the text (between `\n`s) each row is on: rows aligned on their own go where+ // the rewrite will put them, in the paragraph's width.+ let mut line = 0usize;for (index, placed) in g.rows.iter_mut().enumerate() {+ let own = ed.look.aligns.get(line).copied().flatten();+ if placed.ends_with_newline {+ line = line.saturating_add(1);+ }let (last_baseline, last_rect) = sources.last().copied().unwrap_or((first_baseline, first_rect));let (baseline, source_rect) = sources.get(index)@@ -1552,7 +1572,14 @@ fn editor_galley(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width:let base_y = (block.rect[3] - baseline) as f32 * scale;let row = Arc::make_mut(&mut placed.row);placed.pos.y = base_y - ascent;- placed.pos.x = if centered { (width - row.size.x) / 2.0 } else { (source_rect[0] - block.rect[0]) as f32 * scale };+ let free = (width - row.size.x).max(0.0);+ placed.pos.x = match own {+ Some(pdfcraft_engine::TextAlign::Center) => free / 2.0,+ Some(pdfcraft_engine::TextAlign::Right) => free,+ Some(pdfcraft_engine::TextAlign::Left | pdfcraft_engine::TextAlign::Justify) => 0.0,+ None if centered => (width - row.size.x) / 2.0,+ None => (source_rect[0] - block.rect[0]) as f32 * scale,+ };for glyph in &mut row.glyphs {let dy = ascent - glyph.pos.y;glyph.pos.y = ascent;@@ -1578,7 +1605,9 @@ fn editor_galley(ui: &egui::Ui, ed: &LineEditor, text: &str, scale: f32, width:/// The inline editor; returns the edit once the text is applied.pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -> Option<Edit> {// Clicks outside the document (the Format text panel) keep the paragraph open.- let outside = ctx.input(|i| i.pointer.latest_pos()).is_some_and(|p| !view.viewport_rect().contains(p));+ // Where the click that took the focus was: the pointer itself may be gone by then (a touch, a+ // pen lifted away).+ let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(|p| !view.viewport_rect().contains(p));let page = view.line_editor.as_ref()?.page;let xf = view.page_xform(page)?;let hold = view.objects.hold_editor;@@ -1692,6 +1721,7 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -let galley = editor_galley(ui, &snapshot, text.as_str(), scale, wrap_width);if snapshot.changes_with(text.as_str()) { galley } else { unseen(galley) }};+ let before = ed.text.clone();let input = input_id();forget_typing_before(ui.ctx(), input, &mut ed.typing_from, &ed.original);let output = egui::TextEdit::multiline(&mut ed.text)@@ -1719,6 +1749,7 @@ pub(crate) fn overlay(ctx: &egui::Context, view: &mut DocView, info: &DocInfo) -}let r = output.response;if r.changed() {+ ed.follow_rows(&before);// The next pass measures the updated draft with the Apply/Save rewrite.ctx.request_repaint();}diff --git a/crates/ui-egui/src/format_text_ui.rs b/crates/ui-egui/src/format_text_ui.rsindex 749f09dcc..6071b76b6 100644--- a/crates/ui-egui/src/format_text_ui.rs+++ b/crates/ui-egui/src/format_text_ui.rs@@ -39,6 +39,44 @@ pub(crate) struct Fonts<'a> {pub shown: String,}+/// Text being typed in, for the alignment buttons: with some of it selected, they show and set the+/// alignment of the paragraphs (lines between `\n`s) the selection touches; with none, the box's.+pub(crate) struct Paragraphs<'a> {+ pub text: &'a str,+ /// A byte range of `text`; empty or `None` is nothing selected.+ pub selection: Option<std::ops::Range<usize>>,+ /// The box's own alignment is known (added text), so a paragraph set to it keeps no entry of its+ /// own. An edited paragraph's alignment is only guessed from where its rows sit: its rows keep+ /// every alignment set.+ pub tidy: bool,+}++impl Paragraphs<'_> {+ /// The paragraphs a selection touches, or `None` with nothing selected.+ fn selected(&self) -> Option<std::ops::RangeInclusive<usize>> {+ self.selection.clone().filter(|r| !r.is_empty()).map(|r| pdfcraft_engine::paragraph_align::selected(self.text, r))+ }++ /// The alignment the buttons show: the first selected paragraph's, or the box's.+ fn shown(&self, look: &AddedText) -> TextAlign {+ self.selected().map_or(look.align, |which| look.paragraph_align(*which.start()))+ }++ /// `align` picked: for the selected paragraphs, or the whole box (dropping theirs).+ fn choose(&self, look: &mut AddedText, align: TextAlign) {+ match self.selected() {+ Some(which) => {+ let count = pdfcraft_engine::paragraph_align::count(self.text);+ look.aligns = pdfcraft_engine::paragraph_align::set(&look.aligns, count, which, align, self.tidy.then_some(look.align));+ }+ None => {+ look.align = align;+ look.aligns.clear();+ }+ }+ }+}+/// What the panel changed: the style (in place) and a font picked from the list.#[derive(Default)]pub(crate) struct Outcome {@@ -70,7 +108,14 @@ fn number(v: f64) -> String {s.trim_end_matches('0').trim_end_matches('.').to_string()}-pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, look: &mut AddedText, extras: Option<&mut Extras>, fonts: Fonts) -> Outcome {+pub(crate) fn panel(+ ui: &mut egui::Ui,+ t: &Tokens,+ look: &mut AddedText,+ extras: Option<&mut Extras>,+ fonts: Fonts,+ paragraphs: Option<Paragraphs>,+) -> Outcome {let before = (look.clone(), extras.as_deref().copied());let mut out = Outcome::default();widgets::section_title(ui, tl!("Format text"));@@ -148,7 +193,8 @@ pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, look: &mut AddedText, extras:ui.painter().vline(sep.center().x, sep.y_range().shrink(3.0), Stroke::new(1.0, t.divider));planned(ui, "list", tl!("Bulleted list"));planned(ui, "list-ordered", tl!("Numbered list"));- let current = match look.align {+ let shown = paragraphs.as_ref().map_or(look.align, |p| p.shown(look));+ let current = match shown {TextAlign::Left => "align-left",TextAlign::Center => "align-center",TextAlign::Right => "align-right",@@ -164,8 +210,14 @@ pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, look: &mut AddedText, extras:(TextAlign::Right, "align-right", tl!("Align right")),(TextAlign::Justify, "align-justify", tl!("Justify")),] {- if icons::button(ui, icon, 30.0, look.align == a, tip).clicked() {- look.align = a;+ if icons::button(ui, icon, 30.0, shown == a, tip).clicked() {+ match ¶graphs {+ Some(p) => p.choose(look, a),+ None => {+ look.align = a;+ look.aligns.clear();+ }+ }ui.close();}}diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 7d16bc340..4285f1da3 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -534,7 +534,9 @@ fn format_section(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {.map(|f| (f.resource, f.face)).collect();let shown = ed.font_shown(&sources);- let out = crate::format_text_ui::panel(ui, t, &mut ed.look, Some(&mut ed.extras), Fonts { sources: Some(&sources), shown });+ // A selection aligns the rows it touches; the caret alone, the whole paragraph.+ let paragraphs = crate::format_text_ui::Paragraphs { text: &ed.text, selection: ed.selection.clone(), tidy: false };+ let out = crate::format_text_ui::panel(ui, t, &mut ed.look, Some(&mut ed.extras), Fonts { sources: Some(&sources), shown }, Some(paragraphs));let mut changed = out.changed;match out.font {Some(FontChoice::KeepSource) => {@@ -561,6 +563,21 @@ fn format_section(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {}return;}+ // Typing added text: the box's formatting, and alignment for the lines a selection touches.+ if let Some(i) = app.active_ids().map(|(i, _)| i)+ && let Some(draft) = app.views[i].content.draft.clone()+ {+ if draft.index.is_none() && app.quick_tool == crate::QuickTool::AddText {+ crate::content_ui::hint(ui, t);+ }+ let mut style = draft.style.clone();+ let paragraphs = crate::format_text_ui::Paragraphs { text: &draft.text, selection: draft.selection.clone(), tidy: true };+ added_text_format(ui, t, &mut style, Some(paragraphs));+ if style != draft.style {+ app.restyle_draft(i, style);+ }+ return;+ }let image = app.active_ids().and_then(|(i, id)| {let (page, index) = app.views[i].content.selected?;let doc = app.session.get(id)?;@@ -593,34 +610,65 @@ fn format_section(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) {match selected {Some((page, index, text)) => {let mut style = text.clone();- added_text_format(ui, t, &mut style);+ added_text_format(ui, t, &mut style, None);if style != text {// The reusable style follows the selection only when the edit took, so a refused one adds nothing odd later.if app.apply_edit(pdfcraft_engine::Edit::UpdateContent { page, index, content: pdfcraft_engine::AddedContent::Text(style.clone()) }) {- app.text_style = pdfcraft_engine::AddedText { text: String::new(), rect: [0.0; 4], ..style };+ app.text_style = pdfcraft_engine::AddedText { text: String::new(), rect: [0.0; 4], aligns: Vec::new(), ..style };}}}None if app.quick_tool == crate::QuickTool::AddText => {crate::content_ui::hint(ui, t);let mut style = app.text_style.clone();- added_text_format(ui, t, &mut style);+ added_text_format(ui, t, &mut style, None);app.text_style = style;}None => {}}}-/// Format text for added text: the standard families, size, colour, style and alignment.-fn added_text_format(ui: &mut egui::Ui, t: &Tokens, style: &mut pdfcraft_engine::AddedText) {+/// Format text for added text: the standard families, size, colour, style and alignment+/// (of the lines `paragraphs` selects, while the text is being typed).+fn added_text_format(ui: &mut egui::Ui, t: &Tokens, style: &mut pdfcraft_engine::AddedText, paragraphs: Option<crate::format_text_ui::Paragraphs>) {let shown = style.family.label().to_string();- let out = crate::format_text_ui::panel(ui, t, style, None, crate::format_text_ui::Fonts { sources: None, shown });+ let out = crate::format_text_ui::panel(ui, t, style, None, crate::format_text_ui::Fonts { sources: None, shown }, paragraphs);if let Some(crate::format_text_ui::FontChoice::Family(family)) = out.font {style.family = family;}}impl PdfCraftApp {+ /// Format text changed while added text is being typed in view `index`: the box takes the new+ /// style at once and stays open. Text already on the page is updated with what has been typed,+ /// as one undoable change; new text waits until it is finished. Text typed after this styling+ /// starts from it too.+ pub(crate) fn restyle_draft(&mut self, index: usize, style: pdfcraft_engine::AddedText) {+ let Some(view) = self.views.get_mut(index) else { return };+ // Text the standard fonts can't draw stays in the box, unwritten, until it is corrected (#125).+ let blocked = view.content.blocked().is_some();+ let Some(d) = view.content.draft.as_mut() else { return };+ let committed = d.style.clone();+ // `text` and `rect` stay what the page has; the rest is the new style.+ d.style = pdfcraft_engine::AddedText { text: committed.text.clone(), rect: committed.rect, ..style };+ d.focus = true;+ self.text_style = pdfcraft_engine::AddedText { text: String::new(), rect: [0.0; 4], aligns: Vec::new(), ..d.style.clone() };+ let (page, item) = (d.page, d.index);+ let text = d.text.trim_end().to_string();+ let Some(item) = item.filter(|_| !text.trim().is_empty() && !blocked) else { return };+ let aligns = pdfcraft_engine::paragraph_align::remap(&d.text, &text, &d.style.aligns);+ let updated = pdfcraft_engine::AddedText { text, rect: d.rect, aligns, ..d.style.clone() };+ if updated == committed {+ return;+ }+ if self.apply_edit(pdfcraft_engine::Edit::UpdateContent { page, index: item, content: pdfcraft_engine::AddedContent::Text(updated.clone()) })+ && let Some(d) = self.views.get_mut(index).and_then(|v| v.content.draft.as_mut())+ {+ // What the page has now. The aligns stay those of the text in the box.+ d.style = pdfcraft_engine::AddedText { aligns: std::mem::take(&mut d.style.aligns), ..updated };+ }+ }+/// Apply the open paragraph's formatting as one change; the paragraph stays open.pub(crate) fn apply_line_format(&mut self, index: usize, mut ed: crate::edit_text_ui::LineEditor, ctx: Option<&egui::Context>) {let edit = pdfcraft_engine::Edit::EditTextBlock { page: ed.page, block: ed.block, text: ed.text.clone(), style: ed.style() };diff --git a/crates/ui-egui/tests/it/content.rs b/crates/ui-egui/tests/it/content.rsindex de06d44b1..047606461 100644--- a/crates/ui-egui/tests/it/content.rs+++ b/crates/ui-egui/tests/it/content.rs@@ -883,3 +883,35 @@ fn a_resized_added_picture_shows_only_at_its_new_size() {let pixels = h.render().unwrap();assert!(red(&pixels, kept) > 100 && red(&pixels, gone) == 0, "the page raster has the picture at its new size");}++/// Bug A for added text: with one line of the box selected, an alignment applies to that line+/// only, the box stays open, and Undo puts it back and closes the box.+#[test]+fn aligning_a_selected_line_of_added_text_aligns_only_that_line() {+ let mut h = harness();+ let rect = [40.0, 195.0, 240.0, 220.0];+ let text = pdfcraft_engine::AddedText { rect, text: "Line one\nLine two".into(), ..Default::default() };+ assert!(h.state_mut().apply_edit(pdfcraft_engine::Edit::AddText { page: 0, text }));+ assert!(h.state_mut().execute("edit.text"));+ h.run_steps(3);+ let point = at(&h, 45.0, 195.0);+ click(&mut h, point);+ assert_eq!(h.state().views[0].content.draft.as_ref().and_then(|d| d.index), Some(0), "the editor opened on the text");+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::End);+ h.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::Home);+ h.run_steps(2);+ let button = h.get_by_label("Alignment").rect().center();+ click(&mut h, button);+ let item = h.get_by_label("Align right").rect().center();+ click(&mut h, item);+ let aligns = |h: &Harness<'static, PdfCraftApp>| match &added(h)[0].content {+ pdfcraft_engine::AddedContent::Text(t) => (t.align, t.aligns.clone()),+ _ => panic!(),+ };+ assert_eq!(aligns(&h), (pdfcraft_engine::TextAlign::Left, vec![None, Some(pdfcraft_engine::TextAlign::Right)]));+ assert!(h.state().views[0].content.draft.is_some(), "the box stays open");+ h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z);+ h.run_steps(4);+ assert_eq!(aligns(&h), (pdfcraft_engine::TextAlign::Left, vec![]), "Undo puts it back");+ assert!(h.state().views[0].content.draft.is_none(), "and closes the box");+}diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rsindex 2fcf67dc4..d51f7f551 100644--- a/crates/ui-egui/tests/it/editing.rs+++ b/crates/ui-egui/tests/it/editing.rs@@ -6074,3 +6074,56 @@ fn undo_while_typing_takes_back_the_typing_first() {assert_eq!(ed.text, original, "the typing is taken back");assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "the document is untouched");}++/// A paragraph of a short, a wide and a short row, opened in the paragraph editor.+fn three_row_paragraph() -> Harness<'static, PdfCraftApp> {+ let bytes = paragraph_drag_fixture("BT /F1 10 Tf 12 TL 60 400 Td (One two) Tj T* (three four five six seven eight) Tj T* (nine ten) Tj ET", 0, 1);+ let mut h = paragraph_drag_harness(bytes, 0);+ let (at, _) = paragraph_drag_points(&h, "One two three four five six seven eight nine ten", [0.0, 0.0]);+ click_at(&mut h, at);+ assert!(h.state().views[0].line_editor.is_some(), "the paragraph opens for typing");+ h+}++/// Format text's alignment flyout, by pointer.+fn align_by_pointer(h: &mut Harness<'static, PdfCraftApp>, choice: &str) {+ let button = h.get_by_label("Alignment").rect().center();+ click_at(h, button);+ let item = h.get_by_label(choice).rect().center();+ click_at(h, item);+}++fn row_rect(h: &Harness<'static, PdfCraftApp>, starts: &str) -> [f64; 4] {+ let s = h.state();+ s.session.get(s.views[0].id).unwrap().text_lines(0).into_iter().find(|l| l.text.starts_with(starts)).expect("the row").rect+}++/// Bug A: with one row of a paragraph selected, an alignment applies to that row only.+/// Bug C: Undo then puts the paragraph back and closes the editor, instead of leaving it open on+/// a text the page no longer has.+#[test]+fn aligning_a_selected_row_aligns_only_that_row_and_undo_puts_it_back() {+ let mut h = three_row_paragraph();+ let first = row_rect(&h, "One");+ let wide = row_rect(&h, "three");+ let last = row_rect(&h, "nine");+ // Select the last row.+ h.key_press_modifiers(Modifiers::COMMAND, Key::End);+ h.key_press_modifiers(Modifiers::SHIFT, Key::Home);+ h.run_steps(2);+ align_by_pointer(&mut h, "Align right");+ {+ let s = h.state();+ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Edit text"));+ assert!(s.views[0].line_editor.is_some(), "the paragraph stays open");+ }+ let moved = row_rect(&h, "nine");+ assert!((row_rect(&h, "One")[0] - first[0]).abs() < 0.5, "the first row stays put");+ assert!((moved[2] - wide[2]).abs() < 1.0 && moved[0] > last[0] + 20.0, "the last row is right-aligned: {moved:?}");+ h.key_press_modifiers(Modifiers::COMMAND, Key::Z);+ h.run_steps(4);+ let s = h.state();+ assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), None, "the alignment is undone");+ assert!(s.views[0].line_editor.is_none(), "the editor closed with the step it showed");+ assert!((row_rect(&h, "nine")[0] - last[0]).abs() < 0.5, "the last row is back");+}diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex 4af0cd98c..f0deaf5b1 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -1962,8 +1962,8 @@ milestone = "M7"status = "shipped"commands = ["edit.edit_text", "edit.text"]tools = ["text_edit", "content_update"]-evidence = ["crates/edit/src/tests.rs::justify_underline_and_spacing", "crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/edit/src/tests.rs::a_one_row_title_keeps_its_centre_when_it_grows_and_when_it_wraps", "crates/ui-egui/tests/it/editing.rs::the_format_panel_restyles_the_paragraph_being_edited"]-notes = "left, centre, right and justify (word spacing per line, last line left) for existing paragraphs and added text. A centred paragraph is found either from its ragged rows or, for a one row title, from its centre sitting on the page's own centre away from the edge the rest of the text uses, so growing or wrapping it keeps that centre (#2581)"+evidence = ["crates/edit/src/tests.rs::justify_underline_and_spacing", "crates/edit/src/tests.rs::paragraphs_take_new_formatting", "crates/edit/src/tests.rs::a_one_row_title_keeps_its_centre_when_it_grows_and_when_it_wraps", "crates/ui-egui/tests/it/editing.rs::the_format_panel_restyles_the_paragraph_being_edited", "crates/edit/src/tests.rs::one_row_of_a_paragraph_takes_its_own_alignment", "crates/edit/src/tests.rs::one_row_of_a_styled_region_takes_its_own_alignment", "crates/edit/src/tests.rs::added_text_paragraphs_keep_their_own_alignments", "crates/ui-egui/tests/it/editing.rs::aligning_a_selected_row_aligns_only_that_row_and_undo_puts_it_back", "crates/ui-egui/tests/it/content.rs::aligning_a_selected_line_of_added_text_aligns_only_that_line", "crates/automation/tests/it/automation.rs::added_text_lines_take_their_own_alignments"]+notes = "left, centre, right and justify (word spacing per line, last line left) for existing paragraphs and added text. A centred paragraph is found either from its ragged rows or, for a one row title, from its centre sitting on the page's own centre away from the edge the rest of the text uses, so growing or wrapping it keeps that centre (#2581). With text selected, Format text aligns only the lines (rows between line breaks) the selection touches; with only the caret, the whole paragraph or box (aligns in text_edit, page_add_text and content_update). Added text keeps each line's alignment in its /PCAdded parameters, and a justified line's last row is not stretched. Missing: an edited paragraph's per-row alignment is not recorded in the page, so after it is closed and reopened a later rewrite of it can put that row back to the paragraph's alignment (as whole-paragraph justify is lost, #2508/#2515); aligning a row can regroup the paragraph, and the editor then shows only the part it groups first; the added-text editor stretches justified lines with egui's own spacing, close to but not exactly as written"[[feature]]id = "edit.line-paragraph-spacing"