GitCorner

Code

ossartcraftdesigncraft🌐
88f5a00e389b
//! Text Wrap › Contour › Alpha Channel: the outline of a placed raster's visible pixels.
//!
//! The outline is traced once per image and threshold, in the image's pixel space, and kept on
//! the document ([`designcraft_doc::AlphaOutline`]). Composition maps it through the graphic's
//! current transform, so it follows the image when it is moved, scaled or refitted.
use std::collections::BTreeSet;
use std::sync::Arc;

use designcraft_doc::{AlphaOutline, AssetData, AssetId, ContourType, Document, Item, WrapMode};
use designcraft_geom::{BezPath, PathData, Point};

/// Images larger than this many pixels aren't traced (their contour follows the frame).
const MAX_PIXELS: u64 = 40_000_000;
/// The finest grid an outline is traced on; coarser grids when the outline would be too long.
const MAX_GRID: u32 = 256;
/// Boundary edges an outline may have.
const MAX_EDGES: usize = 1 << 16;

/// Trace the outlines new Alpha Channel contours need and drop the ones nothing uses. Cheap when
/// nothing changed: tracing happens only for an image and threshold not seen before.
pub(crate) fn sync(doc: &mut Document) {
    let mut wanted: BTreeSet<(AssetId, u8)> = BTreeSet::new();
    // Every frame, in groups and Paste Into containers too, with the wrap set on the frame or on
    // its placed graphic (Direct Selection sets the graphic's).
    let mut want = |it: &Item| {
        let Some(g) = it.graphic() else { return };
        for w in [&it.wrap, &g.wrap] {
            if w.mode == WrapMode::Contour && w.contour == ContourType::AlphaChannel {
                wanted.insert((g.asset, w.alpha_threshold));
            }
        }
    };
    for sp in doc.spreads.iter().chain(doc.parents.iter()) {
        for top in &sp.items {
            top.walk(&mut want);
        }
    }
    // Objects anchored in text wrap the lines after their anchor; anchored_items lists their
    // children too.
    if doc.has_anchored_items() {
        for (_, it) in doc.anchored_items() {
            want(it);
        }
    }
    if wanted.is_empty() && doc.alpha_outlines.is_empty() {
        return;
    }
    // An outline traced from data the asset no longer has (relinked or updated) is traced again.
    let assets = &doc.assets;
    doc.alpha_outlines.retain(|o| wanted.contains(&(o.asset, o.threshold)) && assets.get(&o.asset).is_some_and(|a| o.traced_from(&a.data)));
    let traced: BTreeSet<(AssetId, u8)> = doc.alpha_outlines.iter().map(|o| (o.asset, o.threshold)).collect();
    let kept = doc.alpha_outlines.len();
    for (asset, threshold) in wanted {
        if traced.contains(&(asset, threshold)) {
            continue;
        }
        let Some(a) = doc.assets.get(&asset).filter(|a| a.is_raster()) else { continue };
        // An image with no outline (unreadable, too large) is remembered as an empty
        // one, so later edits don't decode it again; the contour is then the frame's.
        // A linked image's original is not read here (a document opens without reading its
        // links): its preview is traced, scaled to the original's size; with no preview, the
        // image has no outline yet and is traced once its bytes are resident.
        let o = if a.data.is_linked() && a.data.resident().is_none() {
            let Some(proxy) = a.proxy.as_ref().and_then(|p| Some((p.data.load().ok()?, a.pixels?))) else { continue };
            trace_bytes(&proxy.0, a.data.key(), Some(proxy.1), asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold))
        } else {
            trace(&a.data, asset, threshold).unwrap_or_else(|| no_outline(&a.data, asset, threshold))
        };
        doc.alpha_outlines.push(Arc::new(o));
    }
    // `Document::alpha_outline` finds an outline by binary search.
    if doc.alpha_outlines.len() > kept {
        doc.alpha_outlines.sort_by_key(|o| (o.asset, o.threshold));
    }
}

/// The empty outline standing for an image `trace` found none in: zero-size, which composition
/// takes as no outline, and dropped like a traced one when the asset's data changes.
fn no_outline(data: &AssetData, asset: AssetId, threshold: u8) -> AlphaOutline {
    AlphaOutline {
        asset,
        threshold,
        width: 0,
        height: 0,
        outer: Default::default(),
        holes: Default::default(),
        source: data.key(),
        serial: AlphaOutline::next_serial(),
    }
}

/// The outline of the pixels of `data` more opaque than `threshold`: an image with no
/// transparency gives its rectangle. None for an image that can't be read or is too large.
pub(crate) fn trace(data: &AssetData, asset: AssetId, threshold: u8) -> Option<AlphaOutline> {
    trace_bytes(&data.load().ok()?, data.key(), None, asset, threshold)
}

/// [`trace`] of encoded `bytes` standing for the data under `source`. With `size`, the outline
/// is scaled to an image of that size (a preview traced for the original it stands for).
fn trace_bytes(bytes: &[u8], source: designcraft_doc::SourceKey, size: Option<(u32, u32)>, asset: AssetId, threshold: u8) -> Option<AlphaOutline> {
    let (w, h) = designcraft_images::pixel_size(bytes)?;
    if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_PIXELS {
        return None;
    }
    let img = designcraft_images::decode_rgba(bytes)?;
    if img.width() != w || img.height() != h {
        return None;
    }
    let mut grid = MAX_GRID;
    // The previous grid's mask: a grid half as fine is made from it without reading the pixels again.
    let mut finer: Option<(Vec<bool>, u32, u32)> = None;
    while grid >= 16 {
        let (cols, rows) = (w.min(grid), h.min(grid));
        let mask = match finer.as_ref().and_then(|(m, fc, fr)| coarsen(m, *fc, *fr, cols, rows)) {
            Some(m) => m,
            None => occupancy(img.as_raw(), w, h, cols, rows, threshold),
        };
        // Composition follows an outline of at most MAX_CONTOUR_POINTS path elements (holes
        // included, for Include Inside Edges): a ring of k points is k + 1 elements with its close.
        let fits = |outer: &[Vec<(i32, i32)>], holes: &[Vec<(i32, i32)>]| {
            outer.iter().chain(holes).map(|r| r.len() + 1).sum::<usize>() <= designcraft_compose::MAX_CONTOUR_POINTS
        };
        if let Some((outer, holes)) = rings(&mask, cols as usize, rows as usize).filter(|(o, h)| fits(o, h)) {
            let (tw, th) = size.filter(|&(a, b)| a > 0 && b > 0).unwrap_or((w, h));
            let (sx, sy) = (f64::from(tw) / f64::from(cols), f64::from(th) / f64::from(rows));
            let path = |rings: &[Vec<(i32, i32)>]| {
                let mut p = BezPath::new();
                for ring in rings {
                    let mut pts = ring.iter().map(|&(x, y)| Point::new(f64::from(x) * sx, f64::from(y) * sy));
                    let Some(first) = pts.next() else { continue };
                    p.move_to(first);
                    for q in pts {
                        p.line_to(q);
                    }
                    p.close_path();
                }
                PathData::from_bezpath(&p)
            };
            let serial = AlphaOutline::next_serial();
            return Some(AlphaOutline { asset, threshold, width: tw, height: th, outer: path(&outer), holes: path(&holes), source, serial });
        }
        finer = Some((mask, cols, rows));
        grid /= 2;
    }
    None
}

/// The `cols` × `rows` mask made from a `fc` × `fr` one, when each side has the same number of
/// cells or twice as many (a pixel's coarse cell is then its fine cell, or half of it). None
/// otherwise: the pixels are read again.
fn coarsen(mask: &[bool], fc: u32, fr: u32, cols: u32, rows: u32) -> Option<Vec<bool>> {
    let step = |fine: u32, coarse: u32| match fine {
        f if f == coarse => Some(1),
        f if u64::from(f) == 2 * u64::from(coarse) => Some(2),
        _ => None,
    };
    let (sx, sy) = (step(fc, cols)?, step(fr, rows)?);
    let (fc, cols) = (fc as usize, cols as usize);
    let mut out = vec![false; cols * rows as usize];
    for (i, _) in mask.iter().enumerate().filter(|(_, v)| **v) {
        let (x, y) = (i % fc, i / fc);
        if let Some(c) = out.get_mut(y / sy * cols + x / sx) {
            *c = true;
        }
    }
    Some(out)
}

/// Which cells of a `cols` × `rows` grid hold a pixel of the `w` × `h` RGBA image `rgba` more
/// opaque than `threshold` (a cell is visible when any of its pixels is).
fn occupancy(rgba: &[u8], w: u32, h: u32, cols: u32, rows: u32, threshold: u8) -> Vec<bool> {
    let mut mask = vec![false; (cols as usize) * (rows as usize)];
    // A pixel's cell is (x * cols / w, y * rows / h). Along a row the column is counted up as x
    // passes each cell's edge (cols <= w, so at most one edge per pixel) instead of divided out.
    for (y, row) in rgba.chunks_exact(w as usize * 4).take(h as usize).enumerate() {
        let base = (y as u64 * u64::from(rows) / u64::from(h)) as usize * cols as usize;
        let (mut gx, mut acc, mut edge) = (0usize, 0u64, u64::from(w));
        for px in row.as_chunks::<4>().0 {
            if acc >= edge {
                gx += 1;
                edge += u64::from(w);
            }
            acc += u64::from(cols);
            if px[3] > threshold
                && let Some(c) = mask.get_mut(base + gx)
            {
                *c = true;
            }
        }
    }
    mask
}

/// The closed boundaries of the visible cells, split into outer boundaries and the boundaries of
/// holes (by winding: each boundary keeps the visible cells on the same side). None when the
/// outline would have more than [`MAX_EDGES`] edges.
#[allow(clippy::type_complexity)]
fn rings(mask: &[bool], cols: usize, rows: usize) -> Option<(Vec<Vec<(i32, i32)>>, Vec<Vec<(i32, i32)>>)> {
    use std::collections::BTreeMap;
    let visible = |x: i32, y: i32| {
        x >= 0 && y >= 0 && (x as usize) < cols && (y as usize) < rows && mask.get(y as usize * cols + x as usize).copied().unwrap_or(false)
    };
    let mut edges: BTreeMap<(i32, i32), Vec<(i32, i32)>> = BTreeMap::new();
    let mut count = 0usize;
    for y in 0..rows as i32 {
        for x in 0..cols as i32 {
            if !visible(x, y) {
                continue;
            }
            for (open, a, b) in [
                (!visible(x, y - 1), (x, y), (x + 1, y)),
                (!visible(x + 1, y), (x + 1, y), (x + 1, y + 1)),
                (!visible(x, y + 1), (x + 1, y + 1), (x, y + 1)),
                (!visible(x - 1, y), (x, y + 1), (x, y)),
            ] {
                if open {
                    count += 1;
                    if count > MAX_EDGES {
                        return None;
                    }
                    edges.entry(a).or_default().push(b);
                }
            }
        }
    }
    let (mut outer, mut holes) = (Vec::new(), Vec::new());
    while let Some((&start, _)) = edges.first_key_value() {
        let mut ring = vec![start];
        let mut at = start;
        for _ in 0..=MAX_EDGES {
            let next = edges.get_mut(&at).and_then(Vec::pop)?;
            if edges.get(&at).is_some_and(Vec::is_empty) {
                edges.remove(&at);
            }
            // Drop the middle of straight runs.
            if let [.., a, b] = ring[..]
                && (b.0 - a.0) * (next.1 - b.1) == (b.1 - a.1) * (next.0 - b.0)
            {
                ring.pop();
            }
            if next == start {
                break;
            }
            ring.push(next);
            at = next;
        }
        // Shoelace in y-down space: positive for outer boundaries, negative for holes.
        let area: i64 = ring
            .iter()
            .zip(ring.iter().cycle().skip(1))
            .map(|(&(x0, y0), &(x1, y1))| i64::from(x0) * i64::from(y1) - i64::from(x1) * i64::from(y0))
            .sum();
        if ring.len() >= 3 {
            if area > 0 { outer.push(ring) } else { holes.push(ring) }
        }
    }
    Some((outer, holes))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    use crate::Session;

    /// A 64 × 64 PNG: visible where `on(x, y)`.
    fn png(on: impl Fn(usize, usize) -> bool) -> Vec<u8> {
        png_sized(64, on)
    }

    /// A `size` × `size` PNG: visible where `on(x, y)`.
    fn png_sized(size: usize, on: impl Fn(usize, usize) -> bool) -> Vec<u8> {
        let mut pixels = vec![0; size * size * 4];
        for y in 0..size {
            for x in 0..size {
                let i = (y * size + x) * 4;
                pixels[i] = 120;
                pixels[i + 3] = if on(x, y) { 255 } else { 0 };
            }
        }
        designcraft_render::Rendered { width: size as u32, height: size as u32, pixels }.to_png()
    }

    /// An outline too detailed for composition (here 4,096 separate dots, 20,480 path elements
    /// on the finest grid) is traced on a coarser grid until composition can follow it.
    #[test]
    fn a_fragmented_outline_is_traced_coarser_until_composition_can_follow_it() {
        let dots = png_sized(256, |x, y| x % 4 == 0 && y % 4 == 0);
        let o = trace(&AssetData::embedded(dots), AssetId(1), 25).unwrap();
        let elements = o.outer.to_bezpath().elements().len() + o.holes.to_bezpath().elements().len();
        assert!(elements > 0 && elements <= designcraft_compose::MAX_CONTOUR_POINTS, "{elements} path elements");
    }

    /// An image with no pixel more opaque than the threshold leaves the text alone: with the
    /// frame's contour the caption over it is overset, with Alpha Channel it is set.
    #[test]
    fn an_image_with_nothing_visible_wraps_no_text() {
        let (mut s, image, story) = page(&png(|_, _| false), [150.0, 150.0, 178.0, 178.0]);
        assert!(overset(&s, story), "the frame's contour covers the caption");
        s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
        assert!(!overset(&s, story), "nothing visible: nothing wraps");
        // The same for the wrap set on the placed graphic.
        s.execute("object.textWrap", &json!({"ids": [image], "mode": "none"})).unwrap();
        s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap();
        assert!(!overset(&s, story));
    }

    #[test]
    fn traces_outer_boundaries_and_holes_apart() {
        // A ring: a square with a square hole.
        let data = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y)));
        let o = trace(&AssetData::embedded(data), AssetId(1), 25).unwrap();
        assert_eq!((o.width, o.height), (64, 64));
        assert_eq!((o.outer.subpaths.len(), o.holes.subpaths.len()), (1, 1));
        let (a, b) = (o.outer.bounds().unwrap(), o.holes.bounds().unwrap());
        assert_eq!((a.x0, a.y0, a.x1, a.y1), (8.0, 8.0, 56.0, 56.0));
        assert_eq!((b.x0, b.y0, b.x1, b.y1), (24.0, 24.0, 40.0, 40.0));
        // An opaque image's outline is its rectangle.
        let o = trace(&AssetData::embedded(png(|_, _| true)), AssetId(1), 25).unwrap();
        let a = o.outer.bounds().unwrap();
        assert_eq!((a.x0, a.y0, a.x1, a.y1, o.holes.subpaths.len()), (0.0, 0.0, 64.0, 64.0, 0));
    }

    /// The cell masks match a pixel-by-pixel count (cell = x * cols / w, y * rows / h), and a
    /// mask half as fine made from the finer one matches the mask read from the pixels.
    #[test]
    fn cell_masks_match_the_pixels_and_coarser_masks_match_the_finer_ones() {
        let (w, h) = (600u32, 300u32);
        // An irregular pattern: visible where a small hash says so.
        let on = |x: u32, y: u32| (x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)).rotate_left(7).is_multiple_of(7);
        let mut rgba = vec![0u8; (w * h * 4) as usize];
        for y in 0..h {
            for x in 0..w {
                rgba[((y * w + x) * 4 + 3) as usize] = if on(x, y) { 255 } else { 0 };
            }
        }
        for (cols, rows) in [(256, 256), (128, 128), (100, 37), (600, 300)] {
            let mut expect = vec![false; (cols * rows) as usize];
            for y in 0..h {
                for x in 0..w {
                    if on(x, y) {
                        expect[((y * rows / h) * cols + x * cols / w) as usize] = true;
                    }
                }
            }
            assert_eq!(occupancy(&rgba, w, h, cols, rows, 25), expect, "{cols} x {rows}");
        }
        let fine = occupancy(&rgba, w, h, 256, 256, 25);
        assert_eq!(coarsen(&fine, 256, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25)));
        // Same count on one side, twice on the other.
        let fine = occupancy(&rgba, w, h, 128, 256, 25);
        assert_eq!(coarsen(&fine, 128, 256, 128, 128), Some(occupancy(&rgba, w, h, 128, 128, 25)));
        // Any other ratio is read from the pixels.
        assert_eq!(coarsen(&fine, 128, 256, 100, 128), None);
    }

    #[test]
    fn an_alpha_channel_contour_is_traced_when_set_and_kept_out_of_the_saved_file() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let data = png(|x, _| (16..48).contains(&x));
        let id = s
            .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
            .unwrap()["id"]
            .clone();
        assert!(s.doc().unwrap().doc.alpha_outlines.is_empty());
        s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap();
        let d = &s.doc().unwrap().doc;
        assert_eq!(d.alpha_outlines.len(), 1);
        // Saved and opened again: traced again on open.
        let bytes = crate::cmd::file::to_bytes(d).unwrap();
        let back = crate::cmd::file::from_bytes(&bytes).unwrap();
        assert!(back.alpha_outlines.is_empty(), "not saved");
        let st = crate::DocState::new(back, None);
        assert_eq!(st.doc.alpha_outlines.len(), 1, "traced on open");
        // Wrap off: the outline goes.
        s.execute("object.textWrap", &json!({"ids": [id], "mode": "none"})).unwrap();
        assert!(s.doc().unwrap().doc.alpha_outlines.is_empty());
    }

    /// An outline is traced once: later edits keep it.
    #[test]
    fn an_outline_is_not_traced_on_every_edit() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let data = png(|_, _| true);
        let id = s
            .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "solid.png", "x": 100, "y": 100, "width": 128}))
            .unwrap()["id"]
            .clone();
        s.execute("object.textWrap", &json!({"ids": [id], "mode": "contour", "contour": "alphaChannel"})).unwrap();
        let first = s.doc().unwrap().doc.alpha_outlines.clone();
        assert_eq!(first.len(), 1, "remembered");
        s.execute("frame.create", &json!({"rect": [300, 300, 350, 350]})).unwrap();
        let after = &s.doc().unwrap().doc.alpha_outlines;
        assert!(Arc::ptr_eq(&first[0], &after[0]), "kept, not traced again");
    }

    /// An opaque image's Alpha Channel contour is its rectangle, not the frame: moved within its
    /// frame, it leaves the empty part of the frame to the text.
    #[test]
    fn an_opaque_image_wraps_its_rectangle() {
        let (mut s, image, story) = page(&png(|_, _| true), [105.0, 150.0, 125.0, 178.0]);
        s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
        assert!(overset(&s, story), "the image covers the caption");
        // The graphic moved 30 pt right within its frame: the frame's left 30 pt are empty.
        s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap();
        s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap();
        assert!(!overset(&s, story), "the empty part of the frame takes the caption");
    }

    /// Outlines are traced for a wrap set on the placed graphic and for frames inside groups, and
    /// traced again when the image's data changes under the same asset (relink, link update).
    #[test]
    fn graphic_wraps_nested_frames_and_relinked_images_get_outlines() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let place = |s: &mut Session, x: u64| {
            let data = png(|x, _| (16..48).contains(&x));
            s.execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": x, "y": 100, "width": 128}))
                .unwrap()["id"]
                .as_u64()
                .unwrap()
        };
        let image = place(&mut s, 100);
        // The wrap on the graphic (Direct Selection), not the frame.
        s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel"})).unwrap();
        let frame_wrap = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).unwrap().wrap.mode;
        assert_eq!(frame_wrap, WrapMode::None, "the frame has no wrap of its own");
        assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1, "traced for the graphic's wrap");
        // In a group with another frame: still traced.
        let other = s.execute("frame.create", &json!({"rect": [300, 100, 350, 150]})).unwrap()["id"].as_u64().unwrap();
        s.execute("object.group", &json!({"ids": [image, other]})).unwrap();
        let d = &s.doc().unwrap().doc;
        assert!(d.find(designcraft_doc::ItemId(image)).unwrap().path.len() > 1, "the frame is nested");
        assert_eq!(d.alpha_outlines.len(), 1, "a nested frame keeps its outline");
        // A frame placed and grouped before its wrap is set: traced too.
        let second = place(&mut s, 400);
        let other2 = s.execute("frame.create", &json!({"rect": [600, 100, 650, 150]})).unwrap()["id"].as_u64().unwrap();
        s.execute("object.group", &json!({"ids": [second, other2]})).unwrap();
        s.execute("object.textWrap", &json!({"ids": [second], "mode": "contour", "contour": "alphaChannel", "threshold": 200})).unwrap();
        assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 2);
        // The image data replaced under the same asset, as a relink does: traced again.
        let Some(designcraft_doc::Content::Graphic(g)) = s.doc().unwrap().doc.item(designcraft_doc::ItemId(image)).map(|it| it.content.clone())
        else {
            panic!("a graphic")
        };
        let narrower = AssetData::embedded(png(|x, _| (24..40).contains(&x)));
        s.edit(|d, _| {
            let a = d.assets.get(&g.asset).unwrap();
            let mut a = (**a).clone();
            a.data = narrower.clone();
            d.assets.insert(g.asset, Arc::new(a));
            Ok(())
        })
        .unwrap();
        let d = &s.doc().unwrap().doc;
        let o = d.alpha_outline(g.asset, designcraft_doc::DEFAULT_ALPHA_THRESHOLD).unwrap();
        assert!(o.traced_from(&narrower));
        let b = o.outer.bounds().unwrap();
        assert_eq!((b.x0, b.x1), (24.0, 40.0), "the new image's outline");
    }

    /// An outline traced after others is still found: a threshold lower than a kept outline's
    /// is traced later and must not hide either outline from the lookup.
    #[test]
    fn outlines_traced_later_are_found_by_image_and_threshold() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let data = png(|x, _| (16..48).contains(&x));
        let image = s
            .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
            .unwrap()["id"]
            .as_u64()
            .unwrap();
        s.execute("object.textWrap", &json!({"ids": [image], "content": true, "mode": "contour", "contour": "alphaChannel", "threshold": 200}))
            .unwrap();
        s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap();
        let d = &s.doc().unwrap().doc;
        assert_eq!(d.alpha_outlines.len(), 2, "one outline for each threshold");
        let Some(g) = d.item(designcraft_doc::ItemId(image)).and_then(|it| it.graphic()) else { panic!("a graphic") };
        for threshold in [designcraft_doc::DEFAULT_ALPHA_THRESHOLD, 200] {
            let o = d.alpha_outline(g.asset, threshold);
            assert!(o.is_some_and(|o| o.threshold == threshold), "the outline at {threshold} is found");
        }
        assert!(d.alpha_outline(g.asset, 100).is_none(), "no outline at a threshold nothing uses");
    }

    /// A wrap with the default threshold saves as it did before thresholds were stored; another
    /// threshold is saved.
    #[test]
    fn the_default_threshold_is_left_out_of_a_saved_wrap() {
        let v = serde_json::to_value(designcraft_doc::TextWrap::default()).unwrap();
        assert!(v.get("alphaThreshold").is_none(), "{v}");
        let back: designcraft_doc::TextWrap = serde_json::from_value(v).unwrap();
        assert_eq!(back.alpha_threshold, designcraft_doc::DEFAULT_ALPHA_THRESHOLD);
        let w = designcraft_doc::TextWrap { alpha_threshold: 200, ..Default::default() };
        assert_eq!(serde_json::to_value(w).unwrap()["alphaThreshold"], 200);
    }

    /// A relink that changes only the image data recomposes the text around the new outline.
    #[test]
    fn text_is_composed_again_around_a_relinked_images_outline() {
        let (mut s, image, story) = page(&png(|x, _| x < 32), [180.0, 150.0, 220.0, 178.0]);
        s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
        assert!(!overset(&s, story), "the left half is visible: the caption on the right is set");
        let Some(designcraft_doc::Content::Graphic(g)) =
            s.doc().unwrap().doc.item(designcraft_doc::ItemId(image.as_u64().unwrap())).map(|it| it.content.clone())
        else {
            panic!("a graphic")
        };
        let right = AssetData::embedded(png(|x, _| x >= 32));
        s.edit(|d, _| {
            let mut a = (**d.assets.get(&g.asset).unwrap()).clone();
            a.data = right.clone();
            d.assets.insert(g.asset, Arc::new(a));
            Ok(())
        })
        .unwrap();
        assert!(overset(&s, story), "the right half is visible now: it covers the caption");
    }

    /// An image anchored in text keeps its outline: anchored objects wrap the lines after their
    /// anchor, and they are kept in the story, not on the spread.
    #[test]
    fn an_anchored_image_keeps_its_outline() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let data = png(|x, _| (16..48).contains(&x));
        let image = s
            .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(&data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
            .unwrap()["id"]
            .as_u64()
            .unwrap();
        s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "contour": "alphaChannel"})).unwrap();
        assert_eq!(s.doc().unwrap().doc.alpha_outlines.len(), 1);
        let t = s.execute("frame.create", &json!({"rect": [36, 300, 400, 500], "content": "text", "text": "Before after."})).unwrap();
        s.execute("anchored.insert", &json!({"ids": [image], "story": t["story"], "pos": 7})).unwrap();
        let d = &s.doc().unwrap().doc;
        assert!(d.anchored_item(designcraft_doc::ItemId(image)).is_some(), "the image is in the text");
        assert_eq!(d.alpha_outlines.len(), 1, "the anchored image keeps its outline");
    }

    /// An image placed 128 pt wide at (100, 100) (2 pt per pixel), its wrap a contour with no
    /// offset, and a caption frame at `caption` with 8 pt "Hi".
    fn page(data: &[u8], caption: [f64; 4]) -> (Session, Value, u64) {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let image = s
            .execute("file.place", &json!({"base64": crate::cmd::file::base64_encode(data), "name": "cut.png", "x": 100, "y": 100, "width": 128}))
            .unwrap()["id"]
            .clone();
        let c = s.execute("frame.create", &json!({"rect": caption, "content": "text", "text": "Hi"})).unwrap();
        s.execute("selection.set", &json!({"ids": [c["id"]]})).unwrap();
        s.execute("type.char", &json!({"size": 8})).unwrap();
        s.execute("object.textWrap", &json!({"ids": [image], "mode": "contour", "offset": 0})).unwrap();
        (s, image, c["story"].as_u64().unwrap())
    }

    fn overset(s: &Session, story: u64) -> bool {
        s.cache.get(&s.doc().unwrap().doc, designcraft_doc::StoryId(story), None).is_overset()
    }

    use serde_json::Value;

    /// A caption fits between two legs of a cutout, and the contour follows the image when it's
    /// moved within its frame (it isn't a boundary stored where it was traced).
    #[test]
    fn an_alpha_channel_contour_keeps_gaps_open_and_follows_the_image() {
        // Legs at pixels 8..20 and 44..56: 116..140 and 188..212 on the page.
        let (mut s, image, story) = page(&png(|x, _| (8..20).contains(&x) || (44..56).contains(&x)), [150.0, 120.0, 178.0, 170.0]);
        assert!(overset(&s, story), "the frame's contour covers the gap");
        s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
        assert!(!overset(&s, story), "the gap between the legs stays open");
        // The graphic moved 30 pt right within its frame: its left leg now covers the caption.
        s.execute("selection.set", &json!({"ids": [image], "content": true})).unwrap();
        s.execute("transform.move", &json!({"dx": 30, "dy": 0})).unwrap();
        assert!(overset(&s, story), "the contour moved with the image");
        s.execute("edit.undo", &json!({})).unwrap();
        assert!(!overset(&s, story));
    }

    /// A hole enclosed by the image stays blocked unless Include Inside Edges is on.
    #[test]
    fn holes_are_blocked_unless_inside_edges_are_included() {
        // A ring: outer 116..212, hole 148..180 on the page.
        let ring = png(|x, y| (8..56).contains(&x) && (8..56).contains(&y) && !((24..40).contains(&x) && (24..40).contains(&y)));
        let (mut s, image, story) = page(&ring, [152.0, 152.0, 176.0, 176.0]);
        s.execute("object.textWrap", &json!({"ids": [image], "contour": "alphaChannel"})).unwrap();
        assert!(overset(&s, story), "the hole is blocked with the ring around it");
        s.execute("object.textWrap", &json!({"ids": [image], "insideEdges": true})).unwrap();
        assert!(!overset(&s, story), "Include Inside Edges lets text into the hole");
        for bad in [json!({"ids": [image], "threshold": 255}), json!({"ids": [image], "insideEdges": 1})] {
            assert!(s.execute("object.textWrap", &bad).is_err());
        }
    }
}