use serde_derive::{Deserialize, Serialize};
use crate::{
graphics::Rect, Color, DictItem, ExtendedGraphicsState, Op, PdfResources, Shading,
};
#[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PatternId(pub String);
impl PatternId {
pub fn new() -> Self {
Self(crate::utils::random_character_string_32())
}
}
impl Default for PatternId {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PatternPaintType {
#[default]
Colored,
Uncolored,
}
impl PatternPaintType {
pub(crate) fn number(&self) -> i64 {
match self {
PatternPaintType::Colored => 1,
PatternPaintType::Uncolored => 2,
}
}
}
pub const IDENTITY_MATRIX: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
fn identity_matrix() -> [f32; 6] {
IDENTITY_MATRIX
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "type", content = "data")]
pub enum Pattern {
Tiling {
#[serde(default)]
paint_type: PatternPaintType,
bbox: Rect,
xstep: f32,
ystep: f32,
#[serde(default = "identity_matrix")]
matrix: [f32; 6],
#[serde(default)]
ops: Vec<Op>,
#[serde(default)]
resources: Option<PdfResources>,
},
Shading {
shading: Shading,
#[serde(default = "identity_matrix")]
matrix: [f32; 6],
#[serde(default)]
ext_gstate: Option<ExtendedGraphicsState>,
},
External(DictItem),
}
impl Pattern {
pub fn colored_tiling(bbox: Rect, xstep: f32, ystep: f32, ops: Vec<Op>) -> Self {
Pattern::Tiling {
paint_type: PatternPaintType::Colored,
bbox,
xstep,
ystep,
matrix: IDENTITY_MATRIX,
ops,
resources: None,
}
}
pub fn uncolored_tiling(bbox: Rect, xstep: f32, ystep: f32, ops: Vec<Op>) -> Self {
Pattern::Tiling {
paint_type: PatternPaintType::Uncolored,
bbox,
xstep,
ystep,
matrix: IDENTITY_MATRIX,
ops,
resources: None,
}
}
pub fn from_shading(shading: Shading) -> Self {
Pattern::Shading {
shading,
matrix: IDENTITY_MATRIX,
ext_gstate: None,
}
}
pub fn with_matrix(mut self, new_matrix: [f32; 6]) -> Self {
match &mut self {
Pattern::Tiling { matrix, .. } | Pattern::Shading { matrix, .. } => {
*matrix = new_matrix;
}
Pattern::External(_) => {}
}
self
}
pub fn with_resources(mut self, new_resources: PdfResources) -> Self {
if let Pattern::Tiling { resources, .. } = &mut self {
*resources = Some(new_resources);
}
self
}
pub fn approximate_color(&self, underlying: Option<&Color>) -> Color {
let grey = Color::Rgb(crate::Rgb::new(0.5, 0.5, 0.5, None));
match self {
Pattern::Shading { shading, .. } => match shading.stops.first() {
Some(stop) => {
Color::Rgb(crate::Rgb::new(stop.color[0], stop.color[1], stop.color[2], None))
}
None => grey,
},
Pattern::Tiling {
paint_type: PatternPaintType::Uncolored,
..
} => underlying.cloned().unwrap_or(grey),
Pattern::Tiling { ops, .. } => {
let mut sum = [0.0f32; 3];
let mut count = 0.0f32;
for op in ops {
if let Op::SetFillColor { col } | Op::SetOutlineColor { col } = op {
let rgb = color_to_rgb(col);
for (total, part) in sum.iter_mut().zip(rgb) {
*total += part;
}
count += 1.0;
}
}
if count == 0.0 {
grey
} else {
Color::Rgb(crate::Rgb::new(
sum[0] / count,
sum[1] / count,
sum[2] / count,
None,
))
}
}
Pattern::External(_) => grey,
}
}
}
fn color_to_rgb(color: &Color) -> [f32; 3] {
let clamp = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
match color {
Color::Rgb(c) => [clamp(c.r), clamp(c.g), clamp(c.b)],
Color::Greyscale(g) => {
let v = clamp(g.percent);
[v, v, v]
}
Color::Cmyk(c) => cmyk_to_rgb(c.c, c.m, c.y, c.k),
Color::SpotColor(c) => cmyk_to_rgb(c.c, c.m, c.y, c.k),
}
}
fn cmyk_to_rgb(c: f32, m: f32, y: f32, k: f32) -> [f32; 3] {
let clamp = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let k = 1.0 - clamp(k);
[
(1.0 - clamp(c)) * k,
(1.0 - clamp(m)) * k,
(1.0 - clamp(y)) * k,
]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{GradientStop, Greyscale, Pt, Rgb, ShadingGeometry};
fn cell() -> Rect {
Rect::from_wh(Pt(10.0), Pt(10.0))
}
fn gradient() -> Shading {
Shading {
geometry: ShadingGeometry::Axial { coords: [0.0, 0.0, 100.0, 0.0] },
stops: vec![
GradientStop { offset: 0.0, color: [1.0, 0.0, 0.0] },
GradientStop { offset: 1.0, color: [0.0, 0.0, 1.0] },
],
extend: (true, true),
}
}
#[test]
fn constructors_set_the_paint_type() {
let colored = Pattern::colored_tiling(cell(), 10.0, 10.0, Vec::new());
let uncolored = Pattern::uncolored_tiling(cell(), 10.0, 10.0, Vec::new());
assert!(matches!(
colored,
Pattern::Tiling { paint_type: PatternPaintType::Colored, .. }
));
assert!(matches!(
uncolored,
Pattern::Tiling { paint_type: PatternPaintType::Uncolored, .. }
));
}
#[test]
fn builders_set_matrix_and_resources() {
let matrix = [2.0, 0.0, 0.0, 2.0, 5.0, 5.0];
let p = Pattern::colored_tiling(cell(), 10.0, 10.0, Vec::new())
.with_matrix(matrix)
.with_resources(PdfResources::default());
match p {
Pattern::Tiling { matrix: m, resources, .. } => {
assert_eq!(m, matrix);
assert!(resources.is_some());
}
other => panic!("not a tiling pattern: {other:?}"),
}
match Pattern::from_shading(gradient()).with_matrix(matrix) {
Pattern::Shading { matrix: m, .. } => assert_eq!(m, matrix),
other => panic!("not a shading pattern: {other:?}"),
}
let external = Pattern::External(DictItem::Null);
assert_eq!(external.clone().with_matrix(matrix), external);
}
#[test]
fn pattern_ids_are_distinct() {
assert_ne!(PatternId::new(), PatternId::new());
}
#[test]
fn json_round_trip_and_defaults() {
let p = Pattern::uncolored_tiling(cell(), 12.0, 8.0, vec![Op::SaveGraphicsState])
.with_matrix([1.0, 0.0, 0.0, 1.0, 3.0, 4.0]);
let json = serde_json::to_string(&p).expect("serialize");
assert!(json.contains("\"type\":\"tiling\""), "{json}");
let back: Pattern = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back, p);
let json = r#"{"type":"tiling","data":{
"bbox":{"x":0,"y":0,"width":4,"height":4},
"xstep":4,"ystep":4}}"#;
let p: Pattern = serde_json::from_str(json).expect("defaults");
match p {
Pattern::Tiling { paint_type, matrix, ops, resources, .. } => {
assert_eq!(paint_type, PatternPaintType::Colored);
assert_eq!(matrix, IDENTITY_MATRIX);
assert!(ops.is_empty());
assert!(resources.is_none());
}
other => panic!("not a tiling pattern: {other:?}"),
}
}
#[test]
fn old_resources_json_without_patterns_still_loads() {
let json = r#"{"fonts":{},"xobjects":{},"extgstates":{},"shadings":{},"layers":{}}"#;
let resources: PdfResources = serde_json::from_str(json).expect("old json");
assert!(resources.patterns.map.is_empty());
}
#[test]
fn ops_serialize_with_and_without_color() {
let op = Op::SetFillPattern { id: PatternId("P1".into()), color: None };
let json = serde_json::to_string(&op).expect("serialize");
assert!(json.contains("set-fill-pattern"), "{json}");
let back: Op = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back, op);
let back: Op = serde_json::from_str(
r#"{"type":"set-outline-pattern","data":{"id":"P2"}}"#,
)
.expect("no color");
assert_eq!(back, Op::SetOutlinePattern { id: PatternId("P2".into()), color: None });
}
#[test]
fn add_pattern_registers_it() {
let mut doc = crate::PdfDocument::new("p");
let id = doc.add_pattern(Pattern::from_shading(gradient()));
assert!(doc.resources.patterns.map.contains_key(&id));
}
#[test]
fn approximate_colors() {
let red = Color::Rgb(Rgb::new(1.0, 0.0, 0.0, None));
assert_eq!(Pattern::from_shading(gradient()).approximate_color(None), red);
let uncolored = Pattern::uncolored_tiling(cell(), 4.0, 4.0, Vec::new());
assert_eq!(uncolored.approximate_color(Some(&red)), red);
assert_eq!(
uncolored.approximate_color(None),
Color::Rgb(Rgb::new(0.5, 0.5, 0.5, None))
);
let ops = vec![
Op::SetFillColor { col: red.clone() },
Op::SetOutlineColor { col: Color::Greyscale(Greyscale::new(1.0, None)) },
];
let colored = Pattern::colored_tiling(cell(), 4.0, 4.0, ops);
assert_eq!(
colored.approximate_color(None),
Color::Rgb(Rgb::new(1.0, 0.5, 0.5, None))
);
let none = Pattern::colored_tiling(cell(), 4.0, 4.0, Vec::new());
assert_eq!(none.approximate_color(None), Color::Rgb(Rgb::new(0.5, 0.5, 0.5, None)));
assert_eq!(
Pattern::External(DictItem::Null).approximate_color(None),
Color::Rgb(Rgb::new(0.5, 0.5, 0.5, None))
);
}
}