GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
//! Save PDF › Output: colours converted to the destination (or their numbers preserved), ICC
//! profiles tagging them, images converted too, and the output intent and Trapped entries.

use std::sync::Arc;

use craft_pdf::syntax::Pdf;
use craft_pdf::syntax::object::{Array, Dict, Name, ObjectIdentifier, Stream};
use serde_json::{Value, json};
use vectorcraft_color::cms::{self, Cms, ColorSettings, DEVICE_CMYK, GENERIC_CMYK, SRGB};
use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientPaint, GradientStop, Paint, Swatch};
use vectorcraft_doc::{Appearance, ColorMode, Document, ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_geom::{Affine, Rect, shapes};

use crate::*;

/// A document of `mode` with a rectangle filled with each of `fills`, side by side.
fn doc(mode: ColorMode, fills: &[Color]) -> Document {
    let mut d = Document::new(200.0, 100.0);
    d.color_mode = mode;
    let l = d.layers[0].id;
    for (i, c) in fills.iter().enumerate() {
        let x = 10.0 + 30.0 * i as f64;
        let n =
            Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 10.0, x + 20.0, 30.0)), Appearance::basic(Paint::solid(*c), Paint::None, 0.0));
        d.insert(Some(l), i, n).unwrap();
    }
    d
}

/// The export of `d` with `settings` (content streams left readable).
fn pdf(d: &Document, settings: Value) -> ExportReport {
    let mut settings: PdfSettings = serde_json::from_value(settings).unwrap();
    settings.compression.compress_text = false;
    export_with_report(d, &PdfOptions { settings, ..Default::default() }).unwrap()
}

/// The fill colours the first page's content sets: (operator, operands).
fn colours(pdf: &[u8]) -> Vec<(String, Vec<f32>)> {
    let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap();
    let pages = file.pages();
    let content = String::from_utf8_lossy(pages.iter().next().unwrap().page_stream().unwrap()).into_owned();
    let (mut nums, mut out) = (vec![], vec![]);
    for t in content.split_whitespace() {
        if let Ok(v) = t.parse::<f32>() {
            nums.push(v);
            continue;
        }
        if ["rg", "k", "g", "scn"].contains(&t) {
            out.push((t.to_string(), nums.clone()));
        }
        nums.clear();
    }
    out
}

/// RGB `v` as the writer stores it (8 bits a component). CMYK and grey are written as they are.
fn q8(v: &[f32]) -> Vec<f32> {
    v.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0).collect()
}

fn close(a: &[f32], b: &[f32]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3)
}

/// The colour management of a CMYK destination, as the export builds it.
fn to_cmyk(dest: &str) -> Cms {
    Cms::new(&ColorSettings { cmyk: dest.into(), ..cms::active_settings() }).unwrap()
}

/// The ICC profiles the ICC-based colour spaces of `pdf` use: (components, profile bytes).
fn icc_profiles(pdf: &[u8]) -> Vec<(i32, Vec<u8>)> {
    let file = Pdf::new(Arc::new(pdf.to_vec())).unwrap();
    let text = String::from_utf8_lossy(pdf);
    let mut out = vec![];
    for (at, _) in text.match_indices("[/ICCBased ") {
        let n: i32 = text[at + 11..].split(' ').next().unwrap().parse().unwrap();
        let s = file.xref().get::<Stream<'_>>(ObjectIdentifier::new(n, 0)).unwrap();
        let entry = (s.dict().get::<i32>(b"N").unwrap(), s.decoded().unwrap().into_owned());
        if !out.contains(&entry) {
            out.push(entry);
        }
    }
    out
}

#[test]
fn converting_to_a_cmyk_destination_writes_k_instead_of_rg() {
    let red = Color::rgb(1.0, 0.0, 0.0);
    let d = doc(ColorMode::Rgb, &[red]);
    assert_eq!(colours(&pdf(&d, json!({})).bytes), [("rg".to_string(), vec![1.0, 0.0, 0.0])], "without conversion");
    let ink = to_cmyk(GENERIC_CMYK).srgb_to_cmyk([1.0, 0.0, 0.0], cms::active_settings().intent);
    for conversion in ["destination", "preserveNumbers"] {
        let r = pdf(&d, json!({"output": {"conversion": conversion, "destination": GENERIC_CMYK}}));
        let c = colours(&r.bytes);
        assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{conversion}: {c:?} vs {ink:?}");
        assert!(r.warnings.is_empty(), "{:?}", r.warnings);
    }
    // A blank destination is the document's profile: the RGB document's colours stay RGB.
    assert_eq!(colours(&pdf(&d, json!({"output": {"conversion": "destination"}})).bytes)[0].0, "rg");
}

#[test]
fn preserve_numbers_keeps_cmyk_values_that_destination_converts() {
    let ink = Color::cmyk(0.1, 0.2, 0.3, 0.4);
    let d = doc(ColorMode::Rgb, &[ink, Color::Gray { k: 0.25 }]);
    let numbers = [0.1, 0.2, 0.3, 0.4];
    let fills = |conversion: &str, dest: &str| colours(&pdf(&d, json!({"output": {"conversion": conversion, "destination": dest}})).bytes);
    let kept = fills("preserveNumbers", DEVICE_CMYK);
    assert!(kept[0].0 == "k" && close(&kept[0].1, &numbers), "{kept:?}");
    // Grey stays grey.
    assert!(kept[1].0 == "g" && close(&kept[1].1, &[0.75]), "{kept:?}");
    // Convert to destination: CMYK of another profile goes through Lab into the destination.
    let converted = fills("destination", DEVICE_CMYK);
    let expected = to_cmyk(DEVICE_CMYK).lab_to_cmyk(cms::active().lab(&ink), cms::active_settings().intent);
    assert!(converted[0].0 == "k" && close(&converted[0].1, &expected), "{converted:?} vs {expected:?}");
    assert!(converted[0].1.iter().zip(&numbers).any(|(a, b)| (a - b).abs() > 0.02), "the numbers change: {converted:?}");
    // …unless the destination is their own profile.
    let own = fills("destination", &cms::active_settings().cmyk);
    assert!(close(&own[0].1, &numbers), "{own:?}");
}

#[test]
fn cmyk_inks_grey_and_spot_tints_are_written_as_the_document_holds_them() {
    let fills = [Color::cmyk(0.75, 0.0, 1.0, 0.0), Color::cmyk(0.04, 0.04, 0.04, 0.04), Color::Gray { k: 0.04 }];
    let mut d = doc(ColorMode::Cmyk, &fills);
    d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true });
    let gold = Paint::Solid { color: Color::cmyk(0.0, 0.15, 0.6, 0.075), swatch: Some("Gold".into()), tint: 0.75 };
    let l = d.layers[0].id;
    let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(100.0, 10.0, 120.0, 30.0)), Appearance::basic(gold, Paint::None, 0.0));
    d.insert(Some(l), 3, n).unwrap();
    let c = colours(&pdf(&d, json!({})).bytes);
    let expected = [("k", vec![0.75, 0.0, 1.0, 0.0]), ("k", vec![0.04; 4]), ("g", vec![1.0 - 0.04]), ("scn", vec![0.75])];
    assert_eq!(c, expected.map(|(op, v)| (op.to_string(), v)), "C75 is 0.75, not 191/255");
}

#[test]
fn spot_alternates_and_device_n_gradient_inks_are_written_as_the_document_holds_them() {
    let mut d = doc(ColorMode::Cmyk, &[]);
    d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true });
    let mut gold = GradientStop::new(0.0, Color::cmyk(0.0, 0.2, 0.8, 0.1));
    gold.swatch = Some("Gold".into());
    gold.tint = 0.75;
    let g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![gold, GradientStop::new(1.0, Color::cmyk(0.75, 0.0, 0.0, 0.04))]));
    let l = d.layers[0].id;
    let n = Node::path(
        d.alloc_id(),
        shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 30.0)),
        Appearance::basic(Paint::Gradient(Box::new(g)), Paint::None, 0.0),
    );
    d.insert(Some(l), 0, n).unwrap();
    // A solid fill in the spot color, in its own Separation space.
    let solid = Paint::Solid { color: Color::cmyk(0.0, 0.15, 0.6, 0.075), swatch: Some("Gold".into()), tint: 0.75 };
    let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Appearance::basic(solid, Paint::None, 0.0));
    d.insert(Some(l), 1, n).unwrap();
    let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned();
    let exact = "[/Separation/Gold/DeviceCMYK<</FunctionType 2/Domain[0 1]/Range[0 1 0 1 0 1 0 1]/C0[0 0 0 0]/C1[0 0.2 0.8 0.1]/N 1>>]";
    let spaces = text.matches("[/Separation/Gold/").count();
    assert!(spaces > 0 && text.matches(exact).count() == spaces, "K10 is 0.1, not 26/255, in every Gold space: {text}");
    assert!(text.contains("[/DeviceN[/Cyan/Black/Gold]"), "{text}");
    assert!(text.contains("/C0[0 0 0.75]/C1[0.75 0.04 0]"), "the stops' C75, K4 and 75% Gold are written as they are");
}

#[test]
fn blend_steps_between_spot_gradients_with_process_plates_print_both_inks() {
    let stop = |offset: f32, tint: f32, plates: Option<[f32; 4]>| {
        let mut s = GradientStop::new(offset, Color::cmyk(0.0, 0.2, 0.8, 0.1).tinted(tint));
        s.swatch = Some("Gold".into());
        s.tint = tint;
        s.plates = plates;
        s
    };
    let gradient = |tint: f32, plates: Option<[f32; 4]>| {
        Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop(0.0, tint, plates), stop(1.0, tint, plates)]))))
    };
    let step_pdf = |a: &Paint, b: &Paint| {
        let mut d = doc(ColorMode::Cmyk, &[]);
        d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true });
        let step = vectorcraft_doc::blend::lerp_paint(a, b, 0.5);
        let l = d.layers[0].id;
        let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 30.0)), Appearance::basic(step, Paint::None, 0.0));
        d.insert(Some(l), 0, n).unwrap();
        String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned()
    };
    // The middle step prints 60% Gold over 30% Cyan, in one DeviceN shading of both inks.
    let text = step_pdf(&gradient(0.2, Some([0.2, 0.0, 0.0, 0.0])), &gradient(1.0, Some([0.4, 0.0, 0.0, 0.0])));
    assert!(text.contains("[/DeviceN[/Cyan/Gold]"), "{text}");
    assert!(text.contains("/C0[0.3 0.6]/C1[0.3 0.6]"), "{text}");
    // Without plates the step is a Separation shading of Gold alone.
    let text = step_pdf(&gradient(0.2, None), &gradient(1.0, None));
    assert!(!text.contains("/DeviceN") && text.contains("[/Separation/Gold/"), "{text}");
}

/// A spot swatch's Separation space with alternate C0 M20 Y80 K10 under `colorant` (a PDF name).
fn gold_separation(colorant: &str) -> String {
    format!("[/Separation{colorant}/DeviceCMYK<</FunctionType 2/Domain[0 1]/Range[0 1 0 1 0 1 0 1]/C0[0 0 0 0]/C1[0 0.2 0.8 0.1]/N 1>>]")
}

#[test]
fn spot_inks_named_all_or_none_are_written_under_names_of_their_own() {
    let solid = |name: &str, color: Color| Paint::Solid { color, swatch: Some(name.into()), tint: 0.5 };
    let gold = Color::cmyk(0.0, 0.2, 0.8, 0.1);
    let rect = |d: &mut Document, i: usize, y: f64, paint: Paint, stroke: Paint| {
        let l = d.layers[0].id;
        let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, y, 140.0, y + 20.0)), Appearance::basic(paint, stroke, 1.0));
        d.insert(Some(l), i, n).unwrap();
    };
    let stop = |offset: f32, ink: &str, tint: f32| {
        let mut s = GradientStop::new(offset, gold.tinted(tint));
        s.swatch = Some(ink.into());
        s.tint = tint;
        s
    };
    let gradient = |stops| Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
    for (name, colorant) in [("All", "/All#20Spot"), ("None", "/None#20Spot")] {
        let mut d = doc(ColorMode::Cmyk, &[]);
        for ink in [name, "Gold"] {
            d.swatches.push(Swatch { name: ink.into(), paint: Paint::solid(gold), global: true, spot: true });
        }
        // A fill of the spot ink with a Registration stroke, a gradient of the spot ink's tints,
        // and a gradient from Gold to the spot ink.
        let registration = solid(vectorcraft_color::swatch::REGISTRATION, Color::cmyk(1.0, 1.0, 1.0, 1.0));
        rect(&mut d, 0, 10.0, solid(name, gold), registration);
        rect(&mut d, 1, 40.0, gradient(vec![stop(0.0, name, 1.0), stop(1.0, name, 0.25)]), Paint::None);
        rect(&mut d, 2, 70.0, gradient(vec![stop(0.0, "Gold", 1.0), stop(1.0, name, 1.0)]), Paint::None);
        let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned();
        let spaces = text.matches(&format!("[/Separation{colorant}/")).count();
        assert!(spaces > 0 && text.matches(&gold_separation(colorant)).count() == spaces, "{name}: {text}");
        assert!(!text.contains(&gold_separation(&format!("/{name}"))), "{name} is not the colorant: {text}");
        assert!(text.contains("[/Separation/All/DeviceCMYK<<"), "Registration prints on every plate: {text}");
        assert!(text.contains(&format!("[/DeviceN[/Gold{colorant}]")), "{name}: {text}");
    }

    // A spot swatch already named All Spot keeps its name, and All is numbered past it.
    let mut d = doc(ColorMode::Cmyk, &[]);
    for name in ["All", "All Spot"] {
        d.swatches.push(Swatch { name: name.into(), paint: Paint::solid(gold), global: true, spot: true });
    }
    rect(&mut d, 0, 10.0, solid("All", gold), solid("All Spot", gold));
    let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned();
    assert!(text.contains(&gold_separation("/All#20Spot#202")) && text.contains(&gold_separation("/All#20Spot")), "{text}");
}

#[test]
fn a_lab_spot_ink_named_all_keeps_its_lab_alternate() {
    let mut d = doc(ColorMode::Cmyk, &[]);
    let lab = Color::Lab { l: 60.0, a: 40.0, b: 50.0 };
    d.swatches.push(Swatch { name: "All".into(), paint: Paint::solid(lab), global: true, spot: true });
    let fill = Paint::Solid { color: lab, swatch: Some("All".into()), tint: 1.0 };
    let l = d.layers[0].id;
    let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Appearance::basic(fill, Paint::None, 0.0));
    d.insert(Some(l), 0, n).unwrap();
    let text = String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned();
    assert!(text.contains("[/Separation/All#20Spot[/Lab<<"), "{text}");
    assert!(!text.contains("[/Separation/All/") && !text.contains("[/Separation/All["), "{text}");
}

/// The uncompressed PDF of a CMYK document whose rectangle is filled with gradient `stops`
/// (Perceptual when `perceptual`), with spot swatch "Gold" (C0 M20 Y80 K10).
fn gold_gradient_pdf(stops: Vec<GradientStop>, perceptual: bool) -> String {
    let mut d = doc(ColorMode::Cmyk, &[]);
    d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true });
    let mut g = Gradient::new(GradientKind::Linear, stops);
    if perceptual {
        g.method = GradientMethod::Perceptual;
    }
    let paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
    let l = d.layers[0].id;
    let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 30.0)), Appearance::basic(paint, Paint::None, 0.0));
    d.insert(Some(l), 0, n).unwrap();
    String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned()
}

/// A gradient stop at `offset` linked to "Gold" at `tint`.
fn gold_stop(offset: f32, tint: f32) -> GradientStop {
    let mut s = GradientStop::new(offset, Color::cmyk(0.0, 0.2, 0.8, 0.1).tinted(tint));
    s.swatch = Some("Gold".into());
    s.tint = tint;
    s
}

#[test]
fn perceptual_spot_gradient_stops_keep_their_own_tints() {
    let paper = GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0));
    let text = gold_gradient_pdf(vec![gold_stop(0.0, 0.8), gold_stop(0.5, 0.4), paper], true);
    assert!(text.contains("/FunctionType 3"), "tints on the curve: {text}");
    // The one-tint ends of the stitched functions, in order along the gradient.
    let ends = |key: &str| -> Vec<String> {
        text.match_indices(key)
            .filter_map(|(i, _)| text.get(i + key.len()..)?.split(']').next())
            .filter(|v| !v.contains(' '))
            .map(str::to_string)
            .collect()
    };
    let (c0, c1) = (ends("/C0["), ends("/C1["));
    assert_eq!(c0.first().map(String::as_str), Some("0.8"), "the first stop's 80%: {c0:?}");
    assert_eq!(c1.last().map(String::as_str), Some("0"), "paper white adds no ink: {c1:?}");
    assert!(c1.iter().any(|v| v == "0.4") && c0.iter().any(|v| v == "0.4"), "the middle stop's 40%: {c0:?} {c1:?}");
}

#[test]
fn spot_gradients_keep_a_trace_of_process_ink_at_a_light_stop() {
    for light in [Color::cmyk(0.0, 0.0, 0.0, 0.001), Color::Gray { k: 0.001 }] {
        for perceptual in [false, true] {
            let text = gold_gradient_pdf(vec![gold_stop(0.0, 1.0), GradientStop::new(1.0, light)], perceptual);
            assert!(text.contains("[/DeviceN[/Black/Gold]"), "{light:?}, perceptual {perceptual}: K 0.1% is ink, not paper");
        }
    }
}

/// [`gold_gradient_pdf`] with spot swatch "Leaf" (C100 Y100) in the document too.
fn gold_and_leaf_gradient_pdf(stops: Vec<GradientStop>, perceptual: bool) -> String {
    let mut d = doc(ColorMode::Cmyk, &[]);
    d.swatches.push(Swatch { name: "Gold".into(), paint: Paint::solid(Color::cmyk(0.0, 0.2, 0.8, 0.1)), global: true, spot: true });
    d.swatches.push(Swatch { name: "Leaf".into(), paint: Paint::solid(Color::cmyk(1.0, 0.0, 1.0, 0.0)), global: true, spot: true });
    let mut g = Gradient::new(GradientKind::Linear, stops);
    if perceptual {
        g.method = GradientMethod::Perceptual;
    }
    let paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
    let l = d.layers[0].id;
    let n = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 110.0, 30.0)), Appearance::basic(paint, Paint::None, 0.0));
    d.insert(Some(l), 0, n).unwrap();
    String::from_utf8_lossy(&export(&d, &PdfOptions::uncompressed()).unwrap()).into_owned()
}

#[test]
fn gradients_name_only_the_spot_inks_of_stops_that_color_what_draws() {
    let black = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::cmyk(0.0, 0.0, 0.0, 1.0)) };
    let paper = |offset: f32| GradientStop::new(offset, Color::cmyk(0.0, 0.0, 0.0, 0.0));
    let leaf = |offset: f32, tint: f32| {
        let mut s = GradientStop::new(offset, Color::cmyk(1.0, 0.0, 1.0, 0.0).tinted(tint));
        s.swatch = Some("Leaf".into());
        s.tint = tint;
        s
    };
    let clear_gold = GradientStop { opacity: 0.0, ..gold_stop(0.4, 1.0) };
    for perceptual in [false, true] {
        // Gold in a stretch where every stop is clear, and Gold out of order, where the stops at 0
        // and 0.8 cover the stretches next to it: Gold colors nothing, so no Gold plate.
        let clear = vec![black(0.0, 1.0), black(0.2, 0.0), clear_gold.clone(), black(0.6, 0.0), black(1.0, 1.0)];
        let out_of_order = vec![black(0.0, 1.0), black(0.8, 1.0), gold_stop(0.2, 1.0), black(0.4, 1.0), black(1.0, 1.0)];
        // Gold at a tint of 0 prints no Gold ink.
        let no_tint = vec![gold_stop(0.0, 0.0), black(1.0, 1.0)];
        for (what, stops) in [("clear", clear), ("out of order", out_of_order), ("tint 0", no_tint)] {
            let text = gold_gradient_pdf(stops, perceptual);
            assert!(!text.contains("/Gold"), "{what}, perceptual {perceptual}: {text}");
            assert!(!text.contains("/DeviceN") && !text.contains("/Separation"), "{what}, perceptual {perceptual}: {text}");
        }
        // Without the Gold stop out of order, Leaf's tints over paper are a Separation shading.
        let leaf_only = vec![leaf(0.0, 1.0), leaf(0.8, 0.5), gold_stop(0.2, 1.0), paper(0.4), paper(1.0)];
        let text = gold_and_leaf_gradient_pdf(leaf_only, perceptual);
        assert!(text.contains("[/Separation/Leaf/") && !text.contains("/Gold") && !text.contains("/DeviceN"), "perceptual {perceptual}: {text}");
        // A clear Gold stop next to an opaque one colors the stretch between them.
        let text = gold_gradient_pdf(vec![black(0.0, 1.0), clear_gold.clone(), black(1.0, 1.0)], perceptual);
        assert!(text.contains("[/DeviceN[/Black/Gold]"), "perceptual {perceptual}: {text}");
    }
    // Gold at a tint of 0 over a 30% cyan plate (a DeviceN gradient read from a PDF) keeps its
    // process plate in the same space.
    let plated = GradientStop { plates: Some([0.3, 0.0, 0.0, 0.0]), ..gold_stop(1.0, 0.0) };
    let text = gold_gradient_pdf(vec![GradientStop::new(0.0, Color::cmyk(0.3, 0.0, 0.0, 0.0)), plated], false);
    assert!(text.contains("[/DeviceN[/Cyan/Gold]"), "{text}");
}

#[test]
fn converting_to_rgb_turns_cmyk_into_rg() {
    let ink = Color::cmyk(0.0, 1.0, 1.0, 0.0);
    let d = doc(ColorMode::Cmyk, &[ink]);
    assert_eq!(colours(&pdf(&d, json!({})).bytes)[0].0, "k");
    let c = colours(&pdf(&d, json!({"output": {"conversion": "preserveNumbers", "destination": SRGB}})).bytes);
    assert!(c[0].0 == "rg" && close(&c[0].1, &q8(&cms::active().display_rgb(&ink))), "{c:?}");
}

#[test]
fn an_unknown_destination_is_refused() {
    let d = doc(ColorMode::Rgb, &[Color::BLACK]);
    let set: PdfSettings = serde_json::from_value(json!({"output": {"conversion": "destination", "destination": "No Such Press"}})).unwrap();
    assert!(matches!(set.check(), Err(PdfError::BadSetting(m)) if m.contains("No Such Press")));
    assert!(export(&d, &PdfOptions { settings: set, ..Default::default() }).is_err());
    // Not converting, the destination doesn't matter.
    let set: PdfSettings = serde_json::from_value(json!({"output": {"destination": "No Such Press"}})).unwrap();
    assert_eq!(set.check(), Ok(()));
}

#[test]
fn profiles_tag_colours_with_icc_based_spaces() {
    let d = doc(ColorMode::Rgb, &[Color::rgb(0.2, 0.4, 0.6), Color::cmyk(0.1, 0.2, 0.3, 0.4), Color::Gray { k: 0.5 }]);
    let none = pdf(&d, json!({}));
    assert!(icc_profiles(&none.bytes).is_empty());
    assert!(colours(&none.bytes).iter().all(|c| c.0 != "scn"));
    let all = pdf(&d, json!({"output": {"profiles": "all"}}));
    let profiles = icc_profiles(&all.bytes);
    let mut n: Vec<i32> = profiles.iter().map(|p| p.0).collect();
    n.sort();
    assert_eq!(n, [1, 3, 4], "grey, RGB and CMYK spaces");
    assert!(profiles.iter().any(|p| p.0 == 4 && p.1 == *cms::icc_bytes(&cms::active_settings().cmyk).unwrap()), "the working CMYK profile");
    assert!(colours(&all.bytes).iter().all(|c| c.0 == "scn"), "{:?}", colours(&all.bytes));
    // The destination profile tags converted colours.
    let dest = pdf(&d, json!({"output": {"conversion": "destination", "destination": DEVICE_CMYK, "profiles": "destination"}}));
    let profiles = icc_profiles(&dest.bytes);
    assert!(profiles.iter().any(|p| p.0 == 4 && p.1 == *cms::icc_bytes(DEVICE_CMYK).unwrap()), "the destination");
    // Tagged source profiles: only a document that was assigned profiles is tagged.
    assert!(icc_profiles(&pdf(&d, json!({"output": {"profiles": "taggedSource"}})).bytes).is_empty());
    let mut tagged = d.clone();
    tagged.color_profiles.cmyk = Some(GENERIC_CMYK.into());
    assert_eq!(icc_profiles(&pdf(&tagged, json!({"output": {"profiles": "taggedSource"}})).bytes).len(), 3);
}

#[test]
fn tagged_cmyk_documents_blend_in_the_cmyk_profile_space() {
    let mut d = doc(ColorMode::Cmyk, &[Color::cmyk(1.0, 0.0, 0.0, 0.0)]);
    let mut n = Node::path(
        d.alloc_id(),
        shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)),
        Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0),
    );
    n.opacity = 0.5;
    let l = d.layers[0].id;
    d.insert(Some(l), 1, n).unwrap();
    let r = pdf(&d, json!({"output": {"profiles": "all"}}));
    let text = String::from_utf8_lossy(&r.bytes);
    let group = text.split("/Group<<").nth(1).unwrap();
    let cs: i32 = group.split("/CS ").nth(1).unwrap().split(' ').next().unwrap().parse().unwrap();
    let space = text.split(&format!("\n{cs} 0 obj\n")).nth(1).unwrap();
    let stream: i32 = space.strip_prefix("[/ICCBased ").unwrap().split(' ').next().unwrap().parse().unwrap();
    let file = Pdf::new(Arc::new(r.bytes.clone())).unwrap();
    assert_eq!(file.xref().get::<Stream<'_>>(ObjectIdentifier::new(stream, 0)).unwrap().dict().get::<i32>(b"N"), Some(4), "{group}");
}

/// A 4 × 4 PNG of one colour.
fn png(rgb: [u8; 3]) -> Vec<u8> {
    let img = craft_image_codecs::Image::from_raw(4, 4, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb.repeat(16))
        .unwrap();
    craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap()
}

fn image_doc(bytes: Vec<u8>) -> Document {
    let mut d = Document::new(100.0, 100.0);
    d.images.insert("img".into(), ImageBlob::new("image/png", bytes));
    let image =
        ImageObject { key: "img".into(), width: 4, height: 4, xf: Affine::scale(10.0), link: None, placement: Default::default(), pixels: None };
    let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image)));
    let l = d.layers[0].id;
    d.insert(Some(l), 0, n).unwrap();
    d
}

/// The colour of the first image of the PDF `bytes` imports as, at its first pixel.
fn first_pixel(bytes: &[u8]) -> [u8; 3] {
    let back = import(bytes).unwrap();
    let blob = back.images.values().next().unwrap();
    craft_image_codecs::decode(&blob.bytes)
        .map(|__cimg| {
            let (__w, __h) = __cimg.dimensions();
            match (__cimg.layout(), __cimg.sample_type()) {
                (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8) => {
                    image::DynamicImage::ImageLuma8(image::GrayImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
                }
                (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8) => {
                    image::DynamicImage::ImageLumaA8(image::GrayAlphaImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
                }
                (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8) => {
                    image::DynamicImage::ImageRgb8(image::RgbImage::from_raw(__w, __h, __cimg.into_data()).unwrap())
                }
                _ => image::DynamicImage::ImageRgba8(image::RgbaImage::from_raw(__w, __h, __cimg.to_rgba8()).unwrap()),
            }
        })
        .unwrap()
        .to_rgb8()
        .get_pixel(0, 0)
        .0
}

#[test]
fn images_are_converted_too() {
    let d = image_doc(png([200, 40, 30]));
    let plain = pdf(&d, json!({}));
    assert!(String::from_utf8_lossy(&plain.bytes).contains("/ColorSpace/DeviceRGB"));
    let r = pdf(&d, json!({"output": {"conversion": "preserveNumbers", "destination": GENERIC_CMYK}}));
    assert!(String::from_utf8_lossy(&r.bytes).contains("/ColorSpace/DeviceCMYK"), "a CMYK image");
    // Converted to CMYK and compressed with JPEG: a CMYK JPEG.
    let jpeg =
        pdf(&d, json!({"compression": {"color": {"compression": "jpeg"}}, "output": {"conversion": "destination", "destination": GENERIC_CMYK}}));
    let t = String::from_utf8_lossy(&jpeg.bytes);
    assert!(t.contains("/DCTDecode") && t.contains("/ColorSpace/DeviceCMYK"), "{t}");
    assert!(jpeg.warnings.is_empty(), "{:?}", jpeg.warnings);
    // An RGB destination other than sRGB changes the pixels (unless their numbers are kept).
    assert_eq!(first_pixel(&plain.bytes), [200, 40, 30]);
    let p3 = |conversion: &str| first_pixel(&pdf(&d, json!({"output": {"conversion": conversion, "destination": cms::DISPLAY_P3}})).bytes);
    assert_ne!(p3("destination"), [200, 40, 30]);
    assert_eq!(p3("preserveNumbers"), [200, 40, 30]);
    // Grey images stay grey.
    let grey = image_doc(png([90, 90, 90]));
    let r = pdf(&grey, json!({"output": {"conversion": "destination", "destination": GENERIC_CMYK}}));
    assert!(String::from_utf8_lossy(&r.bytes).contains("/ColorSpace/DeviceGray"));
}

#[test]
fn printers_marks_keep_their_inks() {
    let d = doc(ColorMode::Cmyk, &[Color::cmyk(0.0, 0.0, 1.0, 0.0)]);
    let r = pdf(&d, json!({"marks": {"colorBars": true}, "output": {"conversion": "destination", "destination": SRGB}}));
    let ops: Vec<String> = colours(&r.bytes).into_iter().map(|c| c.0).collect();
    assert!(ops.contains(&"rg".to_string()) && ops.contains(&"k".to_string()), "art converted, colour bars kept: {ops:?}");
}

/// The catalog's output intent of `bytes` (opened with `password`).
fn output_intent(bytes: &[u8], password: Option<&str>, f: impl FnOnce(&Dict<'_>)) {
    let file = crate::pages::open(bytes, password).unwrap();
    let xref = file.xref();
    let catalog = xref.get::<Dict<'_>>(xref.root_id()).unwrap();
    let intents = catalog.get::<Array<'_>>(b"OutputIntents").unwrap();
    f(&intents.iter::<Dict<'_>>().next().unwrap());
}

#[test]
fn the_output_intent_embeds_its_profile_and_trapped_is_written() {
    let mut d = doc(ColorMode::Cmyk, &[Color::cmyk(0.0, 0.0, 1.0, 0.0)]);
    let out = json!({"outputIntent": GENERIC_CMYK, "outputCondition": "Coated (press)", "outputConditionId": "Généric", "registry": "http://example.com", "trapped": true});
    for (title, password) in [("Poster", None), ("", None), ("Poster", Some("secret"))] {
        d.title = title.into();
        let mut set = json!({"output": out});
        if let Some(p) = password {
            set["security"] = json!({"openPassword": p});
        }
        let r = pdf(&d, set);
        assert!(r.warnings.is_empty(), "{:?}", r.warnings);
        output_intent(&r.bytes, password, |oi| {
            assert_eq!(oi.get::<Name<'_>>(b"S").unwrap().as_ref(), b"GTS_PDFX");
            let text = |k: &[u8]| oi.get::<craft_pdf::syntax::object::String<'_>>(k).map(|s| s.as_bytes().to_vec());
            assert_eq!(text(b"OutputCondition").unwrap(), b"Coated (press)");
            assert_eq!(text(b"RegistryName").unwrap(), b"http://example.com");
            // Non-ASCII text is UTF-16 with its byte order mark.
            let id: Vec<u8> = [0xFE, 0xFF].into_iter().chain("Généric".encode_utf16().flat_map(u16::to_be_bytes)).collect();
            assert_eq!(text(b"OutputConditionIdentifier").unwrap(), id);
            let profile = oi.get::<Stream<'_>>(b"DestOutputProfile").unwrap();
            assert_eq!(profile.dict().get::<i32>(b"N"), Some(4));
            assert_eq!(profile.decoded().unwrap().as_ref(), &*cms::icc_bytes(GENERIC_CMYK).unwrap());
        });
        if password.is_none() {
            assert!(String::from_utf8_lossy(&r.bytes).contains("/Trapped/True"), "title {title:?}");
        }
        assert_eq!(
            import_with_report(&r.bytes, &ImportOptions { password: password.map(str::to_string), ..Default::default() })
                .unwrap()
                .document
                .artboards
                .len(),
            1
        );
    }
    // A condition identifier alone (a registered printing condition) names no profile; untrapped
    // output says so.
    let r = pdf(&d, json!({"output": {"outputConditionId": "CGATS TR 001"}}));
    output_intent(&r.bytes, None, |oi| assert!(oi.get::<Stream<'_>>(b"DestOutputProfile").is_none()));
    assert!(String::from_utf8_lossy(&r.bytes).contains("/Trapped/False"));
    // Nothing asked, nothing written.
    let plain = String::from_utf8_lossy(&pdf(&d, json!({})).bytes).into_owned();
    assert!(!plain.contains("/OutputIntents") && !plain.contains("/Trapped"));
}

#[test]
fn pdf_a_keeps_its_own_output_intent() {
    let d = doc(ColorMode::Rgb, &[Color::BLACK]);
    let r = pdf(&d, json!({"standard": "pdfA2b", "output": {"outputIntent": GENERIC_CMYK, "trapped": true}}));
    let text = String::from_utf8_lossy(&r.bytes);
    assert!(text.contains("GTS_PDFA1") && !text.contains("GTS_PDFX") && !text.contains("/Trapped"));
    assert!(r.setting_notes.iter().any(|w| w.contains("PDF/A")), "{:?}", r.setting_notes);
}

#[test]
fn pdf_a_tags_cmyk_colours_with_the_cmyk_profile() {
    let d = doc(ColorMode::Cmyk, &[Color::cmyk(0.1, 0.2, 0.3, 0.4)]);
    let r = pdf(&d, json!({"standard": "pdfA2b"}));
    assert!(icc_profiles(&r.bytes).iter().any(|p| p.0 == 4));
}

/// The streams of `bytes` that hold an ICC profile (`acsp` at offset 36), decoded.
fn icc_streams(bytes: &[u8]) -> Vec<Vec<u8>> {
    let file = Pdf::new(Arc::new(bytes.to_vec())).unwrap();
    let count = crate::patch::Xref::read(bytes).unwrap().count() as i32;
    (1..count)
        .filter_map(|n| file.xref().get::<Stream<'_>>(ObjectIdentifier::new(n, 0)))
        .map(|s| s.decoded().unwrap().into_owned())
        .filter(|data| data.get(36..40) == Some(b"acsp"))
        .collect()
}

/// [`pdf`] with the version and the creation date the standard of `settings` asks for.
fn standard_pdf(d: &Document, settings: Value) -> ExportReport {
    let mut settings: PdfSettings = serde_json::from_value(settings).unwrap();
    (settings.compatibility, settings.compression.compress_text) = (settings.standard.version(), false);
    export_with_report(d, &PdfOptions { settings, created: Some(1_700_000_000), ..Default::default() }).unwrap()
}

/// The output intent's profile, decoded, of `bytes`.
fn intent_profile(bytes: &[u8]) -> Vec<u8> {
    let mut out = vec![];
    output_intent(bytes, None, |oi| out = oi.get::<Stream<'_>>(b"DestOutputProfile").unwrap().decoded().unwrap().into_owned());
    out
}

/// CMYK colors in the profile of a CMYK output intent are DeviceCMYK, which the output intent
/// describes: no ICC-based CMYK space carries the same profile, and it is embedded once (#1954).
#[test]
fn cmyk_colors_in_the_output_intents_profile_are_device_cmyk() {
    let ink = [0.1, 0.2, 0.3, 0.4];
    let d = doc(ColorMode::Cmyk, &[Color::cmyk(ink[0], ink[1], ink[2], ink[3])]);
    let working = cms::active_settings().cmyk;
    let icc = cms::icc_bytes(&working).unwrap();
    for set in [
        json!({"standard": "pdfX4"}),
        json!({"standard": "pdfX4", "output": {"outputIntent": working}}),
        json!({"standard": "pdfX4", "output": {"profiles": "none", "outputIntent": working}}),
        json!({"standard": "pdfX3"}),
    ] {
        let r = standard_pdf(&d, set.clone());
        assert!(r.warnings.is_empty(), "{set}: {:?}", r.warnings);
        assert!(icc_streams(&r.bytes) == [icc.to_vec()], "{set}: the working CMYK profile, once");
        assert!(icc_profiles(&r.bytes).is_empty(), "{set}: no ICC-based color space");
        let c = colours(&r.bytes);
        assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: DeviceCMYK, the numbers kept: {c:?}");
        assert!(intent_profile(&r.bytes) == *icc, "{set}");
    }
    // Another output intent's profile: CMYK colors keep their own, and both are embedded.
    let other = cms::icc_bytes(DEVICE_CMYK).unwrap();
    let r = standard_pdf(&d, json!({"standard": "pdfX4", "output": {"outputIntent": DEVICE_CMYK}}));
    assert_eq!(icc_streams(&r.bytes).len(), 2);
    assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())]);
    assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{:?}", colours(&r.bytes));
    assert!(intent_profile(&r.bytes) == *other);
    // With `none`, every CMYK color is DeviceCMYK, in the output intent's profile.
    for standard in ["pdfX3", "pdfX4"] {
        let set = json!({"standard": standard, "output": {"profiles": "none", "outputIntent": DEVICE_CMYK}});
        let r = standard_pdf(&d, set.clone());
        assert!(icc_streams(&r.bytes) == [other.to_vec()], "{set}");
        let c = colours(&r.bytes);
        assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: {c:?}");
    }
    // With `none`, colors converted to a CMYK destination of another profile keep its tag: they
    // are in the destination's profile, not the output intent's.
    let set = json!({"standard": "pdfX4", "output": {"profiles": "none", "conversion": "destination", "destination": DEVICE_CMYK, "outputIntent": working}});
    let r = standard_pdf(&d, set.clone());
    assert!(icc_profiles(&r.bytes) == [(4, other.to_vec())], "{set}");
    assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes));
    assert!(intent_profile(&r.bytes) == *icc, "{set}");
    // Without a standard, `all` tags CMYK colors, with an output intent of their profile or none.
    for set in [json!({"output": {"profiles": "all"}}), json!({"output": {"profiles": "all", "outputIntent": working}})] {
        let r = standard_pdf(&d, set.clone());
        assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())], "{set}");
        assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes));
    }
}

/// Next to DeviceCMYK colors, RGB colors stay ICC-based (a CMYK output intent leaves no room for
/// DeviceRGB), and transparency groups of a CMYK document blend in DeviceCMYK.
#[test]
fn rgb_stays_tagged_and_groups_blend_in_device_cmyk_beside_device_cmyk_colors() {
    let d = doc(ColorMode::Rgb, &[Color::rgb(0.2, 0.4, 0.6), Color::cmyk(0.1, 0.2, 0.3, 0.4)]);
    for set in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] {
        let r = standard_pdf(&d, set.clone());
        let ops: Vec<String> = colours(&r.bytes).into_iter().map(|c| c.0).collect();
        assert_eq!(ops, ["scn", "k"], "{set}");
        let n: Vec<i32> = icc_profiles(&r.bytes).iter().map(|p| p.0).collect();
        assert_eq!(n, [3], "{set}: sRGB only");
    }
    let mut d = doc(ColorMode::Cmyk, &[Color::cmyk(1.0, 0.0, 0.0, 0.0)]);
    let mut n = Node::path(
        d.alloc_id(),
        shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)),
        Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0),
    );
    n.opacity = 0.5;
    let l = d.layers[0].id;
    d.insert(Some(l), 1, n).unwrap();
    let r = standard_pdf(&d, json!({"standard": "pdfX4"}));
    let text = String::from_utf8_lossy(&r.bytes);
    let groups: Vec<&str> = text.split("/Group<<").skip(1).map(|g| g.split(">>").next().unwrap()).collect();
    assert!(!groups.is_empty() && groups.iter().all(|g| g.contains("/CS/DeviceCMYK")), "{groups:?}");
}

/// The profiles assigned to a document (Edit › Assign Profile) are its colour spaces whatever the
/// working spaces of the session that exports it: a document opened again in a new session,
/// which starts with the default working spaces, keeps its profiles. Its CMYK profile is the PDF/X
/// output intent, whose DeviceCMYK colors are in it, and its RGB colours separate through it.
#[test]
fn colours_are_in_the_profiles_assigned_to_the_document() {
    let working = cms::active_settings().cmyk;
    assert_ne!(working, DEVICE_CMYK, "the document is assigned another profile than the working one");
    let intent = cms::active_settings().intent;
    let grey = Color::rgb(0.5, 0.5, 0.5);
    let mut d = doc(ColorMode::Cmyk, &[Color::cmyk(0.1, 0.2, 0.3, 0.4), grey]);
    d.color_profiles.cmyk = Some(DEVICE_CMYK.into());
    let r = standard_pdf(&d, json!({"standard": "pdfX4"}));
    assert!(!r.warnings.iter().any(|w| w.contains("profile")), "{:?}", r.warnings);
    let own = cms::icc_bytes(DEVICE_CMYK).unwrap();
    assert!(icc_streams(&r.bytes) == [own.to_vec()], "the document's CMYK profile, not the working one");
    output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::<Stream<'_>>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*own));
    let c = colours(&r.bytes);
    assert!(c[0].0 == "k" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}");
    let separated = to_cmyk(DEVICE_CMYK).to_cmyk(&grey, intent);
    assert!(!close(&separated, &cms::active().to_cmyk(&grey, intent)), "the two profiles separate grey differently");
    assert!(c[1].0 == "k" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}");
    // A profile that isn't available leaves the working space, with a warning.
    d.color_profiles.cmyk = Some("No Such Press".into());
    let r = standard_pdf(&d, json!({"standard": "pdfX4"}));
    assert!(r.warnings.iter().any(|w| w.contains("No Such Press")), "{:?}", r.warnings);
    assert!(icc_streams(&r.bytes) == [cms::icc_bytes(&working).unwrap().to_vec()]);
}