mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 15:26:12 +00:00
Merge pull request #6242 from annoybot/fix/pdf-gradient-forms-macos
M4: fix PDF gradient placement in transparency groups
This commit is contained in:
Generated
+2
@@ -6652,6 +6652,8 @@ dependencies = [
|
||||
"kurbo 0.13.1",
|
||||
"log",
|
||||
"md-5",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"roxmltree 0.21.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -52,3 +52,9 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
serde_json = { workspace = true }
|
||||
# `draw_text`, to write test files with live text as other writers do.
|
||||
krilla = { workspace = true, features = ["simple-text"] }
|
||||
|
||||
# An independent raster oracle for gradient placement in PDF forms. These are test-only macOS
|
||||
# bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer.
|
||||
[target.'cfg(target_os = "macos")'.dev-dependencies]
|
||||
objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFData"] }
|
||||
objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGBitmapContext", "CGColorSpace", "CGContext", "CGDataProvider", "CGImage", "CGPDFDocument", "CGPDFPage"] }
|
||||
|
||||
@@ -9,12 +9,11 @@ use craft_pdf::write::{self, Metadata};
|
||||
use krilla::color::separation::{Color as SepColor, SeparationColorant, SeparationSpace};
|
||||
use krilla::color::{cmyk, luma, rgb};
|
||||
use krilla::configure::{Archival, PdfVersion};
|
||||
use krilla::geom::{Path, PathBuilder, Size, Transform};
|
||||
use krilla::geom::{Path, PathBuilder, Size};
|
||||
use krilla::image::Image;
|
||||
use krilla::num::NormalizedF32;
|
||||
use krilla::page::PageSettings;
|
||||
use krilla::paint::{Fill, LinearGradient, RadialGradient, SpreadMethod, Stop, Stroke, StrokeDash};
|
||||
use krilla::surface::Surface;
|
||||
use krilla::text::{Glyph, GlyphId, KrillaGlyph};
|
||||
use kurbo::{PathEl, Shape, Vec2};
|
||||
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
@@ -28,6 +27,7 @@ use crate::forms::Mark;
|
||||
use crate::lab_spot::{find, rfind};
|
||||
use crate::marks::PageBoxes;
|
||||
use crate::output::ColorOut;
|
||||
use crate::surface::Surface;
|
||||
use crate::{Compatibility, ExportReport, PdfError, PdfOptions, Standard};
|
||||
|
||||
mod entry;
|
||||
@@ -131,7 +131,7 @@ mod tests {
|
||||
fn writable_bounds_values_the_transform_and_values_through_it() {
|
||||
let mut pdf = krilla::Document::new();
|
||||
let mut page = pdf.start_page_with(PageSettings::new(Size::from_wh(100.0, 100.0).unwrap()));
|
||||
let mut s = page.surface();
|
||||
let mut s = Surface::page(page.surface(), 100.0);
|
||||
let r = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
assert!(writable(&s, Affine::IDENTITY, r));
|
||||
assert!(!writable(&s, Affine::IDENTITY, Rect::new(-2_147_483_649.0, 0.0, 10.0, 10.0)));
|
||||
|
||||
@@ -3,9 +3,11 @@ use vectorcraft_geom::Point;
|
||||
use super::entry::RgbInCmyk;
|
||||
use super::{
|
||||
Affine, Arc, BezPath, BlendMode, Color, Compatibility, Document, Exporter, Fill, FillRule, HashMap, HashSet, Node, NormalizedF32, Path,
|
||||
PathBuilder, PathEl, Rect, Shape, Standard, Surface, Transform, cmyk, krilla, luma, rgb,
|
||||
PathBuilder, PathEl, Rect, Shape, Standard, Surface, cmyk, krilla, luma, rgb,
|
||||
};
|
||||
|
||||
pub(super) use crate::surface::xf;
|
||||
|
||||
/// How deep inline graphics nest before they are left out.
|
||||
pub(super) const MAX_INLINE_DEPTH: u32 = 4;
|
||||
|
||||
@@ -96,11 +98,6 @@ pub(super) const MAX_GRADIENT_PX: f64 = 4096.0;
|
||||
/// with overflow checks it panics on -2,147,483,648.
|
||||
pub(super) const MAX_COORD: f64 = 1e9;
|
||||
|
||||
pub(super) fn xf(a: Affine) -> Transform {
|
||||
let c = a.as_coeffs();
|
||||
Transform::from_row(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32, c[4] as f32, c[5] as f32)
|
||||
}
|
||||
|
||||
/// The current transform of surface `s` in the content stream it draws into, without that stream's
|
||||
/// root transform (a page's y flip).
|
||||
pub(super) fn ctm(s: &Surface) -> Affine {
|
||||
@@ -203,9 +200,12 @@ pub(super) fn cover(s: &mut Surface, page: Rect, level: u8, opacity: f32) {
|
||||
/// group of that opacity that, unlike the writer's opacity groups, is not isolated.
|
||||
/// The cover is white, so a reader that takes every soft mask as a luminosity mask shows the same.
|
||||
pub(super) fn constant_mask(s: &mut Surface, page: Rect, alpha: f32) -> krilla::mask::Mask {
|
||||
let transform = s.group_transform();
|
||||
let mut sb = s.stream_builder();
|
||||
let mut ms = sb.surface();
|
||||
let mut ms = Surface::stream(sb.surface());
|
||||
ms.push_transform(&transform);
|
||||
cover(&mut ms, page, 255, alpha);
|
||||
ms.pop();
|
||||
ms.finish();
|
||||
krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Alpha)
|
||||
}
|
||||
|
||||
@@ -22,8 +22,10 @@ impl Exporter<'_> {
|
||||
/// Opacity mask → luminosity soft mask. Outside the art the backdrop is black (clip) or white;
|
||||
/// invert is a white Difference rect on top (luminance is linear, so luma(1 − c) = 1 − luma(c)).
|
||||
fn soft_mask(&mut self, s: &mut Surface, m: &vectorcraft_doc::OpacityMask, page: Rect) -> Option<krilla::mask::Mask> {
|
||||
let transform = s.group_transform();
|
||||
let mut sb = s.stream_builder();
|
||||
let mut ms = sb.surface();
|
||||
let mut ms = Surface::stream(sb.surface());
|
||||
ms.push_transform(&transform);
|
||||
// An opaque backdrop when it matters: white outside the art (no clip), or black for the
|
||||
// inverting Difference pass below to turn white.
|
||||
if !m.clip || m.invert {
|
||||
@@ -39,6 +41,8 @@ impl Exporter<'_> {
|
||||
self.image_left_out = image_left_out.map(|outer| outer || incomplete);
|
||||
(self.knockout, self.overprint) = (knockout, overprint);
|
||||
if incomplete {
|
||||
ms.pop();
|
||||
ms.finish();
|
||||
return None;
|
||||
}
|
||||
if m.invert {
|
||||
@@ -46,6 +50,7 @@ impl Exporter<'_> {
|
||||
cover(&mut ms, page, 255, 1.0);
|
||||
ms.pop();
|
||||
}
|
||||
ms.pop();
|
||||
ms.finish();
|
||||
Some(krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity))
|
||||
}
|
||||
@@ -96,21 +101,27 @@ impl Exporter<'_> {
|
||||
s.opacity = 1.0;
|
||||
s
|
||||
};
|
||||
let transform = s.group_transform();
|
||||
let mut sb = s.stream_builder();
|
||||
let mut ms = sb.surface();
|
||||
let mut ms = Surface::stream(sb.surface());
|
||||
ms.push_transform(&transform);
|
||||
cover(&mut ms, page, 255, 1.0);
|
||||
let alpha = {
|
||||
let transform = ms.group_transform();
|
||||
let mut ab = ms.stream_builder();
|
||||
let mut als = ab.surface();
|
||||
let mut als = Surface::stream(ab.surface());
|
||||
als.push_transform(&transform);
|
||||
let overprint = std::mem::take(&mut self.overprint);
|
||||
self.measured_node(&mut als, &shape, page, false, Some(measured));
|
||||
self.overprint = overprint;
|
||||
als.pop();
|
||||
als.finish();
|
||||
krilla::mask::Mask::new(ab.finish(), krilla::mask::MaskType::Alpha)
|
||||
};
|
||||
ms.push_mask(alpha);
|
||||
cover(&mut ms, page, 0, 1.0);
|
||||
ms.pop();
|
||||
ms.pop();
|
||||
ms.finish();
|
||||
krilla::mask::Mask::new(sb.finish(), krilla::mask::MaskType::Luminosity)
|
||||
}
|
||||
|
||||
@@ -351,7 +351,7 @@ impl Exporter<'_> {
|
||||
let cell = Rect::new(0.0, 0.0, pw, ph);
|
||||
let tiles = def.instances_in(Affine::IDENTITY, cell);
|
||||
let mut sb = s.stream_builder();
|
||||
let mut cs = sb.surface();
|
||||
let mut cs = Surface::stream(sb.surface());
|
||||
let reaches_out = tiles.iter().any(|t| t.visual_bounds().is_some_and(|b| cell.intersect(b) != b));
|
||||
let clip = reaches_out.then(|| to_path(&cs, &cell.to_path(0.1))).flatten();
|
||||
if let Some(c) = &clip {
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::entry::RgbInCmyk;
|
||||
use super::exporter::{constant_mask, cover, to_path, writable, xf};
|
||||
use super::{
|
||||
Affine, Arc, Archival, ColorOut, Compatibility, Document, Exporter, HashSet, Image, Metadata, Node, PageSettings, PdfError, PdfVersion, Rect,
|
||||
Shape, Size, Standard, Vec2, find, krilla, rfind, write,
|
||||
Shape, Size, Standard, Surface, Vec2, find, krilla, rfind, write,
|
||||
};
|
||||
|
||||
/// A PDF being written, shared by export and print: the file's configuration and metadata, then
|
||||
@@ -125,7 +125,7 @@ impl Writer {
|
||||
let size = Size::from_wh(w.max(least) as f32, h.max(least) as f32).ok_or_else(|| PdfError::BadSetting(format!("page size {w} × {h}")))?;
|
||||
let at = |b: Rect| krilla::geom::Rect::from_ltrb(b.x0 as f32, b.y0 as f32, b.x1 as f32, b.y1 as f32);
|
||||
let mut page = self.pdf.document_mut().start_page_with(PageSettings::new(size).with_trim_box(at(sheet.trim)).with_bleed_box(at(sheet.bleed)));
|
||||
let mut s = page.surface();
|
||||
let mut s = Surface::page(page.surface(), size.height());
|
||||
let paper = Rect::new(0.0, 0.0, w, h);
|
||||
if sheet.negative {
|
||||
cover(&mut s, paper, 255, 1.0);
|
||||
|
||||
+10
-2
@@ -13,7 +13,6 @@ use std::io::Read;
|
||||
use craft_pdf::write::backend as krilla;
|
||||
use krilla::geom::PathBuilder;
|
||||
use krilla::graphic::Graphic;
|
||||
use krilla::surface::Surface;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
@@ -21,6 +20,7 @@ use vectorcraft_doc::{Document, Node, NodeKind};
|
||||
use crate::encrypt::{Lexer, Obj, StreamSpans, Tok, int, stream_spans};
|
||||
use crate::output::{deflate, text_string};
|
||||
use crate::patch::{Patch, Xref};
|
||||
use crate::surface::{Surface, affine};
|
||||
use crate::{PdfError, PdfSettings, Standard};
|
||||
|
||||
/// What a marked form is.
|
||||
@@ -87,6 +87,9 @@ pub(crate) fn form(s: &mut Surface, mark: Mark, draw: impl FnOnce(&mut Surface))
|
||||
/// form's drawing space), rounded outwards to whole units: [`finish`] gives the form a box that
|
||||
/// covers the paper and the art.
|
||||
pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rect, draw: impl FnOnce(&mut Surface)) {
|
||||
// The art and its box move into page space together; keeping the old local paper here
|
||||
// would clip layers on translated artboards or give the importer a spurious clipping group.
|
||||
let paper = affine(s.group_transform()).transform_rect_bbox(paper);
|
||||
let corner = |x: f64, y: f64| (x as f32, y as f32);
|
||||
marked(s, Mark::Layer(i), [corner(paper.x0.floor(), paper.y0.floor()), corner(paper.x1.ceil(), paper.y1.ceil())], draw);
|
||||
}
|
||||
@@ -94,8 +97,9 @@ pub(crate) fn layer_form(s: &mut Surface, i: usize, paper: vectorcraft_geom::Rec
|
||||
/// Draw `draw` as a form of its own, marked `mark`: an empty clip from the mark's first point
|
||||
/// through `rest`.
|
||||
fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce(&mut Surface)) {
|
||||
let transform = s.group_transform();
|
||||
let mut sb = s.stream_builder();
|
||||
let mut fs = sb.surface();
|
||||
let mut fs = Surface::stream(sb.surface());
|
||||
let (x, y) = mark.at();
|
||||
let mut pb = PathBuilder::new();
|
||||
pb.move_to(x, y);
|
||||
@@ -108,10 +112,14 @@ fn marked(s: &mut Surface, mark: Mark, rest: [(f32, f32); 2], draw: impl FnOnce(
|
||||
fs.push_clip_path(&p, &krilla::paint::FillRule::NonZero);
|
||||
fs.pop();
|
||||
}
|
||||
fs.push_transform(&transform);
|
||||
draw(&mut fs);
|
||||
fs.pop();
|
||||
fs.finish();
|
||||
let stream = sb.finish();
|
||||
s.push_transform(&transform.invert().unwrap_or_default());
|
||||
s.draw_graphic(Graphic::new(stream, false));
|
||||
s.pop();
|
||||
}
|
||||
|
||||
// ---------- finishing the written file ----------
|
||||
|
||||
@@ -70,6 +70,7 @@ mod presets;
|
||||
mod print;
|
||||
mod settings;
|
||||
mod streams;
|
||||
mod surface;
|
||||
mod syntax;
|
||||
|
||||
pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with};
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Keep form XObjects in page space. Quartz resolves shading patterns inside a form against the
|
||||
//! page's initial space, whereas other readers also apply the transform at the form's invocation.
|
||||
//! Moving that transform inside the form makes both interpretations agree (including gradients
|
||||
//! in opacity groups, masks, layers and overprinting art), without rasterizing the art.
|
||||
//!
|
||||
//! krilla's page surface has an implicit y flip which `ctm()` does not include. Remember that
|
||||
//! root separately; a form's surface has an identity root. A group still counts as one push/pop
|
||||
//! for the drawing code, even though moving its transform takes three krilla pushes.
|
||||
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
use craft_pdf::write::backend as krilla;
|
||||
use krilla::blend::BlendMode;
|
||||
use krilla::geom::{Path, Transform};
|
||||
use krilla::mask::Mask;
|
||||
use krilla::num::NormalizedF32;
|
||||
use krilla::paint::FillRule;
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
pub(crate) fn xf(a: Affine) -> Transform {
|
||||
let c = a.as_coeffs();
|
||||
Transform::from_row(c[0] as f32, c[1] as f32, c[2] as f32, c[3] as f32, c[4] as f32, c[5] as f32)
|
||||
}
|
||||
|
||||
pub(crate) fn affine(t: Transform) -> Affine {
|
||||
Affine::new([t.sx(), t.ky(), t.kx(), t.sy(), t.tx(), t.ty()].map(f64::from))
|
||||
}
|
||||
|
||||
struct Push {
|
||||
count: usize,
|
||||
root: Affine,
|
||||
}
|
||||
|
||||
/// A drawing surface whose form groups keep gradients and masks in the same page space.
|
||||
pub(crate) struct Surface<'a> {
|
||||
inner: krilla::surface::Surface<'a>,
|
||||
root: Affine,
|
||||
pushes: Vec<Push>,
|
||||
}
|
||||
|
||||
impl<'a> Surface<'a> {
|
||||
/// Wrap a page while recording the writer's implicit Y flip outside its reported CTM.
|
||||
pub fn page(inner: krilla::surface::Surface<'a>, height: f32) -> Self {
|
||||
Self { inner, root: Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, height.into()]), pushes: vec![] }
|
||||
}
|
||||
|
||||
/// Wrap a form or pattern stream, which starts without a page's implicit Y flip.
|
||||
pub fn stream(inner: krilla::surface::Surface<'a>) -> Self {
|
||||
Self { inner, root: Affine::IDENTITY, pushes: vec![] }
|
||||
}
|
||||
|
||||
/// Current drawing space → page space, for both a form's art and its mask. A singular
|
||||
/// enclosing transform draws no area: keep that form local rather than trying to invert it.
|
||||
pub fn group_transform(&self) -> Transform {
|
||||
let t = xf(self.root * affine(self.inner.ctm()));
|
||||
if t.invert().is_some() { t } else { Transform::identity() }
|
||||
}
|
||||
|
||||
/// Move the enclosing transform inside a form and record its three pushes as one group.
|
||||
fn group(&mut self, push: impl FnOnce(&mut krilla::surface::Surface)) {
|
||||
let t = self.group_transform();
|
||||
self.inner.push_transform(&t.invert().unwrap_or_default());
|
||||
push(&mut self.inner);
|
||||
self.inner.push_transform(&t);
|
||||
self.pushes.push(Push { count: 3, root: self.root });
|
||||
self.root = Affine::IDENTITY;
|
||||
}
|
||||
|
||||
/// Apply opacity in page space when it creates a form; full opacity is a plain push.
|
||||
pub fn push_opacity(&mut self, opacity: NormalizedF32) {
|
||||
if opacity == NormalizedF32::ONE {
|
||||
// krilla does not create a form for full opacity.
|
||||
self.inner.push_opacity(opacity);
|
||||
self.plain_push();
|
||||
} else {
|
||||
self.group(|s| s.push_opacity(opacity));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_isolated(&mut self) {
|
||||
self.group(|s| s.push_isolated());
|
||||
}
|
||||
|
||||
/// The mask's stream is already in [`Self::group_transform`]'s space, like the group's art.
|
||||
pub fn push_mask(&mut self, mask: Mask) {
|
||||
self.group(|s| s.push_mask(mask));
|
||||
}
|
||||
|
||||
fn plain_push(&mut self) {
|
||||
self.pushes.push(Push { count: 1, root: self.root });
|
||||
}
|
||||
|
||||
pub fn push_transform(&mut self, transform: &Transform) {
|
||||
self.inner.push_transform(transform);
|
||||
self.plain_push();
|
||||
}
|
||||
|
||||
pub fn push_clip_path(&mut self, path: &Path, rule: &FillRule) {
|
||||
self.inner.push_clip_path(path, rule);
|
||||
self.plain_push();
|
||||
}
|
||||
|
||||
pub fn push_blend_mode(&mut self, mode: BlendMode) {
|
||||
self.inner.push_blend_mode(mode);
|
||||
self.plain_push();
|
||||
}
|
||||
|
||||
/// Restore the enclosing coordinate space, undoing every writer push for the last group.
|
||||
/// An unmatched pop is logged rather than forwarded to the writer's stack.
|
||||
pub fn pop(&mut self) {
|
||||
let Some(push) = self.pushes.pop() else {
|
||||
log::error!("PDF surface pop without a matching push");
|
||||
return;
|
||||
};
|
||||
for _ in 0..push.count {
|
||||
self.inner.pop();
|
||||
}
|
||||
self.root = push.root;
|
||||
}
|
||||
|
||||
pub fn finish(self) {
|
||||
self.inner.finish();
|
||||
}
|
||||
}
|
||||
|
||||
// Drawing operations use krilla directly; every push/pop above keeps our coordinate state in
|
||||
// step. Stream builders are wrapped with `Surface::stream` when their surfaces are created.
|
||||
impl<'a> Deref for Surface<'a> {
|
||||
type Target = krilla::surface::Surface<'a>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl DerefMut for Surface<'_> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Gradients in forms must follow the art, including on pages with a nonzero origin. Quartz
|
||||
//! exposed a failure the import/render round trip did not: it resolved a form's shading pattern
|
||||
//! in page space, leaving off-centre gradients painted entirely in their last stop's colour.
|
||||
//! These fixtures are original, generated geometry; no user artwork or external files are used.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{Appearance, ColorMode, Document, Knockout, Node, OpacityMask};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_pdf::{PdfOptions, export, import};
|
||||
use vectorcraft_testkit::raster::{assert_similar, render_artboard};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Form {
|
||||
Page,
|
||||
Opacity,
|
||||
Isolated,
|
||||
Nested,
|
||||
PassThrough,
|
||||
Mask,
|
||||
Knockout,
|
||||
Layer,
|
||||
Overprint,
|
||||
}
|
||||
|
||||
const FORMS: [Form; 9] =
|
||||
[Form::Page, Form::Opacity, Form::Isolated, Form::Nested, Form::PassThrough, Form::Mask, Form::Knockout, Form::Layer, Form::Overprint];
|
||||
|
||||
fn rect(d: &mut Document, bounds: Rect, paint: Paint) -> Node {
|
||||
Node::path(d.alloc_id(), shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0))
|
||||
}
|
||||
|
||||
fn group(d: &mut Document, n: Node) -> Node {
|
||||
Node::group(d.alloc_id(), vec![Arc::new(n)])
|
||||
}
|
||||
|
||||
/// Generate off-centre gradient art in each form type, moving the art and artboard together.
|
||||
fn fixture(form: Form, kind: GradientKind, mode: ColorMode, origin: Point) -> (Document, PdfOptions) {
|
||||
let mut d = Document::new_with_mode(120.0, 180.0, mode);
|
||||
let color = |k| if mode == ColorMode::Cmyk { Color::cmyk(0.0, 0.0, 0.0, k) } else { Color::gray(k) };
|
||||
let mut gradient = GradientPaint::new(Gradient {
|
||||
kind,
|
||||
stops: vec![GradientStop::new(0.0, color(1.0)), GradientStop::new(0.6, color(0.4)), GradientStop::new(1.0, color(0.0))],
|
||||
..Default::default()
|
||||
});
|
||||
let (start, end) = match kind {
|
||||
GradientKind::Radial => (Point::new(32.0, 35.0), Point::new(60.0, 35.0)),
|
||||
_ => (Point::new(10.0, 10.0), Point::new(70.0, 70.0)),
|
||||
};
|
||||
gradient.geom = Some(GradientGeom { start, end, aspect: 0.8, focal: None });
|
||||
let mut n = rect(&mut d, Rect::new(10.0, 10.0, 70.0, 70.0), Paint::Gradient(Box::new(gradient)));
|
||||
let mut opts = PdfOptions::default();
|
||||
match form {
|
||||
Form::Page => d.page_isolate = true,
|
||||
Form::Opacity => n.opacity = 0.6,
|
||||
Form::Isolated => {
|
||||
n = group(&mut d, n);
|
||||
n.isolate = true;
|
||||
}
|
||||
Form::Nested => {
|
||||
n.opacity = 0.75;
|
||||
n = group(&mut d, n);
|
||||
n.opacity = 0.8;
|
||||
}
|
||||
Form::PassThrough => {
|
||||
n.blend = BlendMode::Multiply;
|
||||
n = group(&mut d, n);
|
||||
n.opacity = 0.6;
|
||||
}
|
||||
Form::Mask => {
|
||||
let mask = rect(&mut d, Rect::new(10.0, 10.0, 44.0, 70.0), Paint::solid(Color::WHITE));
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask::new(mask, true)));
|
||||
}
|
||||
Form::Knockout => {
|
||||
let top = rect(&mut d, Rect::new(50.0, 50.0, 80.0, 80.0), Paint::solid(Color::WHITE));
|
||||
n = Node::group(d.alloc_id(), vec![Arc::new(n), Arc::new(top)]);
|
||||
n.knockout = Knockout::On;
|
||||
}
|
||||
Form::Layer => opts.settings.create_layers = true,
|
||||
Form::Overprint => n.appearance.fill_mut().unwrap().overprint = true,
|
||||
}
|
||||
n.transform(Affine::translate(origin.to_vec2()), false);
|
||||
d.artboards[0].rect = d.artboards[0].rect + origin.to_vec2();
|
||||
let layer = d.default_layer().unwrap();
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
(d, opts)
|
||||
}
|
||||
|
||||
/// Round trips preserve gradient placement for the form types the importer supports.
|
||||
#[test]
|
||||
fn gradients_in_forms_keep_their_position_when_read_back() {
|
||||
// The importer has a pre-existing mismatch on the knockout's synthesized nested masks;
|
||||
// Quartz below checks its actual PDF output, along with the other forms.
|
||||
for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Knockout)) {
|
||||
for kind in [GradientKind::Linear, GradientKind::Radial] {
|
||||
for origin in [Point::ORIGIN, Point::new(125.0, -80.0)] {
|
||||
let (d, opts) = fixture(form, kind, ColorMode::Rgb, origin);
|
||||
let back = import(&export(&d, &opts).unwrap()).unwrap();
|
||||
assert_similar(&render_artboard(&back), &render_artboard(&d), 5.0, 0.01);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer form bounds stay page-sized after translation, without extra imported clipping groups.
|
||||
#[test]
|
||||
fn translated_layer_forms_cover_the_paper_in_their_new_space() {
|
||||
// The layer-box repair added upstream must move with the gradient fix's form transform.
|
||||
// A local-space paper box would otherwise introduce a clipping group on import.
|
||||
for origin in [Point::ORIGIN, Point::new(125.0, -80.0), Point::new(-250.0, 450.0)] {
|
||||
let (d, mut opts) = fixture(Form::Layer, GradientKind::Radial, ColorMode::Rgb, origin);
|
||||
opts.settings.compression.compress_text = false;
|
||||
let bytes = export(&d, &opts).unwrap();
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
let boxes: Vec<Vec<f64>> = text
|
||||
.split("/Subtype/Form")
|
||||
.skip(1)
|
||||
.map(|form| {
|
||||
form.split("/BBox[").nth(1).unwrap().split(']').next().unwrap().split_ascii_whitespace().map(|v| v.parse().unwrap()).collect()
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(boxes, [vec![0.0, 0.0, 120.0, 180.0]], "{origin:?}: the layer covers exactly the page");
|
||||
let back = import(&bytes).unwrap();
|
||||
let children = back.layers[0].children().unwrap();
|
||||
assert_eq!(children.len(), 1);
|
||||
assert!(children[0].path_data().is_some(), "{origin:?}: no clipping group wraps the layer's art");
|
||||
}
|
||||
}
|
||||
|
||||
// Test the renderer that exhibited the fault, not just our own importer (which accepted the
|
||||
// old files). OS bindings are confined to this integration-test module.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[allow(unsafe_code)]
|
||||
mod quartz {
|
||||
use objc2_core_foundation::CFData;
|
||||
use objc2_core_graphics::{CGBitmapContextCreate, CGColorSpace, CGContext, CGDataProvider, CGImageAlphaInfo, CGPDFDocument};
|
||||
use vectorcraft_testkit::raster::Image;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Render the first PDF page through Quartz as an oracle independent of our importer.
|
||||
fn render(bytes: &[u8]) -> Image {
|
||||
let data = CFData::from_bytes(bytes);
|
||||
let provider = CGDataProvider::with_cf_data(Some(&data)).unwrap();
|
||||
let doc = CGPDFDocument::with_provider(Some(&provider)).unwrap();
|
||||
let page = CGPDFDocument::page(Some(&doc), 1).unwrap();
|
||||
let space = CGColorSpace::new_device_rgb().unwrap();
|
||||
let (width, height) = (120, 180);
|
||||
let mut rgba = vec![255u8; width * height * 4];
|
||||
// SAFETY: the buffer holds every RGBA row, stays allocated and is not accessed until the
|
||||
// context is dropped. All inputs are the small, generated fixtures above.
|
||||
let context = unsafe {
|
||||
CGBitmapContextCreate(rgba.as_mut_ptr().cast(), width, height, 8, width * 4, Some(&space), CGImageAlphaInfo::PremultipliedLast.0)
|
||||
}
|
||||
.unwrap();
|
||||
CGContext::draw_pdf_page(Some(&context), Some(&page));
|
||||
drop(context);
|
||||
Image { width: width as u32, height: height as u32, rgba }
|
||||
}
|
||||
|
||||
/// Quartz places RGB and CMYK radial centres, edges and masks with their translated art.
|
||||
#[test]
|
||||
fn quartz_keeps_off_centre_radials_in_transparency_and_layer_forms() {
|
||||
for mode in [ColorMode::Rgb, ColorMode::Cmyk] {
|
||||
for form in FORMS {
|
||||
for origin in [Point::ORIGIN, Point::new(125.0, -80.0)] {
|
||||
let (d, opts) = fixture(form, GradientKind::Radial, mode, origin);
|
||||
let img = render(&export(&d, &opts).unwrap());
|
||||
let centre = img.over_white(32, 35)[0];
|
||||
let edge = img.over_white(32, 55)[0];
|
||||
assert!(centre < 150 && edge.saturating_sub(centre) > 40, "{mode:?} {form:?} {origin:?}: centre {centre}, edge {edge}");
|
||||
assert_eq!(img.over_white(90, 100), [255; 3], "art stays in its bounds");
|
||||
if matches!(form, Form::Mask) {
|
||||
assert_eq!(img.over_white(46, 35), [255; 3], "the mask moves with the gradient");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Quartz retains the linear ramp's direction inside forms on a translated artboard.
|
||||
#[test]
|
||||
fn quartz_keeps_linear_gradient_directions_in_forms() {
|
||||
for form in FORMS.into_iter().filter(|f| !matches!(f, Form::Mask | Form::Knockout)) {
|
||||
let (d, opts) = fixture(form, GradientKind::Linear, ColorMode::Rgb, Point::new(-30.0, 45.0));
|
||||
let img = render(&export(&d, &opts).unwrap());
|
||||
let (start, end) = (img.over_white(20, 20)[0], img.over_white(60, 60)[0]);
|
||||
assert!(end.saturating_sub(start) > 60, "{form:?}: start {start}, end {end}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient's stop-opacity mask remains aligned with its colour through nested forms.
|
||||
#[test]
|
||||
fn quartz_keeps_gradient_stop_opacity_aligned_inside_nested_forms() {
|
||||
let (mut d, opts) = fixture(Form::Nested, GradientKind::Radial, ColorMode::Rgb, Point::ORIGIN);
|
||||
let mut leaves = vec![];
|
||||
d.walk(|n| {
|
||||
if n.path_data().is_some() {
|
||||
leaves.push(n.id);
|
||||
}
|
||||
});
|
||||
for id in leaves {
|
||||
let fill = d.node_mut(id).unwrap().appearance.fill_mut().unwrap();
|
||||
let Paint::Gradient(g) = &mut fill.paint else { panic!("gradient fixture") };
|
||||
for stop in &mut g.gradient.stops {
|
||||
stop.opacity = 0.6 * (1.0 - stop.offset);
|
||||
}
|
||||
}
|
||||
let img = render(&export(&d, &opts).unwrap());
|
||||
let (centre, edge) = (img.over_white(32, 35)[0], img.over_white(32, 55)[0]);
|
||||
assert!(centre > 145 && centre < 205 && edge > 240, "centre {centre}, edge {edge}");
|
||||
}
|
||||
}
|
||||
@@ -311,6 +311,15 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors,
|
||||
| Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) |
|
||||
| Clipboard: PDF, SVG, PNG, EMF, text | yes | yes | yes | copied files paste as art; cells copied from a spreadsheet (tab-separated text) paste as a table of point type over gridlines, at most 1000 rows, 256 columns and 20,000 cells (#5296) |
|
||||
|
||||
## PDF form gradients
|
||||
|
||||
PDF export's linear and radial gradients stay aligned inside transparency groups, opacity masks,
|
||||
PDF layers and overprinting art. The original synthetic tests in
|
||||
`crates/pdf/tests/gradient_forms.rs` check the output with macOS Quartz and an import/render
|
||||
round trip. The three Quartz checks fail on main `65adb7b21` and pass with the form-space fix;
|
||||
translated layer bounds also have a regression for the current writer's layer-box repair.
|
||||
Stop opacity on translated artboards remains outside this regression coverage.
|
||||
|
||||
## PDF editable imports
|
||||
|
||||
- [x] Explicit `/ActualText` replaces covered glyph text once, including empty strings and nested spans (outer owner wins), while later glyphs retain pen geometry. Synthetic regressions in `crates/pdf/src/tests/actual_text.rs`; no added fonts/assets. UTF-16BE, BOM UTF-8 and PDFDocEncoding reuse the reader's text-string decoder.
|
||||
|
||||
Reference in New Issue
Block a user