GitCorner

Code

ossartcraftphotocraft🌐
856f865cf98d
use super::*;
use photocraft_geom::Rect;

fn session(w: u32, h: u32, depth: u64, mode: &str) -> Session {
    let mut s = Session::new();
    s.execute("file.new", json!({"width": w, "height": h, "depth": depth, "mode": mode})).unwrap();
    paint(&mut s, |x, y| [x as f32 / w as f32, y as f32 / h as f32, 0.5, 1.0]);
    s
}

fn paint(s: &mut Session, f: impl Fn(i32, i32) -> [f32; 4]) {
    s.edit("setup", |doc, active| {
        let b = doc.bounds();
        let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
        let fmt = surf.format();
        let mut data = Vec::new();
        for y in b.y0..b.y1 {
            for x in b.x0..b.x1 {
                data.extend(photocraft_raster::from_rgba(&fmt, f(x, y)));
            }
        }
        surf.write_region(b, &data);
        Ok(())
    })
    .unwrap();
}

fn doc(s: &Session) -> &Document {
    &s.active().unwrap().doc
}

fn colours(d: &Document) -> std::collections::HashSet<[u8; 3]> {
    let surf = d.layers[0].surface().unwrap();
    let mut set = std::collections::HashSet::new();
    for y in 0..d.size.height as i32 {
        for x in 0..d.size.width as i32 {
            let c = surf.rgba(x, y);
            if c[3] > 0.0 {
                set.insert([c[0], c[1], c[2]].map(|v| (v * 255.0).round() as u8));
            }
        }
    }
    set
}

#[test]
fn rotate_arbitrary_grows_canvas_and_keeps_background() {
    for depth in [8, 16, 32] {
        let mut s = session(40, 20, depth, "rgb");
        s.execute("layer.new.layer", json!({})).unwrap();
        paint(&mut s, |x, y| if (15..25).contains(&x) && (5..15).contains(&y) { [1.0, 0.0, 0.0, 1.0] } else { [0.0; 4] });
        s.execute("tools.setColors", json!({"background": "#00ff00"})).unwrap();
        let r = s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw"})).unwrap();
        assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(20), Some(40)));
        let d = doc(&s);
        assert_eq!(d.layers[0].name, "Background");
        // The red square stays centred.
        assert!(d.layers[1].surface().unwrap().rgba(10, 20)[0] > 0.9, "{depth}");
        s.execute("edit.undo", json!({})).unwrap();
        s.execute("image.rotation.arbitrary", json!({"angle": 30, "direction": "ccw"})).unwrap();
        let d = doc(&s);
        assert_eq!(d.size, rotated_size(Size::new(40, 20), 30.0));
        assert!(d.size.width > 40 && d.size.height > 20);
        // Exposed corners take the background colour on the Background layer.
        let corner = d.layers[0].surface().unwrap().rgba(0, 0);
        assert!(corner[1] > 0.9 && corner[0] < 0.1, "{corner:?}");
    }
    let mut s = session(10, 10, 8, "rgb");
    assert!(s.execute("image.rotation.arbitrary", json!({"angle": 10, "direction": "up"})).is_err());
    let n = s.active().unwrap().history.past_len();
    s.execute("image.rotation.arbitrary", json!({"angle": 360})).unwrap();
    assert_eq!(s.active().unwrap().history.past_len(), n, "a full turn changes nothing");
}

#[test]
fn rotate_arbitrary_other_modes() {
    for mode in ["gray", "cmyk", "lab"] {
        let mut s = session(16, 12, 16, mode);
        s.execute("image.rotation.arbitrary", json!({"angle": 45})).unwrap();
        assert_eq!(doc(&s).size, rotated_size(Size::new(16, 12), 45.0), "{mode}");
    }
}

#[test]
fn rotate_arbitrary_keeps_the_background_opaque_with_a_translucent_background_colour() {
    let mut s = session(40, 20, 8, "rgb");
    s.execute("tools.setColors", json!({"background": "#00ff0080"})).unwrap();
    s.execute("image.rotation.arbitrary", json!({"angle": 30})).unwrap();
    let corner = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
    assert_eq!(corner, [0.0, 1.0, 0.0, 1.0], "the uncovered corner is opaque background colour");
}

#[test]
fn rotate_arbitrary_keeps_the_full_precision_angle() {
    // Rounded to f32 this angle crosses a whole pixel: 1003 px instead of 1002, so a rotated crop
    // that sized its canvas with `rotated_size` at f64 would land 1 px off.
    let angle = 0.114_706_514_493_370_71;
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 1000, "height": 1000})).unwrap();
    let r = s.execute("image.rotation.arbitrary", json!({"angle": angle})).unwrap();
    assert_eq!(rotated_size(Size::new(1000, 1000), angle), Size::new(1002, 1002));
    assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(1002), Some(1002)));
}

#[test]
fn rotate_arbitrary_rotates_grouped_locked_children_and_preserves_lock() {
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap();
    s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap();
    s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
    s.execute("layer.setProps", json!({"locks": {"position": true}})).unwrap();
    s.execute("layer.groupLayers", json!({})).unwrap();

    // 1. 30 degree rotation succeeds and canvas grows to 22x22.
    let r30 = s.execute("image.rotation.arbitrary", json!({"angle": 30, "interpolation": "nearest"})).unwrap();
    assert_eq!((r30["width"].as_u64(), r30["height"].as_u64()), (Some(22), Some(22)));

    // 2. Child remains position-locked after canvas rotation.
    let d = doc(&s);
    let group = &d.layers[1];
    let photocraft_doc::LayerContent::Group(g) = &group.content else { panic!("expected group") };
    assert_eq!(g.children.len(), 1);
    let child = &g.children[0];
    assert_eq!(child.name, "Paint");
    assert!(child.locks.position, "position lock must be preserved on child");

    // 3. Free Transform of the child alone still refuses with lock error.
    let child_id = child.id.0;
    s.execute("layer.select", json!({"layer": child_id})).unwrap();
    let err = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 0, 0]})).unwrap_err();
    assert!(err.to_string().contains("locked"), "child Free Transform must remain refused");

    // 4. Undo restores 16x16 size.
    s.execute("edit.undo", json!({})).unwrap();
    assert_eq!(doc(&s).size, Size::new(16, 16));

    // 5. 90 degree rotation also succeeds and composite matches dedicated 90cw turn.
    let r90 = s.execute("image.rotation.arbitrary", json!({"angle": 90, "direction": "cw", "interpolation": "nearest"})).unwrap();
    assert_eq!((r90["width"].as_u64(), r90["height"].as_u64()), (Some(16), Some(16)));
    let d_arb = doc(&s).clone();
    s.execute("edit.undo", json!({})).unwrap();
    s.execute("image.imageRotation.90cw", json!({})).unwrap();
    let d_cw = doc(&s);
    assert_eq!(photocraft_compose::flatten(&d_arb).px, photocraft_compose::flatten(d_cw).px);
}

/// Rotating the whole image turns every layer mask, linked or not, as Rotate 180° does (#9201).
/// Image Rotation › Arbitrary turns the pixels of type in a font that isn't installed instead of
/// re-rendering it in a substitute face (#8860), inside groups too. Type in an installed font
/// still re-renders.
#[test]
fn rotate_arbitrary_keeps_the_pixels_of_type_in_a_missing_font() {
    for depth in [8, 16, 32] {
        for (font, kept) in [("No Such Font 8860", true), ("", false)] {
            let mut s = Session::new();
            s.execute("file.new", json!({"width": 100, "height": 60, "depth": depth})).unwrap();
            let cache = s
                .edit("type", |doc, _| {
                    let mut t = photocraft_doc::TextLayer { text: "Hello!".into(), font_family: font.into(), size_pt: 26.0, ..Default::default() };
                    t.transform = Affine::translate(10.0, 40.0);
                    // Deliberately not what PhotoCraft would draw, so a re-render shows.
                    let fmt = doc.pixel_format();
                    let mut cache = Surface::new(fmt);
                    cache.fill_rect(Rect::new(10, 20, 90, 40), &photocraft_raster::from_rgba(&fmt, [0.4, 0.2, 0.6, 1.0]));
                    t.cache = Some(cache.clone());
                    let ty = Layer::new("Hello!", LayerContent::Text(t));
                    doc.insert_above(None, Layer::group("Group", vec![ty]));
                    Ok(cache)
                })
                .unwrap();
            s.execute("image.rotation.arbitrary", json!({"angle": 30, "interpolation": "bilinear"})).unwrap();
            let LayerContent::Group(g) = &doc(&s).layers.last().unwrap().content else { panic!("group") };
            let LayerContent::Text(t) = &g.children[0].content else { panic!("type layer") };
            // The edit's map: 30° clockwise about the centres of the old and new canvases.
            let new = doc(&s).size;
            let (sn, cs) = 30f64.to_radians().sin_cos();
            let (nx, ny) = (f64::from(new.width) / 2.0, f64::from(new.height) / 2.0);
            let a = [cs, sn, -sn, cs, nx - (cs * 50.0 - sn * 30.0), ny - (sn * 50.0 + cs * 30.0)];
            let h = Homography([a[0], a[2], a[4], a[1], a[3], a[5], 0.0, 0.0, 1.0]);
            let turned = photocraft_algo::transform::warp_surface(&cache, cache.content_bounds(), &h, Interp::Bilinear).unwrap();
            assert_eq!(t.cache.as_ref() == Some(&turned), kept, "font {font:?}, depth {depth}");
        }
    }
}

#[test]
fn rotate_arbitrary_turns_unlinked_layer_masks() {
    for depth in [8, 16] {
        for grouped in [false, true] {
            let mut s = Session::new();
            s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth, "background": "white"})).unwrap();
            s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap();
            s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
            s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
            s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
            s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap();
            let id = s.active().unwrap().active_layer.unwrap();
            if grouped {
                s.execute("layer.groupLayers", json!({})).unwrap();
            }
            let mask = |s: &Session| doc(s).layer(id).unwrap().mask.clone().unwrap();
            let base = s.active().unwrap().doc.clone();
            s.execute("image.rotation.arbitrary", json!({"angle": 180, "interpolation": "nearest"})).unwrap();
            let m = mask(&s);
            assert!(!m.linked);
            let at = |x, y| m.surface.sample_channel(x, y, 0);
            assert!(at(34, 24) > 0.9, "{depth}-bit, grouped {grouped}: the mask turned with its layer");
            assert!(at(4, 4) < 0.1, "{depth}-bit, grouped {grouped}: nothing left at the old place");
            // Rotate 180° and a crop turned by 180° over the whole canvas give the same mask.
            for (id_, p) in [("image.imageRotation.180", json!({})), ("image.crop", json!({"x": 0, "y": 0, "width": 40, "height": 30, "angle": 180}))] {
                s.active_mut().unwrap().doc = base.clone();
                s.execute(id_, p).unwrap();
                let turned = mask(&s);
                for y in 0..30 {
                    for x in 0..40 {
                        let (a, b) = (at(x, y), turned.surface.sample_channel(x, y, 0));
                        assert!((a - b).abs() < 1e-3, "{id_}, {depth}-bit, grouped {grouped}: ({x},{y}) {a} vs {b}");
                    }
                }
            }
            // 90° pins the direction too (180° is its own inverse).
            s.active_mut().unwrap().doc = base.clone();
            s.execute("image.rotation.arbitrary", json!({"angle": 90, "interpolation": "nearest"})).unwrap();
            let arbitrary = mask(&s);
            s.active_mut().unwrap().doc = base.clone();
            s.execute("image.imageRotation.90cw", json!({})).unwrap();
            let turned = mask(&s);
            for y in 0..40 {
                for x in 0..30 {
                    let (a, b) = (arbitrary.surface.sample_channel(x, y, 0), turned.surface.sample_channel(x, y, 0));
                    assert!((a - b).abs() < 1e-3, "90cw, {depth}-bit, grouped {grouped}: ({x},{y}) {a} vs {b}");
                }
            }
        }
    }
}

#[test]
fn flattened_mode_pixels_match_the_allocating_conversion_at_every_channel_count() {
    let px = [[0.0, 0.25, 0.75, 0.0], [0.9, 0.3, 0.2, 0.2], [0.1, 0.7, 0.4, 0.7], [1.0; 4]];
    for mode in [ColorMode::Indexed, ColorMode::Bitmap, ColorMode::Duotone] {
        let mut document = Document::with_background("mode", Size::new(2, 2), ColorMode::Rgb, SampleType::F32, photocraft_doc::Color::WHITE);
        let mut active = None;
        single_layer(&mut document, &mut active, mode, &px, "result", false);
        let fmt = document.pixel_format();
        let mut expected = Surface::new(fmt);
        let converted: Vec<f32> = px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect();
        expected.write_region(document.bounds(), &converted);
        let actual = document.layers[0].surface().unwrap();
        assert_eq!(actual.to_interleaved(document.bounds()), expected.to_interleaved(document.bounds()), "{mode:?}");
        assert_eq!(document.depth, SampleType::U8);
        assert_eq!(active, Some(document.layers[0].id));
    }
}

#[test]
fn indexed_color_rejects_invalid_counts_without_editing_the_document() {
    let mut s = session(12, 12, 16, "rgb");
    let before = s.active().unwrap().history.past_len();
    for colors in [json!(16.5), json!(0), json!(1), json!(257), json!(512), json!(-2), json!("16"), json!(null), json!(true), json!([]), json!(1e100)] {
        assert!(s.execute("image.mode.indexedColor", json!({"colors": colors})).is_err(), "{colors}");
        assert_eq!(s.active().unwrap().history.past_len(), before);
        assert_eq!((doc(&s).mode, doc(&s).depth), (ColorMode::Rgb, SampleType::U16));
    }
    s.execute("image.mode.indexedColor", json!({"colors": 17.0})).unwrap();
    assert!(doc(&s).color_table.as_ref().unwrap().colors.len() <= 17);
}

#[test]
fn indexed_color_palettes_and_dithers() {
    for palette in ["selective", "perceptual", "adaptive", "web", "uniform", "systemMac", "systemWindows"] {
        for dither in ["none", "diffusion", "pattern", "noise"] {
            let mut s = session(24, 16, 16, "rgb");
            let r = s.execute("image.mode.indexedColor", json!({"palette": palette, "colors": 16, "dither": dither, "forced": "none"})).unwrap();
            let d = doc(&s);
            assert_eq!((d.mode, d.depth), (ColorMode::Indexed, SampleType::U8), "{palette} {dither}");
            let table = d.color_table.as_ref().unwrap();
            assert_eq!(table.colors.len() as u64, r["colors"].as_u64().unwrap());
            let used = colours(d);
            assert!(used.iter().all(|c| table.colors.contains(c)), "{palette} {dither}: pixels off the table");
            if !matches!(palette, "web" | "systemMac" | "systemWindows") {
                assert!(table.colors.len() <= 16, "{palette}: {}", table.colors.len());
            }
        }
    }
}

#[test]
fn indexed_exact_preserves_profile_and_samples_through_default_rgb() {
    for depth in [8, 16, 32] {
        for profile in ["adobe-rgb-compat", "display-p3", "prophoto-compat", "none"] {
            let mut s = Session::new();
            s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
            s.execute("edit.assignProfile", json!({"profile": profile})).unwrap();
            paint(&mut s, |_, _| [100.0 / 255.0, 150.0 / 255.0, 200.0 / 255.0, 1.0]);
            let source_profile = doc(&s).icc_profile.clone();
            s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap();
            assert_eq!(doc(&s).icc_profile, source_profile, "{profile} at {depth}-bit: Indexed profile");
            assert_eq!(doc(&s).color_table.as_ref().unwrap().colors, vec![[100, 150, 200]]);
            let indexed_pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
            s.execute("image.mode.rgb", json!({})).unwrap();
            assert_eq!(doc(&s).mode, ColorMode::Rgb);
            assert_eq!(doc(&s).icc_profile, source_profile, "{profile} at {depth}-bit: RGB profile");
            assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), indexed_pixel);
            assert!(doc(&s).color_table.is_none());
            s.execute("edit.undo", json!({})).unwrap();
            assert_eq!(doc(&s).mode, ColorMode::Indexed);
            assert_eq!(doc(&s).icc_profile, source_profile);
            s.execute("edit.redo", json!({})).unwrap();
            assert_eq!(doc(&s).mode, ColorMode::Rgb);
            assert_eq!(doc(&s).icc_profile, source_profile);
            s.execute("edit.undo", json!({})).unwrap();
            s.execute("image.mode.rgb", json!({"profile": "srgb"})).unwrap();
            assert_eq!(doc(&s).icc_profile, Some(craft_cms::Builtin::Srgb.profile().to_bytes()), "an explicit target still converts");
            if profile != "none" {
                assert_ne!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), indexed_pixel);
            }
        }
    }
}

#[test]
fn indexed_matte_blends_edges_without_replacing_clear_pixels() {
    for depth in [8, 16, 32] {
        for (matte, color) in [
            ("black", [0.0, 0.0, 0.0]),
            ("white", [1.0, 1.0, 1.0]),
            ("#0000ff", [0.0, 0.0, 1.0]),
            ("foreground", [0.0, 0.0, 1.0]),
            ("background", [0.0, 1.0, 0.0]),
        ] {
            let mut s = Session::new();
            s.execute("file.new", json!({"width": 4, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
            s.execute("tools.setColors", json!({"foreground": "#0000ff", "background": "#00ff00"})).unwrap();
            paint(&mut s, |x, _| match x {
                0 => [0.0, 1.0, 0.0, 1.0],
                1 => [1.0, 0.0, 0.0, 0.75],
                2 => [1.0, 0.0, 0.0, 0.25],
                _ => [0.0; 4],
            });
            let source = [1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0));
            let expected = source.map(|pixel| [0, 1, 2].map(|i| pixel[i] * pixel[3] + color[i] * (1.0 - pixel[3])));
            s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
            let surface = doc(&s).layers[0].surface().unwrap();
            let edges = [1, 2].map(|x| surface.rgba(x, 0));
            for (edge, expected) in edges.iter().zip(expected) {
                for i in 0..3 {
                    assert!((edge[i] - expected[i]).abs() <= 1.0 / 255.0, "{depth}-bit {matte}: {edge:?} vs {expected:?}");
                }
                assert_eq!(edge[3], 1.0);
            }
            assert_eq!(surface.rgba(3, 0)[3], 0.0, "{matte}: fully transparent pixels stay clear");
            assert_eq!(surface.rgba(0, 0), [0.0, 1.0, 0.0, 1.0]);
            s.execute("edit.undo", json!({})).unwrap();
            assert_eq!([1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)), source);
            s.execute("edit.redo", json!({})).unwrap();
            assert_eq!([1, 2].map(|x| doc(&s).layers[0].surface().unwrap().rgba(x, 0)), edges);
        }
    }
}

#[test]
fn indexed_matte_converts_working_rgb_to_document_profile_at_every_depth() {
    use craft_cms::Transform;

    for depth in [8, 16, 32] {
        for (matte, color) in [("foreground", [0.0, 1.0, 0.0]), ("background", [1.0, 0.0, 0.0])] {
            for (intent, bpc) in [("relative", false), ("absolute", true)] {
                let mut s = Session::new();
                s.execute("edit.colorSettings", json!({"workingRgb": "display-p3", "intent": intent, "bpc": bpc})).unwrap();
                s.execute("file.new", json!({"width": 2, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
                s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
                s.execute("tools.setColors", json!({"foreground": "#00ff00", "background": "#ff0000"})).unwrap();
                paint(&mut s, |x, _| if x == 0 { [1.0, 0.0, 0.0, 0.5] } else { [0.0; 4] });
                let pixel = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
                let profile = doc(&s).icc_profile.clone();
                let source = s.color.working(ColorMode::Rgb);
                let destination = crate::color_cmds::document_profile(doc(&s));
                let transform = Transform::new(&source, &destination, s.color.settings.intent(), bpc).unwrap();
                let mut converted = [0.0; 16];
                transform.eval(&color, &mut converted).unwrap();
                let expected = [0, 1, 2].map(|i| ((pixel[i] * pixel[3] + converted[i].clamp(0.0, 1.0) * (1.0 - pixel[3])) * 255.0).round() as u8);
                s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
                let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
                assert_eq!([edge[0], edge[1], edge[2]].map(|v| (v * 255.0).round() as u8), expected, "{depth}-bit {matte} {intent}, bpc={bpc}");
                assert_eq!(edge[3], 1.0);
                assert_eq!(doc(&s).icc_profile, profile);
                assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(1, 0)[3], 0.0);
            }
        }
    }
}

#[test]
fn indexed_matte_hex_stays_in_document_rgb_coordinates() {
    for depth in [8, 16, 32] {
        let mut s = Session::new();
        s.execute("file.new", json!({"width": 1, "height": 1, "depth": depth, "background": "transparent"})).unwrap();
        s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap();
        paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]);
        s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": "#3366cc"})).unwrap();
        let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
        let expected = [0.5 + 0.5 * 0.2, 0.5 * 0.4, 0.5 * 0.8];
        for (got, want) in edge[..3].iter().zip(expected) {
            assert!((got - want).abs() <= 2.0 / 255.0, "{depth}-bit: {edge:?} vs {expected:?}");
        }
        assert_eq!(edge[3], 1.0);
    }
}

#[test]
fn indexed_matte_named_gray_choices_use_their_document_samples() {
    for (matte, channel) in [("gray", 128.0 / 255.0), ("netscapeGray", 192.0 / 255.0)] {
        let mut s = Session::new();
        s.execute("file.new", json!({"width": 1, "height": 1, "depth": 32, "background": "transparent"})).unwrap();
        paint(&mut s, |_, _| [1.0, 0.0, 0.0, 0.5]);
        s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "matte": matte})).unwrap();
        let edge = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
        assert!((edge[0] - (0.5 + channel * 0.5)).abs() <= 1.0 / 255.0, "{matte}: {edge:?}");
        for value in edge[1..3].iter() {
            assert!((*value - channel * 0.5).abs() <= 2.0 / 255.0, "{matte}: {edge:?}");
        }
        assert_eq!(edge[3], 1.0);
    }
}

#[test]
fn indexed_matte_without_transparency_fills_clear_pixels_and_rejects_bad_input_atomically() {
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 2, "height": 1, "background": "transparent"})).unwrap();
    let before = s.active().unwrap().revision;
    for matte in [json!(false), json!(12), json!("#gg0000"), json!("#000000ff"), json!("unknown")] {
        assert!(s.execute("image.mode.indexedColor", json!({"matte": matte})).is_err(), "{matte}");
        assert_eq!(s.active().unwrap().revision, before);
        assert_eq!(doc(&s).mode, ColorMode::Rgb);
    }
    s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false, "matte": "#0000ff"})).unwrap();
    assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), [0.0, 0.0, 1.0, 1.0]);
    assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, None);
}

#[test]
fn indexed_exact_transparency_and_sources() {
    // Two colours + transparency: exact palette with a transparent entry.
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap();
    paint(&mut s, |x, _| {
        if x < 3 {
            [1.0, 0.0, 0.0, 1.0]
        } else if x < 6 {
            [0.0, 0.0, 1.0, 1.0]
        } else {
            [0.0; 4]
        }
    });
    s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none"})).unwrap();
    let d = doc(&s);
    let t = d.color_table.as_ref().unwrap();
    assert_eq!(t.colors.len(), 3);
    assert_eq!(t.transparent, Some(2));
    assert_eq!(d.layers[0].name, "Index");
    assert_eq!(d.layers[0].surface().unwrap().rgba(7, 0)[3], 0.0);
    // Exact fails on a gradient.
    let mut s = session(64, 64, 8, "rgb");
    assert!(s.execute("image.mode.indexedColor", json!({"palette": "exact"})).is_err());
    // Gray, CMYK and Lab sources flatten through the composite.
    for mode in ["gray", "cmyk", "lab"] {
        let mut s = session(12, 12, 16, mode);
        s.execute("image.mode.indexedColor", json!({"colors": 8})).unwrap();
        assert_eq!(doc(&s).mode, ColorMode::Indexed, "{mode}");
    }
    // Back to RGB drops the table.
    s.execute("image.mode.indexedColor", json!({"colors": 8})).unwrap();
    s.execute("image.mode.rgb", json!({})).unwrap();
    assert!(doc(&s).color_table.is_none());
    s.execute("edit.undo", json!({})).unwrap();
    assert!(doc(&s).color_table.is_some());
}

#[test]
fn color_table_presets_and_entries() {
    let mut s = session(16, 16, 8, "rgb");
    assert!(!s.is_enabled("image.mode.colorTable"));
    s.execute("image.mode.indexedColor", json!({"palette": "uniform", "colors": 8, "dither": "none", "forced": "none"})).unwrap();
    let before = doc(&s).color_table.clone().unwrap();
    // No changes: a report, no history step.
    let n = s.active().unwrap().history.past_len();
    let r = s.execute("image.mode.colorTable", json!({})).unwrap();
    assert_eq!(r["colors"].as_array().unwrap().len(), before.colors.len());
    assert_eq!(s.active().unwrap().history.past_len(), n);
    // Replace entry 0: pixels of index 0 change colour.
    let px0 = doc(&s).layers[0].surface().unwrap().rgba(0, 0);
    let i0 = before.nearest([px0[0], px0[1], px0[2]]);
    s.execute("image.mode.colorTable", json!({"entries": {i0.to_string(): "#ff00ff"}})).unwrap();
    assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(0, 0), [1.0, 0.0, 1.0, 1.0]);
    s.execute("image.mode.colorTable", json!({"table": "blackBody"})).unwrap();
    assert_eq!(doc(&s).color_table.as_ref().unwrap().colors.len(), 256);
    s.execute("image.mode.colorTable", json!({"transparent": 0})).unwrap();
    assert!(s.execute("image.mode.colorTable", json!({"table": "nope"})).is_err());
    assert!(s.execute("image.mode.colorTable", json!({"entries": {"999": "#000000"}})).is_err());
}

#[test]
fn clearing_color_table_transparency_restores_indexed_pixels() {
    let pixel = |s: &mut Session| -> [f32; 4] { serde_json::from_value(s.execute("document.pixel", json!({"x": 5, "y": 8})).unwrap()).unwrap() };
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap();
    s.execute("image.mode.indexedColor", json!({"palette": "exact", "colors": 2, "forced": "none", "dither": "none"})).unwrap();
    assert_eq!(doc(&s).color_table.as_ref().unwrap().colors, vec![[255, 0, 0]]);
    assert_eq!(pixel(&mut s), [1.0, 0.0, 0.0, 1.0]);

    s.execute("image.mode.colorTable", json!({"transparent": 0})).unwrap();
    assert_eq!(pixel(&mut s), [0.0; 4]);
    s.execute("image.mode.colorTable", json!({"transparent": null})).unwrap();
    assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(5, 8), [1.0, 0.0, 0.0, 1.0], "clearing the transparent palette entry should restore the stored pixel");
    assert_eq!(pixel(&mut s), [1.0, 0.0, 0.0, 1.0]);
    s.execute("image.mode.rgb", json!({})).unwrap();
    assert_eq!(pixel(&mut s), [1.0, 0.0, 0.0, 1.0]);

    let mut control = Session::new();
    control.execute("file.new", json!({"width": 16, "height": 16, "background": "#ff0000"})).unwrap();
    control.execute("image.mode.indexedColor", json!({"palette": "exact", "colors": 2, "forced": "none", "dither": "none"})).unwrap();
    control.execute("image.mode.colorTable", json!({"entries": {"0": "#0000ff"}})).unwrap();
    let blue: [f32; 4] = serde_json::from_value(control.execute("document.pixel", json!({"x": 5, "y": 8})).unwrap()).unwrap();
    assert_eq!(blue, [0.0, 0.0, 1.0, 1.0]);
    control.execute("image.mode.colorTable", json!({"transparent": 0})).unwrap();
    control.execute("edit.undo", json!({})).unwrap();
    let restored: [f32; 4] = serde_json::from_value(control.execute("document.pixel", json!({"x": 5, "y": 8})).unwrap()).unwrap();
    assert_eq!(restored, [0.0, 0.0, 1.0, 1.0]);
}

#[test]
fn bitmap_methods_need_grayscale() {
    let mut s = session(32, 32, 16, "rgb");
    assert!(!s.is_enabled("image.mode.bitmap"));
    s.execute("image.mode.grayscale", json!({})).unwrap();
    for method in ["threshold", "pattern", "diffusion", "halftone"] {
        s.execute("image.mode.bitmap", json!({"method": method, "frequency": 12, "shape": "diamond"})).unwrap();
        let d = doc(&s);
        assert_eq!((d.mode, d.depth), (ColorMode::Bitmap, SampleType::U8), "{method}");
        let surf = d.layers[0].surface().unwrap();
        for y in 0..32 {
            for x in 0..32 {
                let v = surf.pixel(x, y)[0];
                assert!(v == 0.0 || v == 1.0, "{method}: {v}");
            }
        }
        s.execute("edit.undo", json!({})).unwrap();
    }
    assert!(s.execute("image.mode.bitmap", json!({"method": "nope"})).is_err());
    // An unlisted halftone shape is a bad-params error, not a silent Round (#507).
    assert!(s.execute("image.mode.bitmap", json!({"method": "halftone", "shape": "hexagon"})).is_err());
    assert_eq!(doc(&s).mode, ColorMode::Grayscale);
    for shape in ["round", "ellipse", "line", "square", "diamond", "cross"] {
        s.execute("image.mode.bitmap", json!({"method": "halftone", "shape": shape})).unwrap();
        s.execute("edit.undo", json!({})).unwrap();
    }
}

#[test]
fn bitmap_halftone_rejects_bad_angles_and_frequencies_without_editing_the_document() {
    // Photoshop's Halftone Screen takes an angle in -180..180 degrees (#4214): 1e39 used to become
    // inf, then NaN in the screen rotation, and an almost white bitmap landed in history.
    let mut s = session(16, 16, 8, "grayscale");
    let before = s.active().unwrap().history.past_len();
    let bad = [
        ("angle", json!(1e39)),
        ("angle", json!(500)),
        ("angle", json!(-181)),
        ("angle", json!(180.01)),
        ("angle", json!("x")),
        ("frequency", json!("x")),
        ("frequency", json!(true)),
    ];
    for (key, value) in bad {
        let mut p = json!({"method": "halftone"});
        p[key] = value.clone();
        assert!(s.execute("image.mode.bitmap", p).is_err(), "{key}: {value}");
        assert_eq!(s.active().unwrap().history.past_len(), before, "{key}: {value}");
        assert_eq!(doc(&s).mode, ColorMode::Grayscale, "{key}: {value}");
    }
    for angle in [-180.0, 30.0, 180.0] {
        s.execute("image.mode.bitmap", json!({"method": "halftone", "angle": angle})).unwrap();
        assert_eq!(doc(&s).mode, ColorMode::Bitmap, "{angle}");
        s.execute("edit.undo", json!({})).unwrap();
    }
    // Frequency stays clamped to the documented 1..999 lines/inch.
    s.execute("image.mode.bitmap", json!({"method": "halftone", "frequency": 1e39})).unwrap();
    assert_eq!(doc(&s).mode, ColorMode::Bitmap);
}

/// A grayscale document `w` x `h` whose column x holds the 8-bit level `x` (a 0..255 ramp).
fn ramp(w: u32, h: u32, depth: u64, dpi: f32) -> Session {
    let mut s = session(w, h, depth, "grayscale");
    paint(&mut s, |x, _| [x as f32 / 255.0, x as f32 / 255.0, x as f32 / 255.0, 1.0]);
    s.edit("dpi", |doc, _| {
        doc.resolution_dpi = dpi;
        Ok(())
    })
    .unwrap();
    s
}

/// The first column of row `y` whose pixel is white among columns `x % m == k`.
fn first_white(d: &Document, y: i32, m: i32, k: i32) -> Option<i32> {
    let surf = d.layers[0].surface().unwrap();
    (0..d.size.width as i32).filter(|x| x % m == k).find(|x| surf.pixel(*x, y)[0] > 0.5)
}

fn add_pattern(s: &mut Session, name: &str, w: u32, h: u32, levels: &[u8]) {
    let mut surf = photocraft_raster::Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false));
    let data: Vec<f32> = levels.iter().map(|v| f32::from(*v) / 255.0).collect();
    surf.write_region(Rect::new(0, 0, w as i32, h as i32), &data);
    let pat = photocraft_doc::pattern::Pattern::new(name, surf, w, h);
    s.edit("pattern", |doc, _| {
        doc.patterns.push(pat);
        Ok(())
    })
    .unwrap();
}

#[test]
/// Compare cross-band Bitmap thresholds with independent full-pattern ranks, including shared tie ranks.
fn bitmap_custom_pattern_ranks_across_row_bands() {
    let mut s = session(1, 1, 8, "grayscale");
    let levels: Vec<u8> = (0..2 * 513).map(|i| [220, 40, 120][(i / 257) % 3]).collect();
    add_pattern(&mut s, "Across bands", 2, 513, &levels);
    let (map, w, h) = custom_pattern_map(&s, "image.mode.bitmap", &json!({"pattern": "Across bands"})).unwrap();
    assert_eq!((w, h), (2, 513));
    for (&value, &level) in map.iter().zip(&levels) {
        let less = levels.iter().filter(|v| **v < level).count();
        let equal = levels.iter().filter(|v| **v == level).count();
        let expected = 1. - (less as f32 + equal as f32 / 2.) / levels.len() as f32;
        assert_eq!(value, expected);
    }
}

#[test]
/// Accept a paintable compact pattern beyond the dense RGBA cap and retain its global threshold ordering.
fn bitmap_custom_pattern_accepts_compact_pattern_past_full_rgba_limit() {
    let mut s = session(1, 1, 8, "grayscale");
    let (w, h) = (4097u32, 4096u32);
    let mut surface = photocraft_raster::Surface::new(PixelFormat::RGBA8);
    surface.write_pixel(0, 0, &[0., 0., 0., 1.]);
    surface.write_pixel(w as i32 - 1, h as i32 - 1, &[0., 0., 0., 1.]);
    let pattern = photocraft_doc::Pattern { id: "compact".into(), name: "Compact".into(), width: w, height: h, surface };
    assert!(pattern.is_paintable());
    assert!(pattern.pixel_count() * 16 > photocraft_doc::pattern::MAX_WORKING_BYTES);
    s.edit("pattern", |doc, _| {
        doc.patterns.push(pattern);
        Ok(())
    })
    .unwrap();
    let (map, mw, mh) = custom_pattern_map(&s, "image.mode.bitmap", &json!({"pattern": "compact"})).unwrap();
    assert_eq!((mw, mh), (w as usize, h as usize));
    assert_eq!(map.len(), mw * mh);
    let n = map.len() as f32;
    assert_eq!(map[0], 1. - 1. / n);
    assert_eq!(*map.last().unwrap(), map[0]);
    assert!((map[1] - (0.5 - 1. / n)).abs() < 1e-7);
}

/// Refuse ranking workspace before expanding a sparse, otherwise paintable large pattern.
#[test]
fn bitmap_custom_pattern_rejects_excessive_ranking_workspace_before_reading_pixels() {
    let mut s = session(1, 1, 8, "grayscale");
    let pattern = photocraft_doc::Pattern {
        id: "large-rank".into(),
        name: "Large rank".into(),
        width: 6000,
        height: 5000,
        surface: photocraft_raster::Surface::new(PixelFormat::RGBA8),
    };
    assert!(pattern.is_paintable());
    s.edit("pattern", |doc, _| {
        doc.patterns.push(pattern);
        Ok(())
    })
    .unwrap();
    let error = custom_pattern_map(&s, "image.mode.bitmap", &json!({"pattern": "large-rank"})).unwrap_err();
    assert!(error.to_string().contains("threshold ranking exceeds the 256 MiB"), "{error}");
}

#[test]
fn bitmap_output_resolution_resamples_and_sets_the_resolution() {
    // Photoshop: a 256 x 4 ramp at 72 ppi converted with Output 144 ppi is 512 x 8 at 144 ppi,
    // its 50% threshold at column 256; at 36 ppi it is 128 x 2, the threshold at column 64.
    for depth in [8, 16] {
        let mut s = ramp(256, 4, depth, 72.0);
        let r = s.execute("image.mode.bitmap", json!({"method": "threshold", "resolution": 144})).unwrap();
        assert_eq!(r, json!({"width": 512, "height": 8, "resolution": 144.0}), "{depth}");
        let d = doc(&s);
        assert_eq!((d.size.width, d.size.height, d.resolution_dpi, d.mode), (512, 8, 144.0, ColorMode::Bitmap), "{depth}");
        assert!(first_white(d, 3, 1, 0).is_some_and(|x| (255..=257).contains(&x)), "{depth}: {:?}", first_white(d, 3, 1, 0));
        // One step back is the grayscale document at its own size and resolution.
        s.execute("edit.undo", json!({})).unwrap();
        let d = doc(&s);
        assert_eq!((d.size.width, d.size.height, d.resolution_dpi, d.mode), (256, 4, 72.0, ColorMode::Grayscale), "{depth}");
        s.execute("image.mode.bitmap", json!({"method": "diffusion", "resolution": 36})).unwrap();
        assert_eq!((doc(&s).size.width, doc(&s).size.height, doc(&s).resolution_dpi), (128, 2, 36.0), "{depth}");
    }
    // Without `resolution`, the input resolution: the size stays.
    let mut s = ramp(256, 4, 8, 300.0);
    s.execute("image.mode.bitmap", json!({"method": "threshold"})).unwrap();
    assert_eq!((doc(&s).size.width, doc(&s).resolution_dpi), (256, 300.0));
    assert_eq!(first_white(doc(&s), 0, 1, 0), Some(128));
}

/// #9212: the Output resolution resamples the pixels outside the canvas too. A 10 px crop that
/// kept a 1000 px document's pixels, converted from 1 to 100 ppi, would grow them to 100000 px a
/// side (20 GB of gray and alpha at 8 bits, past the 8 GiB budget): refused before allocating.
#[test]
fn bitmap_output_resolution_budgets_the_hidden_pixels() {
    let mut s = ramp(1000, 1000, 8, 1.0);
    s.execute("image.crop", json!({"x": 0, "y": 0, "width": 10, "height": 10, "deleteCroppedPixels": false})).unwrap();
    let err = s.execute("image.mode.bitmap", json!({"method": "threshold", "resolution": 100})).unwrap_err().to_string();
    assert!(err.contains("100000 x 100000 px is 10000 megapixels"), "{err}");
    assert_eq!((doc(&s).size.width, doc(&s).mode), (10, ColorMode::Grayscale));
}

#[test]
fn bitmap_halftone_screen_is_laid_out_at_the_output_resolution() {
    // The same 10 lines/inch screen has twice the cell (in pixels) at twice the resolution: the
    // output equals the 72 ppi screen of the image upsampled first.
    let mut a = ramp(64, 64, 8, 72.0);
    a.execute("image.mode.bitmap", json!({"method": "halftone", "frequency": 10, "angle": 0, "resolution": 144})).unwrap();
    let mut b = ramp(64, 64, 8, 72.0);
    b.execute("image.imageSize", json!({"resolution": 144, "resample": "bicubic", "keepPrintSize": true})).unwrap();
    b.execute("image.mode.bitmap", json!({"method": "halftone", "frequency": 10, "angle": 0})).unwrap();
    let (da, db) = (doc(&a), doc(&b));
    assert_eq!(da.size, db.size);
    let (sa, sb) = (da.layers[0].surface().unwrap(), db.layers[0].surface().unwrap());
    let r = da.bounds();
    assert_eq!(sa.read_region(r), sb.read_region(r));
}

#[test]
fn bitmap_custom_pattern_thresholds_against_the_tiled_pattern() {
    // Measured in Photoshop on a 0..255 ramp: a 7x1 pattern 0, 40 .. 240 turns column x white
    // from level 237, 201, 164, 128, 92, 55, 19 (by x % 7): the lighter the pattern pixel, the
    // sooner. A 1x3 pattern 30 / 220 / 120 does the same down the rows.
    for depth in [8, 16] {
        let mut s = ramp(256, 3, depth, 72.0);
        add_pattern(&mut s, "Ramp 7", 7, 1, &[0, 40, 80, 120, 160, 200, 240]);
        add_pattern(&mut s, "Rows 3", 1, 3, &[30, 220, 120]);
        let r = s.execute("image.mode.bitmap", json!({"method": "customPattern", "pattern": "Ramp 7"})).unwrap();
        assert_eq!(r["width"], 256);
        let d = doc(&s);
        assert_eq!(d.mode, ColorMode::Bitmap);
        let firsts: Vec<i32> = (0..7).map(|k| first_white(d, 0, 7, k).unwrap()).collect();
        // The first column at or past each level in its residue class.
        let expect: Vec<i32> = [237, 201, 164, 128, 92, 55, 19].iter().enumerate().map(|(k, t)| (k as i32..256).step_by(7).find(|x| x >= t).unwrap()).collect();
        assert_eq!(firsts, expect, "{depth}");
        s.execute("edit.undo", json!({})).unwrap();
        s.execute("image.mode.bitmap", json!({"method": "customPattern", "pattern": "Rows 3"})).unwrap();
        let rows: Vec<i32> = (0..3).map(|y| first_white(doc(&s), y, 1, 0).unwrap()).collect();
        assert_eq!(rows, [213, 43, 128], "{depth}");
    }
}

#[test]
fn bitmap_rejects_bad_resolutions_and_patterns_without_editing_the_document() {
    let mut s = ramp(64, 4, 16, 72.0);
    let before = s.active().unwrap().history.past_len();
    let bad = [
        json!({"resolution": 0}),
        json!({"resolution": -72}),
        json!({"resolution": 0.5}),
        json!({"resolution": 30_001}),
        json!({"resolution": 1e39}),
        json!({"resolution": "high"}),
        json!({"resolution": [72]}),
        json!({"method": "customPattern", "pattern": "no such pattern"}),
        json!({"method": "customPattern", "pattern": 7}),
        json!({"method": "custom"}),
    ];
    for p in bad {
        assert!(s.execute("image.mode.bitmap", p.clone()).is_err(), "{p}");
        assert_eq!(s.active().unwrap().history.past_len(), before, "{p}");
        let d = doc(&s);
        assert_eq!((d.mode, d.size.width, d.resolution_dpi), (ColorMode::Grayscale, 64, 72.0), "{p}");
    }
    // NaN can't be written in JSON; null is "not given" (the input resolution).
    s.execute("image.mode.bitmap", json!({"resolution": null})).unwrap();
    assert_eq!((doc(&s).size.width, doc(&s).resolution_dpi), (64, 72.0));
    s.execute("edit.undo", json!({})).unwrap();
    // The bounds themselves are fine.
    s.execute("image.mode.bitmap", json!({"resolution": 1})).unwrap();
    assert_eq!((doc(&s).size.width, doc(&s).size.height, doc(&s).resolution_dpi), (1, 1, 1.0));
}

#[test]
fn bitmap_output_resolution_budgets_the_whole_conversion_not_just_the_resample() {
    // 100 x 100 px at 1 ppi to 1000 ppi is 100000 x 100000 px: 10 gigapixels. The resampled
    // document and the conversion's 8-bit result at that size are refused before anything is
    // allocated.
    for depth in [8, 16] {
        let mut s = ramp(100, 100, depth, 1.0);
        let before = s.active().unwrap().history.past_len();
        let e = s.execute("image.mode.bitmap", json!({"method": "diffusion", "resolution": 1000})).unwrap_err().to_string();
        assert!(e.contains("megapixels") && e.contains("Output resolution"), "{depth}: {e}");
        assert_eq!(s.active().unwrap().history.past_len(), before, "{depth}");
        let d = doc(&s);
        assert_eq!((d.mode, d.size.width, d.resolution_dpi), (ColorMode::Grayscale, 100, 1.0), "{depth}");
        // A side past the 300,000 px document limit is refused, not clamped (that would change
        // the print size): 20000 px at 72 ppi is 333,333 px at 1200 ppi.
        let mut wide = ramp(20_000, 1, depth, 72.0);
        let e = wide.execute("image.mode.bitmap", json!({"method": "threshold", "resolution": 1200})).unwrap_err().to_string();
        assert!(e.contains("300000 px"), "{depth}: {e}");
        assert_eq!((doc(&wide).mode, doc(&wide).size.width), (ColorMode::Grayscale, 20_000), "{depth}");
        // 18000 px to 300,000 px exactly is allowed.
        let mut edge = ramp(18_000, 1, depth, 72.0);
        edge.execute("image.mode.bitmap", json!({"method": "threshold", "resolution": 1200})).unwrap();
        assert_eq!(doc(&edge).size.width, 300_000, "{depth}");
        // A size that fits is still converted.
        s.execute("image.mode.bitmap", json!({"method": "diffusion", "resolution": 3})).unwrap();
        assert_eq!((doc(&s).size.width, doc(&s).mode), (300, ColorMode::Bitmap), "{depth}");
    }
}

#[test]
fn bitmap_budgets_a_conversion_at_the_document_resolution_too() {
    // #8477: without a resample nothing was budgeted, and a huge document's full-size f32
    // working buffers aborted the app. 60000 x 60000 px (3.6 gigapixels, a plain white
    // background shares one tile) needs more than the 8 GiB budget at any depth: refused.
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 60_000, "height": 60_000, "mode": "grayscale"})).unwrap();
    let before = s.active().unwrap().history.past_len();
    let e = s.execute("image.mode.bitmap", json!({"method": "threshold"})).unwrap_err().to_string();
    assert!(e.contains("megapixels"), "{e}");
    assert_eq!(s.active().unwrap().history.past_len(), before);
    assert_eq!(doc(&s).mode, ColorMode::Grayscale);
}

/// The Bitmap conversion of `d` the pre-#8477 way, from one full-canvas composite over white.
fn bitmap_oracle(d: &Document, method: Option<BitmapMethod>, custom: Option<(&[f32], usize, usize)>) -> Vec<f32> {
    let px = photocraft_compose::flatten(d).over_background([1.0; 3]).into_px();
    let mut gray: Vec<f32> = px.iter().map(|q| photocraft_color::convert::rgb_to_gray([q[0], q[1], q[2]])).collect();
    let w = d.size.width as usize;
    match (method, custom) {
        (_, Some((map, mw, mh))) => quantize::to_bitmap_custom(&mut gray, w, map, mw, mh),
        (Some(m), None) => quantize::to_bitmap(&mut gray, w, m),
        (None, None) => {}
    }
    gray
}

fn bitmap_pixels(d: &Document) -> Vec<f32> {
    let surf = d.layers[0].surface().unwrap();
    let mut out = Vec::new();
    for y in 0..d.size.height as i32 {
        for x in 0..d.size.width as i32 {
            let p = surf.pixel(x, y);
            assert_eq!(p[1], 1.0, "({x}, {y}) is opaque");
            out.push(p[0]);
        }
    }
    out
}

#[test]
fn bitmap_in_bands_matches_one_full_canvas_conversion() {
    // #8477: the composite is converted in bands (32768 px wide: 256 rows each, so 300 rows are
    // two). Diffusion carries its error across the band edge, and pattern, halftone and custom
    // pattern stay anchored to the image's rows: the result equals one full-canvas conversion.
    let (w, h) = (32_768u32, 300u32);
    let mut s = session(w, h, 8, "grayscale");
    paint(&mut s, |x, y| {
        let v = ((x % 509) as f32 / 509.0 * 0.6 + (y as f32 / 300.0) * 0.4).fract();
        [v, v, v, 1.0]
    });
    add_pattern(&mut s, "Cells", 3, 2, &[10, 200, 90, 250, 150, 40]);
    let cases = [
        ("threshold", None, Some(BitmapMethod::Threshold)),
        ("pattern", None, Some(BitmapMethod::Pattern)),
        ("diffusion", None, Some(BitmapMethod::Diffusion)),
        ("halftone", Some(53.0), None),
        ("customPattern", None, None),
    ];
    for (method, freq, m) in cases {
        let before = doc(&s).clone();
        let mut p = json!({"method": method});
        if let Some(f) = freq {
            p["frequency"] = json!(f);
            p["angle"] = json!(30);
            p["shape"] = json!("diamond");
        }
        if method == "customPattern" {
            p["pattern"] = json!("Cells");
        }
        s.execute("image.mode.bitmap", p.clone()).unwrap();
        let want = match method {
            "halftone" => {
                let cell = (before.resolution_dpi / 53.0).max(2.0);
                bitmap_oracle(&before, Some(BitmapMethod::Halftone { cell, angle: 30.0, shape: HalftoneShape::Diamond }), None)
            }
            "customPattern" => {
                let (map, mw, mh) = custom_pattern_map(&s, "t", &p).unwrap();
                bitmap_oracle(&before, None, Some((&map, mw, mh)))
            }
            _ => bitmap_oracle(&before, m, None),
        };
        // Grayscale stores 0/1 the way `from_rgba` turns the old RGBA output into gray.
        let want: Vec<f32> = want.iter().map(|g| photocraft_raster::from_rgba(&storage_format(ColorMode::Bitmap), [*g, *g, *g, 1.0])[0]).collect();
        let got = bitmap_pixels(doc(&s));
        let diff = got.iter().zip(&want).filter(|(a, b)| (**a - **b).abs() > 1e-6).count();
        assert_eq!(diff, 0, "{method}: {diff} of {} pixels differ", got.len());
        s.execute("edit.undo", json!({})).unwrap();
    }
}

#[test]
fn bitmap_lays_a_transparent_composite_over_white() {
    // Transparent pixels flatten over white before the conversion: an empty canvas is white,
    // 25%-opaque black is light (75% gray) and thresholds to white, 75%-opaque black to black.
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 3, "height": 1, "mode": "grayscale", "background": "transparent"})).unwrap();
    paint(&mut s, |x, _| [0.0, 0.0, 0.0, [0.0, 0.25, 0.75][x as usize]]);
    s.execute("image.mode.bitmap", json!({"method": "threshold"})).unwrap();
    assert_eq!(bitmap_pixels(doc(&s)), [1.0, 1.0, 0.0]);
}

#[test]
fn duotone_inks_and_display() {
    let mut s = session(16, 8, 8, "gray");
    paint(&mut s, |x, _| [x as f32 / 15.0; 4].map(|v| v.min(1.0)));
    assert!(s.execute("image.mode.duotone", json!({"type": "quintone"})).is_err());
    let r = s
        .execute(
            "image.mode.duotone",
            json!({"type": "duotone", "inks": [{"name": "Black"}, {"name": "Orange", "color": "#ff8000", "curve": [[0, 0], [100, 80]]}]}),
        )
        .unwrap();
    assert_eq!(r["inks"], json!(["Black", "Orange"]));
    let d = doc(&s);
    assert_eq!(d.mode, ColorMode::Duotone);
    let inks = &d.duotone.as_ref().unwrap().inks;
    assert_eq!(inks[1].curve.last().unwrap().output, 0.8);
    // Display: warm midtones (red > blue) where the gray image is neutral.
    let shown = display_document(d).unwrap();
    let px = photocraft_compose::render(&shown, Rect::from_xywh(8, 4, 1, 1)).px[0];
    assert!(px[0] > px[2] + 0.05, "{px:?}");
    assert!(display_document(&Document::new("x", Size::new(1, 1), ColorMode::Grayscale, SampleType::U8)).is_none());
    // Tritone defaults and leaving the mode.
    s.execute("image.mode.duotone", json!({"type": "tritone"})).unwrap();
    assert_eq!(doc(&s).duotone.as_ref().unwrap().inks.len(), 3);
    s.execute("image.mode.grayscale", json!({})).unwrap();
    assert!(doc(&s).duotone.is_none());
    assert_eq!(doc(&s).mode, ColorMode::Grayscale);
    assert!(!session(4, 4, 8, "rgb").is_enabled("image.mode.duotone"));
}

#[test]
fn duotone_curve_points_must_be_finite() {
    let mut s = session(4, 4, 8, "gray");
    // 1e39 overflows f32 to inf, which the .pcraft writer refuses to save.
    for curve in [json!([[0, 0], [100, 1e39]]), json!([[0, 0], [1e39, 50]]), json!([[-1e39, 0], [100, 100]])] {
        let r = s.execute("image.mode.duotone", json!({"type": "monotone", "inks": [{"curve": curve}]}));
        assert!(r.is_err(), "{curve} accepted");
        assert_eq!(doc(&s).mode, ColorMode::Grayscale);
    }
    s.execute("image.mode.duotone", json!({"type": "monotone", "inks": [{"curve": [[0, 0], [50, 70], [100, 100]]}]})).unwrap();
    assert_eq!(doc(&s).mode, ColorMode::Duotone);
    photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap();
}

#[test]
fn modes_round_trip_through_pcraft() {
    let mut s = session(12, 12, 8, "rgb");
    s.execute("image.mode.indexedColor", json!({"colors": 6})).unwrap();
    let bytes = photocraft_format::save_to_bytes(doc(&s), &Default::default()).unwrap();
    let back = photocraft_format::load_from_bytes(&bytes).unwrap();
    assert_eq!(back.color_table, doc(&s).color_table);
    assert_eq!(back.mode, ColorMode::Indexed);
}

/// Leaving Duotone for a colour mode keeps the printed look (#2383): the converted pixels are
/// the displayed ink colours, through the destination profile. Grayscale drops the inks.
#[test]
fn duotone_to_colour_modes_keeps_the_ink_colours() {
    use craft_cms::{Builtin, Transform};
    let configs = [
        json!({"type": "duotone"}),
        json!({"type": "monotone", "inks": [{"name": "Orange", "color": "#ff8000", "curve": [[0, 0], [100, 100]]}]}),
        json!({"type": "quadtone"}),
    ];
    for depth in [8, 16, 32] {
        for cfg in &configs {
            for mode in ["rgb", "cmyk", "lab", "grayscale"] {
                let ctx = format!("{depth}-bit {cfg} → {mode}");
                let mut s = session(16, 2, depth, "gray");
                paint(&mut s, |x, _| {
                    let v = x as f32 / 15.0;
                    [v, v, v, 1.0]
                });
                s.execute("image.mode.duotone", cfg.clone()).unwrap();
                let before = s.active().unwrap().doc.clone();
                let gray: Vec<f32> = (0..16).map(|x| before.layers[0].surface().unwrap().pixel(x, 1)[0]).collect();
                let shown = photocraft_compose::render(&display_document(&before).unwrap(), Rect::from_xywh(0, 1, 16, 1)).into_px();
                s.execute(&format!("image.mode.{mode}"), json!({})).unwrap();
                let d = doc(&s);
                assert!(d.duotone.is_none(), "{ctx}");
                let surf = d.layers[0].surface().unwrap();
                let target = match mode {
                    "rgb" => ColorMode::Rgb,
                    "cmyk" => ColorMode::Cmyk,
                    "lab" => ColorMode::Lab,
                    _ => ColorMode::Grayscale,
                };
                assert_eq!(d.mode, target, "{ctx}");
                let srgb = Builtin::Srgb.profile();
                let dst = crate::color_cmds::working_profile(target);
                let t = Transform::new(srgb, &dst, s.color.settings.intent(), s.color.settings.bpc).unwrap();
                for x in 0..16 {
                    let got = surf.pixel(x, 1);
                    let want: Vec<f32> = if target == ColorMode::Grayscale {
                        vec![gray[x as usize]]
                    } else {
                        let mut o = [0.0f32; 16];
                        t.eval(&shown[x as usize][..3], &mut o).unwrap();
                        o[..target.color_channels()].to_vec()
                    };
                    // The display's gradient map samples the inks at 33 stops; dark CMYK
                    // separations magnify that a little.
                    let tol = if target == ColorMode::Cmyk { 0.03 } else { 0.02 };
                    for (g, w) in got.iter().zip(&want) {
                        assert!((g - w).abs() < tol, "{ctx} x={x}: got {got:?}, want {want:?}");
                    }
                }
                // Undo brings back the inks and the gray pixels.
                s.execute("edit.undo", json!({})).unwrap();
                let back = doc(&s);
                assert_eq!((back.mode, &back.duotone), (ColorMode::Duotone, &before.duotone), "{ctx}");
                assert_eq!(back.layers[0].surface().unwrap().pixel(7, 1), before.layers[0].surface().unwrap().pixel(7, 1), "{ctx}");
            }
        }
    }
}

/// Colours stored in a Duotone document (fill layers) take the ink colours too.
#[test]
fn duotone_to_rgb_inks_fill_layer_colours() {
    let mut s = session(4, 4, 8, "gray");
    s.execute("image.mode.duotone", json!({"type": "monotone", "inks": [{"name": "Orange", "color": "#ff8000"}]})).unwrap();
    s.execute("layer.newFillLayer.solidColor", json!({"color": "#808080"})).unwrap();
    s.execute("image.mode.rgb", json!({})).unwrap();
    let d = doc(&s);
    let Some(LayerContent::Fill(photocraft_doc::Fill::Solid(c))) = d.layers.last().map(|l| &l.content) else { panic!("no fill layer") };
    assert_eq!(c.mode, ColorMode::Rgb);
    // Gray 0.5 is half-density orange: (1, 0.75, 0.5).
    for (g, w) in c.c[..3].iter().zip([1.0, 0.75, 0.5]) {
        assert!((g - w).abs() < 0.02, "{c:?}");
    }
}

/// Three-entry Indexed doc (red, blue, transparent at index 2) from an RGB doc with clear pixels.
fn indexed_with_transparency() -> Session {
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap();
    paint(&mut s, |x, _| {
        if x < 3 {
            [1.0, 0.0, 0.0, 1.0]
        } else if x < 6 {
            [0.0, 0.0, 1.0, 1.0]
        } else {
            [0.0; 4]
        }
    });
    s.execute("image.mode.indexedColor", json!({"palette": "exact", "colors": 4, "forced": "none", "dither": "none"})).unwrap();
    assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, Some(2));
    s
}

#[test]
fn shrinking_the_color_table_drops_a_transparent_index_past_its_end() {
    // #4186: the transparent index stayed at 2 after the table shrank to 2 entries, so the palette
    // PNG export refused the table.
    let mut s = indexed_with_transparency();
    s.execute("image.mode.colorTable", json!({"colors": ["#000000", "#ffffff"]})).unwrap();
    let d = doc(&s);
    let t = d.color_table.as_ref().unwrap();
    assert_eq!(t.colors.len(), 2);
    assert!(t.transparent.is_none_or(|i| usize::from(i) < t.colors.len()), "stale transparent index {:?}", t.transparent);
    // The pixels end up exactly as with an explicit `"transparent": null`.
    let mut cleared = indexed_with_transparency();
    cleared.execute("image.mode.colorTable", json!({"colors": ["#000000", "#ffffff"], "transparent": null})).unwrap();
    assert_eq!(doc(&cleared).color_table.as_ref(), Some(t));
    let (a, b) = (d.layers[0].surface().unwrap(), doc(&cleared).layers[0].surface().unwrap());
    for y in 0..8 {
        for x in 0..8 {
            assert_eq!(a.rgba(x, y), b.rgba(x, y), "({x},{y})");
        }
    }
    let png = photocraft_io::export(d, "png", &Default::default()).expect("palette PNG export");
    assert!(png.warnings.iter().any(|w| w.contains("palette PNG")), "{:?}", png.warnings);
    // Undo restores the transparent entry.
    s.execute("edit.undo", json!({})).unwrap();
    assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, Some(2));
}

#[test]
fn color_table_rejects_an_invalid_transparent_index_without_editing() {
    let mut s = indexed_with_transparency();
    let before = doc(&s).color_table.clone();
    let n = s.active().unwrap().history.past_len();
    for t in [json!(999), json!(3), json!(-1), json!(1.5), json!("0"), json!(true)] {
        assert!(s.execute("image.mode.colorTable", json!({"transparent": t})).is_err(), "{t}");
        // Validated against the new colours, before any edit.
        assert!(s.execute("image.mode.colorTable", json!({"colors": ["#000000", "#ffffff"], "transparent": t})).is_err(), "{t}");
    }
    assert!(s.execute("image.mode.colorTable", json!({"colors": ["#000000", "#ffffff"], "transparent": 2})).is_err());
    assert_eq!(doc(&s).color_table, before);
    assert_eq!(s.active().unwrap().history.past_len(), n);
    // A valid index still applies.
    s.execute("image.mode.colorTable", json!({"transparent": 0})).unwrap();
    assert_eq!(doc(&s).color_table.as_ref().unwrap().transparent, Some(0));
}

/// A white 16×16 document in Indexed Color with the two-entry black/white table (#8669's repro).
fn black_white_indexed(transparency: bool) -> Session {
    let mut s = Session::new();
    let background = if transparency { "transparent" } else { "white" };
    s.execute("file.new", json!({"width": 16, "height": 16, "background": background})).unwrap();
    paint(&mut s, |x, _| {
        if x < 2 {
            [0.0; 4]
        } else if x < 4 {
            [0.0, 0.0, 0.0, 1.0]
        } else {
            [1.0; 4]
        }
    });
    s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "transparency": transparency, "dither": "none"})).unwrap();
    s
}

#[test]
fn brush_stroke_stays_in_indexed_color_table() {
    let mut s = black_white_indexed(false);
    assert_eq!(doc(&s).color_table.as_ref().unwrap().colors, vec![[0, 0, 0], [255, 255, 255]]);
    s.execute("paint.stroke", json!({"points": [[8, 8, 1]], "size": 8, "color": "#ff0000", "opacity": 1, "flow": 1})).unwrap();
    // Red's nearest entry is black.
    assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(8, 8), [0.0, 0.0, 0.0, 1.0]);
    // Soft edges and partial opacity blend, and the blends map back onto the table too.
    s.execute("paint.stroke", json!({"points": [[4, 12], [14, 12]], "size": 6, "hardness": 0.0, "color": "#808080", "opacity": 0.5})).unwrap();
    let table = doc(&s).color_table.clone().unwrap();
    assert!(colours(doc(&s)).iter().all(|c| table.colors.contains(c)), "off-table pixels: {:?}", colours(doc(&s)));
    assert_eq!(doc(&s).mode, ColorMode::Indexed);
}

#[test]
fn brush_stroke_keeps_indexed_transparency_binary() {
    let mut s = black_white_indexed(true);
    let table = doc(&s).color_table.clone().unwrap();
    assert!(table.transparent.is_some());
    s.execute("paint.stroke", json!({"points": [[0, 8], [15, 8]], "size": 8, "hardness": 0.0, "color": "#ff0000", "opacity": 0.7})).unwrap();
    let d = doc(&s);
    let surf = d.layers[0].surface().unwrap();
    for (x, y) in (0..16).flat_map(|y| (0..16).map(move |x| (x, y))) {
        let a = surf.rgba(x, y)[3];
        assert!(a == 0.0 || a == 1.0, "alpha {a} at ({x},{y})");
    }
    assert!(colours(d).iter().all(|c| table.colors.contains(c)), "off-table pixels: {:?}", colours(d));
}

#[test]
fn live_brush_preview_matches_indexed_commit() {
    let mut s = black_white_indexed(false);
    let params = json!({"points": [[4, 8], [12, 8]], "size": 7, "hardness": 0.0, "color": "#ff0000", "opacity": 0.6, "smoothing": 0.0, "seed": 1});
    let preview = crate::brush_cmds::LiveStroke::begin(&s, &params).unwrap();
    let table = doc(&s).color_table.clone().unwrap();
    assert!(colours(&preview.doc).iter().all(|c| table.colors.contains(c)), "preview off the table: {:?}", colours(&preview.doc));
    s.execute("paint.stroke", params).unwrap();
    let (live, committed) = (preview.doc.layers[0].surface().unwrap(), doc(&s).layers[0].surface().unwrap());
    for (x, y) in (0..16).flat_map(|y| (0..16).map(move |x| (x, y))) {
        assert_eq!(live.rgba(x, y), committed.rgba(x, y), "preview/commit at ({x},{y})");
    }
}

#[test]
fn indexed_brush_stroke_leaves_pixels_it_did_not_paint() {
    let mut s = black_white_indexed(false);
    // An off-table pixel inside the stroke's bounds but away from its dabs (Paint Bucket can
    // still leave one) is not the stroke's to remap.
    s.edit("setup", |doc, active| {
        let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
        let px = photocraft_raster::from_rgba(&surf.format(), [1.0, 0.0, 0.0, 1.0]);
        surf.write_region(Rect::new(13, 2, 14, 3), &px);
        Ok(())
    })
    .unwrap();
    s.execute("paint.stroke", json!({"points": [[2, 2], [14, 14]], "size": 2, "hardness": 1.0, "color": "#ff0000", "smoothing": 0.0})).unwrap();
    let surf = doc(&s).layers[0].surface().unwrap();
    assert_eq!(surf.rgba(13, 2), [1.0, 0.0, 0.0, 1.0]);
    assert_eq!(surf.rgba(8, 8), [0.0, 0.0, 0.0, 1.0]);
}

#[test]
fn pencil_auto_erase_knows_the_indexed_foreground() {
    let mut s = black_white_indexed(false);
    let pencil = json!({"points": [[8, 8]], "size": 3, "color": "#ff0000", "autoErase": true});
    s.execute("paint.pencil", pencil.clone()).unwrap();
    assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(8, 8), [0.0, 0.0, 0.0, 1.0]);
    // Red painted as black, so a stroke starting there auto-erases to the (white) background.
    let preview = crate::brush_cmds::LiveStroke::begin_with(&s, "paint.pencil", &pencil).unwrap();
    assert_eq!(preview.doc.layers[0].surface().unwrap().rgba(8, 8), [1.0, 1.0, 1.0, 1.0]);
    s.execute("paint.pencil", pencil).unwrap();
    assert_eq!(doc(&s).layers[0].surface().unwrap().rgba(8, 8), [1.0, 1.0, 1.0, 1.0]);
}