PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge main into feat/align-selected-lines
RiceDee43f848d53222
diff --cc crates/automation/src/dispatch.rsindex 4e907478d,87f47e8eb..52af9bda1--- a/crates/automation/src/dispatch.rs+++ b/crates/automation/src/dispatch.rs@@@ -1,7 -1,7 +1,7 @@@use super::error::{Result, ToolError, failed};use super::json::{Args, document_attachment_keys, info, one_based, parse_style_ranges, security, summary};use super::paths::{read_input, write_atomic};- use super::*;-use super::{Arc, Automation, Edit, Value, block_overlapping, comments, json, tools};++use super::{Arc, Automation, Edit, Value, block_overlapping, comments, content, json, tools};/// One piece of a tool's result.#[derive(Clone, Debug, PartialEq)]diff --cc crates/edit/src/added/draw.rsindex 0ad024b92,61297bcf2..9404f939b--- a/crates/edit/src/added/draw.rs+++ b/crates/edit/src/added/draw.rs@@@ -1,8 -1,11 +1,11 @@@use super::layout::{- Piece, arabic_error, hebrew_error, is_arabic, is_hebrew, is_thai, latin_width, lines, norm, shaped_layout, text_rect, thai_error, wrapped,+ Piece, arabic_error, hebrew_error, is_arabic, is_hebrew, is_thai, latin_width, norm, shaped_layout, text_rect, thai_error, wrapped,};use super::types::{AddedText, Align, Family};- use super::*;+ use super::{+ Content, Dict, Document, EditError, GlyphError, GlyphOutline, HashMap, HashSet, ObjRef, Object, PdfString, ShapedCluster, ShapedScript, Stream,- literal, matrix_number, n, shaped_glyph, win_ansi,++ align_code, literal, matrix_number, n, shaped_glyph, win_ansi,+ };fn font_name(base: &str) -> String {format!("PCF{}", base.replace('-', ""))diff --cc crates/edit/src/added/store.rsindex cbafd0f66,5ce5e15d1..7dae55596--- a/crates/edit/src/added/store.rs+++ b/crates/edit/src/added/store.rs@@@ -1,7 -1,7 +1,7 @@@use super::draw::{draw, params};use super::layout::{first_undrawable, is_thai, nums, shaped_arabic, thai_error};-use super::types::{Added, AddedImage, AddedText, Align, CHAR_SPACING_LIMIT, Family, MarkerScan, TAG};-use super::{Content, Dict, Document, EditError, GlyphError, MarkKind, ObjRef, Object, Stream, check, contents, page_list, place_tagged};+use super::types::{Added, AddedImage, AddedText, CHAR_SPACING_LIMIT, Family, MarkerScan, TAG};- use super::*;++use super::{Content, Dict, Document, EditError, GlyphError, MarkKind, ObjRef, Object, Stream, align_from, check, contents, page_list, place_tagged};fn parse(doc: &Document, d: &Dict) -> Option<Content> {let r = nums(doc, d.get(b"Rect"));diff --cc crates/edit/src/text/rewrite.rsindex 5cb5f2a32,513077a02..4d4e16d66--- a/crates/edit/src/text/rewrite.rs+++ b/crates/edit/src/text/rewrite.rs@@@ -1,11 -1,14 +1,14 @@@use super::blocks::{BlockStyle, TextBlock, paragraph_separator, wrap};use super::fallback::{- Encoder, MAX_TYPE3_GLYPHS, drop_unused_fallback_fonts, needs_type3, no_japanese_font, source_encodes, source_family, source_program_completes,- source_show, source_space, source_width, type3_encode, type3_font,+ Encoder, MAX_TYPE3_GLYPHS, Type3Fallback, drop_unused_fallback_fonts, needs_type3, no_japanese_font, source_encodes, source_family,+ source_program_completes, source_show, source_space, source_width, type3_encode, type3_font,};- use super::interp::{Carry, interpret};+ use super::interp::{Carry, Origin, TextState, interpret};use super::lines::{content_streams, page_dict, rewritten_contents, splice, text_lines};- use super::*;+ use super::{- Dict, Document, EditError, HashMap, Matrix, Metrics, Object, Op, PdfString, Pieces, TextLine, TextSession, group_blocks, is_centred, parse,- rewrite_styled_block,++ Dict, Document, EditError, HashMap, Matrix, Metrics, Object, Op, PdfString, Pieces, TextLine, TextSession, alignment_frame, group_blocks,++ is_centred, parse, rewrite_styled_block,+ };/// What replacing a line did.#[derive(Clone, Debug, PartialEq)]@@@ -206,6 -209,532 +209,548 @@@ pub(crate) fn rewrite_block_with_limitTextSession::open(doc, page, block)?.commit_with_limit(doc, text, style, max_glyphs)}+ struct RewriteDispatch {+ upright: bool,+ use_styled_path: bool,+ }++ fn choose_rewrite_path(+ doc: &Document,+ fonts: &Dict,+ block: &TextBlock,+ members: &[&TextLine],+ first: &TextLine,+ text: Option<&str>,+ style: &BlockStyle,+ ) -> Result<RewriteDispatch, EditError> {+ let registered_face = fonts.iter().any(|(name, _)| name.starts_with(b"PCFull"));+ // Hebrew is written back in drawing order by the single-style path. Styled regions do not+ // reorder right-to-left runs.+ let hebrew = text.unwrap_or(&block.text).chars().any(crate::bidi::is_hebrew);+ if hebrew && (!style.ranges.is_empty() || style.resource.is_some()) {+ return Err(EditError::Invalid(+ "formatting part of right-to-left (Hebrew) text, or choosing a document font for it, isn't supported yet".into(),+ ));+ }+ // Turned text is rewritten in its own text space by the single-style path. Styled layout uses+ // page x-coordinates and cannot safely apply those operations to rotated runs.+ let upright = members.iter().all(|line| line.upright());+ if !upright && (!style.ranges.is_empty() || style.resource.is_some()) {+ return Err(EditError::Invalid("formatting part of turned text, or choosing a document font for it, isn't supported yet".into()));+ }+ let visual_indic = members.iter().any(|line| line.visual_order);+ let has_special_text = text.is_some_and(|draft| {+ draft.contains(['\n', '\r'])+ || pdfcraft_fonts::source_shaping::required(draft)+ || !pdfcraft_fonts::embedding::matching_faces(&block.base_font).is_empty()+ });+ let has_multiple_runs = block.rows.iter().any(|row| row.len() > 1)+ || members.iter().any(|line| line.font != first.font || line.size != first.size || line.color != first.color);+ let source_requires_styled_path =+ has_special_text || registered_face || text.is_some_and(|draft| source_program_completes(doc, fonts, first, draft)) || has_multiple_runs;+ let explicit_styled_text = !style.ranges.is_empty() || style.resource.is_some();+ Ok(RewriteDispatch {+ upright,+ use_styled_path: upright+ && !hebrew+ && !visual_indic+ && (explicit_styled_text || (source_requires_styled_path && style.family.is_none() && style.bold.is_none())),+ })+ }++ /// The paragraph's text for writing back: explicit line breaks stay (#1443), and so does each typed+ /// U+0020 space: a run of them is not folded into one (#4199, #3797). `\r\n` and a lone `\r` are+ /// breaks too; other white space is written as one space.+ fn paragraph_text(text: &str) -> String {+ text.replace("\r\n", "\n")+ .chars()+ .map(|c| match c {+ '\r' => '\n',+ c if c != '\n' && paragraph_separator(c) => ' ',+ c => c,+ })+ .collect()+ }++ /// Where a paragraph sits on its page, for choosing the width it is laid out in.+ struct ParaGeometry {+ rect: [f64; 4],+ frame: [f64; 4],+ crop: [f64; 4],+ upright: bool,+ /// The text-to-user scale.+ k: f64,+ /// The size in text space.+ size: f64,+ /// The requested horizontal move, in points.+ dx: f64,+ single_line: bool,+ anchored_right: bool,+ centred: bool,+ }++ impl ParaGeometry {+ /// A paragraph keeps its width (or takes the one asked for); a single line grows to the right+ /// (to the left when right-to-left), up to the page's margin.+ fn width(&self, requested: Option<f64>) -> Result<f64, EditError> {+ let [left, _, right, _] = self.rect;+ let own = (right - left).max(self.size * self.k);+ let width = match requested {+ // Capped at the largest page PDF allows (14 400 pt), even for text set larger than that+ // (`clamp` panics when its minimum is the larger, or NaN).+ Some(w) if w.is_finite() => w.clamp((self.size * self.k).min(14_400.0), 14_400.0),+ Some(_) => return Err(EditError::Invalid("the paragraph's width must be a number".into())),+ // Turned text: the page's margins are along another axis. A single line grows (below).+ None if !self.upright => (self.frame[2] - self.frame[0]).max(self.size * self.k),+ None if self.anchored_right => own.max(right + self.dx - (self.crop[0] + 36.0)),+ // A centred line is not stretched to the margin: its own box is the frame it is centred in.+ None if self.single_line && !self.centred => own.max(self.crop[2] - 36.0 - (left + self.dx)),+ None => own,+ };+ if width.is_finite() { Ok(width) } else { Err(EditError::Invalid("the paragraph's width must be a number".into())) }+ }+ }++ /// How far a baseline starting at `origin` and running along `direction` goes before it is 36 pt+ /// from the page edge `low` or `high`.+ fn margin_reach(origin: f64, direction: f64, low: f64, high: f64) -> f64 {+ if direction > 1e-6 {+ (high - 36.0 - origin) / direction+ } else if direction < -1e-6 {+ (low + 36.0 - origin) / direction+ } else {+ f64::INFINITY+ }+ }++ /// A turned single line grows to fit, up to where its baseline reaches the page's margin.+ fn turned_line_width(first: &TextLine, crop: [f64; 4], offset: [f64; 2], width: f64, text: &str, advance: &Advance<'_>) -> f64 {+ let (x0, y0) = (first.origin.x + offset[0], first.origin.baseline + offset[1]);+ let (ux, uy) = first.direction();+ let tx = margin_reach(x0, ux, crop[0], crop[2]);+ let ty = margin_reach(y0, uy, crop[1], crop[3]);+ let cap = width.max(tx.min(ty)).min(14_400.0);+ text.split('\n').map(|line| advance.of(line)).fold(width, f64::max).min(cap)+ }++ /// The widths of the paragraph's text in the font it will be written in, in user space.+ struct Advance<'a> {+ /// The source font, when its glyphs are reused.+ source: Option<&'a Metrics>,+ type3: Option<&'a Type3Fallback>,+ family: crate::added::Family,+ bold: bool,+ italic: bool,+ size: f64,+ space: f64,+ char_spacing: f64,+ word_spacing: f64,+ scale: f64,+ k: f64,+ }++ impl Advance<'_> {+ fn of(&self, s: &str) -> f64 {+ let extra = s.chars().count() as f64 * self.char_spacing;+ let t = match (self.source, self.type3) {+ (Some(m), _) => {+ let visual_s = if m.visual_order { crate::indic::to_visual(s) } else { s.to_owned() };+ source_width(m, &visual_s, self.size, self.space, self.char_spacing, self.word_spacing)+ }+ (None, Some(fallback)) => {+ // Each character's count in `s`, from one pass over `s`.+ let mut counts: HashMap<char, usize> = HashMap::new();+ for c in s.chars() {+ let count = counts.entry(c).or_insert(0);+ *count = count.saturating_add(1);+ }+ fallback.widths.iter().map(|(ch, width)| counts.get(ch).copied().unwrap_or(0) as f64 * width * self.size).sum::<f64>() + extra+ }+ (None, None) => self.family.std14(self.bold, self.italic).text_width(s, self.size) + extra,+ };+ t * self.scale * self.k+ }+ }++ /// The font a rewritten paragraph is shown in, and how its text is encoded.+ struct FontChoice {+ show_font: String,+ encode: Encoder,+ /// The stand-in face to tell the caller about.+ substituted: Option<String>,+ }++ /// What [`choose_font`] needs to know about the paragraph.+ struct FontInputs<'a> {+ /// The source font, when its glyphs are reused.+ source: Option<&'a Metrics>,+ type3: Option<&'a Type3Fallback>,+ font_name: &'a str,+ flat: &'a str,+ source_base_font: &'a str,+ family: crate::added::Family,+ bold: bool,+ italic: bool,+ family_requested: bool,+ }++ fn choose_font(inputs: &FontInputs<'_>, fonts_res: &mut Dict) -> Result<FontChoice, EditError> {+ if let Some(m) = inputs.source.cloned() {+ let name = inputs.font_name.to_owned();+ return Ok(FontChoice {+ show_font: name.clone(),+ encode: Box::new(move |s: &str| m.encode(s).map(|bytes| vec![(name.clone(), bytes)])),+ substituted: None,+ });+ }+ if let Some(fallback) = inputs.type3.cloned() {+ let substituted = Some(format!("{} Type3", fallback.family));+ let first = fallback.names.first().cloned().ok_or_else(no_japanese_font)?;+ return Ok(FontChoice { show_font: first, encode: Box::new(move |s: &str| type3_encode(&fallback, s)), substituted });+ }+ let flat = inputs.flat;+ let win = pdfcraft_fonts::win_ansi(flat);+ let back: String = win.iter().map(|c| char::from_u32(u32::from(*c)).unwrap_or('?')).collect();+ let base = inputs.family.base_font(inputs.bold, inputs.italic);+ if flat.chars().zip(back.chars()).any(|(a, c)| c == '?' && a != '?') {+ return Err(EditError::Invalid(format!("\"{flat}\" has characters neither {} nor {base} can show", inputs.source_base_font)));+ }+ let mut 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(base));+ f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));+ // Named after its face, as the line and region rewrites name theirs: one name for every+ // stand-in would repoint the paragraphs set in an earlier one at this face (#4280).+ let name = format!("PCEd{}", base.replace('-', ""));+ fonts_res.set(name.clone().into_bytes(), Object::Dict(f));+ let substituted = (!inputs.family_requested).then(|| base.to_string());+ let shown = name.clone();+ Ok(FontChoice { show_font: name, encode: Box::new(move |s: &str| Some(vec![(shown.clone(), pdfcraft_fonts::win_ansi(s))])), substituted })+ }++ /// The paragraph's move in the space it is drawn in: the move is in page space, so it is taken+ /// back through the CTM's linear part. Checked before the fallback fonts are written: a refused+ /// paragraph leaves the document as it was.+ fn drawn_movement(ctm: [f64; 6], dx: f64, dy: f64) -> Result<Option<(f64, f64)>, EditError> {+ if dx == 0.0 && dy == 0.0 {+ return Ok(None);+ }+ let back = Matrix([ctm[0], ctm[1], ctm[2], ctm[3], 0.0, 0.0])+ .invert()+ .ok_or_else(|| EditError::Invalid("the paragraph is drawn in a space it can't be moved in".into()))?;+ Ok(Some(back.apply(dx, dy)))+ }++ /// The paragraph's first text matrix, taken from where its text starts to where it is written.+ fn emit_text_matrix(first: &Origin, emit: &Origin) -> Result<[f64; 6], EditError> {+ if first.ctm == emit.ctm {+ return Ok(first.tm);+ }+ let emit_inv = Matrix(emit.ctm).invert().ok_or_else(|| EditError::Invalid("the paragraph has a singular transform".into()))?;+ Ok(Matrix(first.tm).then(&Matrix(first.ctm)).then(&emit_inv).0)+ }++ /// Line spacing in text space: the paragraph's own (scaled with the size), or 1.2 × the size.+ struct LeadScale {+ k: f64,+ size: f64,+ old_size: f64,+ leading: f64,+ }++ fn line_lead(block: &TextBlock, lines: &[TextLine], style: &BlockStyle, scale: &LeadScale) -> f64 {+ if let Some(m) = style.line_spacing {+ return scale.size * m.clamp(0.5, 5.0);+ }+ // From the first two rows (a row may hold several runs).+ let rows = block.rows.first().zip(block.rows.get(1)).and_then(|(upper, lower)| upper.first().zip(lower.first()));+ if let Some((upper, lower)) = rows.and_then(|(upper, lower)| lines.get(*upper).zip(lines.get(*lower))) {+ return (upper.frame_origin().1 - lower.frame_origin().1) / scale.k * scale.size / scale.old_size;+ }+ if scale.leading > 0.0 { scale.leading } else { scale.size * 1.2 }+ }++ /// The stroking twin of a fill colour operator.+ fn stroke_twin(fill: &Op) -> Op {+ let name = match fill.op.as_slice() {+ b"g" => "G",+ b"rg" => "RG",+ b"k" => "K",+ b"cs" => "CS",+ b"sc" => "SC",+ _ => "SCN",+ };+ Op::new(name, fill.operands.clone())+ }++ /// Underlines in text space (the paragraph's text matrix), in its fill colour.+ fn underline_ops(fill: &[Op], tm: &[f64; 6], size: f64, underlines: &[(f64, f64, f64)]) -> Vec<Op> {+ let n = pdfcraft_content::num;+ let mut ops = vec![Op::new("q", vec![]), Op::new("cm", tm.iter().map(|v| n(*v)).collect())];+ ops.extend(fill.iter().map(stroke_twin));+ ops.push(Op::new("w", vec![n(size * 0.06)]));+ for (x0, x1, y) in underlines {+ ops.push(Op::new("m", vec![n(*x0), n(*y)]));+ ops.push(Op::new("l", vec![n(*x1), n(*y)]));+ }+ ops.push(Op::new("S", vec![]));+ ops.push(Op::new("Q", vec![]));+ ops+ }++ /// Alignment: each line's offset from the left edge.+ struct Alignment {- align: Option<crate::added::Align>,+ width: f64,+ k: f64,+ anchored_right: bool,+ right_edge: f64,+ rtl: bool,+ }++ impl Alignment {- /// `visible` is the width the line is aligned on, in user space; the offset is in text space.- fn offset(&self, visible: f64) -> f64 {++ /// `visible` is the width the line is aligned on, in user space, and `align` its row's++ /// alignment; the offset is in text space.++ fn offset(&self, visible: f64, align: Option<crate::added::Align>) -> f64 {+ let free = (self.width - visible).max(0.0) / self.k;- match self.align {++ match align {+ Some(crate::added::Align::Center) => free / 2.0,+ // A right-to-left line anchored at its right edge may start left of the old box.+ Some(crate::added::Align::Right) if self.anchored_right => (self.right_edge - visible) / self.k,+ Some(crate::added::Align::Right) => free,+ // A justified right-to-left paragraph ends its last line at the right edge.+ Some(crate::added::Align::Justify) if self.rtl => free,+ _ => 0.0,+ }+ }+ }++ /// Everything the wrapped lines of one paragraph are written with.+ struct LineWriter<'a> {+ advance: &'a Advance<'a>,+ alignment: Alignment,+ encode: &'a Encoder,+ source: Option<&'a Metrics>,- justify: bool,++ /// The paragraph's alignment, and the rows aligned on their own ([`BlockStyle::aligns`]).++ align: Option<crate::added::Align>,++ aligns: &'a [Option<crate::added::Align>],+ /// Whether `Tw` reaches every shown space.+ word_spacing_reaches_spaces: bool,+ width: f64,+ scale: f64,+ k: f64,+ size: f64,+ space: f64,+ char_spacing: f64,+ lead: f64,+ }++ /// What carries over from one line to the next.+ struct LineCursor {+ x: f64,+ tw_set: f64,+ shown_font: String,+ }++ impl LineWriter<'_> {++ /// Row `row`'s alignment: its own, or the paragraph's.++ fn align_of(&self, row: usize) -> Option<crate::added::Align> {++ self.aligns.get(row).copied().flatten().or(self.align)++ }+++ /// Justify: each line but the last fills the width. A stretched line shows only its words, as+ /// before #4199: word spacing would reach the spaces before its first word and after its+ /// last, so they are left out. Nothing to stretch over, or a paragraph drawn at `0 Tz`, isn't+ /// justified.- fn stretch(&self, body: &str, last: bool) -> f64 {++ fn stretch(&self, body: &str, last: bool, justify: bool) -> f64 {+ let interior = body.matches(' ').count();- if self.justify && !last && interior > 0 && self.scale.abs() > 1e-6 {++ if justify && !last && interior > 0 && self.scale.abs() > 1e-6 {+ Some((self.width - self.advance.of(body)).max(0.0) / self.k / self.scale / interior as f64).filter(|tw| tw.is_finite()).unwrap_or(0.0)+ } else {+ 0.0+ }+ }++ /// The text to show for a line and the width it is aligned on. Other lines show every space+ /// typed. A left-to-right one is aligned on its width up to its last word; a right-to-left+ /// one on its whole width, since the spaces typed after its last word are drawn on its left+ /// and the ones before its first on its right.+ fn shown<'t>(&self, line: &'t str, body: &'t str, tw: f64) -> (&'t str, f64) {+ if tw > 0.0 {+ (body, self.advance.of(body))+ } else if crate::bidi::rtl_base(line) {+ (line, self.advance.of(line))+ } else {+ (line, self.advance.of(line.trim_end_matches(' ')))+ }+ }+- /// Writes one wrapped line, returning its underline (x0, x1, y) in text space.- fn write_line(&self, index: usize, line: &str, last: bool, cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<(f64, f64, f64), EditError> {++ /// Writes one wrapped line of row `row`, returning its underline (x0, x1, y) in text space.++ fn write_line(++ &self,++ index: usize,++ row: usize,++ line: &str,++ last: bool,++ cursor: &mut LineCursor,++ ops: &mut Vec<Op>,++ ) -> Result<(f64, f64, f64), EditError> {+ let n = pdfcraft_content::num;++ let line_align = self.align_of(row);+ let body = line.trim_matches(' ');+ let interior = body.matches(' ').count();- let tw = self.stretch(body, last);++ let tw = self.stretch(body, last, line_align == Some(crate::added::Align::Justify));+ let (shown, visible) = self.shown(line, body, tw);- let dx = if tw > 0.0 { 0.0 } else { self.alignment.offset(visible) };++ let dx = if tw > 0.0 { 0.0 } else { self.alignment.offset(visible, line_align) };+ if index > 0 || dx != 0.0 {+ ops.push(Op::new("Td", vec![n(dx - cursor.x), n(if index > 0 { -self.lead } else { 0.0 })]));+ }+ cursor.x = dx;+ // Word spacing reaches only single-byte code 32 (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.+ let stretch = if self.word_spacing_reaches_spaces { 0.0 } else { tw };+ let tw = tw - stretch;+ if tw != cursor.tw_set {+ ops.push(Op::new("Tw", vec![n(tw)]));+ cursor.tw_set = tw;+ }+ // Each wrapped line in typing order; drawn left to right (right-to-left runs reversed).+ let visual = crate::bidi::to_visual(shown);+ // Stretched without word spacing: shown up to and including each space, then moved on.+ let pieces: Vec<&str> = if stretch > 0.0 { visual.split_inclusive(' ').collect() } else { vec![visual.as_str()] };+ for piece in pieces {+ self.show_piece(piece, line, tw, cursor, ops)?;+ if stretch > 0.0 && piece.ends_with(' ') {+ ops.push(Op::new("TJ", vec![Object::Array(vec![n(-1000.0 * stretch / self.size)])]));+ }+ }+ let tw = tw + stretch;+ // Underlined to the line's last word, over its stretched gaps.+ let w = (visible + tw * interior as f64 * self.scale * self.k) / self.k;+ Ok((dx, dx + w, -(index as f64) * self.lead - self.size * 0.12))+ }++ fn show_piece(&self, piece: &str, line: &str, tw: f64, cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<(), EditError> {+ let n = pdfcraft_content::num;+ if let Some(metrics) = self.source {+ let indic_piece = if metrics.visual_order { crate::indic::to_visual(piece) } else { piece.to_owned() };+ ops.extend(source_show(metrics, &indic_piece, self.size, self.space, self.char_spacing, tw)?);+ return Ok(());+ }+ for (font, bytes) in (self.encode)(piece).ok_or_else(|| EditError::Invalid(format!("\"{line}\" can't be shown")))? {+ if font != cursor.shown_font {+ ops.push(Op::new("Tf", vec![Object::name(&font), n(self.size)]));+ cursor.shown_font = font;+ }+ ops.push(Op::new("Tj", vec![Object::String(PdfString::literal(bytes))]));+ }+ Ok(())+ }++ /// Writes every wrapped line, returning their underlines.- fn write_all(&self, wrapped: &[String], cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<Vec<(f64, f64, f64)>, EditError> {- wrapped.iter().enumerate().map(|(i, line)| self.write_line(i, line, i + 1 == wrapped.len(), cursor, ops)).collect()++ fn write_all(&self, wrapped: &[(String, usize)], cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<Vec<(f64, f64, f64)>, EditError> {++ wrapped.iter().enumerate().map(|(i, (line, row))| self.write_line(i, *row, line, i + 1 == wrapped.len(), cursor, ops)).collect()+ }+ }++ /// The operators that write a paragraph in its own graphics state, so a new colour (or anything+ /// else) stops at the paragraph.+ struct BlockPlan<'a> {+ block: &'a TextBlock,+ lines: &'a [TextLine],+ style: &'a BlockStyle,+ emit: &'a Origin,+ after: &'a TextState,+ movement: Option<(f64, f64)>,+ state: TextState,+ tm: [f64; 6],+ size: f64,+ underline: bool,+ }+-fn block_ops(plan: &BlockPlan<'_>, writer: &LineWriter<'_>, wrapped: &[String], show_font: String) -> Result<Vec<Op>, EditError> {++fn block_ops(plan: &BlockPlan<'_>, writer: &LineWriter<'_>, wrapped: &[(String, usize)], show_font: String) -> Result<Vec<Op>, EditError> {+ let n = pdfcraft_content::num;+ let mut ops = vec![Op::new("q", vec![])];+ ops.extend(reveal_ops(plan.block, plan.lines, plan.style, plan.emit.ctm)?);+ // Moved: a translation inside that state.+ if let Some((ax, ay)) = plan.movement {+ ops.push(Op::new("cm", vec![n(1.0), n(0.0), n(0.0), n(1.0), n(ax), n(ay)]));+ }+ // Painted as the paragraph was, including what its text object set before the first show.+ ops.extend(plan.state.paint_ops(plan.after));+ ops.push(Op::new("BT", vec![]));+ let mut state = plan.state.clone();+ state.word_spacing = 0.0;+ // The font the next run is shown in: the one the BT sets, until a run of another fallback subset.+ let mut cursor = LineCursor { x: 0.0, tw_set: 0.0, shown_font: show_font.clone() };+ state.font = Some((show_font, plan.size));+ if let Some([r, g, bl]) = plan.style.color {+ state.fill = vec![Op::new("rg", vec![n(r), n(g), n(bl)])];+ }+ ops.extend(state.ops());+ ops.push(Op::new("Tm", plan.tm.iter().map(|v| n(*v)).collect()));+ let underlines = writer.write_all(wrapped, &mut cursor, &mut ops)?;+ ops.push(Op::new("ET", vec![]));+ if plan.underline {+ ops.extend(underline_ops(&state.fill, &plan.tm, plan.size, &underlines));+ }+ ops.push(Op::new("Q", vec![]));+ Ok(ops)+ }++ /// Whether text shown earlier in the same text object stays first: the paragraph then goes where+ /// its last row was, after any backgrounds between the rows, or between two halves of the text+ /// object. The paragraph's own operators (and another drawing on the same baseline: a fake-bold+ /// second copy, an invisible text layer) go, so the new text is all that may show.+ fn shows_before_paragraph(ops: &[Op], from: usize, to: usize, dropped: &std::collections::HashSet<usize>) -> bool {+ ops.get(from..to)+ .unwrap_or_default()+ .iter()+ .enumerate()+ .any(|(i, op)| matches!(op.op.as_slice(), b"Tj" | b"TJ" | b"'" | b"\"") && !dropped.contains(&(from + i)))+ }++ /// A paragraph's single style, with the text-space values read from where it starts.+ struct ParaStyle {+ state: TextState,+ size: f64,+ old_size: f64,+ k: f64,+ }++ /// Spacing and scaling (text state), with the chosen values.+ fn paragraph_style(o: &Origin, style: &BlockStyle) -> Result<(String, ParaStyle), EditError> {+ let (font_name, old_size) = o.state.font.clone().ok_or_else(|| EditError::Invalid("the paragraph has no font".into()))?;+ let k = o.k.max(1e-6);+ // The size in text space: points ÷ the text-to-user scale.+ let size = style.size.map_or(old_size, |pt| (pt / k).max(0.1));+ let mut state = o.state.clone();+ if let Some(c) = style.char_spacing {+ state.char_spacing = c / k;+ }+ if let Some(sc) = style.scale {+ state.scale = (sc / 100.0).clamp(0.1, 10.0);+ }+ Ok((font_name, ParaStyle { state, size, old_size, k }))+ }++ /// The font the paragraph's existing runs use, for reusing its glyphs.+ struct SourceFont {+ metrics: Option<Metrics>,+ reuse: bool,+ space: f64,+ }++ fn source_font(doc: &Document, fonts_res: &Dict, font_name: &str, first: &TextLine, flat: &str, style: &BlockStyle) -> SourceFont {+ let metrics = fonts_res.get(font_name.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned()).map(|d| Metrics::from_dict(doc, &d));+ let visual_indic = metrics.as_ref().is_some_and(|m| m.visual_order) || first.visual_order;+ let indic_text = if visual_indic { crate::indic::to_visual(flat) } else { flat.to_owned() };+ let reuse = style.family.is_none() && style.bold.is_none() && metrics.as_ref().is_some_and(|m| source_encodes(m, &indic_text));+ let space = metrics.as_ref().map_or(0.33, |m| source_space(doc, fonts_res, m));+ SourceFont { metrics, reuse, space }+ }+/// [`rewrite_block_with_limit`] with the page's [`text_lines`], read from `doc` as it is now.pub(crate) fn rewrite_block_from(doc: &mut Document,@@@ -529,98 -850,25 +876,26 @@@Some(m) => m.encode(" ").is_some_and(|b| m.codes(&b).iter().all(|(c, len)| m.is_space(*c, *len))),None => type3.is_none(),};- 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, row)) in wrapped.iter().enumerate() {- let line_align = align_of(*row);- let justify = line_align == Some(crate::added::Align::Justify);- // A stretched (justified) line shows only its words, as before #4199: word spacing would- // reach the spaces before its first word and after its last, so they are left out, and- // the line fills the width from the left edge. Nothing to stretch over, or a paragraph- // drawn at `0 Tz`, isn't justified.- let body = line.trim_matches(' ');- let interior = body.matches(' ').count();- let tw = if justify && i + 1 < wrapped.len() && interior > 0 && o_state.scale.abs() > 1e-6 {- Some((width - advance(body)).max(0.0) / k / o_state.scale / interior as f64).filter(|tw| tw.is_finite())- } else {- None- }- .unwrap_or(0.0);- // Other lines show every space typed. A left-to-right one is aligned on its width up to- // its last word; a right-to-left one on its whole width, since the spaces typed after its- // last word are drawn on its left and the ones before its first on its right.- let (shown, visible) = if tw > 0.0 {- (body, advance(body))- } else if crate::bidi::rtl_base(line) {- (line.as_str(), advance(line))- } else {- (line.as_str(), advance(line.trim_end_matches(' ')))- };- let dx = if tw > 0.0 { 0.0 } else { offset(visible, 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 })]));- }- x = dx;- let stretch = if word_spacing_reaches_spaces { 0.0 } else { tw };- let tw = tw - stretch;- if tw != tw_set {- block_ops.push(Op::new("Tw", vec![n(tw)]));- tw_set = tw;- }- // Each wrapped line in typing order; drawn left to right (right-to-left runs reversed).- let visual = crate::bidi::to_visual(shown);- // Stretched without word spacing: shown up to and including each space, then moved on.- let pieces = if stretch > 0.0 { visual.split_inclusive(' ').collect() } else { vec![visual.as_str()] };- for piece in pieces {- if let Some(metrics) = metrics.as_ref().filter(|_| reuse) {- let indic_piece = if metrics.visual_order { crate::indic::to_visual(piece) } else { piece.to_owned() };- block_ops.extend(source_show(metrics, &indic_piece, size, space, o_state.char_spacing, tw)?);- } else {- for (font, bytes) in encode(piece).ok_or_else(|| EditError::Invalid(format!("\"{line}\" can't be shown")))? {- if font != shown_font {- block_ops.push(Op::new("Tf", vec![Object::name(&font), n(size)]));- shown_font = font;- }- block_ops.push(Op::new("Tj", vec![Object::String(PdfString::literal(bytes))]));- }- }- if stretch > 0.0 && piece.ends_with(' ') {- block_ops.push(Op::new("TJ", vec![Object::Array(vec![n(-1000.0 * stretch / size)])]));- }- }- let tw = tw + stretch;- // Underlined to the line's last word, over its stretched gaps.- let w = (visible + tw * interior as f64 * o_state.scale * k) / k;- underlines.push((dx, dx + w, -(i as f64) * lead - size * 0.12));- }- block_ops.push(Op::new("ET", vec![]));- if style.underline == Some(true) {- // In text space (the paragraph's text matrix), in its fill colour.- let colour: Vec<Op> = state- .fill- .iter()- .map(|f| match f.op.as_slice() {- b"g" => Op::new("G", f.operands.clone()),- b"rg" => Op::new("RG", f.operands.clone()),- b"k" => Op::new("K", f.operands.clone()),- b"cs" => Op::new("CS", f.operands.clone()),- b"sc" => Op::new("SC", f.operands.clone()),- _ => Op::new("SCN", f.operands.clone()),- })- .collect();- block_ops.push(Op::new("q", vec![]));- block_ops.push(Op::new("cm", tm.iter().map(|v| n(*v)).collect()));- block_ops.extend(colour);- block_ops.push(Op::new("w", vec![n(size * 0.06)]));- for (x0, x1, y) in underlines {- block_ops.push(Op::new("m", vec![n(x0), n(y)]));- block_ops.push(Op::new("l", vec![n(x1), n(y)]));- }- block_ops.push(Op::new("S", vec![]));- block_ops.push(Op::new("Q", vec![]));- }- block_ops.push(Op::new("Q", vec![]));+ let writer = LineWriter {+ advance: &advance,- alignment: Alignment { align, width, k, anchored_right, right_edge, rtl },++ alignment: Alignment { width, k, anchored_right, right_edge, rtl },+ encode: &font.encode,+ source: source_metrics,- justify: align == Some(crate::added::Align::Justify),++ align,++ aligns: &style.aligns,+ word_spacing_reaches_spaces,+ width,+ scale: o_state.scale,+ k,+ size,+ space: source.space,+ char_spacing: o_state.char_spacing,+ lead,+ };+ let plan =+ BlockPlan { block: &b, lines: &lines, style, emit, after, movement, state: o_state, tm, size, underline: style.underline == Some(true) };+ let mut block_ops = block_ops(&plan, &writer, &wrapped, font.show_font.clone())?;+ let n = pdfcraft_content::num;block_ops.extend(after.ops().into_iter().filter(|op| !op.is("Tf") || after.font.is_some()));if split {block_ops.insert(0, Op::new("ET", vec![]));diff --cc crates/edit/src/text_regions/grouping.rsindex 4f2e8371a,b8a5abca1..357f1f724--- a/crates/edit/src/text_regions/grouping.rs+++ b/crates/edit/src/text_regions/grouping.rs@@@ -1,4 -1,4 +1,4 @@@- use super::*;-use super::{HashMap, Matrix, TextBlock, TextLine, paragraph_separator, same_base_font, same_font, strip_subset_tag, union};++use super::{BlockStyle, HashMap, Matrix, TextBlock, TextLine, paragraph_separator, same_base_font, same_font, strip_subset_tag, union};fn same_plane(a: &TextLine, b: &TextLine) -> bool {let at = Matrix(a.origin.tm).then(&Matrix(a.origin.ctm));diff --cc crates/edit/src/text_regions/styled.rsindex 6d4fc529a,e8b3b683d..40318dc35--- a/crates/edit/src/text_regions/styled.rs+++ b/crates/edit/src/text_regions/styled.rs@@@ -103,24 -344,128 +344,135 @@@ fn replacement_text<'a>(block: &'a Textif draft.len() > 4_000_000 {return Err(EditError::Invalid("the replacement text is too large".into()));}- if draft == block.editor_text && *style == BlockStyle::default() {- return Ok(LineEdit { substituted: None });+ Ok(draft)+ }++ fn has_no_effective_style_change(block: &TextBlock, draft: &str, style: &BlockStyle) -> bool {+ draft == block.editor_text && *style == BlockStyle::default()+ }++ fn page_font_metrics(+ doc: &Document,+ resource_dict: &Dict,+ block: &TextBlock,+ lines: &[TextLine],+ ) -> (Dict, std::collections::BTreeMap<String, Metrics>) {+ let mut fonts = resource_dict.get(b"Font").and_then(|resource| doc.resolve(resource).as_dict().cloned()).unwrap_or_default();+ for line in lines.iter().filter(|line| line.font.starts_with("PCRange")) {+ let mut font = Dict::new();+ font.set(b"Type".to_vec(), Object::name("Font"));+ font.set(b"Subtype".to_vec(), Object::name("Type1"));+ font.set(b"BaseFont".to_vec(), Object::name(&line.base_font));+ font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));+ fonts.set(line.font.as_bytes().to_vec(), Object::Dict(font));}- let mut ranges: Vec<_> = style.ranges.iter().collect();- ranges.sort_by_key(|r| r.range.start);- if ranges.len() > 1024- || ranges.iter().any(|r| {- r.range.start >= r.range.end- || draft.get(r.range.clone()).is_none()- || [r.size, r.char_spacing, r.scale].iter().flatten().any(|n| !n.is_finite())- || r.size.is_some_and(|n| n <= 0.0 || n > 14400.0)- || r.color.is_some_and(|c| c.iter().any(|n| !n.is_finite() || !(0.0..=1.0).contains(n)))- })- || ranges.windows(2).any(|r| r[0].range.end > r[1].range.start)+ let mut metrics = std::collections::BTreeMap::new();+ for (name, object) in fonts.iter().take(256) {+ if let Some(font) = doc.resolve(object).as_dict() {+ metrics.insert(String::from_utf8_lossy(name).into_owned(), Metrics::from_dict(doc, font));+ }+ }+ for index in &block.lines {+ if let Some(line) = lines.get(*index)+ && !metrics.contains_key(&line.font)+ && let Some(font) = fonts.get(line.font.as_bytes()).and_then(|resource| doc.resolve(resource).as_dict().cloned())+ {+ metrics.insert(line.font.clone(), Metrics::from_dict(doc, &font));+ }+ }+ (fonts, metrics)+ }++ fn paragraph_geometry(doc: &Document, page: &pdfcraft_model::Page, block: &TextBlock, style: &BlockStyle) -> Result<(f64, f64, f64), EditError> {+ if [style.size, style.line_spacing, style.char_spacing, style.scale, style.width].iter().flatten().any(|value| !value.is_finite())+ || style.color.is_some_and(|color| color.iter().any(|value| !value.is_finite())){- return Err(EditError::Invalid("text style ranges must be disjoint UTF-8 boundaries with finite formatting (at most 1024 ranges)".into()));+ return Err(EditError::Invalid("the paragraph's formatting must use finite numbers".into()));}- let source_count = lines.len();+ let [dx, dy] = style.offset.unwrap_or([0.0, 0.0]);+ if !dx.is_finite() || !dy.is_finite() || style.width.is_some_and(|width| !width.is_finite()) {+ return Err(EditError::Invalid("the paragraph's position and width must be finite".into()));+ }+ let natural = if block.invisible || block.rows.len() == 1 {+ (page.crop(doc)[2] - 36.0 - (block.rect[0] + dx)).max(block.rect[2] - block.rect[0])+ } else {+ block.rect[2] - block.rect[0]+ };+ Ok((dx, dy, style.width.unwrap_or(natural).clamp(1.0, 14_400.0)))+ }++ fn wrap_styled_rows(+ chars: &[StyledChar],+ width: f64,+ measure: impl Fn(&[StyledChar]) -> Result<f64, EditError>,-) -> Result<(StyledRows, RowRanges), EditError> {++) -> Result<(StyledRows, RowRanges, Vec<usize>), EditError> {+ let mut rows: Vec<Vec<StyledChar>> = Vec::new();+ 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;+ let mut at = 0;+ while at < chars.len() {+ let Some(item) = chars.get(at) else { break };+ if item.0 == '\r' {+ at += 1;+ continue;+ }+ 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;+ row_start = at;+ continue;+ }+ let mut end = at + 1;+ if !item.0.is_whitespace() {+ // A word ends at a space, or where Chinese or Japanese text may break between characters.+ while let (Some(before), Some(current)) = (chars.get(end - 1), chars.get(end))+ && !current.0.is_whitespace()+ && !crate::linebreak::between(before.0, current.0)+ {+ end += 1;+ }+ }+ let word = chars.get(at..end).unwrap_or_default();+ let word_width = measure(word)?;+ if !row.is_empty() && !item.0.is_whitespace() && row_width + word_width > width + 0.5 {+ while row.last().is_some_and(|c: &StyledChar| c.0.is_whitespace()) {+ 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;+ }+ row.extend_from_slice(word);+ row_width += word_width;+ at = end;+ }+ if !row.is_empty() {+ row_ranges.push(row_start..row_start + row.len());++ row_lines.push(draft_line);+ rows.push(row);+ }- Ok((rows, row_ranges))++ Ok((rows, row_ranges, row_lines))+ }++ fn apply_range_styles<'a>(+ first: &TextLine,+ block: &TextBlock,+ lines: &[TextLine],+ draft: &str,+ ranges: &[&'a RangeStyle],+ style: &BlockStyle,+ ) -> StyledLines<'a> {let mut styled_lines = lines.to_vec();let mut styled_spans = Vec::new();let mut underlines = HashMap::new();@@@ -466,65 -762,7 +769,7 @@@ pub(crate) fn rewrite_styled_block}Ok(width)};- 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;- // Wrap at word boundaries, retaining explicit source row breaks and whitespace.- let mut at = 0;- while at < chars.len() {- let Some(item) = chars.get(at) else { break };- // The CR of a CRLF: the `\n` after it breaks the row.- if item.0 == '\r' {- at += 1;- continue;- }- 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;- row_start = at;- continue;- }- let mut end = at + 1;- if !item.0.is_whitespace() {- // A word ends at a space, or where Chinese or Japanese text may break between characters.- while let (Some(before), Some(c)) = (chars.get(end - 1), chars.get(end))- && !c.0.is_whitespace()- && !crate::linebreak::between(before.0, c.0)- {- end += 1;- }- }- let word = chars.get(at..end).unwrap_or_default();- let w = measure(word)?;- if !row.is_empty() && !item.0.is_whitespace() && row_width + w > width + 0.5 {- while row.last().is_some_and(|c: &(char, usize, String)| c.0.is_whitespace()) {- 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;- }- row.extend_from_slice(word);- row_width += w;- at = end;- }- if !row.is_empty() {- row_ranges.push(row_start..row_start + row.len());- row_lines.push(draft_line);- rows.push(row);- }- let (rows, row_ranges) = wrap_styled_rows(&chars, width, measure)?;++ let (rows, row_ranges, row_lines) = wrap_styled_rows(&chars, width, measure)?;let streams = content_streams(doc, &p.dict)?;let pieces = Pieces::join(&streams.iter().map(|(_, d)| d.as_slice()).collect::<Vec<_>>());let ops = pieces.parse().ops;