Files
pdfcraft/crates/edit/src/text/rewrite.rs
T
Perchenko Anton cc0edc29d1 fix(edit): preserve source fonts in mixed-script paragraphs
## Follow-up after #6806

The main mixed-script font change landed in #6806. This PR covers the remaining case where the source font lacks only a variation selector (U+FE00–U+FE0F). A visible letter now selects the fallback face. The regression compares implicit and explicit fallback in two source fonts, including character spacing, alignment, and save/reopen.

Verified locally on macOS arm64 with the CI-pinned craft-fonts input: `cargo test --locked -p pdfcraft-edit` and `cargo test --locked -p pdfcraft-automation --test it mixed_script` passed, as did formatting, scoped Clippy, the layer and asset checks, and the UI WebAssembly build.

<!-- evening-module-refresh-20261027:start -->
**Latest compatibility update (2026-10-27):** [d10080eb](https://github.com/PerchAnton/pdfcraft/commit/d10080eb060d112d75bbcfd0a74e4e0bab38af61) includes main `1dd2737b` through a normal merge.

Source/fallback helpers follow the extracted text modules. The original per-rewrite advance cache, source spaces and batched missing-glyph fallback are preserved. The cache regressions were run with the pinned optional OFL font input.

Local macOS arm64 / Rust 1.99.1: focused regression tests, formatting, scoped all-target Clippy with `-D warnings`, layering and scoped WebAssembly checks pass. Assets and parity checks also pass. Hosted CI is tracked separately on this head. Temporary build outputs and fixtures are cleaned after validation.
<!-- evening-module-refresh-20261027:end -->

<!-- integration-refresh-20261025:start -->
**Latest integration checks (2026-10-25):** head `54423364bba795cff0b56e7c8f168f355062e3bb` includes main `418ac6a2af49b7ac2fed44ca2cae8d5d1d2cec0d` through a normal merge. On macOS arm64 with Rust 1.99.1, 980 scoped tests pass (0 failed, 5 ignored). Formatting, scoped all-target Clippy with `-D warnings`, layers, assets, parity, and the scoped wasm check pass. Test executables and fixtures were removed after each target. Full-workspace and other-platform checks belong to CI on this head. Six permitted OFL craft-fonts faces at release pin `3d9ab3a1` were SHA-256 verified for the font-dependent regressions.
<!-- integration-refresh-20261025:end -->

## What this changes

Fixes #2750.

Adding `шалом` to an upright, single-style Helvetica paragraph used to redraw the Latin text in the fallback face. Keep source fonts now preserves characters with actual source glyphs and batches only missing glyphs in Type 3 fallback fonts. Unencodable boundary spaces remain real, extractable fallback glyphs; source spaces with glyphs keep their face. Original font dictionaries stay intact.

Mixed-run classification and width measurement share a per-character cache within one paragraph rewrite. It stores both source advances and missing-glyph results for that rewrite's metrics, size and character spacing. Wrapping, alignment, justification and underline measurements reuse these widths; the normalized `Tw = 0` state, scaling and summation order stay consistent with drawing. The cache never survives into another rewrite.

## How you verified it

<!-- pdfcraft-conflict-refresh-20261019:start -->
**Current integration verification (2026-10-19):** main `43550c44` is included through a normal merge, preserving published history. Current head [5ea12797](https://github.com/PerchAnton/pdfcraft/commit/5ea127978fce56e64b93e70e7172cda5a193c41c).

Both roadmaps retain every current-main record and estimate, with only this PR's own status, progress and single milestone-row additions. Automatically merged hunks in the touched modules were reviewed.

**732 scoped tests passed, 0 failed, 4 ignored** (edit, engine and automation). Formatting, strict scoped all-target Clippy, scoped WebAssembly and layers/assets/parity pass; whitespace and both roadmap MD028 scans pass. Checks ran on macOS with Rust 1.95, the existing low-disk profile, two Cargo jobs, locked offline dependencies and command timeouts. Optional fonts use the verified release pin `3d9ab3a1`; no new assets or persistent build settings.

These are the checks of the refreshed branch. Broader/native UI observations below are historical; full-workspace and other operating-system checks belong to current-head hosted CI and are tracked separately.
<!-- pdfcraft-conflict-refresh-20261019:end -->

The deterministic work-budget regression was actually RED before caching: 32 source-character measurements for eight distinct characters. It now passes eight cases across two fonts, short/repeated drafts, narrow/maximum-width frames, justification and underlines. A separate saved-document test checks cache isolation across fonts, sizes, spacing and scale against the saved font metrics, wrapped baselines and underline endpoints. Existing extraction, font preservation, fallback batching and refusal regressions pass.

### Reproducible performance probe

`cargo test -p pdfcraft-edit --lib mixed_script_paragraph_rewrite_timing_probe --profile low-disk --locked --offline -j 2 -- --ignored --nocapture`

macOS arm64, Rust 1.95.0, the same existing optimized development profile and release-pinned craft-fonts `3d9ab3a132ed0eff457e424226a435a901da30d3`. Medians of three full `rewrite_block` calls, excluding fixture open, Cargo and extraction. Input repeats `The quick brown fox шалом ` with centre alignment, underline, `Tc = 1.25` and `Tz = 80`.

| UTF-8 bytes | Frame width (pt) | Before (ms) | Cached (ms) | Speedup |
|---|---|---|---|---|
| 992 | 480 | 3.845 | 0.730 | 5.27x |
| 15872 | 480 | 26.913 | 5.333 | 5.05x |
| 63488 | 480 | 103.914 | 19.830 | 5.24x |
| 15872 | 14400 | 418.305 | 28.449 | 14.7x |

Baseline production code is head `7de05471`. These are synthetic measurements, not release-build or 4 MB draft results. Normal tests enforce a deterministic measurement budget rather than a wall-clock threshold. Greedy wrapping still scans candidates, and final run encoding remains necessary.

## Never-crash, provenance and security

- [x] No new production panic paths, input-derived slicing or unsafe code. UTF-8 encoding uses a fixed four-byte buffer; cache keys are distinct input characters.
- [x] Contributor-original synthetic fixtures only; no Adobe assets, font binaries or copied copyleft implementation.
- [x] Existing atomic refusal, root confinement and opt-in MCP/control behaviour are retained; no new network or permission surface.

## Parity and reach

Existing `text_edit`, `text_edit_layout`, CLI and MCP reach this path. Both roadmaps retain one product note with unchanged estimates; text-editing parity remains partial.

## Anything a reviewer should look at first

This applies to upright single-style paragraphs in Keep source fonts mode. Explicit family/weight changes and turned/RTL/visual-order text retain their selection paths. The separate styled-path one-font-per-character issue (#2592), wider glyph coverage (#2593), unused-resource cleanup (#2487) and a different wrapping algorithm remain outside this PR.
2026-11-18 16:30:26 +07:00

1534 lines
75 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use super::blocks::{BlockStyle, TextBlock, paragraph_separator, row_break, wrap};
use super::fallback::{
Encoder, MAX_TYPE3_GLYPHS, Type3Fallback, Type3Run, drop_unused_fallback_fonts, is_variation_selector, needs_type3, no_japanese_font,
source_character_advance, source_encodes, source_fallback_runs, source_family, source_program_completes, source_runs, source_show, source_space,
source_width, type3_encode, type3_font,
};
use super::interp::{Carry, Origin, TextState, interpret};
use super::lines::{
content_streams, dropped_advances, dropped_side_effects, joined, page_dict, reopen_text_object, rewritten_contents, show_side_effects, splice,
text_lines,
};
use super::{
Dict, Document, EditError, HashMap, HashSet, Matrix, Metrics, Object, Op, PdfString, TextLine, TextSession, alignment_frame, existing_gap,
group_blocks, is_centred, parse, rewrite_changed_words, rewrite_styled_block, row_sources, source_row_step,
};
/// What replacing a line did.
#[derive(Clone, Debug, PartialEq)]
pub struct LineEdit {
/// `Some(font)` when the line's font couldn't show the new text and Helvetica was used.
pub substituted: Option<String>,
}
/// Replace the text of line `line` (an index into [`text_lines`]) on `page` with `text`.
pub fn replace_line(doc: &mut Document, page: usize, line: usize, text: &str) -> Result<LineEdit, EditError> {
let edit = replace_line_with_limit(doc, page, line, text, MAX_TYPE3_GLYPHS)?;
drop_unused_fallback_fonts(doc, page);
Ok(edit)
}
/// Refuses a rewrite that would remove text drawn as a clipping path (`4 Tr` to `7 Tr`). Such
/// glyphs are not ink but a mask, and whatever is painted through them takes their shape.
/// Removing the glyphs removes the mask, and the fill or image behind floods its own rectangle
/// instead -- the artwork is destroyed, in a file that still opens without a warning (#3429).
/// `clear_block` already refuses these for the same reason.
///
/// Every line the rewrite drops is checked, not only the one being replaced: a line's runs need
/// not share a rendering mode (see [`TextLine::clips`]), and [`coincident_ops`] drops a whole
/// overlapping line without regard to its mode -- so a mask could go with text that is ink.
fn refuse_clipping_text(lines: &[TextLine], dropped: &std::collections::HashSet<usize>) -> Result<(), EditError> {
if lines.iter().any(|l| l.clips && l.ops.iter().any(|op| dropped.contains(op))) {
return Err(EditError::Invalid("text used as a clipping path cannot be edited: its glyphs mask the artwork behind them".into()));
}
Ok(())
}
/// [`replace_line`] with the most unique characters one generated font may hold (tests lower it).
pub(crate) fn replace_line_with_limit(doc: &mut Document, page: usize, line: usize, text: &str, max_glyphs: usize) -> Result<LineEdit, EditError> {
let text = text.replace(row_break, " ");
let lines = text_lines(doc, page)?;
let target = lines.get(line).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no line {}", page + 1, line + 1)))?;
target.ensure_editable()?;
// Copies of the line drawn on the same baseline go with it, so the replacement is all that
// shows. Which operators go is settled here, before any font is generated, so that a refusal
// leaves the document untouched.
let mut drops = coincident_ops(&lines, &[&target]);
drops.extend(target.ops.iter().copied());
refuse_clipping_text(&lines, &drops)?;
let p = page_dict(doc, page)?;
let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
let streams = content_streams(doc, &p.dict)?;
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let first = target.ops.first().copied().filter(|i| *i < ops.len()).ok_or_else(|| EditError::Invalid("the page's content changed".into()))?;
// The line's own font, when it can show every character.
let font = fonts_res.get(target.font.as_bytes()).and_then(|f| doc.resolve(f).as_dict().cloned()).map(|d| Metrics::from_dict(doc, &d));
let visual_indic = font.as_ref().is_some_and(|m| m.visual_order) || target.visual_order;
let indic_text = if visual_indic { crate::indic::to_visual(&text) } else { text.clone() };
// Typed in logical order; drawn left to right (right-to-left runs reversed).
let shown = crate::bidi::to_visual(&indic_text);
let reused = font.as_ref().filter(|m| source_encodes(m, &shown));
let mut substituted = None;
let mut replacement: Vec<Op> = Vec::new();
// ' and " also move to the next line (and " sets the spacing); keep that.
replacement.extend(ops.get(first).map(show_side_effects).unwrap_or_default());
match reused {
Some(metrics) => replacement.extend(source_show(
metrics,
&shown,
target.origin.state.font.as_ref().map_or(target.size, |(_, size)| *size),
source_space(doc, &fonts_res, metrics),
target.origin.state.char_spacing,
target.origin.state.word_spacing,
)?),
None => {
let fallback_shown = crate::bidi::to_visual(&text);
if needs_type3(&text) {
let fallback = type3_font(doc, &mut fonts_res, &text, source_family(&target.base_font), target.bold, max_glyphs)?;
let runs = type3_encode(&fallback, &fallback_shown)
.ok_or_else(|| EditError::Invalid(format!("\"{text}\" can't be shown by the {} fallback", fallback.family)))?;
let size = font_size_before(&ops, first).unwrap_or(target.size);
let spacing = target.origin.state.char_spacing;
for run in runs {
replacement.push(Op::new("Tf", vec![Object::name(&run.name), pdfcraft_content::num(size)]));
if let Some(tc) = run.spacing {
// A variation selector's empty glyph: shown at spacing zero, then the
// line's own spacing back, so it adds no advance.
replacement.push(Op::new("Tc", vec![pdfcraft_content::num(tc)]));
replacement.push(Op::new("Tj", vec![Object::String(PdfString::literal(run.bytes))]));
replacement.push(Op::new("Tc", vec![pdfcraft_content::num(spacing)]));
} else {
replacement.push(Op::new("Tj", vec![Object::String(PdfString::literal(run.bytes))]));
}
}
replacement.push(Op::new("Tf", vec![Object::name(&target.font), pdfcraft_content::num(size)]));
substituted = Some(format!("{} Type3", fallback.family));
} else {
// The words the line's font can show keep it; only the others are set in the
// substitute (#2378): a subset without `V` or `ü` no longer turns the whole line
// into Helvetica. Reordered text (right to left, Indic) keeps one run as before.
let mixed = font
.as_ref()
.filter(|_| !visual_indic && fallback_shown == text)
.map(|m| source_runs(m, &text))
.filter(|runs| runs.iter().any(|(own, _)| *own));
// What the substitute has to show: only the runs the line's font can't.
let for_substitute: String = match &mixed {
Some(runs) => runs.iter().filter(|(own, _)| !*own).map(|(_, run)| run.as_str()).collect(),
None => fallback_shown.clone(),
};
let win = pdfcraft_fonts::win_ansi(&fallback_shown);
// WinAnsi turns what it can't show into '?'; refuse rather than print the wrong thing.
let checked = pdfcraft_fonts::win_ansi(&for_substitute);
let back: String = checked.iter().map(|b| char::from_u32(u32::from(*b)).unwrap_or('?')).collect();
if for_substitute.chars().zip(back.chars()).any(|(a, b)| b == '?' && a != '?') {
return Err(EditError::Invalid(format!("\"{text}\" has characters neither {} nor Helvetica can show", target.base_font)));
}
// The size in text space: the current Tf's size.
let size = font_size_before(&ops, first).unwrap_or(target.size);
let family = source_family(&target.base_font);
let base = family.base_font(target.bold, target.italic);
let substitute_name = format!("PCEd{}", base.replace('-', ""));
match mixed {
Some(runs) => {
let space = font.as_ref().map_or(0.33, |m| source_space(doc, &fonts_res, m));
// Marked as one line, so it reads back as one (see `continues_font`).
replacement.push(Op::new("BMC", vec![Object::name("PCEdLine")]));
for (own, run) in runs {
if own {
replacement.push(Op::new("Tf", vec![Object::name(&target.font), pdfcraft_content::num(size)]));
if let Some(m) = font.as_ref() {
replacement.extend(source_show(
m,
&run,
target.origin.state.font.as_ref().map_or(target.size, |(_, size)| *size),
space,
target.origin.state.char_spacing,
target.origin.state.word_spacing,
)?);
}
} else {
replacement.push(Op::new("Tf", vec![Object::name(&substitute_name), pdfcraft_content::num(size)]));
replacement.push(Op::new("Tj", vec![Object::String(PdfString::literal(pdfcraft_fonts::win_ansi(&run)))]));
}
}
replacement.push(Op::new("EMC", Vec::new()));
}
None => {
replacement.push(Op::new("Tf", vec![Object::name(&substitute_name), pdfcraft_content::num(size)]));
replacement.push(Op::new("Tj", vec![Object::String(PdfString::literal(win))]));
}
}
replacement.push(Op::new("Tf", vec![Object::name(&target.font), pdfcraft_content::num(size)]));
substituted = Some(base.to_string());
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"));
fonts_res.set(substitute_name.into_bytes(), Object::Dict(f));
}
}
}
// A line an earlier replacement wrote in two fonts is in a `/PCEdLine` sequence of its own,
// with its fonts and the moves standing in for spaces the source font lacks: those go
// with the line, or each edit would nest one more (review on #2955). The line then starts in
// its own font, set again where the sequence was.
if let Some((open, close)) = target.edited.and_then(|open| Some((open, matching_emc(&ops, open)?))) {
// Only when the sequence holds nothing but this line: a paragraph rewrite keeps the
// delimiters, so other rows can be inside it (review on #2955). Then the sequence stays
// as it is, since it is also what reads its own two-font line back as one, and only
// this line's operators go.
let others_inside = lines.iter().any(|l| l.ops.iter().any(|o| (open..=close).contains(o) && !drops.contains(o)));
// Either way the replacement starts in the line's own font: inside the sequence the font
// in effect at the line's first operator can be the substitute's, which a replacement
// the line's font shows by itself would otherwise inherit (review on #2955).
let size = font_size_before(&ops, first).unwrap_or(target.size);
replacement.insert(0, Op::new("Tf", vec![Object::name(&target.font), pdfcraft_content::num(size)]));
if !others_inside {
// What goes is what the replacement stands in for: the marked-content delimiters
// (nested ones too, which come in pairs), the fonts and the text-showing operators
// (the line's runs and the moves between them). A paragraph rewrite can also write a
// row's positioning and text state (`Tm`, `Td`, `Tw`, ...), a `q`/`Q` or a `BT`/`ET`
// inside kept delimiters; those stay, or the replacement loses its place and the
// content its balance (review on #2955).
drops.extend(
(open..=close)
.filter(|&i| ops.get(i).is_some_and(|o| [b"BMC".as_slice(), b"BDC", b"EMC", b"Tf", b"Tj", b"TJ"].contains(&o.op.as_slice()))),
);
let own_font = |i: usize| ops.get(i).is_some_and(|o| o.is("Tf") && o.name(0) == Some(target.font.as_bytes()) && o.num(1) == Some(size));
// The same font set just before the sequence (by the last edit) is set again here.
if let Some(i) = open.checked_sub(1).filter(|&i| own_font(i)) {
drops.insert(i);
}
// And set back after it: the replacement ends in that font too.
if let Some(i) = close.checked_add(1).filter(|&i| own_font(i)) {
drops.insert(i);
}
}
}
// Rebuild: the line's first operator becomes the replacement, its others go. Each other
// dropped `'` or `"` (a later run, or a copy on the same baseline) leaves its line move and
// spacing behind, as the first one does inside the replacement, and a dropped copy its advance
// where text after it is placed by that (the line's own runs give way to the replacement's).
let mut advances = dropped_advances(doc, &ops, &res, &drops);
for i in &target.ops {
advances.remove(i);
}
let new_data = splice(&pieces, &ops, |i| {
if i == first {
return (std::mem::take(&mut replacement), false);
}
let keep = !drops.contains(&i);
let mut insert = dropped_side_effects(&ops, i, keep, None);
insert.extend(advances.remove(&i));
(insert, keep)
});
let contents = rewritten_contents(doc, &streams, new_data)?;
let page_ref = p.obj;
if substituted.is_some() {
res.set(b"Font".to_vec(), Object::Dict(fonts_res));
}
doc.update_dict(page_ref, |d| {
d.set(b"Contents".to_vec(), contents);
if substituted.is_some() {
d.set(b"Resources".to_vec(), Object::Dict(res));
}
})?;
Ok(LineEdit { substituted })
}
/// The `EMC` that closes the marked-content sequence `BMC`/`BDC` operator `open` begins.
fn matching_emc(ops: &[Op], open: usize) -> Option<usize> {
let mut depth = 0usize;
for (i, op) in ops.iter().enumerate().skip(open) {
match op.op.as_slice() {
b"BMC" | b"BDC" => depth = depth.saturating_add(1),
b"EMC" => {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
}
None
}
/// The size of the last `Tf` before operator `at`.
fn font_size_before(ops: &[Op], at: usize) -> Option<f64> {
ops[..at].iter().rev().find(|o| o.is("Tf")).and_then(|o| o.num(1))
}
/// Operators of every line that is another drawing of one of `targets` (fake bold, an invisible
/// text layer). A surviving copy would show the old text under the replacement.
///
/// A copy overlaps a target by more than half the smaller box and sits on the same baseline
/// (within the tolerance that joins showing operators onto one line). A neighbouring line can
/// share box area when the leading is tighter than the font's ascent plus descent; its baseline
/// is farther away, so it stays.
pub(crate) fn coincident_ops(lines: &[TextLine], targets: &[&TextLine]) -> std::collections::HashSet<usize> {
let area = |r: [f64; 4]| ((r[2] - r[0]) * (r[3] - r[1])).max(0.0);
let mut drop = std::collections::HashSet::new();
for line in lines {
let copy = targets.iter().any(|target| {
let same_text = line.text.trim() == target.text.trim() || (line.origin.state.render_mode == 3) != (target.origin.state.render_mode == 3);
same_text && overlaps_half(line.rect, target.rect, area) && on_same_baseline(line, target)
});
if copy {
drop.extend(line.ops.iter().copied());
}
}
drop
}
fn overlaps_half(a: [f64; 4], b: [f64; 4], area: impl Fn([f64; 4]) -> f64) -> bool {
let ix = (b[2].min(a[2]) - b[0].max(a[0])).max(0.0);
let iy = (b[3].min(a[3]) - b[1].max(a[1])).max(0.0);
let small = area(b).min(area(a));
small > 0.0 && ix * iy / small > 0.5
}
/// Perpendicular distance between baselines, in user space. Horizontal text compares height;
/// turned text compares the distance across the writing direction.
fn on_same_baseline(line: &TextLine, target: &TextLine) -> bool {
let (dir, target_dir) = (line.direction(), target.direction());
let same_dir = (dir.0 - target_dir.0).abs() < 1e-3 && (dir.1 - target_dir.1).abs() < 1e-3;
let same_size = line.size.min(target.size) >= line.size.max(target.size) * 0.8;
let angle = target.rotation().to_radians();
let (sin, cos) = if angle.is_finite() { angle.sin_cos() } else { (0.0, 1.0) };
let dx = line.origin.x - target.origin.x;
let dy = line.origin.baseline - target.origin.baseline;
let offset = dx.mul_add(-sin, dy * cos).abs();
let size = line.size.min(target.size).max(1.0);
same_dir && same_size && offset.is_finite() && offset < size * 0.3
}
/// Rewrite paragraph `block` with new text (or its own) and formatting, rewrapped to its width.
pub fn rewrite_block(doc: &mut Document, page: usize, block: usize, text: Option<&str>, style: &BlockStyle) -> Result<LineEdit, EditError> {
let edit = rewrite_block_with_limit(doc, page, block, text, style, MAX_TYPE3_GLYPHS)?;
drop_unused_fallback_fonts(doc, page);
Ok(edit)
}
/// [`rewrite_block`] with the most unique characters one generated font may hold (tests lower it).
pub(crate) fn rewrite_block_with_limit(
doc: &mut Document,
page: usize,
block: usize,
text: Option<&str>,
style: &BlockStyle,
max_glyphs: usize,
) -> Result<LineEdit, EditError> {
TextSession::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(row_break)
|| 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). Every [`row_break`] is a break
/// too; other white space is written as one space. A line break also starts a paragraph, with the
/// paragraph spacing before it.
fn paragraph_text(text: &str) -> String {
text.replace("\r\n", "\n")
.chars()
.map(|c| match c {
c if row_break(c) => '\n',
c if paragraph_separator(c) => ' ',
c => c,
})
.collect()
}
/// The wrapped lines, and for each the paragraph it starts (see [`wrap_paragraphs`]).
type Wrapped = (Vec<(String, bool, usize)>, Vec<Option<usize>>);
/// Every paragraph (text between line breaks) wrapped on its own, with, per line, the number of
/// the paragraph it starts when it is a paragraph's first line after the first paragraph.
fn wrap_paragraphs(text: &str, width: f64, advance: impl Fn(&str) -> f64) -> Wrapped {
let (mut wrapped, mut starts) = (Vec::new(), Vec::new());
for (paragraph, text) in text.split('\n').enumerate() {
for (line, wrapped_line) in wrap(text, width, &advance).into_iter().enumerate() {
wrapped.push(wrapped_line);
starts.push((paragraph > 0 && line == 0).then_some(paragraph));
}
}
(wrapped, starts)
}
/// The gap before each wrapped line, in text space, beyond the line step: none except before the
/// first line of a paragraph after the first (`starts` says which paragraph that is).
///
/// A spacing that is set (`Some(0.0)` is none) goes before every such line: every line is laid out
/// afresh, and it replaces whatever space the page had there. Unset, the paragraphs follow the same
/// rule as the styled path (`RowSpacing`): a paragraph the draft's line break started anew gets
/// half the size, and one the page already had keeps the space it had above it, so choosing a
/// family or applying the draft again moves no source row. Which paragraph is which comes from
/// aligning the draft to the source's rows ([`row_sources`]).
fn paragraph_gaps(
(b, lines): (&TextBlock, &[TextLine]),
text: &str,
starts: &[Option<usize>],
style: &BlockStyle,
(k, size): (f64, f64),
) -> Result<Vec<f64>, EditError> {
match style.paragraph_spacing {
Some(p) if p.is_finite() => {
let gap = (p / k).clamp(0.0, 14_400.0);
return Ok(starts.iter().map(|s| if s.is_some() { gap } else { 0.0 }).collect());
}
Some(_) => return Err(EditError::Invalid("the paragraph spacing must be a number".into())),
None => {}
}
let mut at = 0;
let ranges: Vec<std::ops::Range<usize>> = text
.split('\n')
.map(|paragraph| {
let range = at..at + paragraph.chars().count();
at = range.end + 1;
range
})
.collect();
let explicit: Vec<bool> = (0..ranges.len()).map(|i| i > 0).collect();
let sources = row_sources(b, text, &ranges, &explicit);
let row_step = source_row_step(b, lines, size * k * 1.5);
Ok(starts
.iter()
.map(|s| match s.and_then(|paragraph| sources.get(paragraph)) {
Some(Some(source)) => existing_gap(b, lines, row_step, *source) / k,
Some(None) => size / 2.0,
None => 0.0,
})
.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> {
partial_advances: &'a HashMap<char, Option<f64>>,
/// 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<'_> {
/// Measures the advance in user space, combining source and fallback glyph widths for mixed runs.
fn of(&self, s: &str) -> f64 {
// A variation selector draws nothing and adds no spacing: it takes no room.
let extra = s.chars().filter(|ch| !is_variation_selector(*ch)).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();
let mut source_advance = 0.0;
let mut fallback_count = 0usize;
for c in s.chars() {
// The selector is emitted with zero spacing, so it cannot widen the line.
if is_variation_selector(c) {
continue;
}
if let Some(width) = self.partial_advances.get(&c).copied().flatten() {
source_advance += width;
} else {
let count = counts.entry(c).or_insert(0);
*count = count.saturating_add(1);
fallback_count = fallback_count.saturating_add(1);
}
}
source_advance
+ fallback.widths.iter().map(|(ch, width)| counts.get(ch).copied().unwrap_or(0) as f64 * width * self.size).sum::<f64>()
+ fallback_count as f64 * self.char_spacing
}
(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![Type3Run { name: name.clone(), bytes, spacing: None }])),
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![Type3Run { name: shown.clone(), bytes: pdfcraft_fonts::win_ansi(s), spacing: None }])),
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 {
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, 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 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> {
source_name: &'a str,
partial_chars: Option<&'a HashSet<char>>,
advance: &'a Advance<'a>,
alignment: Alignment,
encode: &'a Encoder,
source: Option<&'a Metrics>,
/// 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,
}
/// Where a wrapped line stands in its paragraph.
#[derive(Clone, Copy)]
struct LineRow {
/// The last line of the text (not justified).
last: bool,
/// The gap before the line, beyond the line step: set only on a paragraph's first line after
/// the first (see [`paragraph_gaps`]).
gap: f64,
}
/// What carries over from one line to the next.
struct LineCursor {
x: f64,
/// How far the lines have moved down from the first, in text space.
y: 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, justify: bool) -> f64 {
let interior = body.matches(' ').count();
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 of its logical draft row, returning its underline (x0, x1, y) in text space. `wrap`: whether
/// this line continues the previous one because a word did not fit, and, when it does, how
/// many separator characters the wrap consumed (0 for a Chinese/Japanese word split).
fn write_line(
&self,
index: usize,
line: &str,
wrap: (usize, bool, usize),
pos: LineRow,
cursor: &mut LineCursor,
ops: &mut Vec<Op>,
) -> Result<(f64, f64, f64), EditError> {
let n = pdfcraft_content::num;
let (row, soft, gap) = wrap;
let line_align = self.align_of(row);
let body = line.trim_matches(' ');
let interior = body.matches(' ').count();
let tw = self.stretch(body, pos.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, line_align) };
// The line step, plus the gap before a paragraph's first line.
let step = if index > 0 { self.lead + pos.gap } else { 0.0 };
if index > 0 {
// Inside this text object, so the marker starts and ends here. `/PCHard` is a newline
// that was already in the text. `/PCSoft` rejoins when the box widens, with `/N` the
// exact number of separator characters the wrap consumed (0 for a Chinese/Japanese
// word split), so a rejoin restores what was actually there instead of guessing a
// single space and silently dropping the rest of a typed run (#2529).
if soft {
let mut properties = Dict::new();
properties.set(b"N".to_vec(), Object::Int(i64::try_from(gap).unwrap_or(i64::MAX)));
ops.push(Op::new("BDC", vec![Object::name("PCSoft"), Object::Dict(properties)]));
} else {
ops.push(Op::new("BMC", vec![Object::name("PCHard")]));
}
ops.push(Op::new("EMC", vec![]));
}
if index > 0 || dx != 0.0 {
ops.push(Op::new("Td", vec![n(dx - cursor.x), n(-step)]));
}
cursor.x = dx;
cursor.y -= step;
// 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);
// Partial reuse must reach show_piece: its missing spaces and glyphs belong to the fallback.
if let Some(metrics) = self.source.filter(|m| self.partial_chars.is_none() && m.encode(" ").is_none()) {
let indic_line = if metrics.visual_order { crate::indic::to_visual(&visual) } else { visual };
ops.extend(source_show(metrics, &indic_line, self.size, self.space, self.char_spacing, tw + stretch)?);
} else {
// 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, cursor.y - self.size * 0.12))
}
/// Emits text-showing operators for each source or fallback run and tracks the selected font across pieces.
fn show_piece(&self, piece: &str, line: &str, tw: f64, cursor: &mut LineCursor, ops: &mut Vec<Op>) -> Result<(), EditError> {
let n = pdfcraft_content::num;
for (source, run) in source_fallback_runs(piece, self.partial_chars) {
if let Some(metrics) = self.source.filter(|_| self.partial_chars.is_none() || source) {
if cursor.shown_font != self.source_name {
ops.push(Op::new("Tf", vec![Object::name(self.source_name), n(self.size)]));
cursor.shown_font = self.source_name.to_owned();
}
let indic_piece = if metrics.visual_order { crate::indic::to_visual(run) } else { run.to_owned() };
ops.extend(source_show(metrics, &indic_piece, self.size, self.space, self.char_spacing, tw)?);
} else {
for run in (self.encode)(run).ok_or_else(|| EditError::Invalid(format!("\"{line}\" can't be shown")))? {
if run.name != cursor.shown_font {
ops.push(Op::new("Tf", vec![Object::name(&run.name), n(self.size)]));
cursor.shown_font = run.name;
}
if let Some(tc) = run.spacing {
// A variation selector's empty glyph: shown at spacing zero, then the paragraph's
// own spacing back, so it adds no advance.
ops.push(Op::new("Tc", vec![n(tc)]));
ops.push(Op::new("Tj", vec![Object::String(PdfString::literal(run.bytes))]));
ops.push(Op::new("Tc", vec![n(self.char_spacing)]));
} else {
ops.push(Op::new("Tj", vec![Object::String(PdfString::literal(run.bytes))]));
}
}
}
}
Ok(())
}
/// Writes every wrapped line, returning their underlines.
fn write_all(
&self,
wrapped: &[(String, bool, usize)],
gaps: &[f64],
cursor: &mut LineCursor,
ops: &mut Vec<Op>,
) -> Result<Vec<(f64, f64, f64)>, EditError> {
let mut row = 0usize;
wrapped
.iter()
.enumerate()
.map(|(i, (line, soft, gap))| {
if i > 0 && !soft {
row = row.saturating_add(1);
}
// Every line but the last is justified: a line break in the draft separates the rows
// of one paragraph, as the paragraph editor sends them, not paragraphs.
let last = i + 1 >= wrapped.len();
let pos = LineRow { last, gap: gaps.get(i).copied().unwrap_or(0.0) };
self.write_line(i, line, (row, *soft, *gap), pos, 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, bool, usize)],
gaps: &[f64],
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.
let mut ctm = Matrix(plan.emit.ctm);
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)]));
ctm = Matrix([1.0, 0.0, 0.0, 1.0, ax, ay]).then(&ctm);
}
// Painted as the paragraph was, including what its text object set before the first show.
ops.extend(plan.state.paint_ops(plan.after, ctm.0));
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, y: 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, gaps, &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. `phrase` is the size an OCR phrase
/// is drawn at when none is chosen, in place of its first word's own (#3313).
fn paragraph_style(o: &Origin, style: &BlockStyle, phrase: Option<f64>) -> 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.or(phrase).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);
}
// At the phrase's size, the first word's text matrix still carries its own width: scale it
// back, so the line is as wide as the scan whatever size OCR guessed for that word.
if phrase.is_some() && style.size.is_none() && style.scale.is_none() {
state.scale = (state.scale * old_size / size).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,
page: usize,
lines: Vec<TextLine>,
block: usize,
text: Option<&str>,
style: &BlockStyle,
max_glyphs: usize,
) -> Result<LineEdit, EditError> {
let blocks = group_blocks(&lines);
let b = blocks.get(block).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no paragraph {}", page + 1, block + 1)))?;
// Existing PDF paragraphs do not yet persist selected-row alignment intent. Refuse
// that operation before writing anything; whole-paragraph `align` remains supported.
if style.aligns.iter().any(Option::is_some) {
return Err(EditError::Invalid(
"selected-row alignment of existing paragraphs is not supported until it can be preserved across editing sessions".into(),
));
}
// An alignment for a one-row paragraph is laid out across the column it sits in, as a
// paragraph of that width moved to its left edge.
let framed;
let style = match alignment_frame(&lines, &blocks, &b, style, text.unwrap_or(&b.editor_text)) {
Some([left, right]) => {
framed = BlockStyle { width: Some(right - left), offset: Some([left - b.rect[0], 0.0]), ..style.clone() };
&framed
}
None => style,
};
let members: Vec<&TextLine> = b.lines.iter().map(|i| &lines[*i]).collect();
// One clipping run is enough: rewriting the paragraph would drop its mask with the rest.
let mut dropped = coincident_ops(&lines, &members);
dropped.extend(members.iter().flat_map(|l| l.ops.iter().copied()));
refuse_clipping_text(&lines, &dropped)?;
let first = members.first().copied().ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;
members.iter().try_for_each(|line| line.ensure_editable())?;
let p = page_dict(doc, page)?;
// Revealed OCR text may go on top of the page (see `revealed_under_paint`): a page that can't
// take that is refused here, before either rewrite path changes anything.
if b.invisible {
crate::check_on_top(doc, &p)?;
}
if let Some(edit) = text.and_then(|draft| rewrite_changed_words(doc, page, &b, &lines, draft, style, max_glyphs)) {
return Ok(edit);
}
let mut res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let mut fonts_res = res.get(b"Font").map(|f| doc.resolve(f)).and_then(|f| f.as_dict().cloned()).unwrap_or_default();
let dispatch = choose_rewrite_path(doc, &fonts_res, &b, &members, first, text, style)?;
if dispatch.use_styled_path && style.align == Some(crate::added::Align::Justify) {
return Err(EditError::Invalid("justification of mixed-style existing paragraphs is not supported".into()));
}
if dispatch.use_styled_path {
return rewrite_styled_block(doc, page, &b, &lines, text, style, max_glyphs);
}
let upright = dispatch.upright;
let streams = content_streams(doc, &p.dict)?;
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let text = paragraph_text(text.unwrap_or(&b.text));
// The characters to show, for choosing fonts: the breaks are moves, not glyphs.
let flat = text.replace('\n', " ");
let o = &first.origin;
let last = members.last().copied().unwrap_or(first);
let emit = &last.origin;
let (font_name, ParaStyle { state: o_state, size, old_size, k }) = paragraph_style(o, style, b.phrase_size())?;
let source = source_font(doc, &fonts_res, &font_name, first, &flat, style);
let reuse = source.reuse;
// Preserve every drawable source glyph; cache missing-glyph lookups as well.
let visual_indic = source.metrics.as_ref().is_some_and(|m| m.visual_order) || first.visual_order;
let hebrew = flat.chars().any(crate::bidi::is_hebrew);
let mut source_advances: HashMap<char, Option<f64>> = source
.metrics
.as_ref()
.filter(|_| !reuse && upright && !hebrew && !visual_indic && style.family.is_none() && style.bold.is_none() && needs_type3(&flat))
.map(|m| {
let mut advances = HashMap::new();
for ch in flat.chars() {
advances.entry(ch).or_insert_with(|| source_character_advance(m, ch, size, o_state.char_spacing));
}
advances
})
.unwrap_or_default();
// A fallback face needs a visible glyph. If only selectors are missing, use the whole
// paragraph as before; clear the advances too so measuring and drawing use the same font.
if !source_advances.is_empty() && flat.chars().filter(|ch| source_advances.get(ch).copied().flatten().is_none()).all(is_variation_selector) {
source_advances.clear();
}
let source_chars: HashSet<char> = source_advances.iter().filter_map(|(&ch, width)| width.map(|_| ch)).collect();
let partial_reuse = !source_chars.is_empty();
// The chosen style also determines the real Japanese fallback outlines and advances.
let (family, bold, italic) = style.family.unwrap_or((source_family(&b.base_font), b.bold, b.italic));
let bold = style.bold.unwrap_or(bold);
let [dx, dy] = style.offset.unwrap_or([0.0, 0.0]);
if !(dx.is_finite() && dy.is_finite()) {
return Err(EditError::Invalid("the paragraph can't be moved that far".into()));
}
// Right-to-left text (more Hebrew or Arabic letters than Latin) is right-aligned unless an
// alignment is asked for, and a single right-to-left line keeps its right edge as it grows.
let rtl = crate::bidi::rtl_base(&flat);
let anchored_right = rtl && upright && style.width.is_none() && members.len() == 1;
// The paragraph's width along its lines: in user space unless it is turned.
let frame = if upright {
b.rect
} else {
members.iter().map(|l| l.frame_rect()).reduce(|a, f| [a[0].min(f[0]), a[1].min(f[1]), a[2].max(f[2]), a[3].max(f[3])]).unwrap_or(b.rect)
};
// A centred title is laid out in the box it already sits in, so it keeps its centre as it
// grows or wraps, rather than being grown to the right up to the page's margin (#2581).
// Turned text is left alone: its centre lives along its own baseline, not in page space.
let crop = p.crop(doc);
let centred = upright && !rtl && style.width.is_none() && style.align.is_none() && is_centred(&b, &lines, (crop[0] + crop[2]) / 2.0, first.size);
let geometry = ParaGeometry { rect: b.rect, frame, crop, upright, k, size, dx, single_line: members.len() == 1, anchored_right, centred };
let width = geometry.width(style.width)?;
let align = if centred { Some(crate::added::Align::Center) } else { style.align.or(rtl.then_some(crate::added::Align::Right)) };
// Where a right-aligned line ends, from the paragraph's left edge (user space).
let right_edge = if anchored_right { (b.rect[2] - b.rect[0]).max(0.0) } else { width };
let movement = drawn_movement(emit.ctm, dx, dy)?;
let tm = emit_text_matrix(o, emit)?;
let type3 = if !reuse && needs_type3(&flat) {
let missing: String = flat.chars().filter(|ch| !source_chars.contains(ch)).collect();
Some(type3_font(doc, &mut fonts_res, &missing, family, bold, max_glyphs)?)
} else {
None
};
let source_metrics = source.metrics.as_ref().filter(|_| reuse);
let advance = Advance {
partial_advances: &source_advances,
source: source_metrics,
type3: type3.as_ref(),
family,
bold,
italic,
size,
space: source.space,
char_spacing: o_state.char_spacing,
word_spacing: o_state.word_spacing,
scale: o_state.scale,
k,
};
let width = if !upright && style.width.is_none() && members.len() == 1 {
turned_line_width(first, crop, [dx, dy], width, &text, &advance)
} else {
width
};
let right_edge = if anchored_right { right_edge } else { width };
// Every paragraph wrapped on its own; `starts` marks a paragraph's first line (but the first's).
let (wrapped, starts) = wrap_paragraphs(&text, width + 0.5, |s| advance.of(s));
let font = choose_font(
&FontInputs {
source: source_metrics,
type3: type3.as_ref(),
font_name: &font_name,
flat: &flat,
source_base_font: &b.base_font,
family,
bold,
italic,
family_requested: style.family.is_some(),
},
&mut fonts_res,
)?;
let lead = line_lead(&b, &lines, style, &LeadScale { k, size, old_size, leading: o_state.leading });
let gaps = paragraph_gaps((&b, &lines), &text, &starts, style, (k, size))?;
let start = last.ops.first().copied().unwrap_or(emit.bt_op);
let split = shows_before_paragraph(&ops, emit.bt_op, start, &dropped);
// What the text after the paragraph expects, and what is in force where the paragraph is
// drawn: the state at its BT (or where it was split).
let after = if split { &emit.state } else { &emit.bt_state };
// Word spacing reaches only single-byte code 32 (ISO 32000-1 §9.3.3); see `write_line`.
let word_spacing_reaches_spaces = match source_metrics {
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 writer = LineWriter {
source_name: &font_name,
partial_chars: partial_reuse.then_some(&source_chars),
advance: &advance,
alignment: Alignment { width, k, anchored_right, right_edge, rtl },
encode: &font.encode,
source: source.metrics.as_ref().filter(|_| reuse || partial_reuse),
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 at = if split { start } else { emit.bt_op };
// Revealed OCR text that something is painted over goes on top of the page, where it starts
// from the initial state.
let widest = wrapped.iter().map(|(l, _, _)| advance.of(l)).fold(width, f64::max);
let reach = crate::Reach { rect: b.rect, offset: [dx, dy], width: widest, rows: wrapped.len(), pitch: lead * k, upright };
let over = crate::revealed_under_paint(doc, page, b.invisible, reach.bounds(), &ops, at);
let initial = TextState::initial();
let drawn_from = if over { &initial } else { after };
let plan = BlockPlan {
block: &b,
lines: &lines,
style,
emit,
after: drawn_from,
movement,
state: o_state,
tm,
size,
underline: style.underline == Some(true),
};
let mut block_ops = block_ops(&plan, &writer, &wrapped, &gaps, font.show_font.clone())?;
let on_top = crate::lift_on_top(over, &mut block_ops);
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![]));
block_ops.extend(reopen_text_object(emit.tlm, emit.tm, after.font.as_ref().map(|(_, size)| *size), after.scale));
}
let mut advances = dropped_advances(doc, &ops, &res, &dropped);
let new_data = splice(&pieces, &ops, |i| {
let mut insert = if i == at { std::mem::take(&mut block_ops) } else { Vec::new() };
let keep = !dropped.contains(&i);
insert.extend(dropped_side_effects(&ops, i, keep, split.then_some(start)));
insert.extend(advances.remove(&i));
(insert, keep)
});
let contents = rewritten_contents(doc, &streams, new_data)?;
let new_font = !reuse;
if new_font {
res.set(b"Font".to_vec(), Object::Dict(fonts_res));
}
let page_ref = p.obj;
doc.update_dict(page_ref, |d| {
d.set(b"Contents".to_vec(), contents);
if new_font {
d.set(b"Resources".to_vec(), Object::Dict(res));
}
})?;
crate::draw_on_top(doc, &p, emit.ctm, &on_top)?;
Ok(LineEdit { substituted: font.substituted })
}
/// The cover (when [`BlockStyle::cover`] asks for one) and visible rendering that start a
/// rewritten invisible paragraph, drawn in the space whose CTM is `ctm`. Nothing for visible text.
/// The paragraph's `q`/`Q` restores the rendering mode for the invisible text after it; one
/// painted over where it was is drawn on top of the page instead ([`crate::draw_on_top`]).
/// What covering the word in `rect` paints: scanned ink reaches a little past the recognised box,
/// but not past `between`, the words on either side that stay. It always covers the word itself.
pub(crate) fn cover_box(rect: [f64; 4], between: Option<[f64; 2]>) -> [f64; 4] {
let pad = ((rect[3] - rect[1]).abs() * 0.1).clamp(0.5, 2.0);
let [left, right] = between.unwrap_or([f64::NEG_INFINITY, f64::INFINITY]);
[(rect[0] - pad).max(left.min(rect[0])), rect[1] - pad, (rect[2] + pad).min(right.max(rect[2])), rect[3] + pad]
}
pub(crate) fn reveal_ops(block: &TextBlock, lines: &[TextLine], style: &BlockStyle, ctm: [f64; 6]) -> Result<Vec<Op>, EditError> {
if !block.invisible {
return Ok(Vec::new());
}
let n = pdfcraft_content::num;
let mut ops = Vec::new();
if let Some(colour) = style.cover {
if colour.iter().any(|c| !c.is_finite() || !(0.0..=1.0).contains(c)) {
return Err(EditError::Invalid("the cover colour must be RGB values from 0 to 1".into()));
}
let back = Matrix(ctm).invert().ok_or_else(|| EditError::Invalid("the paragraph is drawn in a space it can't be covered in".into()))?;
ops.push(Op::new("q", vec![]));
ops.push(Op::new("rg", colour.map(n).to_vec()));
for rect in block.lines.iter().filter_map(|i| lines.get(*i)).map(|l| cover_box(l.rect, style.cover_between)) {
let corners = [[rect[0], rect[1]], [rect[2], rect[1]], [rect[2], rect[3]], [rect[0], rect[3]]];
for (i, [x, y]) in corners.into_iter().enumerate() {
let (x, y) = back.apply(x, y);
if !(x.is_finite() && y.is_finite()) {
return Err(EditError::Invalid("the paragraph's area can't be covered".into()));
}
ops.push(Op::new(if i == 0 { "m" } else { "l" }, vec![n(x), n(y)]));
}
ops.push(Op::new("h", vec![]));
}
ops.push(Op::new("f", vec![]));
ops.push(Op::new("Q", vec![]));
}
ops.push(Op::new("Tr", vec![Object::Int(0)]));
Ok(ops)
}
/// Existing paragraph indexes, excluding streams owned by an added-content item.
pub(crate) fn selectable_blocks(
doc: &Document,
page: usize,
excluded: &std::collections::BTreeSet<pdfcraft_cos::ObjRef>,
) -> Result<Vec<(usize, TextBlock)>, EditError> {
let p = page_dict(doc, page)?;
let streams = content_streams(doc, &p.dict)?;
let lines = text_lines(doc, page)?;
Ok(group_blocks(&lines)
.into_iter()
.enumerate()
.filter(|(_, b)| {
!b.lines
.iter()
.filter_map(|i| lines.get(*i))
.any(|l| streams.get(l.stream).and_then(|s| s.entry.as_ref()).is_some_and(|r| excluded.contains(&r)))
})
.collect())
}
/// The vertical advance per unit of font size of a font that writes vertically: `/DW2`'s w1
/// (default −1000, §9.7.4.3), or `None` for horizontal text. Per-glyph `/W2` entries are not
/// read. An encoding whose writing mode can't be read is an error, as in [`vertical_encoding`];
/// listing text treats it as horizontal and records the error (see [`Ts::unreadable`]).
pub(super) fn vertical_advance(doc: &Document, font: &Dict) -> Result<Option<f64>, EditError> {
if !vertical_encoding(doc, font)? {
return Ok(None);
}
let descendant = font.get(b"DescendantFonts").and_then(|d| doc.resolve(d).as_array().and_then(|a| a.first().cloned()));
let w1 = descendant
.and_then(|d| doc.resolve(&d).as_dict().and_then(|d| d.get(b"DW2").cloned()))
.and_then(|a| doc.resolve(&a).as_array().and_then(|a| a.get(1).cloned()))
.and_then(|w| doc.resolve(&w).as_f64())
.filter(|w| w.is_finite())
.unwrap_or(-1000.0);
Ok(Some(w1 / 1000.0))
}
/// Detect vertical CMaps before moving horizontal text. A broken/cyclic embedded CMap is
/// refused rather than guessing which direction TJ advances its text matrix.
fn vertical_encoding(doc: &Document, font: &Dict) -> Result<bool, EditError> {
if font.name(b"Subtype") != Some(b"Type0") {
return Ok(false);
}
let mut next = font.get(b"Encoding").cloned();
let mut seen = std::collections::BTreeSet::new();
for _ in 0..8 {
let Some(o) = next.take() else { return Ok(false) };
if let Some(r) = o.as_ref()
&& !seen.insert(r)
{
return Err(EditError::Invalid("the text encoding is cyclic".into()));
}
match &*doc.resolve(&o) {
Object::Name(n) => return Ok(n.ends_with(b"-V")),
Object::Stream(stream) => {
if let Some(mode) = stream.dict.get(b"WMode") {
match mode.as_int() {
Some(1) => return Ok(true),
Some(0) => {}
_ => return Err(EditError::Invalid("the text writing mode is invalid".into())),
}
}
let bytes = stream
.decoded_within(8 * 1024 * 1024)
.map_err(|_| EditError::Invalid("the text encoding cannot be decoded within its size limit".into()))?;
let ops = parse(&bytes).ops;
if let Some(mode) = ops.iter().rev().find(|op| op.is("def") && op.name(0) == Some(b"WMode")) {
return match mode.num(1) {
Some(0.0) => Ok(false),
Some(1.0) => Ok(true),
_ => Err(EditError::Invalid("the text writing mode is invalid".into())),
};
}
next = stream
.dict
.get(b"UseCMap")
.cloned()
.or_else(|| ops.iter().rev().find(|op| op.is("usecmap")).and_then(|op| op.operands.first().cloned()));
}
_ => return Err(EditError::Invalid("the text encoding is invalid".into())),
}
}
Err(EditError::Invalid("the text encoding is nested too deeply".into()))
}
/// The text-showing operators of paragraphs `indexes` (from [`group_blocks`] of the page's
/// lines), as indexes among the page's joined operators. `editable`: refuse a line that can't be
/// edited (moving rewrites its operators; copying takes them as they are).
pub(crate) fn paragraph_ops(doc: &Document, page: usize, indexes: &[usize], editable: bool) -> Result<std::collections::BTreeSet<usize>, EditError> {
let mut selected = std::collections::BTreeSet::new();
if indexes.is_empty() {
return Ok(selected);
}
let lines = text_lines(doc, page)?;
let blocks = group_blocks(&lines);
for index in indexes {
let b = blocks.get(*index).ok_or_else(|| EditError::Invalid("a selected paragraph no longer exists".into()))?;
for line in &b.lines {
let l = lines.get(*line).ok_or_else(|| EditError::Invalid("a selected text line no longer exists".into()))?;
if editable {
l.ensure_editable()?;
}
selected.extend(l.ops.iter().copied());
}
}
Ok(selected)
}
/// Where each text-showing operator of `ops` (a page's joined operators, drawn with `resources`)
/// starts its glyphs: the text matrix there, and its rendering mode (`Tr`).
pub(crate) fn show_starts(doc: &Document, ops: &[Op], resources: &Dict) -> Result<HashMap<usize, (Matrix, i64)>, EditError> {
let shown = interpret(doc, ops, resources, &mut HashMap::new(), &mut Carry::new(), None, None)?;
Ok(shown.into_iter().map(|s| (s.op, (s.tm, s.state.render_mode))).collect())
}
/// Translate paragraphs together without re-encoding glyphs, changing fonts or reflowing.
/// Numeric TJ offsets and text rise temporarily move each selected show operation, then
/// restore both advances and rise. The PDF reader advances the original glyph bytes itself:
/// no approximate font metrics are used to position following, unselected text (§9.4.4).
pub(crate) fn translate_blocks(doc: &mut Document, page: usize, indexes: &[usize], offset: [f64; 2]) -> Result<(), EditError> {
if indexes.is_empty() {
return Ok(());
}
let p = page_dict(doc, page)?;
let streams = content_streams(doc, &p.dict)?;
let selected = paragraph_ops(doc, page, indexes, true)?;
let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let fonts = res.get(b"Font").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
let pieces = joined(&streams);
let ops = pieces.parse().ops;
let shown = interpret(doc, &ops, &res, &mut HashMap::new(), &mut Carry::new(), None, None)?;
let mut patches = HashMap::new();
// Keep full precision: a tiny rounded text-space change can be magnified by a CTM,
// and restoring rise/spacing must not alter following unselected text.
let n = Object::Real;
for s in shown.into_iter().filter(|s| selected.contains(&s.op)) {
if !(0..=3).contains(&s.state.render_mode) {
return Err(EditError::Invalid("text used as a clipping path cannot be moved in a group".into()));
}
let font = fonts
.get(&s.font)
.map(|f| doc.resolve(f))
.and_then(|f| f.as_dict().cloned())
.ok_or_else(|| EditError::Invalid("a selected paragraph has no font".into()))?;
if vertical_encoding(doc, &font)? {
return Err(EditError::Invalid("vertical text cannot be moved in a group".into()));
}
let inverse = s.tm.then(&s.state.ctm).invert().ok_or_else(|| EditError::Invalid("a selected paragraph has no area".into()))?;
let [a, b, c, d, _, _] = inverse.0;
let (dx, dy) = (a * offset[0] + c * offset[1], b * offset[0] + d * offset[1]);
let denominator = s.state.size * s.state.scale;
let shift = if dx == 0.0 {
0.0
} else if denominator.abs() > 1e-12 {
-1000.0 * dx / denominator
} else {
return Err(EditError::Invalid("a selected paragraph has no horizontal advance".into()));
};
let rise = s.state.rise + dy;
if ![shift, rise, dx, dy].iter().all(|v| v.is_finite() && v.abs() <= 1e12) {
return Err(EditError::Invalid("the paragraph move is too large".into()));
}
let original = ops.get(s.op).ok_or_else(|| EditError::Invalid("a selected text operation is missing".into()))?;
let mut replacement = Vec::new();
let show = if original.is("'") || original.is("\"") {
if original.is("\"") {
let spacing = original
.operands
.get(..2)
.filter(|a| a.iter().all(|o| o.as_f64().is_some()))
.ok_or_else(|| EditError::Invalid("a text operation has invalid spacing".into()))?;
for (operator, operand) in ["Tw", "Tc"].into_iter().zip(spacing) {
replacement.push(Op::new(operator, vec![operand.clone()]));
}
}
replacement.push(Op::new("T*", vec![]));
Op::new("Tj", vec![original.operands.last().cloned().ok_or_else(|| EditError::Invalid("a text operation has no string".into()))?])
} else {
original.clone()
};
if dy != 0.0 {
replacement.push(Op::new("Ts", vec![n(rise)]));
}
if shift != 0.0 {
replacement.push(Op::new("TJ", vec![Object::Array(vec![n(shift)])]));
}
replacement.push(show);
if shift != 0.0 {
replacement.push(Op::new("TJ", vec![Object::Array(vec![n(-shift)])]));
}
if dy != 0.0 {
replacement.push(Op::new("Ts", vec![n(s.state.rise)]));
}
patches.insert(s.op, replacement);
}
if patches.len() != selected.len() {
return Err(EditError::Invalid("a selected text operation cannot be moved".into()));
}
let data = splice(&pieces, &ops, |i| patches.remove(&i).map_or((Vec::new(), true), |v| (v, false)));
let contents = rewritten_contents(doc, &streams, data)?;
doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
Ok(())
}