GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
//! Legacy `.ai` files (version 7) written, then read back as File › Open reads them.

use std::sync::Arc;

use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_geom::{Affine, AnchorKind, FillRule, PathData, Rect, shapes};

use super::*;

/// A node of `doc` filled `fill` (and stroked `stroke` 2 pt wide), path `path`.
fn shape(doc: &mut Document, path: PathData, fill: Paint, stroke: Paint) -> Node {
    Node::path(doc.alloc_id(), path, Appearance::basic(fill, stroke, 2.0))
}

fn red() -> Paint {
    Paint::solid(Color::rgb(1.0, 0.0, 0.0))
}

/// A 200 × 100 document: a layer `Back` holding a group of a red square (stroked blue) and a
/// locked one, a compound ring, a clipping group and a gradient square; a hidden layer `Front`
/// holding an ellipse and a 2 × 1 image.
fn sample() -> Document {
    let mut doc = Document::new(200.0, 100.0);
    doc.layers.clear();
    let back = doc.add_layer(Some("Back"));
    let front = doc.add_layer(Some("Front"));
    let a = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), red(), Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
    let mut b = shape(&mut doc, shapes::rectangle(Rect::new(50.0, 10.0, 80.0, 40.0)), Paint::solid(Color::gray(0.5)), Paint::None);
    b.locked = true;
    let group = Node::group(doc.alloc_id(), vec![Arc::new(a), Arc::new(b)]);
    doc.insert(Some(back), usize::MAX, group).unwrap();
    let outer = shape(&mut doc, shapes::rectangle(Rect::new(100.0, 10.0, 140.0, 50.0)), Paint::None, Paint::None);
    let inner = shape(&mut doc, shapes::rectangle(Rect::new(110.0, 20.0, 130.0, 40.0)), Paint::None, Paint::None);
    let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd });
    ring.appearance = Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), Paint::None, 0.0).into();
    doc.insert(Some(back), usize::MAX, ring).unwrap();
    let clip = Node::new(
        doc.alloc_id(),
        NodeKind::Path {
            path: shapes::rectangle(Rect::new(160.0, 20.0, 180.0, 40.0)),
            rule: FillRule::NonZero,
            live: None,
            clipping: true,
            guide: false,
        },
    );
    let clipped = shape(&mut doc, shapes::rectangle(Rect::new(150.0, 10.0, 190.0, 50.0)), Paint::solid(Color::gray(0.25)), Paint::None);
    let window = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(clipped)], clip: true });
    doc.insert(Some(back), usize::MAX, window).unwrap();
    let g = Gradient::new(
        GradientKind::Linear,
        vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.0))],
    );
    let shaded = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 60.0, 50.0, 90.0)), Paint::Gradient(Box::new(GradientPaint::new(g))), Paint::None);
    doc.insert(Some(back), usize::MAX, shaded).unwrap();
    let ellipse = shape(&mut doc, shapes::ellipse(Rect::new(100.0, 60.0, 160.0, 90.0)), red(), Paint::None);
    doc.insert(Some(front), usize::MAX, ellipse).unwrap();
    let mut png = vec![];
    let img = image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 0, 255, 255]).unwrap();
    {
        let __dyn: image::DynamicImage = img.into();
        let (__w, __h) = (__dyn.width(), __dyn.height());
        let (__layout, __sample, __raw) = match __dyn {
            image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageLuma16(b) => (
                craft_image_codecs::ChannelLayout::Gray,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageLumaA16(b) => (
                craft_image_codecs::ChannelLayout::GrayA,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageRgb16(b) => (
                craft_image_codecs::ChannelLayout::Rgb,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageRgba16(b) => (
                craft_image_codecs::ChannelLayout::Rgba,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
        };
        let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
        craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
            .map(|__b| png.extend_from_slice(&__b))
    }
    .unwrap();
    let blob = ImageBlob::new("image/png", png);
    let key = blob.content_key();
    doc.images.insert(key.clone(), blob);
    let im = ImageObject {
        key,
        width: 2,
        height: 1,
        xf: Affine::new([10.0, 0.0, 0.0, 10.0, 170.0, 70.0]),
        link: None,
        placement: Default::default(),
        pixels: None,
    };
    let im = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im)));
    doc.insert(Some(front), usize::MAX, im).unwrap();
    if let Some(l) = doc.layers.get_mut(1) {
        Arc::make_mut(l).visible = false;
    }
    doc
}

fn write(doc: &Document) -> LegacyAiOutput {
    write_with(doc, LegacyAiOptions::default())
}

/// The format has no conic gradient: a conic fill, and a conic stroke (written as its filled
/// outline), are solid wedges clipped to the shape, with a warning, and print as the canvas
/// draws them ([`write`] runs the file).
#[test]
fn conic_gradients_are_written_as_wedges_clipped_to_the_shape() {
    let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
    let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, stops));
    g.geom = Some(vectorcraft_color::GradientGeom {
        start: vectorcraft_geom::Point::new(100.0, 50.0),
        end: vectorcraft_geom::Point::new(140.0, 30.0),
        aspect: -0.7,
        focal: None,
    });
    let conic = Paint::Gradient(Box::new(g));
    for (fill, stroke) in [(conic.clone(), Paint::None), (Paint::None, conic)] {
        let mut doc = Document::new(200.0, 100.0);
        let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), fill.clone(), stroke.clone());
        let l = doc.layers[0].id;
        doc.insert(Some(l), 0, n).unwrap();
        let out = write(&doc);
        assert!(out.warnings.iter().any(|w| w == CONIC), "{:?}", out.warnings);
        let text = String::from_utf8_lossy(&out.bytes);
        assert!(!text.contains("%AI5_BeginGradient"), "no gradient stands in");
        assert!(text.matches("\nf\n").count() >= CONIC_WEDGES, "a wedge a degree");
    }
}

/// The format's gradients pad past their ends: a linear gradient that repeats or reflects is
/// written with its stops repeated across the shape (a definition of its own, not named after the
/// swatch), and a conic one as wedges that repeat with the stops (which print as the canvas
/// draws them), with a warning.
#[test]
fn spread_gradients_are_written_with_their_stops_repeated() {
    use vectorcraft_color::{GradientGeom, GradientSpread};
    let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
    let linear = |spread| {
        let mut g = GradientPaint::new(Gradient { spread, repeats: 3, ..Gradient::new(GradientKind::Linear, stops.clone()) });
        // Across the shape: three runs.
        g.geom = Some(GradientGeom {
            start: vectorcraft_geom::Point::new(20.0, 50.0),
            end: vectorcraft_geom::Point::new(180.0, 50.0),
            aspect: 1.0,
            focal: None,
        });
        g.swatch = Some("Bands".into());
        Paint::Gradient(Box::new(g))
    };
    for (spread, colors) in [
        (GradientSpread::Repeat, ["0 0 1", "1 0 0", "0 0 1", "1 0 0", "0 0 1", "1 0 0"]),
        (GradientSpread::Reflect, ["0 0 1", "1 0 0", "1 0 0", "0 0 1", "0 0 1", "1 0 0"]),
    ] {
        let mut doc = Document::new(200.0, 100.0);
        let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), linear(spread), Paint::None);
        let l = doc.layers[0].id;
        doc.insert(Some(l), 0, n).unwrap();
        let out = write(&doc);
        assert!(out.warnings.iter().any(|w| w == SPREAD), "{:?}", out.warnings);
        let text = String::from_utf8_lossy(&out.bytes);
        assert!(text.contains("(Gradient) 0 6 Bd") && !text.contains("(Bands)"), "{text}");
        // A linear definition lists its stops from the last to the first, each RGB stop as
        // `c m y k r g b 2 …`.
        let def = text.split("(Gradient) 0 6 Bd\n[\n").nth(1).unwrap();
        for (line, rgb) in def.lines().take(6).zip(colors) {
            assert!(line.contains(&format!(" {rgb} 2 ")), "{spread:?}: {line} lacks {rgb}\n{def}");
        }
    }
    let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Reflect, repeats: 3, ..Gradient::new(GradientKind::Conic, stops) });
    g.geom = Some(GradientGeom {
        start: vectorcraft_geom::Point::new(100.0, 50.0),
        end: vectorcraft_geom::Point::new(140.0, 30.0),
        aspect: 1.0,
        focal: None,
    });
    let mut doc = Document::new(200.0, 100.0);
    let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
    let l = doc.layers[0].id;
    doc.insert(Some(l), 0, n).unwrap();
    let text = String::from_utf8_lossy(&write(&doc).bytes).into_owned();
    assert!(text.matches("\nf\n").count() >= 3 * CONIC_WEDGES, "a wedge a degree for each run");
}

/// A gradient repeated more times than the reader keeps stops for is written with no more stops
/// than it reads, with a warning, so it opens with every stop that was written.
#[test]
fn many_repeats_are_written_within_the_stops_the_reader_reads() {
    use vectorcraft_color::{GradientGeom, GradientSpread};
    let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
    // A run of 0.4 pt across a shape 160 pt wide: 400 runs.
    let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(GradientKind::Linear, stops) });
    g.geom = Some(GradientGeom {
        start: vectorcraft_geom::Point::new(20.0, 50.0),
        end: vectorcraft_geom::Point::new(60.0, 50.0),
        aspect: 1.0,
        focal: None,
    });
    let mut doc = Document::new(200.0, 100.0);
    let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
    let l = doc.layers[0].id;
    doc.insert(Some(l), 0, n).unwrap();
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w == SPREAD_CAPPED), "{:?}", out.warnings);
    let text = String::from_utf8_lossy(&out.bytes).into_owned();
    let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap();
    let written = def.matches(" %_Bs\n").count();
    assert!((2..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops");
    let read = crate::import(&out.bytes).unwrap().document;
    let mut stops = None;
    read.walk(|n| {
        if let (None, Paint::Gradient(g)) = (&stops, n.appearance.fill_paint()) {
            stops = Some(g.gradient.stops.len());
        }
    });
    assert_eq!(stops, Some(written), "every stop written is read");
}

/// The format's gradients mix their stops' colors directly: a gradient mixed around the hue wheel
/// is written with the colors on its way around the wheel as stops, no more than the reader
/// reads, with a warning, and opens with the colors it had.
#[test]
fn hue_wheel_gradients_are_written_with_the_stops_on_their_curve() {
    use vectorcraft_color::GradientMethod;
    for (method, middle) in [(GradientMethod::HueCounterclockwise, [0.0, 1.0, 0.0]), (GradientMethod::HueClockwise, [1.0, 0.0, 1.0])] {
        let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
        let g = GradientPaint::new(Gradient { method, ..Gradient::new(GradientKind::Linear, stops) });
        let want = g.gradient.clone();
        let mut doc = Document::new(200.0, 100.0);
        let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
        let l = doc.layers[0].id;
        doc.insert(Some(l), 0, n).unwrap();
        let out = write(&doc);
        assert!(out.warnings.iter().any(|w| w == HUE_STOPS), "{method:?}: {:?}", out.warnings);
        let text = String::from_utf8_lossy(&out.bytes).into_owned();
        let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap();
        let written = def.matches(" %_Bs\n").count();
        // The two ends and each sixth of the wheel between them, where the way turns in RGB.
        assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{method:?}: {written} stops");
        let read = crate::import(&out.bytes).unwrap().document;
        let mut back = None;
        read.walk(|n| {
            if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) {
                back = Some(g.gradient.clone());
            }
        });
        let back = back.unwrap();
        assert!(back.method.is_classic(), "{method:?}");
        let mid = back.sample(0.5).0.to_rgb();
        assert!(mid.iter().zip(middle).all(|(a, b)| (a - b).abs() < 0.03), "{method:?}: the middle is {mid:?}");
        for k in 0..=100 {
            let t = k as f32 / 100.0;
            let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb());
            assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "{method:?} at {t}: {a:?} vs {b:?}");
        }
    }
}

/// The written definition of the gradient named `name` in `text`, and how many stops it holds.
fn definition<'a>(text: &'a str, name: &str) -> (&'a str, usize) {
    let def = text.split(&format!("%AI5_BeginGradient: ({name})\n")).nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap();
    (def, def.matches(" %_Bs\n").count())
}

/// The format's gradients mix their stops' colors directly: a Perceptual gradient is written in
/// process colors with the colors on its curve as stops, no more than the reader reads, in a
/// definition of its own rather than its swatch's, with a warning, and opens with the colors it
/// had. A Classic gradient keeps its own stops and gives no warning.
#[test]
fn perceptual_gradients_are_written_with_the_stops_on_their_curve() {
    use vectorcraft_color::{GradientMethod, Swatch};
    let mut doc = Document::new(200.0, 100.0);
    for (name, color) in [("Night", Color::cmyk(1.0, 1.0, 0.0, 0.0)), ("Sun", Color::cmyk(0.0, 0.0, 1.0, 0.0))] {
        doc.swatches.push(Swatch { name: name.into(), paint: Paint::solid(color), global: true, spot: true });
    }
    let stop = |offset: f32, color: Color, swatch: &str| GradientStop { swatch: Some(swatch.into()), ..GradientStop::new(offset, color) };
    let stops = vec![stop(0.0, Color::cmyk(1.0, 1.0, 0.0, 0.0), "Night"), stop(1.0, Color::cmyk(0.0, 0.0, 1.0, 0.0), "Sun")];
    let mut g = GradientPaint::new(Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) });
    g.swatch = Some("Dusk".into());
    let want = g.gradient.clone();
    // The same stops mixed directly stray from the Perceptual curve, so a file holding only the
    // two stops would not open with the colors it had.
    let classic = Gradient { method: GradientMethod::Classic, ..want.clone() };
    assert!(
        (0..=100).any(|k| {
            let t = k as f32 / 100.0;
            want.sample(t).0.to_rgb().iter().zip(classic.sample(t).0.to_rgb()).any(|(a, b)| (a - b).abs() > 0.05)
        }),
        "the methods mix alike"
    );
    let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
    let l = doc.layers[0].id;
    doc.insert(Some(l), 0, n).unwrap();
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings);
    assert!(!out.warnings.iter().any(|w| w == HUE_STOPS), "{:?}", out.warnings);
    let text = String::from_utf8_lossy(&out.bytes).into_owned();
    assert!(!text.contains("(Dusk)"), "the curve is not the swatch's gradient");
    assert!(!text.contains("(Night)") && !text.contains("(Sun)"), "the stops are process colors: {text}");
    let (_, written) = definition(&text, "Gradient");
    assert!((3..=crate::import::MAX_GRADIENT_STOPS).contains(&written), "{written} stops");
    let read = crate::import(&out.bytes).unwrap().document;
    let mut back = None;
    read.walk(|n| {
        if let (None, Paint::Gradient(g)) = (&back, n.appearance.fill_paint()) {
            back = Some(g.gradient.clone());
        }
    });
    let back = back.unwrap();
    assert!(back.method.is_classic());
    assert_eq!(back.stops.len(), written, "every stop written is read");
    assert!(back.stops.iter().all(|s| s.swatch.is_none()), "{:?}", back.stops);
    for k in 0..=100 {
        let t = k as f32 / 100.0;
        let (a, b) = (want.sample(t).0.to_rgb(), back.sample(t).0.to_rgb());
        assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.03), "at {t}: {a:?} vs {b:?}");
    }

    // Classic: its own two stops, its spot colors and its swatch's name, without the warning.
    let mut doc = Document::new(200.0, 100.0);
    doc.swatches.push(Swatch { name: "Night".into(), paint: Paint::solid(Color::cmyk(1.0, 1.0, 0.0, 0.0)), global: true, spot: true });
    let mut g = GradientPaint::new(classic);
    g.swatch = Some("Dusk".into());
    let n = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
    let l = doc.layers[0].id;
    doc.insert(Some(l), 0, n).unwrap();
    let out = write(&doc);
    assert!(!out.warnings.iter().any(|w| w == PERCEPTUAL_STOPS), "{:?}", out.warnings);
    let text = String::from_utf8_lossy(&out.bytes).into_owned();
    assert_eq!(definition(&text, "Dusk").1, 2);
    assert!(text.contains("%%DocumentCustomColors: (Night)"), "{text}");
}

/// A radial gradient repeated out from a center far from the shape is written with its ramp points
/// (percent) to five decimals, so its runs keep their places hundreds of runs out.
#[test]
fn far_runs_keep_their_places() {
    use vectorcraft_color::{GradientGeom, GradientSpread};
    let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
    let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, ..Gradient::new(GradientKind::Radial, stops) });
    // Runs 0.25 pt apart, the shape 480 runs and more from the center.
    let c = vectorcraft_geom::Point::new(-100.0, 50.0);
    g.geom = Some(GradientGeom { start: c, end: c + vectorcraft_geom::Vec2::new(0.25, 0.0), aspect: 1.0, focal: None });
    let bounds = Rect::new(20.0, 10.0, 180.0, 90.0);
    let padded = g.gradient.padded_within(&g.geom.unwrap(), bounds, crate::import::MAX_GRADIENT_STOPS).unwrap();
    let mut doc = Document::new(200.0, 100.0);
    let n = shape(&mut doc, shapes::rectangle(bounds), Paint::Gradient(Box::new(g)), Paint::None);
    let l = doc.layers[0].id;
    doc.insert(Some(l), 0, n).unwrap();
    let text = String::from_utf8_lossy(&write(&doc).bytes).into_owned();
    let def = text.split("%AI5_BeginGradient: (Gradient)\n").nth(1).and_then(|d| d.split("%AI5_EndGradient").next()).unwrap();
    let ramps: Vec<f64> = def.lines().filter_map(|l| l.strip_suffix(" %_Bs")).map(|l| l.rsplit(' ').next().unwrap().parse().unwrap()).collect();
    assert_eq!(ramps.len(), padded.gradient.stops.len());
    for (ramp, stop) in ramps.iter().zip(&padded.gradient.stops) {
        assert!((ramp / 100.0 - f64::from(stop.offset)).abs() < 2e-7, "{ramp} for {}", stop.offset);
    }
}

/// The format has no diamond gradient: a diamond fill, and a diamond stroke (written as its filled
/// outline), are four path objects clipped to the shape, each a linear gradient over a quadrant
/// of the diamond's frame, with a warning; the definition is not named after the swatch.
#[test]
fn diamond_gradients_are_written_as_four_linear_gradients_clipped_to_the_shape() {
    let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
    let mut g = GradientPaint::new(Gradient::new(GradientKind::Diamond, stops));
    g.geom = Some(vectorcraft_color::GradientGeom {
        start: vectorcraft_geom::Point::new(100.0, 50.0),
        end: vectorcraft_geom::Point::new(140.0, 30.0),
        aspect: 0.7,
        focal: None,
    });
    g.swatch = Some("Gem".into());
    let diamond = Paint::Gradient(Box::new(g));
    for (fill, stroke) in [(diamond.clone(), Paint::None), (Paint::None, diamond)] {
        let mut doc = Document::new(200.0, 100.0);
        let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), fill.clone(), stroke.clone());
        let l = doc.layers[0].id;
        doc.insert(Some(l), 0, n).unwrap();
        let out = write(&doc);
        assert!(out.warnings.iter().any(|w| w == DIAMOND), "{:?}", out.warnings);
        let text = String::from_utf8_lossy(&out.bytes);
        assert_eq!(text.matches("%AI5_BeginGradient: (Gradient)").count(), 1, "one linear definition: {text}");
        assert!(!text.contains("(Gem)"), "not named after the swatch");
        assert_eq!(text.matches(" Bg\n").count(), 4, "a gradient a quadrant");
    }
}

/// A diamond gradient that repeats is four linear gradients over the quadrants of its frame, each
/// with its stops repeated out to the shape's edge, with a warning.
#[test]
fn a_spread_diamond_repeats_in_each_quadrant() {
    use vectorcraft_color::GradientSpread;
    let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
    let mut g = GradientPaint::new(Gradient { spread: GradientSpread::Repeat, repeats: 3, ..Gradient::new(GradientKind::Diamond, stops) });
    g.geom = Some(vectorcraft_color::GradientGeom {
        start: vectorcraft_geom::Point::new(100.0, 50.0),
        end: vectorcraft_geom::Point::new(140.0, 30.0),
        aspect: 0.7,
        focal: None,
    });
    let mut doc = Document::new(200.0, 100.0);
    let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), Paint::Gradient(Box::new(g)), Paint::None);
    let l = doc.layers[0].id;
    doc.insert(Some(l), 0, n).unwrap();
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w == DIAMOND) && out.warnings.iter().any(|w| w == SPREAD), "{:?}", out.warnings);
    let text = String::from_utf8_lossy(&out.bytes).into_owned();
    assert_eq!(text.matches(" Bg\n").count(), 4, "a gradient a quadrant");
    let defs: Vec<usize> =
        text.split("%AI5_BeginGradient: ").skip(1).map(|d| d.split("%AI5_EndGradient").next().unwrap_or("").matches(" %_Bs\n").count()).collect();
    assert!(!defs.is_empty() && defs.iter().all(|&n| n >= 6), "stops in each definition: {defs:?}");
}

/// `doc` written with options `o`. Every file the tests write is also run as a PostScript program
/// ([`prints_as`]) and must draw what `doc` draws.
fn write_with(doc: &Document, o: LegacyAiOptions) -> LegacyAiOutput {
    let o = LegacyAiOptions { title: "Sample".into(), created: Some(0), ..o };
    let out = export_legacy_ai(doc, &o).unwrap();
    prints_as(&out.bytes, doc, &o);
    out
}

/// `doc` as the prolog prints the file written from it with options `o`: without its layers that
/// don't print, its type as its glyphs' outlines where the writer writes them (all type with
/// [`LegacyAiOptions::outline_text`], else the type 8-bit text can't hold) and left out where it
/// writes text objects, its
/// hidden objects shown when `o` writes them visible, and its gradient fills and strokes painted
/// in their first stop's color.
fn as_printed(doc: &Document, o: &LegacyAiOptions) -> Document {
    // A run's glyphs, laid out, with its ruby's, as one path with the run's fill (the renderer
    // draws no type), and its colour bitmap glyphs as images (their pixels added to `images`), its
    // COLR glyphs as their layers.
    fn outlined(t: &vectorcraft_doc::TextObject, images: &mut std::collections::BTreeMap<String, ImageBlob>) -> Node {
        let layout = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
        let mut nodes: Vec<Arc<Node>> = t
            .runs
            .iter()
            .enumerate()
            .map(|(i, run)| {
                let mut bp = kurbo::BezPath::new();
                for g in layout.glyphs.iter().chain(&layout.ruby).filter(|g| g.run == i) {
                    bp.extend(g.outline.iter());
                }
                let path = PathData::from_bezpath(&bp).transformed(t.xf);
                Arc::new(Node::path(vectorcraft_doc::NodeId(0), path, Appearance::basic(run.style.fill.clone(), Paint::None, 0.0)))
            })
            .collect();
        for g in &layout.glyphs {
            let Some((image, to_text)) = g.placed_image() else { continue };
            let key = image.blob.content_key();
            images.insert(key.clone(), image.blob.clone());
            let im = ImageObject {
                key,
                width: image.width,
                height: image.height,
                xf: t.xf * to_text,
                link: None,
                placement: Default::default(),
                pixels: None,
            };
            nodes.push(Arc::new(Node::new(vectorcraft_doc::NodeId(0), NodeKind::Image(Box::new(im)))));
        }
        // COLR glyphs: their layers.
        nodes.extend(layout.glyphs.iter().filter_map(|g| g.placed_colour(t.xf)).map(Arc::new));
        Node::group(vectorcraft_doc::NodeId(0), nodes)
    }
    fn plain(doc: &Document, nodes: &mut Vec<Arc<Node>>, o: &LegacyAiOptions, images: &mut std::collections::BTreeMap<String, ImageBlob>) {
        nodes.retain(|n| match &n.kind {
            NodeKind::Text(t) => o.outline_text || !writable(doc, t),
            NodeKind::Layer { printable, .. } => *printable,
            _ => true,
        });
        for n in nodes {
            if let NodeKind::Text(t) = &n.kind {
                *n = Arc::new(outlined(t, images));
            }
            let n = Arc::make_mut(n);
            if o.hidden == HiddenObjects::Visible && !matches!(n.kind, NodeKind::Layer { .. }) {
                n.visible = true;
            }
            for item in &mut n.appearance.items {
                let paint = match item {
                    AppearanceItem::Fill(f) => &mut f.paint,
                    AppearanceItem::Stroke(s) => &mut s.paint,
                };
                // Conic gradients are written as wedges, which print.
                if let Paint::Gradient(g) = paint
                    && g.gradient.kind != GradientKind::Conic
                {
                    *paint = g.gradient.stops.first().map_or(Paint::None, |s| Paint::solid(s.color));
                }
            }
            if let Some(c) = n.children_mut() {
                plain(doc, c, o, images);
            }
        }
    }
    let mut d = doc.clone();
    let mut images = std::mem::take(&mut d.images);
    plain(doc, &mut d.layers, o, &mut images);
    d.images = images;
    d
}

/// The legacy `.ai` `bytes` run as a PostScript program (VectorCraft's PostScript reader, with the
/// file's prolog) draws as `doc`, written with options `o` (its first artboard the file's), prints
/// ([`as_printed`]): the same art in the same places, in the same colours.
fn prints_as(bytes: &[u8], doc: &Document, o: &LegacyAiOptions) {
    let text = String::from_utf8_lossy(bytes);
    let nums = |key: &str| -> Vec<f64> {
        let line = text.lines().find_map(|l| l.strip_prefix(key)).unwrap_or_else(|| panic!("no {key}"));
        line.split_whitespace().map(|v| v.parse().unwrap()).collect()
    };
    // The art's box (the page the program draws on) and the artboard's top, in art space (y up).
    let [llx, lly, urx, ury] = nums("%%HiResBoundingBox:")[..] else { panic!() };
    let top = nums("%AI3_TileBox:")[3];
    let board = doc.artboards[0].rect;
    let there = Rect::new(board.x0 + llx, board.y0 + top - ury, board.x0 + urx, board.y0 + top - lly);
    let scale = 300.0 / (urx - llx).max(ury - lly).max(1.0);
    let want = vectorcraft_render::Renderer::new().render_region(&as_printed(doc, o), there, scale, true);
    let drew = match crate::import_with(bytes, false) {
        Ok(page) => {
            assert!(!page.preview, "read as its program");
            vectorcraft_render::Renderer::new().render_region(&page.document, Rect::new(0.0, 0.0, urx - llx, ury - lly), scale, true)
        }
        // A page that marks nothing (type alone): blank.
        Err(e) if e.contains("draws nothing") => {
            vectorcraft_render::Renderer::new().render_region(&Document::new(1.0, 1.0), Rect::new(0.0, 0.0, urx - llx, ury - lly), scale, true)
        }
        Err(e) => panic!("the file doesn't run as PostScript: {e}"),
    };
    assert_eq!((drew.width, drew.height), (want.width, want.height));
    let differ = drew
        .pixels
        .as_chunks::<4>()
        .0
        .iter()
        .zip(want.pixels.as_chunks::<4>().0)
        .filter(|(a, b)| a.iter().zip(*b).any(|(x, y)| x.abs_diff(*y) > 48))
        .count();
    let share = differ as f64 / f64::from(want.width * want.height).max(1.0);
    assert!(share < 0.002, "the program draws {:.2}% of the page differently", share * 100.0);
}

fn children(n: &Node) -> &[Arc<Node>] {
    n.children().map_or(&[][..], Vec::as_slice)
}

#[test]
fn writes_the_documented_operators() {
    let out = write(&sample());
    let text = String::from_utf8(out.bytes).unwrap();
    for needle in [
        "%!PS-Adobe-3.0\n",
        "%AI5_FileFormat 3\n",
        "%%CreationDate: (1/1/1970) (00:00)\n",
        "%AI5_ArtSize: 200 100",
        "%AI3_TemplateBox: 100 50 100 50",
        "%AI5_NumLayers: 2",
        "(Back) Ln",
        "(Front) Ln",
        "%AI5_BeginGradient: (Gradient)",
        "\nu\n",
        "\n*u\n",
        "\nq\n",
        "\n1 A\n",
        "XI\n",
        "%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\nend\n%%EOF\n",
    ] {
        assert!(text.contains(needle), "missing {needle:?} in\n{text}");
    }
    // The prolog is the writer's own procedure set, named in the header, in the dictionary the
    // setup begins; it defines the page trailer's `annotatepage` (§3).
    let prolog = text.split("%%BeginProlog\n").nth(1).and_then(|t| t.split("%%EndProlog\n").next()).unwrap();
    assert!(prolog.starts_with(&format!("%%BeginResource: procset {PROCSET}\n/VCLegacy ")), "{prolog}");
    assert!(prolog.ends_with("end\n%%EndResource\n") && prolog.contains("\n/annotatepage {} bd\n"), "{prolog}");
    assert!(text.contains(&format!("%%DocumentSuppliedResources: procset {PROCSET}\n")), "{text}");
    // The hidden layer is written hidden: visible 0.
    assert!(text.contains("%AI5_BeginLayer\n0 1 1 1 0 0 1 "), "{text}");
    // Art space is y up from the artboard's bottom-left: the red square (10..40 down from the top)
    // is 60..90 up. Its corners are corner points (upper case, AI7 spec §5.3.2); its fill RGB
    // (`r g b Xa`, §5.4.1).
    assert!(text.contains("1 0 0 Xa\n"), "{text}");
    assert!(text.contains("10 90 m\n40 90 L\n40 60 L\n10 60 L\n10 90 L\nb\n"), "{text}");
    // The ellipse's points are smooth (lower case).
    assert!(text.contains(" c\n") && !text.contains(" C\n"), "{text}");
    // The clipping path: closed by `h`, then `W n` (§5.6.2).
    assert!(text.contains(" L\nh\nW\nn\n"), "{text}");
    // Gradients: counted (`Bn`), each stop's operands before `%_Bs` (§3.5).
    assert!(text.contains("%%BeginSetup\nVCLegacy begin\n1 Bn\n%AI5_BeginGradient: (Gradient)\n(Gradient) 0 2 Bd\n[\n"), "{text}");
    assert!(text.contains(" 2 50 100 %_Bs\n") && !text.contains("Np\n"), "{text}");
    assert!(text.contains("1 0 0 1 0 0 Bg\nf\n0 BB\n"), "{text}");
    // The image: operands and `XI` on a line, its samples on comment lines (§8).
    assert!(text.contains("] 0 0 2 1 2 1 8 3 0 0 0 0 XI\n%FF00000000FF\n%AI5_EndRaster\n"), "{text}");
}

/// An image's matrix (§8) is an art-space matrix applied to its pixels with their rows running
/// downwards, `(u, -v)`: a rotated image is written with the matrix the reader and other apps
/// place it by, prints where it is, and reads back where it was (#2269).
#[test]
fn a_rotated_image_keeps_its_place() {
    let mut doc = Document::new(200.0, 100.0);
    let img = craft_image_codecs::Image::from_raw(
        2,
        1,
        craft_image_codecs::ChannelLayout::Rgba,
        craft_image_codecs::SampleType::U8,
        vec![255, 0, 0, 255, 0, 0, 255, 255],
    )
    .unwrap();
    let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
    let blob = ImageBlob::new("image/png", png);
    let key = blob.content_key();
    doc.images.insert(key.clone(), blob);
    // Turned 90° clockwise on the page: the pixel rows run down, the next row is to the left.
    let xf = Affine::new([0.0, 10.0, -10.0, 0.0, 100.0, 40.0]);
    let im = Node::new(
        doc.alloc_id(),
        NodeKind::Image(Box::new(ImageObject { key, width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None })),
    );
    doc.layers.clear();
    let layer = doc.add_layer(Some("Art"));
    doc.insert(Some(layer), usize::MAX, im).unwrap();
    let out = write(&doc);
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    // In art space (y up) the rows run down, (0, -10) a pixel, and the next row is to the left,
    // (-10, 0): [a b] = (0, -10) and [c d] = (10, 0), as the matrix takes (u, -v).
    let line = text.lines().find(|l| l.ends_with(" XI")).unwrap();
    let m: Vec<f64> = line.trim_start_matches('[').split(']').next().unwrap().split_whitespace().map(|v| v.parse().unwrap()).collect();
    assert_eq!(m[..4], [0.0, -10.0, 10.0, 0.0], "{line}");
    let read = crate::import(&out.bytes).unwrap().document;
    let mut found = None;
    read.walk(|n| {
        if let NodeKind::Image(im) = &n.kind {
            found = Some(im.xf);
        }
    });
    let back = found.unwrap();
    assert!(back.as_coeffs().iter().zip(xf.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{back:?}");
}

/// A 16 × 16 RGB image of `doc` filling `r`.
fn picture(doc: &mut Document, r: Rect) -> Node {
    let mut png = vec![];
    {
        let __dyn: image::DynamicImage = (image::RgbaImage::from_fn(16, 16, |u, v| image::Rgba([(u * 16) as u8, (v * 16) as u8, 128, 255]))).into();
        let (__w, __h) = (__dyn.width(), __dyn.height());
        let (__layout, __sample, __raw) = match __dyn {
            image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageLuma16(b) => (
                craft_image_codecs::ChannelLayout::Gray,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageLumaA16(b) => (
                craft_image_codecs::ChannelLayout::GrayA,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageRgb16(b) => (
                craft_image_codecs::ChannelLayout::Rgb,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageRgba16(b) => (
                craft_image_codecs::ChannelLayout::Rgba,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
        };
        let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
        craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
            .map(|__b| png.extend_from_slice(&__b))
    }
    .unwrap();
    let blob = ImageBlob::new("image/png", png);
    let key = blob.content_key();
    doc.images.insert(key.clone(), blob);
    let xf = Affine::new([r.width() / 16.0, 0.0, 0.0, r.height() / 16.0, r.x0, r.y0]);
    Node::new(
        doc.alloc_id(),
        NodeKind::Image(Box::new(ImageObject { key, width: 16, height: 16, xf, link: None, placement: Default::default(), pixels: None })),
    )
}

/// A layer `Below` holding a clipping group (a circle clipping an image, as in #2692), a group
/// holding an image and an image; a layer `Above` holding an orange square. Without `images`,
/// `Below` is empty.
fn images_below_a_square(images: bool) -> Document {
    let mut doc = Document::new(400.0, 200.0);
    doc.layers.clear();
    let below = doc.add_layer(Some("Below"));
    let above = doc.add_layer(Some("Above"));
    if images {
        let clip = Node::new(
            doc.alloc_id(),
            NodeKind::Path {
                path: shapes::ellipse(Rect::new(30.0, 30.0, 170.0, 170.0)),
                rule: FillRule::NonZero,
                live: None,
                clipping: true,
                guide: false,
            },
        );
        let clipped = picture(&mut doc, Rect::new(20.0, 20.0, 180.0, 180.0));
        let window = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(clipped)], clip: true });
        doc.insert(Some(below), usize::MAX, window).unwrap();
        let grouped = picture(&mut doc, Rect::new(200.0, 20.0, 240.0, 60.0));
        let group = Node::group(doc.alloc_id(), vec![Arc::new(grouped)]);
        doc.insert(Some(below), usize::MAX, group).unwrap();
        let loose = picture(&mut doc, Rect::new(250.0, 20.0, 290.0, 60.0));
        doc.insert(Some(below), usize::MAX, loose).unwrap();
    }
    let orange = Paint::solid(Color::rgb(247.0 / 255.0, 148.0 / 255.0, 29.0 / 255.0));
    let square = shape(&mut doc, shapes::rectangle(Rect::new(220.0, 100.0, 380.0, 180.0)), orange, Paint::None);
    doc.insert(Some(above), usize::MAX, square).unwrap();
    doc
}

/// Each image the file holds (§8.4): the lines from `%AI5_File:` to the line after
/// `%AI5_EndRaster`.
fn rasters(text: &str) -> Vec<Vec<&str>> {
    let lines: Vec<&str> = text.lines().collect();
    let mut out = vec![];
    for (i, l) in lines.iter().enumerate() {
        if *l == "%AI5_File:" {
            let end = lines[i..].iter().position(|l| *l == "%AI5_EndRaster").map(|n| i + n).unwrap();
            out.push(lines[i..=(end + 1).min(lines.len() - 1)].to_vec());
        }
    }
    out
}

/// Every image, in a clipping group, a group or neither, is written as §8.1's syntax and §8.4's
/// examples write one: `%AI5_File:`, `%AI5_BeginRaster`, the matrix with a space inside each
/// bracket and the operands on the `XI` line, the samples in hex on comment lines of 60 digits,
/// `%AI5_EndRaster`. A line `F`, which the examples do not show, follows each image. The art
/// after the images is written as it is without them, and the file reads back with its layers,
/// clipping group, images and square (#2692, #2830).
#[test]
fn images_are_written_in_the_form_the_specification_shows() {
    let out = write(&images_below_a_square(true));
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    let images = rasters(&text);
    assert_eq!(images.len(), 3, "{text}");
    for lines in &images {
        let [file, begin, xi, data @ .., end, paint] = lines.as_slice() else { panic!("{lines:?}") };
        assert_eq!((*file, *begin, *end, *paint), ("%AI5_File:", "%AI5_BeginRaster", "%AI5_EndRaster", "F"));
        let matrix = xi.strip_prefix("[ ").and_then(|l| l.strip_suffix(" ] 0 0 16 16 16 16 8 3 0 0 0 0 XI")).unwrap_or_else(|| panic!("{xi}"));
        assert_eq!(matrix.split(' ').filter(|v| v.parse::<f64>().is_ok()).count(), 6, "{xi}");
        let digits: Vec<&str> = data.iter().map(|l| l.strip_prefix('%').unwrap_or_else(|| panic!("{l}"))).collect();
        let (last, full) = digits.split_last().unwrap();
        assert!(full.iter().all(|d| d.len() == 60) && (1..=60).contains(&last.len()), "{digits:?}");
        assert!(digits.iter().all(|d| d.bytes().all(|b| b.is_ascii_hexdigit())), "{digits:?}");
        assert_eq!(digits.concat().len(), 16 * 16 * 3 * 2);
    }
    // The clipping group: `q`, the clipping path painted `h W n` (§5.6.2), the image, `Q`; the
    // group: `u`, the image, `U`; the loose image, then the layer's end.
    assert!(text.contains("\nh\nW\nn\n%AI5_File:\n") && text.contains("\n%AI5_EndRaster\nF\nQ\n"), "{text}");
    assert!(text.contains("\nu\n%AI5_File:\n") && text.contains("\n%AI5_EndRaster\nF\nU\n"), "{text}");
    assert!(text.contains("\n%AI5_EndRaster\nF\nLB\n"), "{text}");
    let layer = |t: &str| -> String {
        let at = t.find("(Above) Ln\n").unwrap();
        t[at..].split("%AI5_EndLayer--").next().unwrap().to_string()
    };
    let alone = String::from_utf8(write(&images_below_a_square(false)).bytes).unwrap();
    assert_eq!(layer(&text), layer(&alone));
    let doc = crate::import(&out.bytes).unwrap().document;
    let names: Vec<_> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
    assert_eq!(names, ["Below", "Above"]);
    let below = children(&doc.layers[0]);
    assert_eq!(below.len(), 3, "{below:#?}");
    let NodeKind::Group { children: window, clip: true } = &below[0].kind else { panic!("{:?}", below[0].kind) };
    assert_eq!(window.len(), 2, "{window:#?}");
    assert!(matches!(window[0].kind, NodeKind::Path { clipping: true, .. }) && matches!(window[1].kind, NodeKind::Image(_)), "{window:#?}");
    assert!(
        matches!(&below[1].kind, NodeKind::Group { children, clip: false } if children.len() == 1 && matches!(children[0].kind, NodeKind::Image(_)))
    );
    assert!(matches!(below[2].kind, NodeKind::Image(_)));
    let above = children(&doc.layers[1]);
    assert_eq!(above.len(), 1);
    let rgb = above[0].appearance.fill_paint().color().map(|c| c.to_rgb()).unwrap();
    assert!(rgb.iter().zip([247.0, 148.0, 29.0]).all(|(c, want)| (c * 255.0 - want).abs() < 0.1), "{rgb:?}");
}

/// An image's samples are written as upper-case hex on `%` comment lines (§8.1, §8.4) of 60
/// digits, the last line shorter, each line ending with a newline: no samples write no line, and
/// samples that fill their last line exactly write no empty `%` line after it.
#[test]
fn image_samples_are_written_as_hex_lines() {
    let hex = |samples: &[u8]| {
        let mut s = String::new();
        super::writer::Writer::push_hex(&mut s, samples);
        s
    };
    let mut samples = vec![0x00, 0x09, 0x0A, 0xAF, 0xFF];
    samples.extend(0x10..=0x29);
    assert_eq!(hex(&samples), "%00090AAFFF101112131415161718191A1B1C1D1E1F202122232425262728\n%29\n");
    assert_eq!(hex(&samples[..30]), "%00090AAFFF101112131415161718191A1B1C1D1E1F202122232425262728\n");
    assert_eq!(hex(&samples[..29]), "%00090AAFFF101112131415161718191A1B1C1D1E1F2021222324252627\n");
    assert_eq!(hex(&[0xAB]), "%AB\n");
    assert_eq!(hex(&[]), "");
    // Appended after what is already written.
    let mut s = String::from("0 0 1 1 1 1 8 3 0 0 0 0 XI\n");
    super::writer::Writer::push_hex(&mut s, &[0xC0, 0xFF, 0xEE]);
    assert_eq!(s, "0 0 1 1 1 1 8 3 0 0 0 0 XI\n%C0FFEE\n");
}

/// The hex lines are the same as formatting each sample with `{:02X}` and breaking the digits
/// into lines of [`HEX_LINE`], for every length up to three lines and one more sample, and for
/// every byte value.
#[test]
fn image_hex_matches_formatted_samples() {
    let formatted = |samples: &[u8]| {
        let digits: String = samples.iter().map(|c| format!("{c:02X}")).collect();
        let lines: Vec<String> = digits.as_bytes().chunks(HEX_LINE).map(|l| format!("%{}\n", std::str::from_utf8(l).unwrap())).collect();
        lines.concat()
    };
    let all: Vec<u8> = (0..=255u8).cycle().skip(7).take(3 * HEX_LINE / 2 + 1).collect();
    for n in 0..=all.len() {
        let mut s = String::new();
        super::writer::Writer::push_hex(&mut s, &all[..n]);
        assert_eq!(s, formatted(&all[..n]), "{n} samples");
    }
    let every: Vec<u8> = (0..=255u8).collect();
    let mut s = String::new();
    super::writer::Writer::push_hex(&mut s, &every);
    assert_eq!(s, formatted(&every));
}

/// The pieces of an image cut into a raster mesh warp (as Object › Expand leaves a Warp on an
/// image) are written as the image whole once, then each as the part of it that its triangle shows,
/// and the file draws as the document does ([`write`] runs it).
#[test]
fn the_pieces_of_a_warped_image_are_written_as_the_parts_they_show() {
    // GUARDS: each of a warped image's 200 pieces was written with all of the image's samples.
    let mut doc = Document::new(200.0, 160.0);
    let mut png = vec![];
    {
        let __dyn: image::DynamicImage =
            (image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba([(x * 4) as u8, (y * 4) as u8, ((x * 7 + y * 13) % 256) as u8, 255]))).into();
        let (__w, __h) = (__dyn.width(), __dyn.height());
        let (__layout, __sample, __raw) = match __dyn {
            image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageLuma16(b) => (
                craft_image_codecs::ChannelLayout::Gray,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageLumaA16(b) => (
                craft_image_codecs::ChannelLayout::GrayA,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageRgb16(b) => (
                craft_image_codecs::ChannelLayout::Rgb,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageRgba16(b) => (
                craft_image_codecs::ChannelLayout::Rgba,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
        };
        let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
        craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
            .map(|__b| png.extend_from_slice(&__b))
    }
    .unwrap();
    let blob = ImageBlob::new("image/png", png);
    let key = blob.content_key();
    doc.images.insert(key.clone(), blob);
    let im = ImageObject {
        key,
        width: 64,
        height: 64,
        xf: Affine::new([2.0, 0.0, 0.0, 2.0, 20.0, 10.0]),
        link: None,
        placement: Default::default(),
        pixels: None,
    };
    let photo = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im.clone())));
    let bend = |p: vectorcraft_geom::Point| vectorcraft_geom::Point::new(p.x, p.y + 12.0 * ((p.x - 20.0) / 128.0 * std::f64::consts::PI).sin());
    let warped = vectorcraft_doc::live::mesh_warp_image(&photo, &im, &bend, 10, false, false);
    let layer = doc.layers[0].id;
    doc.insert(Some(layer), usize::MAX, warped).unwrap();
    let text = String::from_utf8(write(&doc).bytes).unwrap();
    let images = rasters(&text);
    assert_eq!(images.len(), 200);
    let digits = |lines: &Vec<&str>| {
        lines.iter().filter_map(|l| l.strip_prefix('%')).filter(|l| l.bytes().all(|b| b.is_ascii_hexdigit())).map(str::len).sum::<usize>()
    };
    let whole = 64 * 64 * 3 * 2;
    assert_eq!(digits(&images[0]), whole, "the first piece holds the whole image");
    // Each piece holds its cell (two triangles share one) and 2 pixels more around it.
    let total: usize = images.iter().map(digits).sum();
    assert!(total < 10 * whole, "{total} digits of samples for an image of {whole}");
}

/// An image whose data is empty is left out with the note for empty or too large images, and an
/// image whose data can't be decoded is left out with the decode note.
#[test]
fn empty_images_get_the_size_note_and_undecodable_ones_the_decode_note() {
    let notes = |bytes: Vec<u8>| {
        let mut doc = Document::new(100.0, 100.0);
        doc.layers.clear();
        let layer = doc.add_layer(Some("Images"));
        let blob = ImageBlob::new("image/png", bytes);
        let key = blob.content_key();
        doc.images.insert(key.clone(), blob);
        let im = ImageObject { key, width: 4, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
        let node = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im)));
        doc.insert(Some(layer), usize::MAX, node).unwrap();
        let out = export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap();
        assert!(rasters(&String::from_utf8(out.bytes).unwrap()).is_empty());
        out.warnings
    };
    assert_eq!(notes(vec![]), [LARGE_IMAGE]);
    assert_eq!(notes(b"not an image".to_vec()), [UNDECODED]);
}

/// A gray image of `doc`, `w` × `h` pixels of `gray`, colorized `paint`, placed 10 pt a pixel
/// at (`x`, `y`).
fn colorized_image(doc: &mut Document, (w, h): (u32, u32), gray: Vec<u8>, paint: &Paint, (x, y): (f64, f64)) -> Node {
    let mut png = vec![];
    {
        let __dyn: image::DynamicImage = (image::GrayImage::from_raw(w, h, gray).unwrap()).into();
        let (__w, __h) = (__dyn.width(), __dyn.height());
        let (__layout, __sample, __raw) = match __dyn {
            image::DynamicImage::ImageLuma8(b) => (craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageLumaA8(b) => (craft_image_codecs::ChannelLayout::GrayA, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageRgb8(b) => (craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageRgba8(b) => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, b.into_raw()),
            image::DynamicImage::ImageLuma16(b) => (
                craft_image_codecs::ChannelLayout::Gray,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageLumaA16(b) => (
                craft_image_codecs::ChannelLayout::GrayA,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageRgb16(b) => (
                craft_image_codecs::ChannelLayout::Rgb,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            image::DynamicImage::ImageRgba16(b) => (
                craft_image_codecs::ChannelLayout::Rgba,
                craft_image_codecs::SampleType::U16,
                b.into_raw().into_iter().flat_map(|s| s.to_ne_bytes()).collect(),
            ),
            other => (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, other.into_rgba8().into_raw()),
        };
        let __cimg = craft_image_codecs::Image::from_raw(__w, __h, __layout, __sample, __raw).unwrap();
        craft_image_codecs::encode(&__cimg, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default())
            .map(|__b| png.extend_from_slice(&__b))
    }
    .unwrap();
    let blob = ImageBlob::new("image/png", png);
    let key = blob.content_key();
    doc.images.insert(key.clone(), blob);
    let xf = Affine::new([10.0, 0.0, 0.0, 10.0, x, y]);
    let im = ImageObject { key, width: w, height: h, xf, link: None, placement: Default::default(), pixels: None };
    let mut n = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im)));
    n.extras_mut().colorize = Some(Box::new(paint.clone()));
    n
}

/// A colorized image whose pixels are black or white is written as a 1-bit image mask
/// (ImageMask 1) after its color as the fill: its black pixels are 0 bits, which take the color, and its
/// white pixels 1 bits, which are clear. It prints in its color over the square behind it and
/// reads back colorized with that color and with the same clear pixels. A colorized image with
/// gray pixels is written with its color in its pixels, over white, with the note for
/// transparent pixels.
#[test]
fn colorized_images_keep_their_color() {
    let mut doc = Document::new(200.0, 100.0);
    doc.layers.clear();
    let layer = doc.add_layer(Some("Art"));
    let square = shape(&mut doc, shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 30.0)), red(), Paint::None);
    doc.insert(Some(layer), usize::MAX, square).unwrap();
    let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0));
    // 1 0 0 1 0 1 1 0 / 0 1 1 0 1 0 0 1 in black (1) and white (0).
    let mask: Vec<u8> = "1001011001101001".bytes().map(|b| if b == b'1' { 0 } else { 255 }).collect();
    let bitmap = colorized_image(&mut doc, (8, 2), mask.clone(), &paint, (10.0, 10.0));
    doc.insert(Some(layer), usize::MAX, bitmap).unwrap();
    let out = write(&doc);
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    let images = rasters(&text);
    assert_eq!(images.len(), 1, "{text}");
    let [_, _, xi, data @ .., _, _] = images[0].as_slice() else { panic!("{:?}", images[0]) };
    assert!(xi.ends_with(" ] 0 0 8 2 8 2 1 1 0 0 0 1 XI"), "{xi}");
    // Each row is a byte: the black pixels are 0 bits.
    assert_eq!(data, &["%6996"], "{text}");
    let at = text.find("%AI5_File:\n").unwrap();
    assert!(text[..at].ends_with("0 0.5 1 0 k\n"), "{text}");
    assert!(out.warnings.is_empty(), "{:?}", out.warnings);
    let read = crate::import(&out.bytes).unwrap().document;
    let mut found = vec![];
    read.walk(|n| {
        if let NodeKind::Image(im) = &n.kind {
            found.push((read.image_blob(im).and_then(ImageBlob::coverage), n.extras().colorize.as_deref().cloned()));
        }
    });
    let want: Vec<u8> = mask.iter().map(|&v| 255 - v).collect();
    assert_eq!(found, [(Some((8, 2, want)), Some(paint.clone()))]);

    // Gray pixels: the color at each pixel's strength, over white.
    let mut doc = Document::new(200.0, 100.0);
    doc.layers.clear();
    let layer = doc.add_layer(Some("Art"));
    let tint = colorized_image(&mut doc, (2, 1), vec![0, 128], &Paint::solid(Color::rgb(1.0, 0.0, 0.0)), (10.0, 10.0));
    doc.insert(Some(layer), usize::MAX, tint).unwrap();
    let out = write(&doc);
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    let images = rasters(&text);
    let [_, _, xi, data @ .., _, _] = images[0].as_slice() else { panic!("{:?}", images[0]) };
    assert!(xi.ends_with(" ] 0 0 2 1 2 1 8 3 0 0 0 0 XI"), "{xi}");
    assert_eq!(data, &["%FF0000FF8080"], "{text}");
    assert_eq!(out.warnings, [IMAGE_ALPHA]);
}

/// The pieces of a colorized warped image work out the image's coverage once, and an image with
/// other data works out its own: a black and white image's pieces are written as image masks
/// in its color, and a gray image's pieces with its color in their pixels.
#[test]
fn the_pieces_of_a_colorized_warped_image_work_out_its_coverage_once() {
    // GUARDS: each piece of a colorized warped image decoded the image again for its coverage.
    let mut doc = Document::new(400.0, 200.0);
    doc.layers.clear();
    let layer = doc.add_layer(Some("Art"));
    let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0));
    let checks: Vec<u8> = (0..16 * 16).map(|i| if (i % 16 + i / 16) % 2 == 0 { 0 } else { 255 }).collect();
    let ramp: Vec<u8> = (0..16 * 16).map(|i| (i % 16 * 16) as u8).collect();
    for (gray, x) in [(checks, 10.0), (ramp, 210.0)] {
        let photo = colorized_image(&mut doc, (16, 16), gray, &paint, (x, 10.0));
        let NodeKind::Image(im) = &photo.kind else { panic!("{:?}", photo.kind) };
        let bend = move |p: vectorcraft_geom::Point| vectorcraft_geom::Point::new(p.x, p.y + 8.0 * ((p.x - x) / 160.0 * std::f64::consts::PI).sin());
        let warped = vectorcraft_doc::live::mesh_warp_image(&photo, im, &bend, 4, false, false);
        doc.insert(Some(layer), usize::MAX, warped).unwrap();
    }
    super::writer::COVERAGE_RUNS.with(|n| n.set(0));
    let out = write(&doc);
    assert_eq!(super::writer::COVERAGE_RUNS.with(std::cell::Cell::get), 2, "once for each image");
    let text = String::from_utf8(out.bytes).unwrap();
    let images = rasters(&text);
    assert_eq!(images.len(), 64, "32 pieces of each image");
    let xi = |piece: &Vec<&str>| piece.iter().find(|l| l.ends_with(" XI")).map(|l| l.to_string()).unwrap_or_default();
    assert!(images[..32].iter().all(|p| xi(p).ends_with(" 1 1 0 0 0 1 XI")), "{:?}", images[..32].iter().map(xi).collect::<Vec<_>>());
    assert!(images[32..].iter().all(|p| xi(p).ends_with(" 8 3 0 0 0 0 XI")), "{:?}", images[32..].iter().map(xi).collect::<Vec<_>>());
    // The first piece holds the whole image: each row of 16 pixels in two bytes, its black pixels 0 bits.
    assert!(xi(&images[0]).ends_with(" ] 0 0 16 16 16 16 1 1 0 0 0 1 XI"), "{}", xi(&images[0]));
    let data: Vec<&str> = images[0].iter().filter_map(|l| l.strip_prefix('%')).filter(|l| l.bytes().all(|b| b.is_ascii_hexdigit())).collect();
    assert_eq!(data.concat(), "5555AAAA".repeat(8));
    assert_eq!(out.warnings, [IMAGE_ALPHA]);
}

/// An image mask is only for a colorized image the writer draws as the document does: not one
/// with an opacity mask turned on, and not one with more pixels than the writer writes.
#[test]
fn image_masks_are_for_images_the_writer_draws_as_they_are() {
    let mut doc = Document::new(200.0, 100.0);
    let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0));
    let mut n = colorized_image(&mut doc, (2, 1), vec![0, 255], &paint, (10.0, 10.0));
    assert!(writes_image_mask(&doc, &n));
    let art = shape(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Paint::solid(Color::gray(1.0)), Paint::None);
    n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, false)));
    assert!(!writes_image_mask(&doc, &n));
    if let Some(m) = n.extras_mut().mask.as_mut() {
        m.disabled = true;
    }
    assert!(writes_image_mask(&doc, &n));
    let big = colorized_image(&mut doc, (8193, 8193), vec![255; 8193 * 8193], &paint, (10.0, 10.0));
    assert!(!writes_image_mask(&doc, &big));
}

#[test]
fn a_gradient_fill_and_its_stroke_are_one_object() {
    let mut doc = Document::new(100.0, 100.0);
    let g = Gradient::new(
        GradientKind::Radial,
        vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 1.0))],
    );
    let mut paint = GradientPaint::new(g);
    paint.geom = Some(vectorcraft_color::GradientGeom {
        start: vectorcraft_geom::Point::new(30.0, 30.0),
        end: vectorcraft_geom::Point::new(50.0, 30.0),
        aspect: 1.0,
        focal: Some(vectorcraft_geom::Point::new(35.0, 30.0)),
    });
    let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), Paint::Gradient(Box::new(paint)), red());
    let layer = doc.layers[0].id;
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let text = String::from_utf8(write(&doc).bytes).unwrap();
    // `2 BB` strokes the filled path (§3.5.3); the highlight is a quarter of the radius out (§3.5.5).
    assert!(text.contains("Bb\n5 0 0 0.25 Bh\n1 (Gradient) 30 70 0 20 1 0 0 1 0 0 Bg\nf\n2 BB\n"), "{text}");
    let doc = crate::import(text.as_bytes()).unwrap().document;
    let n = &children(&doc.layers[0])[0];
    let Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("{:?}", n.appearance) };
    assert_eq!(g.gradient.kind, GradientKind::Radial);
    assert_eq!(n.appearance.stroke_paint().color(), Some(Color::rgb(1.0, 0.0, 0.0)));
}

/// An RGB gradient stop's CMYK equivalent is the one of its RGB values as written (to four
/// decimals), so the reopened file writes the same stops.
#[test]
fn rgb_stops_are_written_again_unchanged() {
    let mut doc = Document::new(100.0, 100.0);
    let rgb = |i: u16| {
        let v = |s: f32| (f32::from(i) * s + 0.123_456_7).fract();
        Color::rgb(v(0.137_911_3), v(0.271_828_2), v(0.314_159_3))
    };
    let stops = (0..12u16).map(|i| GradientStop::new(f32::from(i) / 11.0, rgb(i))).collect();
    let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
    let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), paint, Paint::None);
    let layer = doc.layers[0].id;
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let stops = |bytes: Vec<u8>| String::from_utf8(bytes).unwrap().lines().filter(|l| l.ends_with("%_Bs")).map(String::from).collect::<Vec<_>>();
    let first = write(&doc).bytes;
    let again = write(&crate::import(&first).unwrap().document).bytes;
    let (first, again) = (stops(first), stops(again));
    assert_eq!(first.len(), 12, "{first:?}");
    assert_eq!(again, first);
}

/// With a working RGB space other than sRGB, a Lab fill and a freeform gradient's average color
/// are written as RGB values in the working RGB space, so they read back as RGB colors that show as
/// the colors they were written for.
#[test]
fn a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space() {
    const CHILD: &str = "VECTORCRAFT_TEST_LEGACY_AI_WIDE_GAMUT_LAB";
    if std::env::var_os(CHILD).is_none() {
        // Color settings are process-wide: exercise this profile in a separate test process.
        let output = std::process::Command::new(std::env::current_exe().unwrap())
            .args(["--exact", "legacy_ai::tests::a_lab_fill_reads_back_as_the_same_color_in_a_wide_gamut_working_space", "--nocapture"])
            .env(CHILD, "1")
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
            "isolated color profile test failed:\n{stdout}\n{}",
            String::from_utf8_lossy(&output.stderr),
        );
        return;
    }
    use vectorcraft_color::cms;
    cms::set_active(&cms::ColorSettings { rgb: cms::WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap();
    assert!(!cms::active().rgb_is_srgb());
    let lab = Color::lab(60.0, 20.0, -30.0);
    let mut doc = Document::new(100.0, 100.0);
    let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), Paint::solid(lab), Paint::None);
    let layer = doc.layers[0].id;
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    // A freeform gradient is written as the average of its stops' display colors.
    let (a, b) = (Color::rgb(0.9, 0.2, 0.1), Color::lab(50.0, -40.0, -20.0));
    let stops = vec![GradientStop::new(0.0, a), GradientStop::new(1.0, b)];
    let free = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Freeform, stops))));
    let n = shape(&mut doc, shapes::rectangle(Rect::new(60.0, 10.0, 90.0, 50.0)), free, Paint::None);
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let average = {
        let (a, b) = (a.to_rgb(), b.to_rgb());
        [0, 1, 2].map(|i| (a[i] + b[i]) / 2.0)
    };
    // Written without [`write`]'s printed comparison, which paints a gradient in its first stop's
    // color and not in the average color the writer writes for a freeform gradient.
    let back = crate::import(&export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap().bytes).unwrap().document;
    let mut read = vec![];
    back.walk(|n| {
        if let NodeKind::Path { .. } = n.kind {
            read.push(n.appearance.fill_paint());
        }
    });
    let [Paint::Solid { color: got @ Color::Rgb { .. }, .. }, Paint::Solid { color: avg @ Color::Rgb { .. }, .. }] = read.as_slice() else {
        panic!("two RGB fills: {read:?}")
    };
    for (got, w, what) in [(got, lab.to_rgb(), "Lab fill"), (avg, average, "freeform gradient's average")] {
        let g = got.to_rgb();
        assert!(g.iter().zip(w).all(|(a, b)| (a - b).abs() < 2e-3), "{what} {got:?} shows as {g:?}, not {w:?}");
    }
}

/// A gradient from white to #1b2a6b, the colors of #2687's circle, placed at `geom` (None: fitted
/// to the object).
fn white_to_navy(kind: GradientKind, geom: Option<vectorcraft_color::GradientGeom>) -> Paint {
    let navy = Color::rgb(27.0 / 255.0, 42.0 / 255.0, 107.0 / 255.0);
    let g = Gradient::new(kind, vec![GradientStop::new(0.0, Color::rgb(1.0, 1.0, 1.0)), GradientStop::new(1.0, navy)]);
    Paint::Gradient(Box::new(GradientPaint { geom, ..GradientPaint::new(g) }))
}

/// A 400 × 400 document: #2687's radial circle (center 100, 100, radius 80) and linear square;
/// below them a radial square in a group, a radial compound ring, a clipping group whose clipping
/// path and member are radial, a square stroked radial, and a radial square whose elliptical
/// gradient has its focal point 30 pt above the center, past its 20 pt radius.
fn radials() -> Document {
    let mut doc = Document::new(400.0, 400.0);
    let layer = doc.layers[0].id;
    let radial = || white_to_navy(GradientKind::Radial, None);
    let circle = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 20.0, 180.0, 180.0)), radial(), Paint::None);
    let square = shape(&mut doc, shapes::rectangle(Rect::new(220.0, 20.0, 380.0, 180.0)), white_to_navy(GradientKind::Linear, None), Paint::None);
    let member = shape(&mut doc, shapes::rectangle(Rect::new(20.0, 220.0, 60.0, 260.0)), radial(), Paint::None);
    let group = Node::group(doc.alloc_id(), vec![Arc::new(member)]);
    let outer = shape(&mut doc, shapes::rectangle(Rect::new(80.0, 220.0, 120.0, 260.0)), Paint::None, Paint::None);
    let inner = shape(&mut doc, shapes::rectangle(Rect::new(90.0, 230.0, 110.0, 250.0)), Paint::None, Paint::None);
    let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd });
    ring.appearance = Appearance::basic(radial(), Paint::None, 0.0).into();
    let mut clip = Node::new(
        doc.alloc_id(),
        NodeKind::Path {
            path: shapes::rectangle(Rect::new(140.0, 220.0, 180.0, 260.0)),
            rule: FillRule::NonZero,
            live: None,
            clipping: true,
            guide: false,
        },
    );
    clip.appearance = Appearance::basic(radial(), Paint::None, 0.0).into();
    let clipped = shape(&mut doc, shapes::rectangle(Rect::new(130.0, 210.0, 190.0, 270.0)), radial(), Paint::None);
    let window = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(clipped)], clip: true });
    let stroked = shape(&mut doc, shapes::rectangle(Rect::new(200.0, 220.0, 240.0, 260.0)), Paint::None, radial());
    let geom = vectorcraft_color::GradientGeom {
        start: vectorcraft_geom::Point::new(300.0, 240.0),
        end: vectorcraft_geom::Point::new(320.0, 240.0),
        aspect: 2.0,
        focal: Some(vectorcraft_geom::Point::new(300.0, 210.0)),
    };
    let off_center =
        shape(&mut doc, shapes::rectangle(Rect::new(260.0, 220.0, 340.0, 260.0)), white_to_navy(GradientKind::Radial, Some(geom)), Paint::None);
    for n in [circle, square, group, ring, window, stroked, off_center] {
        doc.insert(Some(layer), usize::MAX, n).unwrap();
    }
    doc
}

/// Every radial gradient instance has its highlight `Bh` (§3.5.5): `0 0 0 0 Bh` when it is at the
/// center (§3.5.6), on fills, strokes, in groups, compound paths and clipping groups, and an
/// off-center one within the gradient's circle. Linear instances have none. VectorCraft reads
/// back one linear and at least seven radial gradients, each with its stops, and the circle, the
/// square and the off-center square in their place.
#[test]
fn radial_gradients_have_their_highlight() {
    let out = write(&radials());
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    // One definition for the radial gradient, one for the linear one (§3.5.2).
    assert!(text.contains("2 Bn\n%AI5_BeginGradient: (Gradient)\n(Gradient) 1 2 Bd\n[\n"), "{text}");
    assert!(text.contains("%AI5_BeginGradient: (Gradient 2)\n(Gradient 2) 0 2 Bd\n[\n"), "{text}");
    // Each instance, `Bb` to `BB`.
    let instances: Vec<&str> = text.split("Bb\n").skip(1).filter_map(|t| t.split_inclusive("BB\n").next()).collect();
    let radial: Vec<&str> = instances.iter().copied().filter(|i| i.contains(" (Gradient) ")).collect();
    let linear: Vec<&str> = instances.iter().copied().filter(|i| i.contains(" (Gradient 2) ")).collect();
    assert_eq!((radial.len() + linear.len(), linear.len()), (instances.len(), 1), "{instances:#?}");
    assert!(radial.len() >= 8, "{radial:#?}");
    for i in &radial {
        let bh = i.lines().next().unwrap_or_default();
        assert!(bh.ends_with(" Bh") && bh.split_whitespace().count() == 5, "{i}");
    }
    assert!(!linear[0].contains("Bh"), "{}", linear[0]);
    for needle in [
        // #2687's circle and square.
        "\nBb\n0 0 0 0 Bh\n1 (Gradient) 100 300 0 80 1 0 0 1 0 0 Bg\nf\n0 BB\n",
        "\nBb\n1 (Gradient 2) 220 300 0 160 1 0 0 1 0 0 Bg\nf\n0 BB\n",
        // In a group.
        "\nBb\n0 0 0 0 Bh\n1 (Gradient) 40 160 0 20 1 0 0 1 0 0 Bg\nf\n0 BB\nU\n",
        // Both subpaths of the compound ring (§5.3.5).
        "\nBb\n0 0 0 0 Bh\n1 (Gradient) 100 160 0 20 1 0 0 1 0 0 Bg\nf\n0 BB\n90 170 m\n",
        "\nBb\n0 0 0 0 Bh\n1 (Gradient) 100 160 0 20 1 0 0 1 0 0 Bg\nf\n0 BB\n*U\n",
        // The clipping path's fill and the clipped square (§5.6.2).
        "\nBb\n0 0 0 0 Bh\n1 (Gradient) 160 160 0 20 1 0 0 1 0 0 Bg\nf\n0 BB\n",
        "\nBb\n0 0 0 0 Bh\n1 (Gradient) 160 160 0 30 1 0 0 1 0 0 Bg\nf\n0 BB\nQ\n",
        // The stroke, written as its outline filled.
        "\nBb\n0 0 0 0 Bh\n1 (Gradient) 220 160 0 21 1 0 0 1 0 0 Bg\nf\n0 BB\n",
        // The focal point 30 pt up, 1.5 radii out: written on the circle, straight up.
        "\nBb\n0 20 90 1 Bh\n1 (Gradient) 300 160 0 20 1 0 0 1 0 0 Bg\nf\n0 BB\n",
    ] {
        assert!(text.contains(needle), "missing {needle:?} in\n{text}");
    }
    for expected in [STROKES, ELLIPTICAL] {
        assert!(out.warnings.iter().any(|w| w == expected), "{expected} not in {:?}", out.warnings);
    }
    // Read back: every gradient keeps its stops, the document holds the linear square and at
    // least seven radial gradients, and the circle, the square and the off-center square keep
    // their place.
    let doc = crate::import(&out.bytes).unwrap().document;
    let mut found = vec![];
    doc.walk(|n| {
        for i in &n.appearance.items {
            if let AppearanceItem::Fill(f) = i
                && let Paint::Gradient(g) = &f.paint
            {
                found.push((**g).clone());
            }
        }
    });
    let kinds = |k: GradientKind| found.iter().filter(|g| g.gradient.kind == k).count();
    // Seven radial objects (a compound path's members carry its fill too) and the linear square.
    assert!(kinds(GradientKind::Radial) >= 7 && kinds(GradientKind::Linear) == 1, "{found:#?}");
    let near = |a: vectorcraft_geom::Point, x: f64, y: f64| (a.x - x).abs() < 1e-3 && (a.y - y).abs() < 1e-3;
    for g in &found {
        let [white, navy] = g.gradient.stops.as_slice() else { panic!("{g:?}") };
        assert_eq!((white.offset, navy.offset, white.color), (0.0, 1.0, Color::rgb(1.0, 1.0, 1.0)), "{g:?}");
        let rgb = navy.color.to_rgb();
        assert!([27.0, 42.0, 107.0].iter().zip(rgb).all(|(want, got)| (want / 255.0 - got).abs() < 1e-3), "{rgb:?}");
    }
    let placed = |x: f64, y: f64| found.iter().filter_map(|g| g.geom.map(|m| (g.gradient.kind, m))).find(|(_, m)| near(m.start, x, y));
    let Some((GradientKind::Radial, circle)) = placed(100.0, 100.0) else { panic!("{found:#?}") };
    assert!(near(circle.end, 180.0, 100.0) && circle.focal.is_none(), "{circle:?}");
    let Some((GradientKind::Linear, square)) = placed(220.0, 100.0) else { panic!("{found:#?}") };
    assert!(near(square.end, 380.0, 100.0), "{square:?}");
    let Some((GradientKind::Radial, off)) = placed(300.0, 240.0) else { panic!("{found:#?}") };
    assert!(near(off.end, 320.0, 240.0) && off.focal.is_some_and(|f| near(f, 300.0, 220.0)), "{off:?}");
}

/// A radial gradient's stops are listed from the first to the last, as §3.5.2's radial definition
/// lists them (10, then 100), and a linear gradient's stops are listed from the last to the first
/// (§1.4.3). Each stop keeps its color and its midpoint to the next stop. The reference app read a
/// radial gradient's stops listed from the last as one color (two stops) or inverted (three
/// stops), reported on #2807. Both gradients read back with their stops.
#[test]
fn radial_gradient_stops_are_listed_from_the_first() {
    let white = Color::rgb(1.0, 1.0, 1.0);
    let red = Color::rgb(1.0, 0.0, 0.0);
    let navy = Color::rgb(27.0 / 255.0, 42.0 / 255.0, 107.0 / 255.0);
    let stop = |offset: f32, color: Color, midpoint: f32| GradientStop { midpoint, ..GradientStop::new(offset, color) };
    let stops = vec![stop(0.0, white, 0.3), stop(0.3, red, 0.7), stop(1.0, navy, 0.5)];
    let mut doc = Document::new(200.0, 100.0);
    let layer = doc.layers[0].id;
    for (kind, x) in [(GradientKind::Radial, 10.0), (GradientKind::Linear, 110.0)] {
        let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(kind, stops.clone()))));
        let n = shape(&mut doc, shapes::rectangle(Rect::new(x, 10.0, x + 80.0, 90.0)), paint, Paint::None);
        doc.insert(Some(layer), usize::MAX, n).unwrap();
    }
    let out = write(&doc);
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    // Each `%_Bs` line of a definition: its RGB color (`c m y k r g b 2`), midpoint and ramp point.
    let listed = |head: &str| -> Vec<([f64; 3], f64, f64)> {
        let def = text.split(head).nth(1).and_then(|t| t.split("BD\n").next()).unwrap_or_else(|| panic!("no {head:?} in\n{text}"));
        def.lines()
            .map(|l| {
                let n: Vec<f64> = l.trim_end_matches(" %_Bs").split_whitespace().map(|v| v.parse().unwrap()).collect();
                let [_, _, _, _, r, g, b, style, mid, ramp] = n.as_slice() else { panic!("{l}") };
                assert_eq!(*style, 2.0, "{l}");
                ([*r, *g, *b], *mid, *ramp)
            })
            .collect()
    };
    let rgb = |c: Color| c.to_rgb().map(f64::from);
    let first_first = [(rgb(white), 30.0, 0.0), (rgb(red), 70.0, 30.0), (rgb(navy), 50.0, 100.0)];
    let mut last_first = first_first;
    last_first.reverse();
    let same = |got: &[([f64; 3], f64, f64)], want: &[([f64; 3], f64, f64)]| {
        got.len() == want.len()
            && got.iter().zip(want).all(|((c, m, r), (wc, wm, wr))| {
                c.iter().zip(wc).all(|(a, b)| (a - b).abs() < 1e-3) && (m - wm).abs() < 1e-3 && (r - wr).abs() < 1e-3
            })
    };
    let radial = listed("(Gradient) 1 3 Bd\n[\n");
    assert!(same(&radial, &first_first), "{radial:?}\n{text}");
    let linear = listed("(Gradient 2) 0 3 Bd\n[\n");
    assert!(same(&linear, &last_first), "{linear:?}\n{text}");
    // Read back: both gradients, each stop at its offset with its color and midpoint.
    let doc = crate::import(&out.bytes).unwrap().document;
    let read: Vec<_> = children(&doc.layers[0])
        .iter()
        .filter_map(|n| if let Paint::Gradient(g) = n.appearance.fill_paint() { Some(g.gradient.clone()) } else { None })
        .collect();
    assert_eq!(read.iter().map(|g| g.kind).collect::<Vec<_>>(), [GradientKind::Radial, GradientKind::Linear], "{read:#?}");
    for g in &read {
        let got: Vec<_> = g.stops.iter().map(|s| (rgb(s.color), f64::from(s.midpoint) * 100.0, f64::from(s.offset) * 100.0)).collect();
        assert!(same(&got, &first_first), "{g:#?}");
    }
}

#[test]
fn reads_back_with_layers_groups_and_paths() {
    let out = write(&sample());
    let imported = crate::import(&out.bytes).unwrap();
    let doc = imported.document.clone();
    let names: Vec<_> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
    assert_eq!(names, ["Back", "Front"], "{:?}", imported.warnings);
    assert!(doc.layers[0].visible);
    assert!(!doc.layers[1].visible);
    let back = children(&doc.layers[0]);
    assert_eq!(back.len(), 4, "{back:#?}");
    // The group of two squares, the second locked.
    let NodeKind::Group { children: pair, clip: false } = &back[0].kind else { panic!("{:?}", back[0].kind) };
    assert_eq!(pair.len(), 2);
    assert!(!pair[0].locked && pair[1].locked);
    let a = &pair[0];
    assert_eq!(a.appearance.fill_paint().color(), Some(Color::rgb(1.0, 0.0, 0.0)));
    assert_eq!(a.appearance.stroke_paint().color(), Some(Color::rgb(0.0, 0.0, 1.0)));
    // Four corners: the start point written again to close it isn't a fifth.
    let sq = a.path_data().unwrap();
    assert!(sq.subpaths[0].closed && sq.subpaths[0].anchors.len() == 4, "{sq:?}");
    assert!(sq.subpaths[0].anchors.iter().all(|p| p.kind == AnchorKind::Corner), "{sq:?}");
    let bounds = a.visual_bounds().unwrap();
    assert!((bounds.x0 - 9.0).abs() < 0.01 && (bounds.y0 - 9.0).abs() < 0.01, "{bounds:?}");
    // The ring: a compound path, even-odd.
    assert!(matches!(&back[1].kind, NodeKind::Compound { children, rule: FillRule::EvenOdd } if children.len() == 2), "{:?}", back[1].kind);
    // The clipping group: its clipping path first.
    let NodeKind::Group { children: window, clip: true } = &back[2].kind else { panic!("{:?}", back[2].kind) };
    assert!(matches!(window[0].kind, NodeKind::Path { clipping: true, .. }));
    // The gradient square.
    let Paint::Gradient(g) = back[3].appearance.fill_paint() else { panic!("{:?}", back[3].appearance) };
    assert_eq!(g.gradient.kind, GradientKind::Linear);
    assert_eq!(g.gradient.stops.len(), 2);
    assert_eq!(g.gradient.stops[0].color, Color::rgb(1.0, 1.0, 1.0));
    // The hidden layer: the ellipse with smooth points, and the image.
    let front = children(&doc.layers[1]);
    assert_eq!(front.len(), 2, "{:?} {:?}", front.iter().map(|n| &n.kind).collect::<Vec<_>>(), imported.warnings);
    let path = front[0].path_data().unwrap();
    assert_eq!(path.subpaths.len(), 1);
    assert!(path.subpaths[0].closed);
    assert!(path.subpaths[0].anchors.iter().all(|a| a.kind == AnchorKind::Smooth), "{path:?}");
    assert_eq!(path.subpaths[0].anchors.len(), 4, "{path:?}");
    let NodeKind::Image(im) = &front[1].kind else { panic!("{:?}", front[1].kind) };
    assert_eq!((im.width, im.height), (2, 1));
    let b = front[1].visual_bounds().unwrap();
    assert!((b.x0 - 170.0).abs() < 0.01 && (b.y0 - 70.0).abs() < 0.01 && (b.x1 - 190.0).abs() < 0.01, "{b:?}");
}

#[test]
fn spot_colours_are_custom_colours() {
    let mut doc = Document::new(100.0, 100.0);
    doc.swatches.push(vectorcraft_color::Swatch {
        name: "Spot Test".into(),
        paint: Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0)),
        global: true,
        spot: true,
    });
    let fill = Paint::Solid { color: Color::cmyk(0.0, 0.25, 0.5, 0.0), swatch: Some("Spot Test".into()), tint: 0.5 };
    let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), fill, Paint::None);
    let layer = doc.layers[0].id;
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let out = write(&doc);
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    assert!(text.contains("%%DocumentCustomColors: (Spot Test)"), "{text}");
    assert!(text.contains("0 0.5 1 0 (Spot Test) 0.5 x"), "{text}");
    let doc = crate::import(&out.bytes).unwrap().document;
    let n = &children(&doc.layers[0])[0];
    let Paint::Solid { swatch, tint, .. } = n.appearance.fill_paint() else { panic!() };
    assert_eq!(swatch.as_deref(), Some("Spot Test"));
    assert!((tint - 0.5).abs() < 1e-6);
}

/// A document with a spot color swatch for each of `spots`, a square filled with each at half
/// tint, and a square whose linear gradient fill (the first spot color to white) names the
/// gradient swatch `gradient` (the document holds no such swatch; the writer reads only the
/// fill's name).
fn spots_and_gradient(spots: &[&str], gradient: &str) -> Document {
    let mut doc = Document::new(200.0, 100.0);
    let layer = doc.layers[0].id;
    for (i, name) in spots.iter().enumerate() {
        let c = i as f32 * 0.5;
        doc.swatches.push(vectorcraft_color::Swatch {
            name: (*name).into(),
            paint: Paint::solid(Color::cmyk(c, 0.5, 1.0, 0.0)),
            global: true,
            spot: true,
        });
        let fill = Paint::Solid { color: Color::cmyk(c / 2.0, 0.25, 0.5, 0.0), swatch: Some((*name).into()), tint: 0.5 };
        let x = 10.0 + 40.0 * i as f64;
        let n = shape(&mut doc, shapes::rectangle(Rect::new(x, 10.0, x + 30.0, 40.0)), fill, Paint::None);
        doc.insert(Some(layer), usize::MAX, n).unwrap();
    }
    let mut first = GradientStop::new(0.0, Color::cmyk(0.0, 0.5, 1.0, 0.0));
    first.swatch = Some(spots[0].into());
    let g = Gradient::new(GradientKind::Linear, vec![first, GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))]);
    let mut paint = GradientPaint::new(g);
    paint.swatch = Some(gradient.into());
    let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 50.0, 50.0, 90.0)), Paint::Gradient(Box::new(paint)), Paint::None);
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    doc
}

/// `doc` written with the title `title`, and run as a PostScript program ([`prints_as`]).
fn write_titled(doc: &Document, title: &str) -> LegacyAiOutput {
    let o = LegacyAiOptions { title: title.into(), created: Some(0), ..LegacyAiOptions::default() };
    let out = export_legacy_ai(doc, &o).unwrap();
    prints_as(&out.bytes, doc, &o);
    out
}

/// The spot colors and gradients of the objects of `doc`'s first layer, in paint order: each
/// solid fill's swatch, and each gradient fill's swatch with its first stop's.
fn inks(doc: &Document) -> Vec<Option<String>> {
    let mut out = vec![];
    for n in children(&doc.layers[0]) {
        match n.appearance.fill_paint() {
            Paint::Solid { swatch, .. } => out.push(swatch.clone()),
            Paint::Gradient(g) => {
                out.push(g.swatch.clone());
                out.push(g.gradient.stops.first().and_then(|s| s.swatch.clone()));
            }
            _ => {}
        }
    }
    out
}

/// The title, spot color names and gradient names are written in Windows-1252, as layer names
/// are: é is 351 (octal) in the header's custom colors, each `x`, the gradient's definition, its
/// stops and `Bg`. The spot color and gradient names read back as they were.
#[test]
fn spot_gradient_and_title_names_are_written_in_windows_1252() {
    let doc = spots_and_gradient(&["Caf\u{e9}"], "D\u{e9}grad\u{e9}");
    let out = write_titled(&doc, "R\u{e9}sum\u{e9}");
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    for needle in [
        "%%Title: (R\\351sum\\351)\n",
        "%%DocumentCustomColors: (Caf\\351)\n",
        "%%CMYKCustomColor: 0 0.5 1 0 (Caf\\351)\n",
        "0 0.5 1 0 (Caf\\351) 0.5 x\n",
        "%AI5_BeginGradient: (D\\351grad\\351)\n(D\\351grad\\351) 0 2 Bd\n",
        "0 0.5 1 0 (Caf\\351) 0 3 50 0 %_Bs\n",
        "1 (D\\351grad\\351) ",
    ] {
        assert!(text.contains(needle), "missing {needle:?} in\n{text}");
    }
    assert!(!text.contains("\\303"), "{text}");
    assert!(!out.warnings.iter().any(|w| w == TITLE_AND_COLOR_NAMES), "{:?}", out.warnings);
    let read = crate::import(&out.bytes).unwrap().document;
    let names = inks(&read);
    let want = ["Caf\u{e9}", "D\u{e9}grad\u{e9}", "Caf\u{e9}"].map(|n| Some(n.to_string()));
    assert_eq!(names, want);
}

/// A character Windows-1252 can't hold is written as `?`, with one warning for all of these
/// names. Names that become the same are numbered, so the header, each `x` and each `Bg` still
/// tell the colors and gradients apart.
#[test]
fn names_outside_windows_1252_are_replaced_and_kept_apart() {
    // 赤 and 青 (spot colors), 渐变 and グラ (gradients), 日本 (the title).
    let mut doc = spots_and_gradient(&["\u{8d64}", "\u{9752}"], "\u{6e10}\u{53d8}");
    let g = Gradient::new(
        GradientKind::Linear,
        vec![GradientStop::new(0.0, Color::cmyk(1.0, 0.0, 0.0, 0.0)), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))],
    );
    let mut paint = GradientPaint::new(g);
    paint.swatch = Some("\u{30b0}\u{30e9}".into());
    let n = shape(&mut doc, shapes::rectangle(Rect::new(60.0, 50.0, 100.0, 90.0)), Paint::Gradient(Box::new(paint)), Paint::None);
    let layer = doc.layers[0].id;
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let out = write_titled(&doc, "\u{65e5}\u{672c}");
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    for needle in [
        "%%Title: (??)\n",
        "%%DocumentCustomColors: (?)\n%%+ (? 2)\n",
        "%%CMYKCustomColor: 0 0.5 1 0 (?)\n%%+ 0.5 0.5 1 0 (? 2)\n",
        "0 0.5 1 0 (?) 0.5 x\n",
        "0.5 0.5 1 0 (? 2) 0.5 x\n",
        "(??) 0 2 Bd\n",
        "(?? 2) 0 2 Bd\n",
        "0 0.5 1 0 (?) 0 3 50 0 %_Bs\n",
        "1 (??) ",
        "1 (?? 2) ",
    ] {
        assert!(text.contains(needle), "missing {needle:?} in\n{text}");
    }
    assert_eq!(out.warnings.iter().filter(|w| *w == TITLE_AND_COLOR_NAMES).count(), 1, "{:?}", out.warnings);
    assert!(!out.warnings.iter().any(|w| w == LAYER_NAME), "{:?}", out.warnings);
    let read = crate::import(&out.bytes).unwrap().document;
    let want = [Some("?"), Some("? 2"), Some("??"), Some("?"), Some("?? 2"), None].map(|n| n.map(String::from));
    assert_eq!(inks(&read), want);
}

/// `doc` written with [`Numbered::take`](super::writer::Numbered::take) numbering names by its
/// counters (`scanned` false) or by searching the names given for each number it tries.
fn export_numbering(doc: &Document, scanned: bool) -> LegacyAiOutput {
    let o = LegacyAiOptions { created: Some(0), ..LegacyAiOptions::default() };
    super::writer::SCANNED_NAMES.with(|s| s.set(scanned));
    let out = export_legacy_ai(doc, &o);
    super::writer::SCANNED_NAMES.with(|s| s.set(false));
    out.unwrap()
}

/// A linear gradient from `color` to white, named `swatch`.
fn gradient_from(color: Color, swatch: Option<&str>) -> Paint {
    let g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, color), GradientStop::new(1.0, Color::cmyk(0.0, 0.0, 0.0, 0.0))]);
    let mut paint = GradientPaint::new(g);
    paint.swatch = swatch.map(String::from);
    Paint::Gradient(Box::new(paint))
}

/// A name the counters give is the first free `name 2`, `name 3`… for every order of names, those
/// already numbered (`Sky 2`, `Gradient 2 2`) and the empty name included.
#[test]
fn numbered_names_are_the_first_free_number() {
    let bases = ["Gradient", "Gradient 2", "Gradient 3", "Gradient 2 2", "Sky", "Sky 2", "Sky 4", "?", "? 2", ""];
    let mut seed = 7u32;
    let order: Vec<&str> = (0..3000)
        .map(|_| {
            seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
            bases[(seed >> 16) as usize % bases.len()]
        })
        .collect();
    let names = |scanned: bool| {
        super::writer::SCANNED_NAMES.with(|s| s.set(scanned));
        let mut numbered = super::writer::Numbered::default();
        let names: Vec<String> = order.iter().map(|b| numbered.take((*b).to_string())).collect();
        super::writer::SCANNED_NAMES.with(|s| s.set(false));
        names
    };
    let (counted, scanned) = (names(false), names(true));
    for (i, (c, s)) in counted.iter().zip(&scanned).enumerate() {
        assert_eq!(c, s, "name {i}, {:?}", order[i]);
    }
    let given: std::collections::HashSet<&String> = counted.iter().collect();
    assert_eq!(given.len(), counted.len(), "every name is given once");
}

/// Gradient definitions and spot colors whose names collide are numbered as the file has always
/// numbered them: a gradient's swatch name or `Gradient`, then the first free number, with equal
/// gradients sharing a definition. The whole file is the same either way.
#[test]
fn colliding_gradient_and_spot_names_are_numbered_as_before() {
    let mut doc = spots_and_gradient(&["\u{8d64}", "?", "\u{9752}", "? 2"], "Gradient 3");
    let layer = doc.layers[0].id;
    let swatches = [None, None, Some("Gradient"), None, Some("\u{6e10}"), Some("?"), None, Some("Gradient 2"), Some("")];
    for (i, swatch) in swatches.into_iter().enumerate() {
        let c = i as f32 / 10.0;
        for repeat in 0..2 {
            let x = 10.0 + 15.0 * i as f64;
            let r = Rect::new(x, 60.0 + 15.0 * f64::from(repeat), x + 10.0, 70.0 + 15.0 * f64::from(repeat));
            let n = shape(&mut doc, shapes::rectangle(r), gradient_from(Color::cmyk(c, 1.0 - c, 0.5, 0.0), swatch), Paint::None);
            doc.insert(Some(layer), usize::MAX, n).unwrap();
        }
    }
    let out = export_numbering(&doc, false);
    let before = export_numbering(&doc, true);
    let text = String::from_utf8(out.bytes).unwrap();
    assert_eq!(text, String::from_utf8(before.bytes).unwrap());
    assert_eq!(out.warnings, before.warnings);
    let defined: Vec<&str> = text.lines().filter_map(|l| l.strip_suffix(" 0 2 Bd")).collect();
    let want = [
        "(Gradient 3)",
        "(Gradient)",
        "(Gradient 2)",
        "(Gradient 4)",
        "(Gradient 5)",
        "(?)",
        "(? 2)",
        "(Gradient 6)",
        "(Gradient 2 2)",
        "(Gradient 7)",
    ];
    assert_eq!(defined, want);
    for name in want {
        assert_eq!(text.matches(&format!("1 {name} ")).count(), if name == "(Gradient 3)" { 1 } else { 2 }, "{name}");
    }
    assert!(text.contains("%%DocumentCustomColors: (?)\n%%+ (? 2)\n%%+ (? 3)\n%%+ (? 2 2)\n"), "{text}");
}

/// The time this thread has run, and how it was measured.
fn thread_time() -> (std::time::Duration, &'static str) {
    if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::<u64>().ok()) {
        return (std::time::Duration::from_nanos(ns), "thread CPU time");
    }
    static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
    (START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time")
}

/// The time to write 1,500 objects that each have a gradient of their own and no swatch name,
/// with a few named ones that collide, numbering names by counters and by searching the names
/// given: the median of 7 runs of each, alternating, with the files compared. Run with
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture many_unnamed_gradients`.
#[test]
#[ignore = "timing"]
fn many_unnamed_gradients_are_named_quickly() {
    let mut doc = Document::new(1000.0, 1000.0);
    let layer = doc.layers[0].id;
    let count = 1500u16;
    for i in 0..count + 4 {
        let swatch = match i {
            0 => Some("Gradient 3"),
            1 => Some("Gradient"),
            2 | 3 => Some("Sky"),
            _ => None,
        };
        let t = f32::from(i) / f32::from(count + 4);
        let (x, y) = (f64::from(i % 40) * 25.0, f64::from(i / 40) * 25.0);
        let paint = gradient_from(Color::rgb(t, 1.0 - t, (t * 7.0).fract()), swatch);
        let n = shape(&mut doc, shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), paint, Paint::None);
        doc.insert(Some(layer), usize::MAX, n).unwrap();
    }
    let mut times = [vec![], vec![]];
    let mut files: [Option<Vec<u8>>; 2] = [None, None];
    let mut how = "";
    for _ in 0..7 {
        for (k, scanned) in [false, true].into_iter().enumerate() {
            let (start, h) = thread_time();
            let out = export_numbering(&doc, scanned);
            times[k].push(thread_time().0.saturating_sub(start));
            how = h;
            let defs = String::from_utf8_lossy(&out.bytes).lines().filter(|l| l.ends_with(" Bd")).count();
            assert_eq!(defs, usize::from(count) + 4);
            files[k].get_or_insert(out.bytes);
        }
    }
    assert_eq!(files[0], files[1]);
    for t in &mut times {
        t.sort();
    }
    let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
    println!("{} gradient definitions, median of 7 runs ({how}):", count + 4);
    println!("| naming | median (ms) | runs (ms) |");
    println!("|---|---:|---|");
    for (k, label) in ["counters", "search of the names given"].into_iter().enumerate() {
        let runs: Vec<String> = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect();
        println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", "));
    }
}

/// #6502: the legacy writer gives Yellow, Magenta and Cyan (presets 4, 5 and 6) the file's
/// indexes 6, 4 and 5, and they open as the same presets.
#[test]
fn layer_presets_are_written_with_the_files_colour_index() {
    let mut doc = Document::new(100.0, 100.0);
    doc.layers.clear();
    for i in 3..8u8 {
        let id = doc.alloc_id();
        doc.layers.push(Arc::new(Node::layer(id, &format!("P{i}"), vectorcraft_doc::LayerColor::Preset(i))));
    }
    let out = write(&doc);
    let text = String::from_utf8_lossy(&out.bytes).replace("\r\n", "\n");
    for (i, index) in [(3, 3), (4, 6), (5, 4), (6, 5), (7, 7)] {
        let [r, g, b] = vectorcraft_doc::LAYER_COLORS[i].1;
        let want = format!(" 0 {index} {r} {g} {b} Lb\n(P{i}) Ln\n");
        assert!(text.contains(&want), "missing {want:?} in\n{text}");
    }
    let read = crate::import(&out.bytes).unwrap().document;
    let colors: Vec<_> = read
        .layers
        .iter()
        .filter_map(|l| match l.kind {
            NodeKind::Layer { color, .. } => Some(color),
            _ => None,
        })
        .collect();
    assert_eq!(colors, (3..8u8).map(vectorcraft_doc::LayerColor::Preset).collect::<Vec<_>>());
}

#[test]
fn losses_are_warned() {
    let mut doc = sample();
    // A sublayer, a hidden object, a named object, type and half opacity.
    let back = doc.layers[0].id;
    let sub = Node::layer(doc.alloc_id(), "Sub", vectorcraft_doc::LayerColor::Preset(2));
    let sub = doc.insert(Some(back), usize::MAX, sub).unwrap();
    let mut hidden = shape(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), red(), Paint::None);
    hidden.visible = false;
    doc.insert(Some(sub), usize::MAX, hidden).unwrap();
    let mut named = shape(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), red(), Paint::None);
    named.name = Some("Named".into());
    named.opacity = 0.5;
    doc.insert(Some(sub), usize::MAX, named).unwrap();
    let w = write(&doc).warnings;
    for expected in [SUBLAYERS, HIDDEN_LAYER, NAMES, TRANSPARENCY] {
        assert!(w.iter().any(|x| x == expected), "{expected} not in {w:?}");
    }
    // The sublayer is a group in its layer.
    let doc = crate::import(&write(&doc).bytes).unwrap().document;
    let last = children(&doc.layers[0]).last().unwrap();
    assert!(matches!(&last.kind, NodeKind::Group { children, .. } if children.len() == 1), "{:?}", last.kind);
}

#[test]
fn several_fills_and_odd_strokes_become_objects() {
    let mut doc = Document::new(100.0, 100.0);
    let mut n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 50.0)), red(), Paint::solid(Color::gray(1.0)));
    let mut a = (*n.appearance).clone();
    if let Some(AppearanceItem::Stroke(s)) = a.items.iter_mut().find(|i| !i.is_fill()) {
        s.align = vectorcraft_doc::StrokeAlign::Inside;
    }
    n.appearance = a.into();
    let layer = doc.layers[0].id;
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
    let doc = crate::import(&out.bytes).unwrap().document;
    let n = &children(&doc.layers[0])[0];
    // The fill, then the stroke's outline filled.
    assert!(matches!(&n.kind, NodeKind::Group { children, .. } if children.len() == 2), "{:?}", n.kind);
}

#[test]
fn art_stays_put_on_an_artboard_a_fraction_of_a_point_tall() {
    let mut doc = Document::new(100.0, 364.252);
    let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 20.0, 30.0, 40.0)), red(), Paint::None);
    let layer = doc.layers[0].id;
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let text = String::from_utf8(write(&doc).bytes).unwrap();
    // The artboard's top is on a whole point (365); the template box's centre is the artboard's.
    assert!(text.contains("%AI3_TemplateBox: 50 182.874 50 182.874\n"), "{text}");
    assert!(text.contains("10 345 m\n"), "{text}");
    let doc = crate::import(text.as_bytes()).unwrap().document;
    let b = children(&doc.layers[0])[0].visual_bounds().unwrap();
    assert!((b.x0 - 10.0).abs() < 1e-3 && (b.y0 - 20.0).abs() < 1e-3 && (b.y1 - 40.0).abs() < 1e-3, "{b:?}");
}

/// The file prints as the document with every layer shown: run as a PostScript program
/// ([`write_with`] checks it), its paths, fills, strokes, compound path, clipping group and image
/// draw where and as the document has them (its gradient filled with its first stop's colour, as
/// the prolog fills gradients). Read for its layers, it is read from its program, which has the
/// gradient.
#[test]
fn prints_as_the_document() {
    let mut doc = sample();
    if let Some(l) = doc.layers.get_mut(1) {
        Arc::make_mut(l).visible = true;
    }
    let out = write(&doc);
    let read = crate::import(&out.bytes).unwrap().document;
    let mut gradients = 0;
    read.walk(|n| {
        gradients += n.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Fill(f) if matches!(f.paint, Paint::Gradient(_)))).count()
    });
    assert_eq!((read.layers.len(), gradients), (2, 1));
}

#[test]
fn needs_an_artboard() {
    let mut doc = Document::new(100.0, 100.0);
    doc.artboards.clear();
    assert!(export_legacy_ai(&doc, &LegacyAiOptions::default()).is_err());
}

/// Every text object of `doc`'s layers, in paint order.
fn texts(doc: &Document) -> Vec<(Node, vectorcraft_doc::TextObject)> {
    let mut out = vec![];
    doc.walk(|n| {
        if let NodeKind::Text(t) = &n.kind {
            out.push((n.clone(), (**t).clone()));
        }
    });
    out
}

fn style(size: f64, fill: Paint) -> vectorcraft_doc::CharStyle {
    vectorcraft_doc::CharStyle { size, fill, ..vectorcraft_doc::CharStyle::default() }
}

/// A document of point type (two paragraphs, the second centred, accented letters and a euro
/// sign), area type in a 100 × 50 frame and type on a path starting a quarter of the way along.
fn typed() -> Document {
    use vectorcraft_doc::{Justify, ParaStyle, TextKind, TextObject, TextRun};
    let mut doc = Document::new(300.0, 200.0);
    let layer = doc.layers[0].id;
    let mut point = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "Héllo €5\nWorld", style(18.0, red()));
    point.runs.push(TextRun::new(" again", style(12.0, Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)))));
    point.set_paragraph_styles(vec![ParaStyle::default(), ParaStyle { justify: Justify::Center, ..ParaStyle::default() }]);
    let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "Area type flows in its frame", style(10.0, Paint::solid(Color::BLACK)));
    area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)) };
    area.xf = Affine::translate((20.0, 80.0));
    let mut on_path = TextObject::point(vectorcraft_geom::Point::ZERO, "Along a path", style(12.0, Paint::solid(Color::gray(0.5))));
    let mut line = PathData::new(vec![]);
    line.subpaths.push(vectorcraft_geom::SubPath::polyline(&[(150.0, 150.0).into(), (250.0, 150.0).into(), (250.0, 190.0).into()], false));
    on_path.kind = TextKind::OnPath { path: line, start: 0.25, end: None };
    on_path.xf = Affine::IDENTITY;
    for t in [point, area, on_path] {
        let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
        doc.insert(Some(layer), usize::MAX, n).unwrap();
    }
    doc
}

#[test]
fn type_is_written_as_text_objects() {
    let out = write(&typed());
    let text = String::from_utf8(out.bytes).unwrap();
    for needle in [
        "%%DocumentFonts: ",
        "%%IncludeFont: ",
        "\nTE\n",
        "%AI3_BeginEncoding: _",
        "0 To\n1 0 0 1 20 160 0 Tp\nTP\n",
        "1 To\n",
        "2 To\n",
        " Tf\n",
        "TO\n",
    ] {
        assert!(text.contains(needle), "missing {needle:?} in\n{text}");
    }
    // Windows-1252: é is 351 (octal), the euro sign 200, the paragraph ends with `\r`.
    assert!(text.contains("(H\\351llo \\2005\\r) Tx\n"), "{text}");
    // The second paragraph centred.
    assert!(text.contains("1 Ta\n"), "{text}");
    // The area's frame in art space, painted with nothing.
    assert!(text.contains("20 120 m\n"), "{text}");
    assert!(!out.warnings.iter().any(|w| w == TYPE), "{:?}", out.warnings);
}

/// A legacy `.ai` text object names a font, not a setting of its variation axes: type with
/// Variable Font settings is written in the font's style, with the warning that they are left out.
#[test]
fn variable_font_settings_are_warned_as_left_out() {
    let mut doc = typed();
    assert!(!write(&doc).warnings.iter().any(|w| w == TYPE_ATTRIBUTES));
    let id = texts(&doc)[0].0.id;
    if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
        t.runs[0].style.font_axes.insert("wght".into(), 650.0);
    }
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
    assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text");
}

/// A legacy `.ai` text object has no Insert Aki (§15.4): type with Insert Aki Left or Right is
/// written as text with the warning that it is left out. Written as outlines, the glyphs keep the
/// space it adds, and nothing is reported.
#[test]
fn insert_aki_is_warned_as_left_out_of_text() {
    for (left, right) in [(250.0, 0.0), (0.0, 125.0)] {
        let mut doc = typed();
        let id = texts(&doc)[0].0.id;
        if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
            t.runs[0].style.aki_left = left;
            t.runs[0].style.aki_right = right;
        }
        let out = write(&doc);
        assert!(out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{left} {right}: {:?}", out.warnings);
        assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text");
    }
    let width = |aki: f64| {
        let mut st = style(20.0, red());
        st.aki_left = aki;
        st.aki_right = aki;
        let t = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "HH", st);
        let mut doc = Document::new(300.0, 200.0);
        let layer = doc.layers[0].id;
        let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
        doc.insert(Some(layer), usize::MAX, n).unwrap();
        let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() });
        assert!(!out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
        let back = crate::import(&out.bytes).unwrap().document;
        children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap().width()
    };
    // Between the two H's: 0.5 em after the first and 0.5 em before the second, 20 pt.
    let (plain, spaced) = (width(0.0), width(500.0));
    assert!((spaced - plain - 20.0).abs() < 0.05, "{plain} {spaced}");
}

/// Standard Vertical Roman Alignment is written as `Tv` and Tate-chu-yoko in horizontal type as a
/// Kumi block recorded for later use, `TY` (§15.3.4), each where it changes: the marks read back
/// on the same characters, a block is closed before its text object ends, and type with neither
/// mark has neither operator.
#[test]
fn vertical_roman_and_tate_chu_yoko_are_written_and_read_back() {
    use vectorcraft_doc::{TextObject, TextRun};
    let plain = style(12.0, Paint::solid(Color::BLACK));
    let roman = vectorcraft_doc::CharStyle { standard_vertical_roman: true, ..plain.clone() };
    let tcy = vectorcraft_doc::CharStyle { tate_chu_yoko: true, ..plain.clone() };
    let both = vectorcraft_doc::CharStyle { tate_chu_yoko: true, standard_vertical_roman: true, ..plain.clone() };
    let mut doc = Document::new(300.0, 200.0);
    let layer = doc.layers[0].id;
    let mut marked = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "A", plain.clone());
    for (text, st) in [("12", &tcy), ("b", &roman), ("c", &both), ("34", &tcy)] {
        marked.runs.push(TextRun::new(text, st.clone()));
    }
    let next = TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "D", plain.clone());
    for t in [marked, next] {
        let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
        doc.insert(Some(layer), usize::MAX, n).unwrap();
    }
    let out = write(&doc);
    assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    assert_eq!((text.matches("1 TY\n").count(), text.matches("0 TY\n").count()), (2, 2), "{text}");
    assert_eq!((text.matches("1 Tv\n").count(), text.matches("0 Tv\n").count()), (1, 1), "{text}");
    // The last block ends before its text object does.
    assert!(text.contains("(34) Tx\n0 TY\nTO\n"), "{text}");
    let read = texts(&crate::import(&out.bytes).unwrap().document);
    let flags = |t: &TextObject| -> Vec<(String, bool, bool)> {
        let mut out: Vec<(String, bool, bool)> = vec![];
        for r in &t.runs {
            let key = (r.style.tate_chu_yoko, r.style.standard_vertical_roman);
            match out.last_mut() {
                Some(last) if (last.1, last.2) == key => last.0.push_str(&r.text),
                _ => out.push((r.text.clone(), key.0, key.1)),
            }
        }
        out
    };
    let s = |x: &str| x.to_string();
    assert_eq!(
        flags(&read[0].1),
        [(s("A"), false, false), (s("12"), true, false), (s("b"), false, true), (s("c"), true, true), (s("34"), true, false)]
    );
    assert_eq!(flags(&read[1].1), [(s("D"), false, false)]);

    // Type with neither mark has neither operator.
    let text = String::from_utf8(write(&typed()).bytes).unwrap();
    assert!(!text.contains(" Tv\n") && !text.contains(" TY\n"), "{text}");
}

/// A legacy `.ai` text path holds the path and where the type starts on it, and no Align to Path
/// or end bracket: type on a path with either is written as text, with the warning that they are
/// left out. An end bracket at the end of an open path, or once around a closed one, is kept. A
/// path with a second subpath is written with its first one only, with the same warning.
#[test]
fn type_on_a_path_alignment_and_end_bracket_are_warned_as_left_out() {
    use vectorcraft_doc::{PathAlign, TextKind, TextObject};
    let along = |closed: bool| {
        let pts = [(150.0, 150.0).into(), (250.0, 150.0).into(), (250.0, 190.0).into()];
        PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, closed)])
    };
    let warned = |edit: &dyn Fn(&mut TextObject)| {
        let mut doc = Document::new(300.0, 200.0);
        let layer = doc.layers[0].id;
        let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Along", style(12.0, Paint::solid(Color::BLACK)));
        t.kind = TextKind::OnPath { path: along(false), start: 0.25, end: None };
        t.xf = Affine::IDENTITY;
        edit(&mut t);
        let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
        doc.insert(Some(layer), usize::MAX, n).unwrap();
        let out = write(&doc);
        assert!(String::from_utf8(out.bytes).unwrap().contains("(Along) Tx\n"), "still written as text");
        out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES)
    };
    assert!(!warned(&|_| {}));
    for align in [PathAlign::Ascender, PathAlign::Descender, PathAlign::Center] {
        assert!(warned(&|t| t.path_align = align), "{align:?}");
    }
    assert!(warned(&|t| t.kind = TextKind::OnPath { path: along(false), start: 0.25, end: Some(0.6) }));
    assert!(warned(&|t| t.kind = TextKind::OnPath { path: along(true), start: 0.25, end: Some(0.9) }));
    assert!(!warned(&|t| t.kind = TextKind::OnPath { path: along(false), start: 0.25, end: Some(1.0) }));
    assert!(!warned(&|t| t.kind = TextKind::OnPath { path: along(true), start: 0.1, end: Some(0.1) }));
    assert!(!warned(&|t| t.kind = TextKind::OnPath { path: along(true), start: 0.7, end: None }));
    // A closed path's span that wraps past the path's start and stops short of a full turn.
    assert!(warned(&|t| t.kind = TextKind::OnPath { path: along(true), start: 0.7, end: Some(0.5) }));
    // An open path's end bracket before its start bracket.
    assert!(warned(&|t| t.kind = TextKind::OnPath { path: along(false), start: 0.5, end: Some(0.3) }));
    // Type that starts before its open path: the text path holds a start on the path only.
    assert!(warned(&|t| t.kind = TextKind::OnPath { path: along(false), start: -0.25, end: None }));
    assert!(!warned(&|t| t.kind = TextKind::OnPath { path: along(false), start: 0.0, end: None }));
    // It is written starting at the path's start: the same text object as a start of 0.
    let written = |start: f64| {
        let mut doc = Document::new(300.0, 200.0);
        let layer = doc.layers[0].id;
        let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "Along", style(12.0, Paint::solid(Color::BLACK)));
        t.kind = TextKind::OnPath { path: along(false), start, end: None };
        t.xf = Affine::IDENTITY;
        let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
        doc.insert(Some(layer), usize::MAX, n).unwrap();
        write(&doc).bytes
    };
    assert_eq!(written(-0.25), written(0.0));
    assert_ne!(written(0.25), written(0.0));
    let two = |first_closed: bool| {
        let mut path = along(first_closed);
        let pts = [(150.0, 100.0).into(), (250.0, 100.0).into()];
        path.subpaths.push(vectorcraft_geom::SubPath::polyline(&pts, false));
        path
    };
    assert!(warned(&|t| t.kind = TextKind::OnPath { path: two(true), start: 0.25, end: None }));
    assert!(warned(&|t| t.kind = TextKind::OnPath { path: two(false), start: 0.25, end: None }));
}

/// Optical kerning, Optical Margin Alignment, System Layout, fractional widths off and an area
/// type frame with a second subpath are not held by a legacy `.ai` text object: type with any of
/// them is written as text, with the warning that they are left out. Manual kerning is held
/// (`Tk`), with no warning.
#[test]
fn optical_kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
    use vectorcraft_doc::{TextKind, TextObject};
    let warned = |edit: &dyn Fn(&mut TextObject)| {
        let mut doc = typed();
        let id = texts(&doc)[0].0.id;
        if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
            edit(t);
        }
        let out = write(&doc);
        assert!(String::from_utf8(out.bytes).unwrap().contains(") Tx\n"), "still written as text");
        out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES)
    };
    assert!(!warned(&|_| {}));
    assert!(!warned(&|t| t.runs[0].style.kerning = Some(0.0)));
    assert!(!warned(&|t| t.runs[0].style.kerning = Some(50.0)));
    assert!(!warned(&|t| t.runs[0].style.kerning_before = 50.0));
    assert!(warned(&|t| t.runs[0].style.optical_kerning = true));
    assert!(warned(&|t| t.optical_margin = true));
    assert!(warned(&|t| t.system_layout = true));
    assert!(warned(&|t| t.fractional_widths = false));
    let square = |x: f64| {
        let pts = [(x, 10.0).into(), (x + 80.0, 10.0).into(), (x + 80.0, 90.0).into(), (x, 90.0).into()];
        vectorcraft_geom::SubPath::polyline(&pts, true)
    };
    assert!(!warned(&|t| t.kind = TextKind::Area { frame: PathData::new(vec![square(10.0)]) }));
    assert!(warned(&|t| t.kind = TextKind::Area { frame: PathData::new(vec![square(10.0), square(120.0)]) }));
}

/// Manual kerning is written as `0 value Tk` after each character that has it, the space before a
/// paragraph's first character as `Tk` before it, and a soft hyphen as a discretionary hyphen
/// (`T+`, §15.4.6.1 and §15.4.10.1); each reads back on the same characters.
#[test]
fn manual_kerning_and_soft_hyphens_are_written_and_read_back() {
    use vectorcraft_doc::{CharStyle, TextObject, TextRun};
    let plain = style(12.0, Paint::solid(Color::BLACK));
    let kerned = CharStyle { kerning: Some(-80.0), ..plain.clone() };
    let before = CharStyle { kerning_before: 40.0, ..plain.clone() };
    let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "AV", kerned.clone());
    for (text, st) in [("A co\u{ad}op\n", &plain), ("W", &before), ("ord", &plain), ("d\u{ad}", &kerned)] {
        t.runs.push(TextRun::new(text, st.clone()));
    }
    let mut doc = Document::new(300.0, 200.0);
    let layer = doc.layers[0].id;
    let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let out = write(&doc);
    assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    assert!(text.contains("(A) Tx\n0 -80 Tk\n(V) Tx\n0 -80 Tk\n"), "{text}");
    assert!(text.contains("(A co) Tx\nT+\n(op\\r) Tx\n"), "{text}");
    assert!(text.contains("0 40 Tk\n(W) Tx\n"), "{text}");
    // A soft hyphen with manual kerning keeps it too.
    assert!(text.contains("(d) Tx\n0 -80 Tk\nT+\n0 -80 Tk\n"), "{text}");
    let read = texts(&crate::import(&out.bytes).unwrap().document);
    let runs: Vec<(String, Option<f64>, f64)> = read[0].1.runs.iter().map(|r| (r.text.clone(), r.style.kerning, r.style.kerning_before)).collect();
    let s = |x: &str| x.to_string();
    assert_eq!(
        runs,
        [
            (s("AV"), Some(-80.0), 0.0),
            (s("A co\u{ad}op\n"), None, 0.0),
            (s("W"), None, 40.0),
            (s("ord"), None, 0.0),
            (s("d\u{ad}"), Some(-80.0), 0.0)
        ]
    );
}

/// Manual kerning of 0 is written as `0 0 Tk` and reads back as manual kerning, not as the
/// automatic kerning of a pair with no `Tk`.
#[test]
fn manual_kerning_of_zero_is_written_and_read_back() {
    use vectorcraft_doc::{CharStyle, TextObject, TextRun};
    let plain = style(12.0, Paint::solid(Color::BLACK));
    let zero = CharStyle { kerning: Some(0.0), ..plain.clone() };
    let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "AV", zero);
    t.runs.push(TextRun::new("To", plain));
    let mut doc = Document::new(300.0, 200.0);
    let layer = doc.layers[0].id;
    let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let out = write(&doc);
    let text = String::from_utf8(out.bytes.clone()).unwrap();
    assert!(text.contains("(A) Tx\n0 0 Tk\n(V) Tx\n0 0 Tk\n"), "{text}");
    let read = texts(&crate::import(&out.bytes).unwrap().document);
    let runs: Vec<(String, Option<f64>)> = read[0].1.runs.iter().map(|r| (r.text.clone(), r.style.kerning)).collect();
    assert_eq!(runs, [("AV".to_string(), Some(0.0)), ("To".to_string(), None)]);
}

/// Type whose font size measures the cap height is written at the em size it is drawn at, with
/// no warning: 14 pt measuring a 0.7 em cap height reads back as 20 pt type.
#[test]
fn a_font_height_reference_is_written_as_the_size_drawn() {
    use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
    vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
    let mut doc = typed();
    let id = texts(&doc)[0].0.id;
    if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
        let st = &mut t.runs[0].style;
        (st.font_family, st.size) = (HEIGHT_FAMILY.into(), 14.0);
        st.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight;
    }
    let out = write(&doc);
    assert!(!out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES || w == TYPE), "{:?}", out.warnings);
    let imported = crate::import(&out.bytes).unwrap();
    let size = texts(&imported.document)[0].1.runs[0].style.size;
    assert!((size - 20.0).abs() < 1e-6, "{size}");
}

/// Type on a path with Dynamic Text is written at the sizes it is drawn at, with a warning that
/// the setting itself is not written; without Dynamic Text there is no warning.
#[test]
fn dynamic_text_is_written_at_its_drawn_sizes_with_a_warning() {
    let mut doc = typed();
    assert!(!write(&doc).warnings.iter().any(|w| w == DYNAMIC_TEXT));
    let id = texts(&doc).into_iter().find(|(_, t)| matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })).unwrap().0.id;
    let mut drawn = 0.0;
    if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
        t.runs[0].style.size = 4.0;
        t.dynamic_text = true;
        drawn = 4.0 * vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale;
    }
    assert!(drawn > 4.0, "{drawn}");
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings);
    let imported = crate::import(&out.bytes).unwrap();
    let (_, back) = texts(&imported.document).into_iter().find(|(_, t)| t.runs.iter().any(|r| r.text.contains("path"))).unwrap();
    assert!(!back.dynamic_text);
    assert!((back.runs[0].style.size - drawn).abs() < 1e-3, "{} vs {drawn}", back.runs[0].style.size);
    // Type written as outlines loses the setting too, and says so.
    if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
        t.runs[0].text.push('\u{2192}');
    }
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w == TYPE) && out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings);
    let out = write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() });
    assert!(out.warnings.iter().any(|w| w == DYNAMIC_TEXT), "{:?}", out.warnings);
}

/// Dynamic Text fits type whose size measures the cap height at the size the Character panel
/// shows: 1,000 pt measuring a 0.7 em cap height on a long path grows to the 1,296 pt limit and is
/// written at the em size drawn there, as text and as outlines.
#[test]
fn dynamic_text_with_a_font_height_reference_is_written_at_its_drawn_size() {
    use vectorcraft_doc::{TextKind, TextObject};
    use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
    let db = vectorcraft_text::FontDb::global();
    db.add_font(height_font(true).unwrap());
    let mut t = TextObject::point(vectorcraft_geom::Point::ZERO, "HE", style(1000.0, red()));
    let st = &mut t.runs[0].style;
    st.font_family = HEIGHT_FAMILY.into();
    st.font_height_reference = vectorcraft_doc::FontHeightReference::CapHeight;
    let mut line = PathData::new(vec![]);
    line.subpaths.push(vectorcraft_geom::SubPath::polyline(&[(0.0, 2000.0).into(), (100_000.0, 2000.0).into()], false));
    t.kind = TextKind::OnPath { path: line, start: 0.0, end: None };
    t.xf = Affine::IDENTITY;
    t.dynamic_text = true;
    let lay = vectorcraft_text::layout(db, &t);
    assert!((lay.fit_scale - 1.296).abs() < 1e-9, "{}", lay.fit_scale);
    let em = 1296.0 / 0.7;
    let mut glyphs = kurbo::BezPath::new();
    for g in &lay.glyphs {
        glyphs.extend(g.outline.iter());
    }
    let want = glyphs.bounding_box();
    let mut doc = Document::new(300.0, 200.0);
    let layer = doc.layers[0].id;
    let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let back = crate::import(&write(&doc).bytes).unwrap().document;
    let size = texts(&back)[0].1.runs[0].style.size;
    assert!((size - em).abs() < 1e-3, "{size} vs {em}");
    let back = crate::import(&write_with(&doc, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }).bytes).unwrap().document;
    let b = children(&children(&back.layers[0])[0])[0].visual_bounds().unwrap();
    assert!((b.height() - want.height()).abs() < 0.05 && (b.width() - want.width()).abs() < 0.05, "{b:?}, laid out at {want:?}");
}

/// Characters with Auto leading are written with their paragraph's Auto Leading share of the
/// size: 18 pt type in paragraphs at 150% is written with 27 pt leading.
#[test]
fn auto_leading_is_written_at_the_paragraphs_share() {
    let mut doc = typed();
    let id = texts(&doc)[0].0.id;
    if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
        t.edit_paras(None, |p| p.justification.auto_leading = 150.0);
    }
    let text = String::from_utf8(write(&doc).bytes).unwrap();
    assert!(text.contains("\n27 0 Tl\n"), "{text}");
}

/// A legacy `.ai` paragraph has no list: type with a bulleted or numbered list is written as its
/// text, with the warning that the bullets and numbers are left out.
#[test]
fn bulleted_and_numbered_lists_are_warned_as_left_out() {
    use vectorcraft_doc::text::{Bullet, NumberStyle, ParaList};
    for list in [ParaList::bulleted(Bullet::Square), ParaList::numbered(NumberStyle::UpperRoman)] {
        let mut doc = typed();
        let id = texts(&doc)[0].0.id;
        if let Some(NodeKind::Text(t)) = doc.node_mut(id).map(|n| &mut n.kind) {
            t.para.list = Some(list);
            t.normalize_paras();
        }
        let out = write(&doc);
        assert!(out.warnings.iter().any(|w| w == TYPE_ATTRIBUTES && w.contains("bulleted and numbered lists")), "{list:?}: {:?}", out.warnings);
        assert!(String::from_utf8(out.bytes).unwrap().contains("(H\\351llo \\2005\\r) Tx\n"), "still written as text");
    }
}

/// A closed path whose anchors' kinds differ from what their handles suggest: a corner with
/// handles in line, a smooth point with handles that aren't, a smooth point without handles and a
/// corner.
fn mixed_kinds() -> vectorcraft_geom::SubPath {
    use vectorcraft_geom::{Anchor, Point, SubPath};
    let at = |p: (f64, f64), h_in: (f64, f64), h_out: (f64, f64), kind| Anchor {
        p: Point::from(p),
        h_in: Point::from(h_in),
        h_out: Point::from(h_out),
        kind,
    };
    SubPath::new(
        vec![
            at((10.0, 10.0), (0.0, 10.0), (20.0, 10.0), AnchorKind::Corner),
            at((40.0, 40.0), (40.0, 30.0), (50.0, 50.0), AnchorKind::Smooth),
            at((70.0, 10.0), (70.0, 10.0), (70.0, 10.0), AnchorKind::Smooth),
            at((90.0, 10.0), (90.0, 10.0), (90.0, 10.0), AnchorKind::Corner),
        ],
        true,
    )
}

/// The case of each segment operator written reads back as the kind of the anchor it ends on,
/// the first anchor's from the segment back to it.
#[test]
fn anchor_kinds_read_back() {
    let mut doc = Document::new(200.0, 100.0);
    let layer = doc.layers[0].id;
    let n = shape(&mut doc, PathData::new(vec![mixed_kinds()]), red(), Paint::None);
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let read = crate::import(&write(&doc).bytes).unwrap().document;
    let path = children(&read.layers[0])[0].path_data().unwrap();
    let want: Vec<_> = mixed_kinds().anchors.iter().map(|a| a.kind).collect();
    assert_eq!(path.subpaths[0].anchors.iter().map(|a| a.kind).collect::<Vec<_>>(), want, "{path:?}");
    let points: Vec<_> = path.subpaths[0].anchors.iter().map(|a| (a.p, a.h_in, a.h_out)).collect();
    let wrote: Vec<_> = mixed_kinds().anchors.iter().map(|a| (a.p, a.h_in, a.h_out)).collect();
    assert_eq!(points, wrote);
}

/// An area's frame and the path type runs along keep their anchors' kinds too.
#[test]
fn text_paths_keep_their_anchor_kinds() {
    use vectorcraft_doc::{TextKind, TextObject};
    let mut doc = Document::new(300.0, 200.0);
    let layer = doc.layers[0].id;
    let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "Area", style(10.0, Paint::solid(Color::BLACK)));
    area.kind = TextKind::Area { frame: PathData::new(vec![mixed_kinds()]) };
    let mut along = mixed_kinds();
    along.closed = false;
    let mut on_path = TextObject::point(vectorcraft_geom::Point::ZERO, "Along", style(10.0, Paint::solid(Color::BLACK)));
    on_path.kind = TextKind::OnPath { path: PathData::new(vec![along.clone()]), start: 0.0, end: None };
    for t in [area, on_path] {
        let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
        doc.insert(Some(layer), usize::MAX, n).unwrap();
    }
    let imported = crate::import(&write(&doc).bytes).unwrap();
    let found = texts(&imported.document);
    assert_eq!(found.len(), 2, "{:?}", imported.warnings);
    let kinds = |p: &PathData| p.subpaths[0].anchors.iter().map(|a| a.kind).collect::<Vec<_>>();
    let TextKind::Area { frame } = &found[0].1.kind else { panic!("{:?}", found[0].1.kind) };
    // The frame's anchors after its first, which its handles decide.
    assert_eq!(kinds(frame).get(1..4), kinds(&PathData::new(vec![mixed_kinds()])).get(1..4), "{frame:?}");
    let TextKind::OnPath { path, .. } = &found[1].1.kind else { panic!("{:?}", found[1].1.kind) };
    assert_eq!(kinds(path).get(1..), kinds(&PathData::new(vec![along])).get(1..), "{path:?}");
}

#[test]
fn type_reads_back_as_text() {
    use vectorcraft_doc::{Justify, TextKind};
    let imported = crate::import(&write(&typed()).bytes).unwrap();
    let found = texts(&imported.document);
    assert_eq!(found.len(), 3, "{:?}", imported.warnings);
    let squeeze = |s: &str| s.replace(' ', "");
    // Point type: the characters, paragraphs, sizes, colours and place.
    let (_, point) = &found[0];
    assert!(matches!(point.kind, TextKind::Point));
    assert_eq!(point.plain_text(), "Héllo €5\nWorld again");
    assert_eq!(point.runs.len(), 2, "{:?}", point.runs);
    let first = &point.runs[0].style;
    assert_eq!(squeeze(&first.font_family), "SourceSans3", "{first:?}");
    assert!((first.size - 18.0).abs() < 1e-6 && first.leading.is_none(), "{first:?}");
    assert_eq!(first.fill.color(), Some(Color::rgb(1.0, 0.0, 0.0)));
    assert_eq!(point.runs[1].style.fill.color(), Some(Color::cmyk(1.0, 0.0, 0.0, 0.0)));
    assert!((point.runs[1].style.size - 12.0).abs() < 1e-6);
    assert_eq!(point.para_at(0).justify, Justify::Left);
    assert_eq!(point.para_at(1).justify, Justify::Center);
    let origin = point.xf * vectorcraft_geom::Point::ZERO;
    assert!((origin.x - 20.0).abs() < 1e-3 && (origin.y - 40.0).abs() < 1e-3, "{:?}", point.xf);
    // Area type: its frame where it was.
    let (_, area) = &found[1];
    let TextKind::Area { frame } = &area.kind else { panic!("{:?}", area.kind) };
    let b = frame.transformed(area.xf).to_bezpath().bounding_box();
    assert!((b.x0 - 20.0).abs() < 1e-3 && (b.y0 - 80.0).abs() < 1e-3 && (b.x1 - 120.0).abs() < 1e-3 && (b.y1 - 130.0).abs() < 1e-3, "{b:?}");
    assert_eq!(area.plain_text(), "Area type flows in its frame");
    // Type on a path: its path and where along it the type starts.
    let (_, along) = &found[2];
    let TextKind::OnPath { path, start, .. } = &along.kind else { panic!("{:?}", along.kind) };
    assert!((start - 0.25).abs() < 1e-2, "{start}");
    let b = path.transformed(along.xf).to_bezpath().bounding_box();
    assert!((b.x0 - 150.0).abs() < 1e-3 && (b.y1 - 190.0).abs() < 1e-3, "{b:?}");
}

/// Area type that Shrink Text to Fit scales down is written at the sizes, leading and baseline
/// shifts it draws at, so it reads back fitting its frame.
#[test]
fn shrunk_area_type_is_written_at_the_size_it_draws_at() {
    use vectorcraft_doc::{TextKind, TextObject, TextRun};
    let mut doc = Document::new(300.0, 200.0);
    let layer = doc.layers[0].id;
    let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "Area type that is too long ", style(14.0, Paint::solid(Color::BLACK)));
    let raised = vectorcraft_doc::CharStyle { baseline_shift: 3.0, leading: Some(20.0), ..style(14.0, red()) };
    area.runs.push(TextRun::new("for its frame shrinks", raised));
    area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 40.0)) };
    area.area.fit = vectorcraft_doc::AreaFit::ShrinkText { min_percent: 10.0 };
    area.xf = Affine::translate((20.0, 80.0));
    let fit = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &area).fit_scale;
    assert!(fit < 0.9, "the text is shrunk to fit: {fit}");
    let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(area)));
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let imported = crate::import(&write(&doc).bytes).unwrap();
    let found = texts(&imported.document);
    let (_, back) = found.first().expect("the area type reads back");
    let sizes: Vec<(f64, f64, Option<f64>)> = back.runs.iter().map(|r| (r.style.size, r.style.baseline_shift, r.style.leading)).collect();
    assert_eq!(sizes.len(), 2, "{sizes:?}");
    assert!((sizes[0].0 - 14.0 * fit).abs() < 1e-3 && (sizes[1].0 - 14.0 * fit).abs() < 1e-3, "{sizes:?} at {fit}");
    assert!((sizes[1].1 - 3.0 * fit).abs() < 1e-3, "{sizes:?} at {fit}");
    assert!(sizes[1].2.is_some_and(|l| (l - 20.0 * fit).abs() < 1e-3), "{sizes:?} at {fit}");
    assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), back).overflow, "it fits its frame as written");
}

#[test]
fn type_8_bit_text_cant_hold_and_type_asked_for_as_outlines_are_outlines() {
    use vectorcraft_doc::TextObject;
    let mut doc = Document::new(200.0, 100.0);
    let layer = doc.layers[0].id;
    let t = TextObject::point(vectorcraft_geom::Point::new(10.0, 50.0), "Ωmega 日本", style(12.0, red()));
    let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w == TYPE), "{:?}", out.warnings);
    assert!(!String::from_utf8_lossy(&out.bytes).contains(" To\n"));
    // Type that could be text, asked for as outlines.
    let out = write_with(&typed(), LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() });
    let text = String::from_utf8(out.bytes).unwrap();
    assert!(!text.contains(" To\n") && !text.contains("%%DocumentFonts"), "{text}");
    assert!(!out.warnings.iter().any(|w| w == TYPE), "{:?}", out.warnings);
}

/// A legacy `.ai` text object has no character rotation: point type and area type with a rotated
/// character between ordinary ones (turned either way, shifted off the baseline and scaled) are
/// written as their outlines, with the warning, and read back as paths where the laid-out glyphs
/// are, the rotated character turned. A full turn writes text.
#[test]
fn type_with_rotated_characters_is_outlines_that_keep_the_rotation() {
    use vectorcraft_doc::{CharStyle, TextKind, TextObject, TextRun};
    let typed = |turn: f64, area: bool| {
        let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 80.0), "HE", style(30.0, red()));
        let turned = CharStyle { rotation: turn, baseline_shift: 4.0, h_scale: 120.0, v_scale: 80.0, ..style(30.0, red()) };
        t.runs.push(TextRun::new("L", turned));
        t.runs.push(TextRun::new("TH", style(30.0, red())));
        if area {
            t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)) };
            t.xf = Affine::translate((20.0, 40.0));
        }
        t
    };
    // Each run's laid-out glyphs' box, in the document.
    let boxes = |t: &TextObject| -> Vec<kurbo::Rect> {
        let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
        (0..t.runs.len())
            .map(|i| {
                let mut bp = kurbo::BezPath::new();
                for g in lay.glyphs.iter().filter(|g| g.run == i) {
                    bp.extend(g.outline.iter());
                }
                bp.apply_affine(t.xf);
                bp.bounding_box()
            })
            .collect()
    };
    let near = |a: kurbo::Rect, b: kurbo::Rect| (a.x0 - b.x0).abs().max((a.y0 - b.y0).abs()).max((a.x1 - b.x1).abs()).max((a.y1 - b.y1).abs());
    for (turn, area) in [(30.0, false), (-45.0, true)] {
        let t = typed(turn, area);
        assert!(rotated(&t));
        let want = boxes(&t);
        let unturned = boxes(&typed(0.0, area));
        assert!(near(want[1], unturned[1]) > 1.0, "the turn moves the glyph: {:?} {:?}", want[1], unturned[1]);
        let mut doc = Document::new(300.0, 200.0);
        let layer = doc.layers[0].id;
        let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
        doc.insert(Some(layer), usize::MAX, n).unwrap();
        let out = write(&doc);
        assert!(out.warnings.iter().any(|w| w == ROTATED_TYPE), "{:?}", out.warnings);
        assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
        assert!(!String::from_utf8_lossy(&out.bytes).contains(" To\n"), "not a text object");
        let back = crate::import(&out.bytes).unwrap().document;
        assert!(texts(&back).is_empty(), "no type reads back");
        let parts = children(&children(&back.layers[0])[0]);
        assert_eq!(parts.len(), 3, "one compound path for each run");
        for (i, part) in parts.iter().enumerate() {
            let b = part.visual_bounds().unwrap();
            assert!(near(b, want[i]) < 0.05, "run {i} at {turn}°: {b:?}, laid out at {:?}", want[i]);
        }
    }
    // A full turn draws the character upright: text.
    let mut doc = Document::new(300.0, 200.0);
    let layer = doc.layers[0].id;
    let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(typed(360.0, false))));
    doc.insert(Some(layer), usize::MAX, n).unwrap();
    let out = write(&doc);
    assert!(String::from_utf8_lossy(&out.bytes).contains(" To\n"), "a text object");
    assert!(!out.warnings.iter().any(|w| w == ROTATED_TYPE), "{:?}", out.warnings);
}

/// Ruby (furigana), which a text object can't hold, makes type 8-bit text could hold outlines,
/// with the reading's glyphs among them, where the canvas draws them (the file prints as the
/// document draws).
#[test]
fn type_with_ruby_is_outlines_with_the_reading() {
    use vectorcraft_doc::{RubySpan, TextObject};
    let typed = |ruby: bool| {
        let mut doc = Document::new(200.0, 100.0);
        let layer = doc.layers[0].id;
        let mut t = TextObject::point(vectorcraft_geom::Point::new(10.0, 60.0), "AB", style(30.0, red()));
        if ruby {
            t.ruby = vec![RubySpan::new(0, 2, "xyz")];
        }
        let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
        let reading = lay.ruby.iter().flat_map(|g| g.outline.elements()).filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count();
        let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
        doc.insert(Some(layer), usize::MAX, n).unwrap();
        (doc, reading)
    };
    let moves = |text: &str| text.lines().filter(|l| l.ends_with(" m")).count();
    let (doc, reading) = typed(true);
    assert!(reading >= 3, "the reading has ink: {reading}");
    let out = write(&doc);
    assert!(out.warnings.iter().any(|w| w == TYPE), "{:?}", out.warnings);
    let with_ruby = String::from_utf8(out.bytes).unwrap();
    assert!(!with_ruby.contains(" To\n"), "not a text object");
    let plain = String::from_utf8(write_with(&typed(false).0, LegacyAiOptions { outline_text: true, ..LegacyAiOptions::default() }).bytes).unwrap();
    assert_eq!(moves(&with_ruby), moves(&plain) + reading, "the reading's contours are written");
}

/// A layer `Art` holding a group of a shown square and a hidden one; a hidden layer `Off` holding
/// a hidden square.
fn with_hidden() -> Document {
    let mut doc = Document::new(200.0, 100.0);
    doc.layers.clear();
    let art = doc.add_layer(Some("Art"));
    let off = doc.add_layer(Some("Off"));
    let shown = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), red(), Paint::None);
    let mut hidden = shape(&mut doc, shapes::rectangle(Rect::new(50.0, 10.0, 80.0, 40.0)), red(), Paint::None);
    hidden.visible = false;
    hidden.locked = true;
    let group = Node::group(doc.alloc_id(), vec![Arc::new(shown), Arc::new(hidden)]);
    doc.insert(Some(art), usize::MAX, group).unwrap();
    let mut also = shape(&mut doc, shapes::rectangle(Rect::new(100.0, 10.0, 140.0, 40.0)), red(), Paint::None);
    also.visible = false;
    doc.insert(Some(off), usize::MAX, also).unwrap();
    if let Some(l) = doc.layers.get_mut(1) {
        Arc::make_mut(l).visible = false;
    }
    doc
}

#[test]
fn hidden_objects_go_to_a_hidden_layer_above_their_own() {
    let out = write(&with_hidden());
    assert!(out.warnings.iter().any(|w| w == HIDDEN_LAYER), "{:?}", out.warnings);
    let doc = crate::import(&out.bytes).unwrap().document;
    let names: Vec<_> = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect();
    assert_eq!(names, ["Art", "Art (hidden)", "Off"]);
    assert!(doc.layers[0].visible && !doc.layers[1].visible && !doc.layers[2].visible);
    // The group keeps the shown square; the hidden one, still locked, is in the hidden layer.
    let group = &children(&doc.layers[0])[0];
    assert_eq!(children(group).len(), 1);
    let moved = children(&doc.layers[1]);
    assert_eq!(moved.len(), 1);
    assert!(moved[0].locked);
    let b = moved[0].visual_bounds().unwrap();
    assert!((b.x0 - 50.0).abs() < 0.01, "{b:?}");
    // In a hidden layer, hidden objects stay where they are.
    assert_eq!(children(&doc.layers[2]).len(), 1);
}

#[test]
fn hidden_objects_can_be_left_out_or_shown() {
    let out = write_with(&with_hidden(), LegacyAiOptions { hidden: HiddenObjects::Omit, ..LegacyAiOptions::default() });
    assert!(out.setting_notes.iter().any(|w| w == HIDDEN), "{:?}", out.setting_notes);
    let doc = crate::import(&out.bytes).unwrap().document;
    assert_eq!(doc.layers.len(), 2);
    assert_eq!(children(&children(&doc.layers[0])[0]).len(), 1);
    let out = write_with(&with_hidden(), LegacyAiOptions { hidden: HiddenObjects::Visible, ..LegacyAiOptions::default() });
    assert!(out.setting_notes.iter().any(|w| w == HIDDEN_SHOWN), "{:?}", out.setting_notes);
    let doc = crate::import(&out.bytes).unwrap().document;
    assert_eq!(doc.layers.len(), 2);
    let pair = children(&children(&doc.layers[0])[0]);
    assert_eq!(pair.len(), 2);
    assert!(pair.iter().all(|n| n.visible));
}

#[test]
fn layer_names_outside_latin_1_are_replaced_and_warned() {
    let layered = |name: &str| {
        let mut doc = Document::new(100.0, 100.0);
        doc.layers.clear();
        let layer = doc.add_layer(Some(name));
        let n = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), red(), Paint::None);
        doc.insert(Some(layer), usize::MAX, n).unwrap();
        // A hidden object, so the layer also gets a hidden layer named after it.
        let mut hidden = shape(&mut doc, shapes::rectangle(Rect::new(50.0, 10.0, 80.0, 40.0)), red(), Paint::None);
        hidden.visible = false;
        doc.insert(Some(layer), usize::MAX, hidden).unwrap();
        write(&doc)
    };
    let out = layered("\u{b808}\u{c774}\u{c5b4} 1 Caf\u{e9}");
    let text = String::from_utf8_lossy(&out.bytes);
    assert!(text.contains("(??? 1 Caf\\351) Ln"), "{text}");
    assert!(text.contains("(??? 1 Caf\\351 \\(hidden\\)) Ln"), "{text}");
    assert!(out.warnings.iter().any(|w| w == LAYER_NAME), "{:?}", out.warnings);
    // A name Latin-1 can hold is written as it is, with no warning.
    assert!(!layered("Caf\u{e9}").warnings.iter().any(|w| w == LAYER_NAME));
}

/// Type written as outlines writes its colour bitmap glyphs (emoji) as images where they sit.
#[test]
fn colour_bitmap_glyphs_of_outlined_type_are_images() {
    use vectorcraft_doc::{CharStyle, TextObject};
    use vectorcraft_text::test_fonts::{COLOUR_CHAR, colour_bitmap_family, colour_bitmap_font};
    vectorcraft_text::FontDb::global().add_font(colour_bitmap_font(false).unwrap());
    let mut doc = Document::new(200.0, 100.0);
    let st = CharStyle { font_family: colour_bitmap_family(false).into(), size: 32.0, ..CharStyle::default() };
    // Cyrillic, which 8-bit text can't hold: the type is written as outlines.
    let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), &format!("{COLOUR_CHAR}\u{416}"), st);
    let l = doc.layers[0].id;
    let id = doc.alloc_id();
    doc.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
    let text = String::from_utf8(write(&doc).bytes).unwrap();
    let images = rasters(&text);
    assert_eq!(images.len(), 1, "{text}");
    assert!(images[0][2].ends_with(" ] 0 0 16 16 16 16 8 3 0 0 0 0 XI"), "{:?}", images[0]);
}

#[test]
fn colr_glyphs_of_outlined_type_are_vector_art() {
    use vectorcraft_doc::{CharStyle, TextObject};
    use vectorcraft_text::test_fonts::{COLOUR_CHAR, colr_family, colr_font};
    vectorcraft_text::FontDb::global().add_font(colr_font(false).unwrap());
    let mut doc = Document::new(200.0, 100.0);
    let st = CharStyle { font_family: colr_family(false).into(), size: 32.0, ..CharStyle::default() };
    // Cyrillic, which 8-bit text can't hold: the type is written as outlines.
    let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), &format!("{COLOUR_CHAR}\u{416}"), st);
    let l = doc.layers[0].id;
    let id = doc.alloc_id();
    doc.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
    let text = String::from_utf8(write(&doc).bytes).unwrap();
    assert!(rasters(&text).is_empty(), "no images: {text}");
    assert!(text.contains("1 0 0 Xa"), "the red layer: {text}");
}

/// An instance stained blue by its fill writes its symbol's red art in blue, as the canvas draws it.
#[test]
fn a_stained_instance_is_written_in_its_stained_color() {
    let mut doc = Document::new(200.0, 100.0);
    let art = shape(&mut doc, shapes::rectangle(Rect::new(0.0, 0.0, 40.0, 40.0)), red(), Paint::None);
    doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) });
    let mut n = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((50.0, 30.0)) });
    n.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into();
    let l = doc.layers[0].id;
    doc.insert(Some(l), 0, n).unwrap();
    let text = String::from_utf8(write(&doc).bytes).unwrap();
    assert!(text.contains("0 0 1 Xa") && !text.contains("1 0 0 Xa"), "{text}");
}

/// A graph whose records read back whole is written with them (§17), and opens again as the same
/// live graph: its table, type and settings, its series' groups tagged in order, without a warning
/// about graphs.
#[test]
fn graphs_are_written_with_their_records_and_open_live() {
    use crate::ai_graph::sample;
    for (what, doc) in sample::kept() {
        let out = write(&doc);
        assert!(!out.warnings.iter().any(|w| w == GRAPHS), "{what}: {:?}", out.warnings);
        let text = String::from_utf8(out.bytes.clone()).unwrap();
        assert_eq!((text.matches("%_Gs\n").count(), text.matches("%_GS\n").count()), (1, 1), "{what}: {text}");
        let read = crate::import(&out.bytes).unwrap();
        let written = sample::graphs(&doc);
        let graphs = sample::graphs(&read.document);
        assert_eq!(graphs.len(), 1, "{what}: {:?}", read.warnings);
        assert!(sample::same(&written[0].0, &graphs[0].0), "{what}: {:#?}\n{:#?}", written[0].0, graphs[0].0);
        assert_eq!(graphs[0].1, written[0].1, "{what}: the members and their series");
    }
}

/// A graph inside a group is written with its records too, and opens on its own group.
#[test]
fn a_graph_in_a_group_is_written_with_its_records() {
    use crate::ai_graph::sample;
    let mut doc = Document::new(400.0, 300.0);
    let graph = sample::graph(&mut doc, sample::spec(vectorcraft_doc::GraphKind::Column));
    let frame = shape(&mut doc, shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), red(), Paint::None);
    let outer = Node::group(doc.alloc_id(), vec![Arc::new(frame), Arc::new(graph)]);
    let l = doc.layers[0].id;
    doc.insert(Some(l), 0, outer).unwrap();
    let out = write(&doc);
    assert!(!out.warnings.iter().any(|w| w == GRAPHS), "{:?}", out.warnings);
    let read = crate::import(&out.bytes).unwrap();
    let graphs = sample::graphs(&read.document);
    assert_eq!(graphs.len(), 1, "{:?}", read.warnings);
    assert!(sample::same(&sample::graphs(&doc)[0].0, &graphs[0].0));
    let layer = children(&read.document.layers[0]);
    assert!(layer[0].extras().graph.is_none() && layer[0].children().is_some_and(|c| c.len() == 2), "{layer:#?}");
}

/// A graph whose records wouldn't read back as it is is written as its art, without records, with
/// the warning, and opens as that art.
#[test]
fn graphs_the_records_cant_keep_are_written_as_their_art() {
    use crate::ai_graph::sample;
    for (what, doc) in sample::unkept() {
        let out = export_legacy_ai(&doc, &LegacyAiOptions::default()).unwrap();
        assert!(out.warnings.iter().any(|w| w == GRAPHS), "{what}: {:?}", out.warnings);
        let text = String::from_utf8_lossy(&out.bytes).into_owned();
        assert!(!text.contains("%_Gs") && !text.contains(" Go\n") && !text.contains("%_GS"), "{what}: {text}");
        let read = crate::import(&out.bytes).unwrap();
        assert!(sample::graphs(&read.document).is_empty(), "{what}");
        let paths = |d: &Document| {
            let mut count = 0;
            d.walk(|n| count += usize::from(matches!(n.kind, NodeKind::Path { .. })));
            count
        };
        assert_eq!(paths(&read.document), paths(&doc), "{what}: the graph's art is kept");
    }
}