PDF export: tracked changes take the Track Changes Options colours (#5232) (#6144)

* PDF export: tracked changes take the Track Changes Options colours (#5232)

PDF and page image exports now respect Review › Track Changes Options
colours (insertColor, deleteColor) and mark preferences (deleteMark:
hidden), matching on-screen behavior instead of always defaulting to
author-0 magenta (#5232).

Fixes #5232

Co-authored-by: cdhdt <cdhoudetot@ik.me>

* Page images and print preview draw headers at full strength (#6267)

The downloaded page image and print preview built RenderOptions::default(),
whose dim_header is true, so a tracked change in a header or footer faded
there while PDF and file.exportPng drew it at full strength. Both now use
full-strength header display, with page_image_options shared across
file.exportPng, file.strictReport's page check and downloaded page images.

file.printPdf documents its compress parameter, which the colour regressions
use to read the content stream.

* Docs: record tracked-change export colours and preview parity (#5232, #6267)

ROADMAP, gaps, file-format parity and UI parity now record the export
colours and marks, final-text print pagination, and the preview matching
the print job. #6263, #6265 and #6266 remain.

* Fix merge conflict markers in PDF and engine option structs (#5232)

* docs: remove stray branch labels in ROADMAP, gaps and ui-parity (#5232)

---------

Co-authored-by: cdhdt <cdhoudetot@ik.me>
Co-authored-by: batistalucasv <batistalucasv@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
batistalucasv
2026-11-20 19:56:55 +00:00
committed by GitHub
co-authored by cdhdt batistalucasv Claude Sonnet 5.5
parent fea7a9182e
commit f5f29dc076
16 changed files with 435 additions and 29 deletions
+2 -2
View File
File diff suppressed because one or more lines are too long
+14 -7
View File
@@ -131,7 +131,7 @@ pub fn specs() -> Vec<CommandSpec> {
.pure(),
CommandSpec::new("file.printPdf", "Print to PDF", "File › Print", crate::print::print_pdf_to_file)
.params(
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size)}"#,
r#"{"path": string, "pagesPerSheet"?: 1 | 2 | 4 | 6 | 9 | 16 | "booklet" | "bookletReverse", "range"?: "all" | "current" | "selection" (the pages the selection touches) | "custom", "pages"?: "1-3,5" (implies custom), "parity"?: "all" | "odd" | "even", "copies"?: 1-999, "collate"?: bool (default true), "paper"?: "none" | "Letter" | "Legal" | "A4" | … (a Layout › Size name: scale every page to this paper, centred; the document keeps its size), "compress"?: bool (default true: compress the PDF's content streams; false writes the same pages uncompressed, which is larger)"#,
)
.pure(),
CommandSpec::new("file.print", "Print", "File", |s, _| {
@@ -485,8 +485,8 @@ fn save_as(s: &mut Session, v: &Value) -> CmdResult {
}
/// How a copy is written: Print Markup from the command's `markup`, else the File › Print
/// setting (`file.printMarkup`); comments as Track Changes Options show them; digits as the
/// Numeral setting shows them on screen.
/// setting (`file.printMarkup`); comments and revision marks/colours as Track Changes Options show them;
/// digits as the Numeral setting shows them on screen.
pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
let markup = p::bool(v, "markup").unwrap_or(s.prefs.print_markup);
crate::io::ExportOptions {
@@ -494,6 +494,7 @@ pub fn export_options(s: &Session, v: &Value) -> crate::io::ExportOptions {
comments: markup && s.prefs.markup.comments,
word2003: p::str(v, "format") == Some(FORMAT_WORD_2003),
numeral: s.view.numeral.resolve(crate::session::system_locale()),
revisions: s.prefs.markup.clone(),
strict: p::bool(v, "strict").unwrap_or(false),
}
}
@@ -517,7 +518,10 @@ fn strict_report(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {}", page + 1)));
}
crate::strict::strict_report(&s.doc, &l, &crate::strict::png_display(), Some(page..=page), wordcraft_layout::StrictOutput::Png)
// The page image `file.exportPng` writes: the printed page, tracked changes marked as
// Track Changes Options mark them.
let display = crate::io_ext::page_image_options(&opts).display;
crate::strict::strict_report(&s.doc, &l, &display, Some(page..=page), wordcraft_layout::StrictOutput::Png)
}
None => {
let out = super::references::output_fields(&s.doc);
@@ -527,6 +531,7 @@ fn strict_report(s: &mut Session, v: &Value) -> CmdResult {
Ok(report.to_json())
}
/// Exports a page of the current document as a PNG image at the requested scale.
fn export_png(s: &mut Session, v: &Value) -> CmdResult {
// No path: the app asks where to save, as file.exportPdf does (#2313).
let Some(path) = p::str(v, "path") else {
@@ -536,11 +541,13 @@ fn export_png(s: &mut Session, v: &Value) -> CmdResult {
let page = crate::p::page_index(p::u64(v, "page").unwrap_or(1));
let strict = p::bool(v, "strict").unwrap_or(false);
let scale = p::f32(v, "scale").unwrap_or(2.0).clamp(0.1, 8.0);
let l = s.export_layout_with(export_options(s, v).markup);
let export = export_options(s, v);
let l = s.export_layout_with(export.markup);
let pg = l.pages.get(page).ok_or_else(|| CmdError::Params(format!("no page {}", page + 1)))?;
// A page image is the printed page: headers and footers at full strength. Dimming them is
// the on-screen cue while editing the body, not part of the page.
let opts = wordcraft_render::RenderOptions { display: crate::strict::png_display(), ..Default::default() };
// the on-screen cue while editing the body, not part of the page. Tracked changes are marked
// as Track Changes Options mark them on screen.
let opts = crate::io_ext::page_image_options(&export);
if !path.to_ascii_lowercase().ends_with(".png") {
return Err(CmdError::Params("path must end in .png".into()));
}
+4 -1
View File
@@ -53,7 +53,7 @@ pub fn is_word_package(ext: &str) -> bool {
}
/// How a copy in another format is written.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ExportOptions {
/// Print Markup: PDFs show tracked changes marked up and, with `comments`, each page scaled
/// down beside a markup area with the comments in balloons (page images get the area too);
@@ -66,6 +66,9 @@ pub struct ExportOptions {
pub word2003: bool,
/// How digits look in PDFs and page images (the Numeral setting, `System` resolved).
pub numeral: wordcraft_layout::NumeralMode,
/// How tracked changes are marked in PDFs and page images (Track Changes Options): the
/// insertion and deletion marks and colours the screen shows (#5232).
pub revisions: wordcraft_layout::display::MarkupOptions,
/// A PDF or page image is written only if nothing in it is silently missing (a character no
/// face can draw, a picture that is missing or can't be decoded); else the save fails with
/// `strict: …` (#6005). Ignored for other formats.
+56 -2
View File
@@ -98,6 +98,15 @@ pub fn save(ext: &str, doc: &Document, opts: &crate::io::ExportOptions) -> Optio
}
}
/// How a page image is drawn: the printed page, headers and footers at full strength, tracked
/// changes marked as Track Changes Options mark them. One place for `file.exportPng`,
/// `file.strictReport`'s page check and a downloaded page image.
pub(crate) fn page_image_options(opts: &crate::io::ExportOptions) -> wordcraft_render::RenderOptions {
let mut ro = wordcraft_render::RenderOptions { display: crate::strict::png_display(), ..Default::default() };
ro.display.revisions = opts.revisions.clone();
ro
}
/// Render page `page` as PNG at `scale` px/pt. With Print Markup's comments the page has its
/// markup area with the comments in balloons (page images always show tracked changes).
pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::ExportOptions) -> Result<Vec<u8>, String> {
@@ -105,6 +114,7 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
let doc = out.as_ref().unwrap_or(doc);
let lo = wordcraft_layout::LayoutOptions {
comment_balloons: opts.markup && opts.comments,
hide_marked: opts.revisions.hidden_deletions(),
numeral: opts.numeral,
output_page_refs: true,
bookmark_error: crate::locale::bookmark_error(),
@@ -113,11 +123,55 @@ pub fn render_png(doc: &Document, page: usize, scale: f32, opts: &crate::io::Exp
let l = wordcraft_layout::layout(doc, &mut wordcraft_layout::LayoutCache::new(), &lo);
let p = l.pages.get(page).ok_or_else(|| format!("no page {}", page + 1))?;
if opts.strict {
let report = crate::strict::strict_report(doc, &l, &crate::strict::png_display(), Some(page..=page), wordcraft_layout::StrictOutput::Png);
let display = page_image_options(opts).display;
let report = crate::strict::strict_report(doc, &l, &display, Some(page..=page), wordcraft_layout::StrictOutput::Png);
if !report.passed() {
return Err(report.refusal());
}
}
let img = wordcraft_render::render_page(doc, p, scale, &Default::default());
let img = wordcraft_render::render_page(doc, p, scale, &page_image_options(opts));
Ok(img.to_png())
}
#[cfg(test)]
mod tests {
use super::*;
/// A page image is the printed page: headers and footers draw at full strength (#6267).
#[test]
fn a_page_image_draws_headers_at_full_strength() {
let opts = crate::io::ExportOptions::default();
let ro = page_image_options(&opts);
assert!(!ro.display.dim_header, "a page image is the printed page");
assert_eq!(ro.display.revisions, opts.revisions, "the Track Changes Options reach the image");
let mut d = Document::from_text("body");
let png = wordcraft_geom::picture::encode_format(
&image::DynamicImage::from(image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 0, 0, 255]))),
image::ImageFormat::Png,
)
.unwrap();
let media = d.add_media(png, "png");
let mut hp = wordcraft_doc::Paragraph::new();
let obj = wordcraft_doc::para::InlineObject::Image {
media,
w: 40.0,
h: 40.0,
alt: String::new(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
hp.insert_object(0, obj, &Default::default()).unwrap();
let id = d.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
d.last_section.headers.default = Some(id);
let rendered = render_png(&d, 0, 1.0, &opts).unwrap();
let l = wordcraft_layout::layout(&d, &mut wordcraft_layout::LayoutCache::new(), &wordcraft_layout::LayoutOptions::default());
let full = wordcraft_render::render_page(&d, &l.pages[0], 1.0, &ro).to_png();
let dimmed = wordcraft_render::render_page(&d, &l.pages[0], 1.0, &wordcraft_render::RenderOptions::default()).to_png();
assert_eq!(rendered, full, "render_png draws headers at full strength");
assert_ne!(rendered, dimmed, "render_png does not dim headers");
}
}
+4 -1
View File
@@ -221,7 +221,7 @@ impl Session {
let markup = crate::cmd::file::export_options(self, v);
let out = crate::cmd::references::output_fields(&self.doc);
let doc = out.as_ref().unwrap_or(&self.doc);
let lay = self.export_layout_of(doc, markup.markup);
let lay = self.output_layout_of(doc, markup.markup, !markup.markup);
let plan = plan(v, lay.pages.len(), self.current_pages(&lay))?;
let mut single = v.clone();
single["copies"] = json!(1);
@@ -238,6 +238,9 @@ impl Session {
comments: markup.comments,
paper,
links,
numeral: markup.numeral,
revisions: markup.revisions.clone(),
compress: p::bool(v, "compress").unwrap_or(true),
..Default::default()
};
let bytes = wordcraft_pdf::export_layout(doc, &lay, &opts).map_err(|e| CmdError::Failed(e.to_string()))?;
+20 -4
View File
@@ -168,16 +168,32 @@ impl Session {
/// area with the comments in balloons. Fields Word fills in for output show their fresh
/// results ([`crate::cmd::references::output_fields`]).
pub fn export_layout_with(&self, markup: bool) -> Arc<DocLayout> {
let out = crate::cmd::references::output_fields(&self.doc);
self.export_layout_of(out.as_ref().unwrap_or(&self.doc), markup)
self.output_layout(markup, false)
}
/// [`Session::export_layout_with`] of `doc`, this document as it is output.
pub(crate) fn export_layout_of(&self, doc: &Document, markup: bool) -> Arc<DocLayout> {
/// The layout a print job draws ([`Session::print_pdf`]): with `markup` as
/// [`Session::export_layout_with`]; without it the final text, as Word's "No Markup", so tracked
/// deletions, which the job doesn't draw, take no space either, whatever Track Changes
/// Options say. Page images keep [`Session::export_layout_with`]: they always show markup.
pub fn print_layout(&self, markup: bool) -> Arc<DocLayout> {
self.output_layout(markup, !markup)
}
/// The print-view layout for output; `final_text` leaves tracked deletions out.
fn output_layout(&self, markup: bool, final_text: bool) -> Arc<DocLayout> {
let out = crate::cmd::references::output_fields(&self.doc);
self.output_layout_of(out.as_ref().unwrap_or(&self.doc), markup, final_text)
}
/// [`Session::output_layout`] of `doc`, this document as it is output; `final_text` leaves tracked deletions out.
pub(crate) fn output_layout_of(&self, doc: &Document, markup: bool, final_text: bool) -> Arc<DocLayout> {
let (fn_name, fn_path) = self.resolved_filenames();
let opts = LayoutOptions {
view: ViewMode::Print,
hide_deleted: final_text,
comment_balloons: markup && self.prefs.markup.comments,
// Deletions Track Changes Options mark Hidden take no space, as on screen.
hide_marked: self.prefs.markup.hidden_deletions(),
numeral: self.view.numeral.resolve(SYSTEM_LOCALE.get().map(String::as_str)),
filename: Some(Arc::from(fn_name.as_str())),
filepath: Some(Arc::from(fn_path.as_str())),
+1
View File
@@ -197,6 +197,7 @@ pub(crate) fn pdf_options(opts: &ExportOptions) -> wordcraft_pdf::PdfOptions {
include_markup: opts.markup,
comments: opts.markup && opts.comments,
numeral: opts.numeral,
revisions: opts.revisions.clone(),
bookmark_error: crate::locale::bookmark_error(),
..Default::default()
}
+107
View File
@@ -8600,6 +8600,113 @@ fn insert_icon_places_a_picture_of_the_requested_size_that_saves_and_recolours()
assert!(s.run("picture.iconColor", &json!({})).is_err());
}
/// #5232: a PDF with markup (file.exportPdf, file.printPdf) marks tracked changes in the Track
/// Changes Options colours, not always by author.
#[test]
fn markup_pdf_takes_the_track_changes_option_colours() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
let markup = json!({"markup": true});
let uncompressed_markup = json!({"markup": true, "compress": false});
let pdf = |s: &Session| crate::io::save_bytes_opts("x.pdf", &s.doc, &cmd::file::export_options(s, &markup)).unwrap();
let print = |s: &Session| s.print_pdf(&markup).unwrap().0;
let (by_author, printed_by_author) = (pdf(&s), print(&s));
// Exports are deterministic, so differences are solely due to the colours.
assert_eq!(pdf(&s), by_author, "pdf export must be deterministic");
assert_eq!(print(&s), printed_by_author, "print_pdf must be deterministic");
let has = |t: &[&str], op: &str| {
let want: Vec<_> = op.split_ascii_whitespace().collect();
t.windows(want.len()).any(|w| w == want.as_slice())
};
let by_author_print_uncompressed = s.print_pdf(&uncompressed_markup).unwrap().0;
let by_author_print_raw = String::from_utf8_lossy(&by_author_print_uncompressed);
let by_author_print_tokens: Vec<_> = by_author_print_raw.split_ascii_whitespace().collect();
assert!(!has(&by_author_print_tokens, "0 0 1 rg") && !has(&by_author_print_tokens, "1 0 0 rg"), "by-author print has no pure blue or red");
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let opts = cmd::file::export_options(&s, &markup);
assert_eq!(opts.revisions.insert_color, Some(wordcraft_doc::props::Rgb(0, 0, 255)));
assert_eq!(opts.revisions.delete_color, Some(wordcraft_doc::props::Rgb(255, 0, 0)));
let coloured_pdf = pdf(&s);
let coloured_print = print(&s);
assert_ne!(coloured_pdf, by_author, "file.exportPdf ignores the tracking colours");
assert_ne!(coloured_print, printed_by_author, "file.printPdf ignores the tracking colours");
let coloured_print_uncompressed = s.print_pdf(&uncompressed_markup).unwrap().0;
let print_raw = String::from_utf8_lossy(&coloured_print_uncompressed);
let print_tokens: Vec<_> = print_raw.split_ascii_whitespace().collect();
assert!(has(&print_tokens, "0 0 1 rg"), "coloured print_pdf has blue operator for insertion");
assert!(has(&print_tokens, "1 0 0 rg"), "coloured print_pdf has red operator for deletion");
}
/// #5232 review: File › Print without Print Markup leaves out tracked deletions in layout,
/// so the page count matches the PDF export and deletions take no blank space.
#[test]
fn print_jobs_without_markup_lay_out_the_final_text() {
let text: Vec<String> = (0..200).map(|i| format!("Line {i} of the original agreement")).collect();
let mut s = Session::new(wordcraft_doc::Document::from_text(&text.join("\n")));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.all", &json!({})).unwrap();
s.run("text.insert", &json!({"text": "Replaced"})).unwrap();
// With markup: 200 deleted lines take space in print.
let (marked_pdf, marked_plan) = s.print_pdf(&json!({"markup": true})).unwrap();
assert!(marked_plan.chosen > 1);
assert!(marked_pdf.starts_with(b"%PDF-"));
// Without markup: final text only, 1 page.
let (plain_pdf, plain_plan) = s.print_pdf(&json!({"markup": false})).unwrap();
assert_eq!(plain_plan.chosen, 1);
assert!(plain_pdf.starts_with(b"%PDF-"));
}
/// #5232 review: page images (render_png and file.exportPng) respect Track Changes Options
/// colours and hidden deletions.
#[test]
fn markup_png_takes_the_track_changes_option_colours() {
let mut s = Session::new(wordcraft_doc::Document::from_text("Governed by Kansas law."));
s.run("review.trackChanges", &json!({"value": true})).unwrap();
s.run("select.text", &json!({"text": "Kansas"})).unwrap();
s.run("text.insert", &json!({"text": "Missouri"})).unwrap();
let markup_opts = json!({"markup": true});
let by_author_opts = cmd::file::export_options(&s, &markup_opts);
let by_author_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &by_author_opts).unwrap();
// Change tracking options to blue insertions / red deletions.
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let coloured_opts = cmd::file::export_options(&s, &markup_opts);
let coloured_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &coloured_opts).unwrap();
assert_ne!(by_author_png, coloured_png, "PNG export must reflect tracking colours");
// Also verify via file.exportPng command.
struct TempDir(std::path::PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let dir = TempDir(std::env::temp_dir().join(format!("wordcraft-tracking-png-{}", std::process::id())));
std::fs::create_dir_all(&dir.0).unwrap();
let p1 = dir.0.join("by_author.png");
let p2 = dir.0.join("coloured.png");
s.run("review.trackingOptions", &json!({"insertColor": "byAuthor", "deleteColor": "byAuthor"})).unwrap();
s.run("file.exportPng", &json!({"path": p1.to_string_lossy(), "markup": true, "scale": 1.0})).unwrap();
s.run("review.trackingOptions", &json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
s.run("file.exportPng", &json!({"path": p2.to_string_lossy(), "markup": true, "scale": 1.0})).unwrap();
assert_ne!(std::fs::read(&p1).unwrap(), std::fs::read(&p2).unwrap());
assert_eq!(std::fs::read(&p1).unwrap(), by_author_png);
assert_eq!(std::fs::read(&p2).unwrap(), coloured_png);
// Verify hidden deletions take no space in PNG export.
s.run("review.trackingOptions", &json!({"deleteMark": "hidden"})).unwrap();
let hidden_opts = cmd::file::export_options(&s, &markup_opts);
let hidden_png = crate::io_ext::render_png(&s.doc, 0, 1.0, &hidden_opts).unwrap();
assert_ne!(hidden_png, coloured_png, "hidden deletions must affect PNG pixels/layout");
}
/// Print Markup (#589): `file.printMarkup` or a command's `markup` puts the comments into PDFs
/// (balloons beside the scaled page) and at the end of HTML, Markdown and text copies.
#[test]
+1
View File
@@ -220,6 +220,7 @@ impl Exporter<'_> {
}
}
/// Draws the content of a single page (background, watermark, headers, footers, body items, and comments) onto the surface.
pub(crate) fn page(&mut self, s: &mut Surface, page: &Page, w: f32, h: f32) {
if let Some(c) = self.doc.settings.page_color
&& let Some(p) = rect_path(&Rect::new(0.0, 0.0, w, h))
+6
View File
@@ -50,6 +50,9 @@ pub struct PdfOptions {
/// How [`export`] shows digits (the Numeral setting; callers resolve `System`, see
/// [`NumeralMode::resolve`]). [`export_layout`] keeps the layout it is given.
pub numeral: NumeralMode,
/// How tracked changes are marked (Track Changes Options): the insertion and deletion marks
/// and colours the screen shows (#5232). Default: marks as on screen, colours by author.
pub revisions: wordcraft_layout::display::MarkupOptions,
/// What [`export`] shows for a page reference to a bookmark the document doesn't have, in the
/// interface language (`None`: Word's English "Error! Bookmark not defined."). [`export_layout`]
/// keeps the layout it is given.
@@ -70,6 +73,7 @@ impl PdfOptions {
dim_body: false,
markup: self.include_markup,
placeholders: false,
revisions: self.revisions.clone(),
..Default::default()
}
}
@@ -79,6 +83,7 @@ impl PdfOptions {
pub fn layout_options(&self) -> wordcraft_layout::LayoutOptions {
wordcraft_layout::LayoutOptions {
hide_deleted: !self.include_markup,
hide_marked: self.revisions.hidden_deletions(),
comment_balloons: self.comments,
numeral: self.numeral,
output_page_refs: true,
@@ -105,6 +110,7 @@ impl Default for PdfOptions {
links: true,
paper: None,
numeral: NumeralMode::Arabic,
revisions: wordcraft_layout::display::MarkupOptions::default(),
bookmark_error: None,
}
}
+143
View File
@@ -4,6 +4,7 @@ use wordcraft_doc::para::InlineObject;
use wordcraft_doc::picfx::PicFx;
use wordcraft_doc::props::NumRef;
use wordcraft_doc::{Block, CharProps, Document, ListKind, Paragraph, Table, Watermark, para_block};
use wordcraft_layout::display::{DeleteMark, MarkupOptions};
use crate::*;
use wordcraft_layout::LayoutOptions;
@@ -167,6 +168,65 @@ fn extract_text(bytes: &[u8]) -> Vec<String> {
.collect()
}
/// Extract text runs with their RGB fill colour from `bytes`.
fn extract_colored_text(bytes: &[u8]) -> Vec<(String, [u8; 3])> {
use hayro_interpret::font::Glyph;
use hayro_interpret::{
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
interpret_page,
};
use hayro_syntax::Pdf;
/// A testing device that records extracted text runs along with their RGB fill colour.
struct Ex(Vec<(String, [u8; 3])>);
impl Device<'_> for Ex {
/// Ignore soft masks during text extraction.
fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
/// Ignore blend modes during text extraction.
fn set_blend_mode(&mut self, _: BlendMode) {}
/// Ignore paths during text extraction.
fn draw_path(&mut self, _: &kurbo::BezPath, _: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {}
/// Ignore clip paths during text extraction.
fn push_clip_path(&mut self, _: &ClipPath) {}
/// Ignore transparency groups during text extraction.
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
/// Records glyph text with its non-stroking RGB color, merging adjacent glyphs of identical color.
fn draw_glyph(&mut self, g: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, paint: &Paint<'_>, mode: &GlyphDrawMode) {
if matches!(mode, GlyphDrawMode::Stroke(_)) {
return;
}
let Paint::Color(color) = paint else { return };
let rgba = color.to_rgba().to_rgba8();
let rgb = [rgba[0], rgba[1], rgba[2]];
let ch = match g.as_unicode() {
Some(hayro_cmap::BfString::Char(c)) => c.to_string(),
Some(hayro_cmap::BfString::String(s)) => s.to_string(),
None => "\u{FFFD}".to_string(),
};
if let Some((last_text, last_rgb)) = self.0.last_mut()
&& *last_rgb == rgb
{
last_text.push_str(&ch);
return;
}
self.0.push((ch, rgb));
}
/// Ignore images during text extraction.
fn draw_image(&mut self, _: Image<'_, '_>, _: kurbo::Affine) {}
/// Ignore clip path pop during text extraction.
fn pop_clip_path(&mut self) {}
/// Ignore transparency group pop during text extraction.
fn pop_transparency_group(&mut self) {}
}
let pdf = Pdf::new(bytes.to_vec()).expect("parse");
let cache = InterpreterCache::new();
let mut ex = Ex(Vec::new());
for page in pdf.pages().iter() {
let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default());
interpret_page(page, &mut ctx, &mut ex);
}
ex.0
}
fn squash(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
@@ -293,6 +353,89 @@ fn tracked_deletions_are_left_out_without_markup() {
assert_eq!(text, "Keep DELETEDTEXT INSERTED");
}
/// #5232: the Track Changes Options colours (blue insertions, red deletions) reach the PDF instead
/// of every revision taking its author's colour.
#[test]
fn markup_takes_the_track_changes_option_colours() {
use wordcraft_doc::props::Rgb;
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
let n = p.len();
p.insert_text(n, "Missouri", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
d.body = vec![para_block(p)];
// By author: both revisions take Ada's colour (#B01E8F = [176, 30, 143]), no pure blue or red.
let by_author_bytes = export(&d, &PdfOptions { include_markup: true, compress: false, ..Default::default() }).unwrap();
let by_author_runs = extract_colored_text(&by_author_bytes);
let kansas_author = by_author_runs.iter().find(|(s, _)| s.contains("Kansas")).map(|(_, c)| *c).expect("Kansas present");
let missouri_author = by_author_runs.iter().find(|(s, _)| s.contains("Missouri")).map(|(_, c)| *c).expect("Missouri present");
assert_eq!(kansas_author, missouri_author, "by-author colours must match for the same author");
assert_ne!(kansas_author, [255, 0, 0], "by-author is not red");
assert_ne!(missouri_author, [0, 0, 255], "by-author is not blue");
// With explicit Track Changes colours: insertions are blue, deletions are red.
let blue = Rgb(0, 0, 255);
let red = Rgb(255, 0, 0);
let coloured_opts = PdfOptions {
include_markup: true,
compress: false,
revisions: MarkupOptions { insert_color: Some(blue), delete_color: Some(red), ..Default::default() },
..Default::default()
};
let coloured_bytes = export(&d, &coloured_opts).unwrap();
let coloured_runs = extract_colored_text(&coloured_bytes);
let kansas_color = coloured_runs.iter().find(|(s, _)| s.contains("Kansas")).map(|(_, c)| *c).expect("Kansas present");
let missouri_color = coloured_runs.iter().find(|(s, _)| s.contains("Missouri")).map(|(_, c)| *c).expect("Missouri present");
assert_eq!(kansas_color, [255, 0, 0], "deleted Kansas must be red");
assert_eq!(missouri_color, [0, 0, 255], "inserted Missouri must be blue");
// Also assert the PDF content stream has the corresponding color operators preceding each run.
let raw = String::from_utf8_lossy(&coloured_bytes);
let tokens: Vec<_> = raw.split_ascii_whitespace().collect();
let has = |op: &str| {
let want: Vec<_> = op.split_ascii_whitespace().collect();
tokens.windows(want.len()).any(|w| w == want.as_slice())
};
assert!(has("1 0 0 rg"), "raw PDF stream contains red non-stroking operator");
assert!(has("0 0 1 rg"), "raw PDF stream contains blue non-stroking operator");
}
/// #5232: deletions marked Hidden in Track Changes Options take no space and are omitted from
/// the exported PDF with markup.
#[test]
fn hidden_deletions_stay_out_of_markup_pdf() {
use wordcraft_doc::{Revision, RevisionKind};
let mut d = Document::new();
d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Ada".into(), date: String::new(), move_name: None });
d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None });
let mut p = Paragraph::with_text("Keep ", CharProps::default());
let n = p.len();
p.insert_text(n, "Kansas ", &CharProps { del: Some(0), ..Default::default() }).unwrap();
let n = p.len();
p.insert_text(n, "Missouri", &CharProps { ins: Some(1), ..Default::default() }).unwrap();
d.body = vec![para_block(p)];
// Strikethrough: deleted Kansas is included in markup PDF.
let strike_opts = PdfOptions {
include_markup: true,
revisions: MarkupOptions { delete_mark: DeleteMark::Strikethrough, ..Default::default() },
..Default::default()
};
let strike_text = squash(&extract_text(&export(&d, &strike_opts).unwrap()).concat());
assert_eq!(strike_text, "Keep Kansas Missouri");
// Hidden: deleted Kansas is omitted from markup PDF.
let hidden_opts =
PdfOptions { include_markup: true, revisions: MarkupOptions { delete_mark: DeleteMark::Hidden, ..Default::default() }, ..Default::default() };
let hidden_text = squash(&extract_text(&export(&d, &hidden_opts).unwrap()).concat());
assert_eq!(hidden_text, "Keep Missouri");
}
#[test]
fn deleted_heading_text_stays_out_of_bookmarks_and_tags() {
use wordcraft_doc::{Revision, RevisionKind};
+69 -7
View File
@@ -144,15 +144,24 @@ pub(crate) const PAGES_PER_SHEET: [(&str, &str); 8] = [
("bookletReverse", "Booklet (right binding)"),
];
/// What the preview's layout is made from besides the document's text: the revision, Print
/// Markup, the file name and path FILENAME fields show (#6282: Save As and Rename change them
/// without an edit), and the font database generation the app has seen (#6283:
/// `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, bool, (String, String), u64);
/// The settings that decide how tracked changes and comments look in the print preview:
/// Print Markup and Track Changes Options.
type MarkupKey = (bool, wordcraft_layout::display::MarkupOptions);
/// The [`MarkupKey`] now.
fn markup_key(app: &WordApp) -> MarkupKey {
(app.session.prefs.print_markup, app.session.prefs.markup.clone())
}
/// What the preview's layout is made from besides the document's text: the document id, the
/// revision, Print Markup and Track Changes Options, the file name and path FILENAME fields show
/// (#6282: Save As and Rename change them without an edit), and the font database generation the
/// app has seen (#6283: `WordApp::watch_fonts` moves it when fonts are added or removed).
type LayoutKey = (u64, u64, MarkupKey, (String, String), u64);
/// The [`LayoutKey`] now.
fn layout_key(app: &WordApp) -> LayoutKey {
(app.session.rev(), app.session.prefs.print_markup, app.session.resolved_filenames(), app.font_generation)
(app.session.document_id(), app.session.rev(), markup_key(app), app.session.resolved_filenames(), app.font_generation)
}
/// The output layout, kept in `cache` while what it is made from ([`LayoutKey`]) is unchanged.
@@ -164,11 +173,21 @@ fn layout_of(app: &WordApp, cache: &mut Option<(LayoutKey, Arc<DocLayout>)>) ->
{
return l.clone();
}
let l = app.session.export_layout_with(app.session.prefs.print_markup);
let l = app.session.print_layout(app.session.prefs.print_markup);
*cache = Some((key, l.clone()));
l
}
/// How the preview draws a page: tracked changes marked as the print job marks them, headers and
/// footers at full strength (the preview is the printed page, not the editing view).
pub(super) fn preview_options(app: &WordApp) -> wordcraft_render::RenderOptions {
let mut opts = wordcraft_render::RenderOptions::default();
opts.display.markup = app.session.prefs.print_markup;
opts.display.revisions = app.session.prefs.markup.clone();
opts.display.dim_header = false;
opts
}
/// One choice list over `(id, label)` pairs, named `label`; true when the choice changed.
fn choice(ui: &mut Ui, label: &str, salt: &str, current: &mut String, items: &[(&str, &str)]) -> bool {
let mut changed = false;
@@ -584,4 +603,47 @@ mod tests {
let (sparse, dense) = (at(1.0), at(2.0));
assert!(sparse > 0 && dense > sparse * 2, "{dense} {sparse}");
}
/// The preview pages as the print job does (#5269 review): without Print Markup tracked
/// deletions take no space, whatever Track Changes Options mark them with.
#[test]
fn the_preview_pages_as_the_print_job() {
let text: Vec<String> = (0..200).map(|i| format!("Line {i} of the old text")).collect();
let doc = wordcraft_doc::Document::from_text(&text.join("\n"));
let mut app = crate::WordApp::new(wordcraft_engine::Session::new(doc), Default::default());
let mut cache = None;
app.run("review.trackChanges", json!({"value": true})).unwrap();
app.run("select.all", json!({})).unwrap();
app.run("text.insert", json!({"text": "Kept"})).unwrap();
// The preview is the printed page: headers and footers draw at full strength (#6267).
assert!(!preview_options(&app).display.dim_header);
let mut pages = |app: &crate::WordApp| (layout_of(app, &mut cache).pages.len(), app.session.print_pdf(&json!({})).unwrap().1.chosen);
app.run("file.printMarkup", json!({"value": true})).unwrap();
let (marked, job) = pages(&app);
assert!(marked > 1 && marked == job, "{marked} vs {job}");
app.run("file.printMarkup", json!({"value": false})).unwrap();
assert_eq!(pages(&app), (1, 1));
// The cached layout follows the Delete mark option too (it changes the layout with markup).
app.run("file.printMarkup", json!({"value": true})).unwrap();
app.run("review.trackingOptions", json!({"deleteMark": "hidden"})).unwrap();
assert_eq!(pages(&app), (1, 1));
// Changing revision colours refreshes the preview revision even on the same page count.
let rev_before = preview::inputs(&app);
app.run("review.trackingOptions", json!({"insertColor": "0000FF", "deleteColor": "FF0000"})).unwrap();
let rev_after = preview::inputs(&app);
assert_ne!(rev_before, rev_after, "tracking colours refresh preview revision");
}
/// Two documents at the same revision drawn in one window's context (#5270 review): each
/// preview gets its own layout, not the other's cached one.
#[test]
fn the_preview_cache_tells_documents_apart() {
let long: Vec<String> = (0..200).map(|i| format!("Line {i}")).collect();
let app = |text: &str| crate::WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(text)), Default::default());
let (long, short) = (app(&long.join("\n")), app("One line"));
assert_eq!(long.session.rev(), short.session.rev(), "the test needs equal revisions");
let mut cache = None;
assert!(layout_of(&long, &mut cache).pages.len() > 1);
assert_eq!(layout_of(&short, &mut cache).pages.len(), 1);
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ use craft::ui::primitives::textures::{Priority, Revision, TextureState, ThumbRen
use egui::{Color32, ColorImage, Ui};
use wordcraft_layout::DocLayout;
use super::{PrintPage, layout_key};
use super::{PrintPage, layout_key, preview_options};
use crate::WordApp;
/// The salt of the preview's thumbnail store.
@@ -68,7 +68,7 @@ impl ThumbSource<usize> for SheetSource<'_> {
}
let x0 = ((slot.x + (slot.width - pg.w * k) / 2.0) * scale).round() as i64;
let y0 = ((slot.y + (slot.height - pg.h * k) / 2.0) * scale).round() as i64;
let page = wordcraft_render::render_page(&self.app.session.doc, pg, page_scale, &Default::default());
let page = wordcraft_render::render_page(&self.app.session.doc, pg, page_scale, &preview_options(self.app));
let straight = page.to_straight();
let row_len = (page.width as usize).max(1) * 4;
for (row, line) in straight.chunks_exact(row_len).enumerate() {
File diff suppressed because one or more lines are too long
+2 -1
View File
File diff suppressed because one or more lines are too long
+2 -1
View File
File diff suppressed because one or more lines are too long