GitCorner

Code

ossartcraftdesigncraft🌐
88f5a00e389b
#[cfg(not(target_arch = "wasm32"))]
use super::EngineError;
#[cfg(test)]
use super::bytes::base64_encode;
use super::bytes::{base64_decode, from_bytes};
use super::{
    Affine, Asset, AssetId, Content, Graphic, Item, ItemId, PdfCrop, Rect, Result, Selection, Session, Shape, Value, bad, json, ok, shapes, str_param,
};
use crate::cmd::links::{FileLink, give_placed};
use crate::cmd::native_links::Pending;

pub(super) fn file_place(s: &mut Session, p: &Value) -> Result<Value> {
    // The file's size and time before it is read (a linked text file remembers them).
    let mut before = None;
    let (bytes, name, link) = if let Some(b) = str_param(p, "base64") {
        (base64_decode(b), str_param(p, "name").unwrap_or("image").to_string(), None)
    } else if let Some(path) = str_param(p, "path") {
        before = crate::cmd::datamerge::fingerprint_from_path(path);
        #[cfg(not(target_arch = "wasm32"))]
        let b = crate::io::read_file(path).map_err(EngineError::Other)?;
        #[cfg(target_arch = "wasm32")]
        let b: Vec<u8> = vec![];
        let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.into());
        (b, name, Some(path.to_string()))
    } else {
        s.ui_requests.push(crate::UiRequest::Pick { purpose: "place".into(), params: json!({}) });
        return ok();
    };
    // A frame named outright is not replaced while it is locked (the selected frame is the user's own choice).
    if let Some(fid) = crate::cmd::id_param(p, "frame")
        && s.doc()?.doc.item(fid).is_some_and(|it| it.locked)
    {
        return Err(bad("file.place", "the frame is locked"));
    }
    // A page of another layout (IDML or DesignCraft): its objects, as one group.
    let format = craft_file_formats::detect(&name, &bytes);
    if matches!(format, Some(craft_file_formats::Format::Idml | craft_file_formats::Format::DesignCraft)) {
        return place_layout_page(s, p, &bytes, format);
    }
    // Keep the EPS source for link comparison; rendering uses its preview at the bounding box size.
    let eps_size = eps_size(&bytes, "file.place")?;
    // A file placed from a path links to it unless `embed`.
    let embed = p.get("embed").and_then(Value::as_bool) == Some(true);
    let document = document_of(s);
    // Video and sound: a media frame (Window › Interactive › Media).
    if let Some(mime) = designcraft_doc::media_mime(&name) {
        let file = link.as_deref().map(|l| FileLink::of(std::path::Path::new(l), before));
        let mut asset = Asset { name, mime: mime.to_string(), ..Default::default() };
        let pending = give_placed(&mut asset, bytes, file, embed, document.as_deref());
        let r = crate::cmd::media::place_media(s, p, asset)?;
        prepare_placed(s, pending);
        return Ok(r);
    }
    // Text files (plain, Word, RTF) flow into frames.
    if designcraft_textimport::is_text_file(&name) {
        return crate::cmd::place_text::place_text(s, p, &name, &bytes, link, before);
    }
    let want_w = p
        .get("width")
        .filter(|value| !value.is_null())
        .map(|value| {
            value
                .as_f64()
                .filter(|width| width.is_finite() && *width > 0.0)
                .ok_or_else(|| bad("file.place", "`width` must be a finite number greater than zero"))
        })
        .transpose()?;
    // Image Import Options: which page of a PDF (1-based).
    if format == Some(craft_file_formats::Format::Pdf) {
        designcraft_render::check_pdf_input_size(bytes.len()).map_err(|e| bad("file.place", e.to_string()))?;
    }
    let pdf_page = match p.get("pdfPage").and_then(Value::as_u64) {
        Some(n) if format == Some(craft_file_formats::Format::Pdf) => {
            let count = designcraft_render::pdf_page_count(&bytes).unwrap_or(1);
            let invalid_page = || bad("file.place", format!("the PDF has {count} page(s)"));
            let one_based = usize::try_from(n).map_err(|_| invalid_page())?;
            if one_based == 0 || one_based > count {
                return Err(invalid_page());
            }
            let zero_based = one_based.checked_sub(1).ok_or_else(invalid_page)?;
            u32::try_from(zero_based).map_err(|_| invalid_page())?
        }
        _ => 0,
    };
    let (pw, ph) = match pdf_page {
        0 => designcraft_render::image_size(&bytes).ok_or_else(|| bad("file.place", "unsupported or corrupt image"))?,
        n => designcraft_render::pdf_page_size(&bytes, n as usize)
            .map(|(w, h)| (w.round().max(1.0) as u32, h.round().max(1.0) as u32))
            .ok_or_else(|| bad("file.place", "can't read that PDF page"))?,
    };
    // 72 ppi by default unless the file says otherwise; scale so it fits the page when huge. PDF pages
    // and SVGs keep their exact size: rounding it to whole points would stretch them unevenly.
    let (nw, nh) = eps_size.or_else(|| designcraft_render::natural_size(&bytes, pdf_page as usize)).unwrap_or((pw as f64, ph as f64));
    // Image Import Options › Crop to: the graphic spans that box of the PDF page.
    let is_pdf = format == Some(craft_file_formats::Format::Pdf);
    let pdf_crop = match str_param(p, "pdfCrop") {
        Some(k) if is_pdf => PdfCrop::from_name(k)
            .ok_or_else(|| bad("file.place", format!("unknown pdfCrop `{k}` (crop, art, trim, bleed, media, contentVisible, contentAll)")))?,
        _ => PdfCrop::Crop,
    };
    let mime = designcraft_render::image_mime(&bytes).to_string();
    let file = link.as_deref().map(|l| FileLink::of(std::path::Path::new(l), before));
    let mut asset = Asset { page: pdf_page, name, mime, pixels: Some((pw, ph)), pdf_crop, ..Default::default() };
    // The graphic's natural size: the box in points (the whole page when the box can't be found,
    // and then the document says so).
    let cropped = crop_pdf_from(&mut asset, &bytes);
    let pending = give_placed(&mut asset, bytes, file, embed, document.as_deref());
    let (bw, bh) = match cropped {
        Some(size) => size,
        None => {
            asset.pdf_crop = PdfCrop::Crop;
            (nw, nh)
        }
    };
    // A file joining the place cursor's queue goes after the ones already there, whatever is selected.
    let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true);
    let append = p.get("append").and_then(Value::as_bool) == Some(true);
    let target_frame = crate::cmd::id_param(p, "frame").or_else(|| {
        if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) {
            return None;
        }
        let st = s.active()?;
        st.selection.items.iter().copied().find(|i| st.doc.item(*i).is_some_and(|it| it.path.encloses_area() && it.takes_graphic()))
    });
    // `"spread": null` counts as omitted, like the other placement parameters.
    let spread = match p.get("spread") {
        Some(Value::Null) => designcraft_doc::SpreadRef::Doc(0),
        _ => crate::cmd::spread_param(p, "file.place")?,
    };
    let lid = s.doc()?.active_layer;
    let px = p.get("x").and_then(Value::as_f64);
    let py = p.get("y").and_then(Value::as_f64);
    if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param {
        let r = load_cursor(s, asset, (bw, bh), append)?;
        prepare_placed(s, pending);
        return Ok(r);
    }
    let r = s.edit(|d, sel| {
        let fresh = AssetId(d.alloc());
        let aid = d.add_asset(Asset { id: fresh, ..asset });
        // The width the whole page (or image) gets; the height follows the proportions.
        let w = match want_w {
            Some(w) => w,
            None => {
                let page_w = d.settings.page_width * 0.6;
                nw.min(page_w)
            }
        };
        let id = if let Some(fid) = target_frame {
            let it = d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?;
            let r = it.inner_bounds();
            // Fill the frame proportionally once. Auto-Fit stays off, so resizing the frame crops.
            let k = (r.width() / bw).max(r.height() / bh);
            let (gw, gh) = (bw * k, bh * k);
            let xf = Affine::translate((r.x0 + (r.width() - gw) / 2.0, r.y0 + (r.height() - gh) / 2.0)) * Affine::scale(k);
            validate_placement((bw, bh), r, xf, "file.place")?;
            it.content = Content::Graphic(Graphic {
                layer_options: None,
                asset: aid,
                size: (bw, bh),
                xf,
                clip: None,
                auto_fit: Default::default(),
                fit_align: 4,
                crop: [0.0; 4],
                wrap: Default::default(),
                fill: Default::default(),
            });
            fid
        } else {
            let sp = d.spread(spread).ok_or_else(|| bad("file.place", "no such spread"))?;
            let pr = sp.pages.first().map(|pg| pg.margin_rect()).unwrap_or(Rect::new(36.0, 36.0, 300.0, 300.0));
            let (x, y) = (px.unwrap_or(pr.x0), py.unwrap_or(pr.y0));
            let id = ItemId(d.alloc());
            let k = w / nw;
            let r = crate::cmd::finite_rect("file.place", Rect::new(x, y, x + bw * k, y + bh * k))?;
            let xf = Affine::translate((x, y)) * Affine::scale(k);
            validate_placement((bw, bh), r, xf, "file.place")?;
            let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(r));
            it.object_style = d.styles.default_graphic_frame.clone();
            if let Some(e) = d.styles.object_effects(&it.object_style) {
                it.effects = e.clone();
            }
            it.content = Content::Graphic(Graphic {
                layer_options: None,
                asset: aid,
                size: (bw, bh),
                xf,
                clip: None,
                auto_fit: Default::default(),
                fit_align: 4,
                crop: [0.0; 4],
                wrap: Default::default(),
                fill: Default::default(),
            });
            d.insert_item(spread, it, None)?;
            id
        };
        *sel = Selection::items(vec![id]);
        Ok(json!({"id": id.0, "asset": aid.0}))
    })?;
    prepare_placed(s, pending);
    Ok(r)
}

/// Have the hash and proxy of graphics just placed into the active document made in the
/// background ([`crate::cmd::native_links::prepare`]).
pub(crate) fn prepare_placed(s: &mut Session, pending: impl IntoIterator<Item = Pending>) {
    if let Ok(st) = s.doc_mut() {
        crate::cmd::native_links::prepare(st, pending.into_iter().collect());
    }
}

/// Sets `a.pdf_box` to where its `pdf_crop` box sits on its page and returns the box's size in
/// points. The crop box is the whole page and has none; nor has a page that can't be read, which
/// keeps its crop choice (a missing link relinked later gets its box then). Only a PDF with
/// another box chosen is read.
pub(crate) fn crop_pdf(a: &mut Asset) -> Option<(f64, f64)> {
    a.pdf_box = None;
    if !crops_pdf(a) {
        return None;
    }
    let bytes = a.data.load().ok()?;
    crop_pdf_from(a, &bytes)
}

/// [`crop_pdf`] with `a`'s bytes, `bytes`, in hand.
pub(crate) fn crop_pdf_from(a: &mut Asset, bytes: &[u8]) -> Option<(f64, f64)> {
    a.pdf_box = None;
    if !crops_pdf(a) || !designcraft_render::is_pdf(bytes) {
        return None;
    }
    let (frac, size) = designcraft_render::pdf_crop_box(bytes, a.page as usize, a.pdf_crop)?;
    a.pdf_box = Some(frac);
    Some(size)
}

/// Whether `a` is a PDF placed with a box other than its crop box, which only its bytes locate.
fn crops_pdf(a: &Asset) -> bool {
    a.pdf_crop != PdfCrop::Crop && a.mime == "application/pdf"
}

/// A file to place: its bytes and name, and its link record when it was read from a path.
pub(crate) struct Source {
    pub bytes: Vec<u8>,
    pub name: String,
    file: Option<FileLink>,
    /// `embed: true`: the bytes are kept in the document instead of linking the file.
    embed: bool,
}

impl Source {
    /// Give `a` these bytes: linked to the file they were read from once the returned work is
    /// done, else embedded ([`give_placed`]). `a`'s `mime` and `page` are set.
    pub(crate) fn give(self, a: &mut Asset, document: Option<&std::path::Path>) -> Option<Pending> {
        give_placed(a, self.bytes, self.file, self.embed, document)
    }
}

/// The file of the document open in `s`, which relative links are recorded against.
pub(crate) fn document_of(s: &Session) -> Option<std::path::PathBuf> {
    s.doc().ok()?.path.as_deref().map(std::path::PathBuf::from)
}

/// The file `p` names: `{path, embed?}` or `{base64, name?}`. Its size and time are taken before
/// it is read, so a later version that replaces it while a network or syncing source is being
/// loaded isn't vouched for ([`crate::cmd::links::loaded_fingerprint`]).
pub(crate) fn read_source(p: &Value) -> Result<Source> {
    let embed = p.get("embed").and_then(Value::as_bool) == Some(true);
    if let Some(b) = str_param(p, "base64") {
        return Ok(Source { bytes: base64_decode(b), name: str_param(p, "name").unwrap_or("image").to_string(), file: None, embed });
    }
    let path = str_param(p, "path").ok_or_else(|| bad("place", "missing `path` or `base64`"))?;
    let before = crate::cmd::datamerge::fingerprint_from_path(path);
    #[cfg(not(target_arch = "wasm32"))]
    let b = crate::io::read_file(path).map_err(EngineError::Other)?;
    #[cfg(target_arch = "wasm32")]
    let b: Vec<u8> = vec![];
    let name = std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.into());
    let file = Some(FileLink::of(std::path::Path::new(path), before));
    Ok(Source { bytes: b, name, file, embed })
}

fn eps_size(bytes: &[u8], command: &str) -> Result<Option<(f64, f64)>> {
    if !designcraft_images::is_eps(bytes) {
        return Ok(None);
    }
    designcraft_images::eps_size(bytes)
        .map(Some)
        .ok_or_else(|| bad(command, "the EPS has a missing or invalid bounding box (dimensions must be 0.001–20,000 points)"))
}

/// Fitting can overflow even with finite inputs. Never persist NaN/Inf as JSON nulls.
pub(crate) fn validate_placement(size: (f64, f64), frame: Rect, xf: Affine, command: &str) -> Result<()> {
    let valid_rect = |r: Rect| [r.x0, r.y0, r.x1, r.y1, r.width(), r.height()].iter().all(|n| n.is_finite()) && r.width() >= 0.0 && r.height() >= 0.0;
    if !size.0.is_finite()
        || !size.1.is_finite()
        || size.0 <= 0.0
        || size.1 <= 0.0
        || !valid_rect(frame)
        || !xf.as_coeffs().iter().all(|n| n.is_finite())
        || !valid_rect(xf.transform_rect_bbox(Rect::new(0.0, 0.0, size.0, size.1)))
    {
        return Err(bad(command, "image placement exceeds finite geometry limits"));
    }
    Ok(())
}

/// Decode and validate the complete batch before replacing the placement cursor.
pub(super) fn place_load(s: &mut Session, p: &Value) -> Result<Value> {
    let append = p.get("append").and_then(Value::as_bool) == Some(true);
    let embed = p.get("embed").and_then(Value::as_bool) == Some(true);
    let document = document_of(s);
    if p.get("files").is_none() {
        let source = read_source(p)?;
        let bytes = &source.bytes;
        let (pw, ph) = designcraft_render::image_size(bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?;
        let natural = eps_size(bytes, "place.load")?.or_else(|| designcraft_render::natural_size(bytes, 0)).unwrap_or((pw as f64, ph as f64));
        let mut asset = Asset {
            name: source.name.clone(),
            mime: designcraft_render::image_mime(bytes).to_string(),
            pixels: Some((pw, ph)),
            ..Default::default()
        };
        let pending = source.give(&mut asset, document.as_deref());
        let r = load_cursor(s, asset, natural, append)?;
        prepare_placed(s, pending);
        return Ok(r);
    }
    let sources = p.get("files").and_then(Value::as_array).ok_or_else(|| bad("place.load", "files must be an array"))?;
    if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES {
        return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images")));
    }
    check_cursor_room(s, sources.len(), append, "place.load")?;
    let mut images = Vec::with_capacity(sources.len());
    let mut pending = Vec::new();
    for source in sources {
        let mut source = read_source(source)?;
        source.embed |= embed;
        let bytes = &source.bytes;
        let (pw, ph) =
            designcraft_render::image_size(bytes).ok_or_else(|| bad("place.load", format!("unsupported or corrupt image: {}", source.name)))?;
        let size = eps_size(bytes, "place.load")?.or_else(|| designcraft_render::natural_size(bytes, 0)).unwrap_or((pw as f64, ph as f64));
        validate_placement(size, Rect::new(0.0, 0.0, size.0, size.1), Affine::IDENTITY, "place.load")?;
        let mut asset = Asset {
            name: source.name.clone(),
            mime: designcraft_render::image_mime(bytes).to_string(),
            pixels: Some((pw, ph)),
            ..Default::default()
        };
        pending.extend(source.give(&mut asset, document.as_deref()));
        images.push((asset, size));
    }
    let queue = s.edit(|d, _| {
        let mut queue = std::collections::VecDeque::with_capacity(images.len());
        for (mut asset, size) in images {
            asset.id = AssetId(d.alloc());
            queue.push_back(crate::LoadedGraphic { asset: d.add_asset(asset), size });
        }
        Ok(queue)
    })?;
    prepare_placed(s, pending);
    if append && s.loaded.is_some() {
        s.loaded_queue.extend(queue);
    } else {
        s.loaded_queue = queue;
        s.loaded = s.loaded_queue.pop_front();
    }
    s.set_tool("placeGun");
    Ok(json!({"remaining": loaded_count(s), "loaded": true}))
}

/// Most images the place cursor holds, and so most one `place.load` takes.
const MAX_LOADED_IMAGES: usize = 1000;

/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds.
fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> {
    let held = if append { loaded_count(s) } else { 0 };
    if held.saturating_add(incoming) > MAX_LOADED_IMAGES {
        return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}")));
    }
    Ok(())
}

/// How many images the place cursor holds: the current one and those queued after it.
fn loaded_count(s: &Session) -> usize {
    s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some()))
}

/// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with
/// `append` and an image already loaded, queued after it).
fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result<Value> {
    check_cursor_room(s, 1, append, "place.load")?;
    let name = asset.name.clone();
    let (pw, ph) = asset.pixels.unwrap_or_default();
    let aid = s.edit(|d, _| {
        asset.id = AssetId(d.alloc());
        Ok(d.add_asset(asset))
    })?;
    let image = crate::LoadedGraphic { asset: aid, size };
    if append && s.loaded.is_some() {
        s.loaded_queue.push_back(image);
    } else {
        s.loaded_queue.clear();
        s.loaded = Some(image);
    }
    s.set_tool("placeGun");
    Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph, "loaded": true}))
}

/// Cancel every pending image if Undo removed an asset used by the cursor.
fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> {
    // An empty cursor is its own error, and leaves the tool as it is.
    if s.loaded.is_none() {
        return Err(bad(command, "nothing loaded in the place cursor"));
    }
    let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset)));
    if !valid {
        s.unload_place_cursor();
        return Err(bad(command, "the loaded graphic is no longer in the document"));
    }
    Ok(())
}

/// Place the current image and advance the cursor only after success.
pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result<Value> {
    validate_place_cursor(s, "place.drop")?;
    let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?;
    let sr = crate::cmd::spread_param(p, "place.drop")?;
    let lid = s.doc()?.active_layer;
    let frame = crate::cmd::id_param(p, "frame");
    let rect = crate::cmd::rect_param(p, "rect");
    let (x, y) = (crate::cmd::f64_or(p, "x", 0.0), crate::cmd::f64_or(p, "y", 0.0));
    let d = &s.doc()?.doc;
    let (frame_rect, xf, auto_fit) = if let Some(fid) = frame {
        let r = d.item(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?.inner_bounds();
        let k = (r.width() / nw).max(r.height() / nh);
        let xf = Affine::translate((r.x0 + (r.width() - nw * k) / 2.0, r.y0 + (r.height() - nh * k) / 2.0)) * Affine::scale(k);
        // Fill the frame proportionally once. Auto-Fit stays off, so resizing the frame crops.
        (r, xf, Default::default())
    } else {
        if d.spread(sr).is_none() {
            return Err(bad("place.drop", "no such spread"));
        }
        // Drag: fit proportionally; click: actual size at the point.
        let (r, k) = match rect {
            Some(r) if r.width() > designcraft_tools::PLACE_DRAG_MIN && r.height() > designcraft_tools::PLACE_DRAG_MIN => {
                let k = (r.width() / nw).min(r.height() / nh);
                (Rect::new(r.x0, r.y0, r.x0 + nw * k, r.y0 + nh * k), k)
            }
            _ => (Rect::new(x, y, x + nw, y + nh), 1.0),
        };
        (r, Affine::translate((r.x0, r.y0)) * Affine::scale(k), Default::default())
    };
    validate_placement((nw, nh), frame_rect, xf, "place.drop")?;
    let r = s.edit(|d, sel| {
        let graphic = Content::Graphic(Graphic {
            layer_options: None,
            asset: aid,
            size: (nw, nh),
            xf,
            clip: None,
            auto_fit,
            fit_align: 4,
            crop: [0.0; 4],
            wrap: Default::default(),
            fill: Default::default(),
        });
        let id = if let Some(fid) = frame {
            d.item_mut(fid).ok_or(designcraft_doc::DocError::NoItem(fid))?.content = graphic;
            fid
        } else {
            let id = ItemId(d.alloc());
            let mut it = Item::new(id, lid, Shape::Rectangle, shapes::rectangle(frame_rect));
            it.object_style = d.styles.default_graphic_frame.clone();
            if let Some(e) = d.styles.object_effects(&it.object_style) {
                it.effects = e.clone();
            }
            it.content = graphic;
            d.insert_item(sr, it, None)?;
            id
        };
        *sel = Selection::items(vec![id]);
        Ok(json!({"id": id.0}))
    })?;
    advance_place_cursor(s);
    Ok(r)
}

/// Advance in file order, returning to selection when the queue is exhausted.
fn advance_place_cursor(s: &mut Session) {
    s.loaded = s.loaded_queue.pop_front();
    if s.loaded.is_none() {
        s.set_tool("selection");
    }
}

/// Drop the current loaded image without placing it and move to the next; the last one ends placing.
pub(super) fn place_skip(s: &mut Session, _p: &Value) -> Result<Value> {
    validate_place_cursor(s, "place.skip")?;
    advance_place_cursor(s);
    Ok(json!({"remaining": loaded_count(s)}))
}

/// Rotate the loaded images: `dir` 1 makes the next one current (the current one goes to the back),
/// -1 the previous one (the last goes to the front).
pub(super) fn place_cycle(s: &mut Session, p: &Value) -> Result<Value> {
    const ID: &str = "place.cycle";
    let dir = p.get("dir").and_then(Value::as_i64).filter(|d| matches!(d, 1 | -1)).ok_or_else(|| bad(ID, "dir must be 1 or -1"))?;
    validate_place_cursor(s, ID)?;
    if let Some(current) = s.loaded {
        if dir == 1 {
            s.loaded_queue.push_back(current);
            s.loaded = s.loaded_queue.pop_front();
        } else if let Some(last) = s.loaded_queue.pop_back() {
            s.loaded_queue.push_front(current);
            s.loaded = Some(last);
        }
    }
    Ok(json!({"remaining": loaded_count(s)}))
}

/// Validate bounded grid dimensions and a finite nonnegative gutter.
fn grid_dimensions(p: &Value, command: &str, default_columns: usize, default_rows: usize) -> Result<(usize, usize, f64)> {
    let dimension = |key, default| -> Result<usize> {
        match p.get(key) {
            None => Ok(default),
            Some(v) => v
                .as_u64()
                .filter(|n| (1..=100).contains(n))
                .and_then(|n| usize::try_from(n).ok())
                .ok_or_else(|| bad(command, "rows and columns must be integers between 1 and 100")),
        }
    };
    let gutter = crate::cmd::f64_or(p, "gutter", 6.0);
    if !gutter.is_finite() || gutter < 0.0 {
        return Err(bad(command, "gutter must be finite and nonnegative"));
    }
    Ok((dimension("columns", default_columns)?, dimension("rows", default_rows)?, gutter))
}

/// Calculate row-major cells, rejecting gutters that leave no usable space.
fn grid_cells(rect: Rect, columns: usize, rows: usize, gutter: f64, command: &str) -> Result<Vec<Rect>> {
    let (columns, rows) = (columns.max(1), rows.max(1));
    let w = (rect.width() - gutter * columns.saturating_sub(1) as f64) / columns as f64;
    let h = (rect.height() - gutter * rows.saturating_sub(1) as f64) / rows as f64;
    if ![rect.x0, rect.y0, rect.x1, rect.y1, w, h].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 {
        return Err(bad(command, "the grid area is too small for its rows, columns and gutter"));
    }
    Ok((0..rows)
        .flat_map(|row| {
            (0..columns).map(move |column| {
                let x = rect.x0 + column as f64 * (w + gutter);
                let y = rect.y0 + row as f64 * (h + gutter);
                Rect::new(x, y, x + w, y + h)
            })
        })
        .collect())
}

/// Insert a proportionally fitted image into one grid cell.
fn insert_grid_image(
    d: &mut designcraft_doc::Document,
    spread: designcraft_doc::SpreadRef,
    layer: designcraft_doc::LayerId,
    image: crate::LoadedGraphic,
    rect: Rect,
    command: &str,
) -> Result<ItemId> {
    let crate::LoadedGraphic { asset, size: (nw, nh) } = image;
    if !d.assets.contains_key(&asset) {
        return Err(bad(command, "a loaded image is no longer in the document"));
    }
    let k = (rect.width() / nw).min(rect.height() / nh);
    let xf = Affine::translate((rect.x0 + (rect.width() - nw * k) / 2.0, rect.y0 + (rect.height() - nh * k) / 2.0)) * Affine::scale(k);
    validate_placement((nw, nh), rect, xf, command)?;
    let id = ItemId(d.alloc());
    let mut item = Item::new(id, layer, Shape::Rectangle, shapes::rectangle(rect));
    item.object_style = d.styles.default_graphic_frame.clone();
    if let Some(effects) = d.styles.object_effects(&item.object_style) {
        item.effects = effects.clone();
    }
    item.content = Content::Graphic(Graphic {
        layer_options: None,
        asset,
        size: (nw, nh),
        xf,
        auto_fit: designcraft_doc::Fitting::FitProportionally,
        fit_align: 4,
        crop: [0.0; 4],
        clip: None,
        wrap: Default::default(),
        fill: Default::default(),
    });
    d.insert_item(spread, item, None)?;
    Ok(id)
}

/// Place a row-major grid as one undoable edit.
pub(super) fn place_grid(s: &mut Session, p: &Value) -> Result<Value> {
    const ID: &str = "place.grid";
    validate_place_cursor(s, ID)?;
    let (columns, rows, gutter) = grid_dimensions(p, ID, 1, 1)?;
    let rect = crate::cmd::rect_param(p, "rect").ok_or_else(|| bad(ID, "missing rect"))?;
    let cells = grid_cells(rect, columns, rows, gutter, ID)?;
    let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().take(cells.len()).collect();
    if images.is_empty() {
        return Err(bad(ID, "nothing loaded in the place cursor"));
    }
    let layer = s.doc()?.active_layer;
    let spread = crate::cmd::spread_param(p, ID)?;
    let ids = s.edit(|d, sel| {
        let mut ids = Vec::with_capacity(images.len());
        for (image, rect) in images.iter().zip(cells) {
            ids.push(insert_grid_image(d, spread, layer, *image, rect, ID)?);
        }
        *sel = Selection::items(ids.clone());
        Ok(ids)
    })?;
    for _ in &ids {
        advance_place_cursor(s);
    }
    Ok(json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "remaining": loaded_count(s)}))
}

/// Place all queued images on new pages as one undoable edit.
pub(super) fn place_contact_sheet(s: &mut Session, p: &Value) -> Result<Value> {
    const ID: &str = "place.contactSheet";
    validate_place_cursor(s, ID)?;
    let (columns, rows, gutter) = grid_dimensions(p, ID, 3, 4)?;
    let margin = crate::cmd::f64_or(p, "margin", 36.0);
    if !margin.is_finite() || margin < 0.0 {
        return Err(bad(ID, "invalid margin"));
    }
    let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().collect();
    if images.is_empty() {
        return Err(bad(ID, "load images first using File > Place"));
    }
    let layer = s.doc()?.active_layer;
    let per_page = columns.saturating_mul(rows).max(1);
    let count = images.len().div_ceil(per_page);
    let ids = s.edit(|d, sel| {
        let after = d.page_count().saturating_sub(1);
        d.insert_pages(Some(after), count, None)?;
        let mut ids = Vec::with_capacity(images.len());
        for (page_offset, chunk) in images.chunks(per_page).enumerate() {
            let index = after.saturating_add(1).saturating_add(page_offset);
            let (si, pi) = d.page_loc(index).ok_or_else(|| bad(ID, "missing page"))?;
            let b = d.spreads.get(si).and_then(|sp| sp.pages.get(pi)).ok_or_else(|| bad(ID, "missing page"))?.bounds();
            let cells = grid_cells(Rect::new(b.x0 + margin, b.y0 + margin, b.x1 - margin, b.y1 - margin), columns, rows, gutter, ID)?;
            for (image, rect) in chunk.iter().zip(cells) {
                ids.push(insert_grid_image(d, designcraft_doc::SpreadRef::Doc(si), layer, *image, rect, ID)?);
            }
        }
        *sel = Selection::items(ids.clone());
        Ok(ids)
    })?;
    for _ in &ids {
        advance_place_cursor(s);
    }
    Ok(json!({"pages": count, "images": ids.len()}))
}

/// File › Place of an IDML or DesignCraft document: the objects of one page (`layoutPage`,
/// 1-based) grouped, top-left at x/y (default: the source position on the first page).
fn place_layout_page(s: &mut Session, p: &Value, bytes: &[u8], format: Option<craft_file_formats::Format>) -> Result<Value> {
    const ID: &str = "file.place";
    let src = if format == Some(craft_file_formats::Format::Idml) {
        crate::cmd::interchange::import_idml_confined(bytes, str_param(p, "path").map(std::path::Path::new)).map_err(|e| bad(ID, e.to_string()))?
    } else {
        from_bytes(bytes)?
    };
    let n = src.page_count();
    let page = p.get("layoutPage").and_then(Value::as_u64).unwrap_or(1) as usize;
    if page == 0 || page > n {
        return Err(bad(ID, format!("the document has {n} page(s)")));
    }
    let (si, pi) = src.page_loc(page - 1).ok_or_else(|| bad(ID, "no such page"))?;
    let sp = &src.spreads[si];
    let pr = sp.pages[pi].bounds();
    let ids: Vec<ItemId> = sp.items.iter().filter(|it| !it.hidden && sp.page_at_x(it.bounds().center().x) == Some(pi)).map(|it| it.id).collect();
    if ids.is_empty() {
        return Err(bad(ID, format!("page {page} has no objects")));
    }
    let to = crate::cmd::spread_param(p, ID)?;
    let off = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) {
        (Some(x), Some(y)) => designcraft_geom::Vec2::new(x - pr.x0, y - pr.y0),
        _ => designcraft_geom::Vec2::new(-pr.x0, -pr.y0),
    };
    let placed = s.edit(|d, sel| {
        for sw in &src.swatches {
            if d.swatch(&sw.name).is_none() {
                d.swatches.push(sw.clone());
            }
        }
        let missing_p: Vec<_> = src.styles.paragraph.iter().filter(|ps| d.styles.para(&ps.name).is_none()).cloned().collect();
        let missing_c: Vec<_> = src.styles.character.iter().filter(|cs| d.styles.char_style(&cs.name).is_none()).cloned().collect();
        if !missing_p.is_empty() || !missing_c.is_empty() {
            let st = d.styles_mut();
            st.paragraph.extend(missing_p);
            st.character.extend(missing_c);
        }
        let new = crate::cmd::object::duplicate_from(d, &src, &ids, to, off)?;
        *sel = Selection::items(new.clone());
        Ok(new)
    })?;
    if placed.len() > 1 {
        let g = s.execute("object.group", &json!({"ids": placed.iter().map(|i| i.0).collect::<Vec<_>>()}))?;
        return Ok(json!({"id": g["id"], "items": placed.len()}));
    }
    Ok(json!({"id": placed[0].0, "items": 1}))
}

#[cfg(all(test, not(target_arch = "wasm32")))]
pub(super) mod image_place_tests {
    use designcraft_doc::{AssetId, Content, ItemId};
    use designcraft_geom::Rect;
    use serde_json::{Value, json};

    use crate::Session;

    pub(in crate::cmd::file) fn image_file() -> std::io::Result<tempfile::NamedTempFile> {
        image_file_with_color(30)
    }

    fn image_file_with_color(red: u8) -> std::io::Result<tempfile::NamedTempFile> {
        let file = tempfile::Builder::new().suffix(".png").tempfile()?;
        let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [red, 90, 180, 255].repeat(800) }.to_png();
        std::fs::write(file.path(), png)?;
        Ok(file)
    }

    /// With nothing in the place cursor, placing says so and leaves the tool as it is (the
    /// cursor's graphic gone from the document is another error).
    #[test]
    fn an_empty_place_cursor_says_so_and_keeps_the_tool() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        s.set_tool("rectangleFrame");
        for (cmd, p) in
            [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]})), ("place.contactSheet", json!({}))]
        {
            let e = s.execute(cmd, &p).unwrap_err().to_string();
            assert!(e.contains("nothing loaded"), "{cmd}: {e}");
            assert_eq!(s.tool_id(), "rectangleFrame", "{cmd}");
        }
    }

    fn test_png(shade: u8) -> String {
        let png = designcraft_render::Rendered { width: 4, height: 4, pixels: vec![shade; 4 * 4 * 4] }.to_png();
        crate::cmd::base64_encode(&png)
    }

    fn loaded_names(s: &Session) -> Vec<String> {
        let Ok(st) = s.doc() else { return Vec::new() };
        let d = &st.doc;
        s.loaded.iter().chain(s.loaded_queue.iter()).map(|g| d.assets[&g.asset].name.clone()).collect()
    }

    #[test]
    fn skip_drops_the_current_image_and_the_last_one_ends_placing() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let files: Vec<_> = (0..3).map(|i| json!({"base64": test_png(i as u8), "name": format!("{i}.png")})).collect();
        s.execute("place.load", &json!({"files": files})).unwrap();
        assert_eq!(s.execute("place.skip", &json!({})).unwrap()["remaining"], 2);
        assert_eq!(loaded_names(&s), ["1.png", "2.png"]);
        s.execute("place.skip", &json!({})).unwrap();
        assert_eq!(s.tool_id(), "placeGun");
        s.execute("place.skip", &json!({})).unwrap();
        assert!(s.loaded.is_none());
        assert_eq!(s.tool_id(), "selection");
        assert!(s.execute("place.skip", &json!({})).is_err());
    }

    #[test]
    fn cycle_rotates_the_loaded_images_both_ways() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let files: Vec<_> = (0..3).map(|i| json!({"base64": test_png(i as u8), "name": format!("{i}.png")})).collect();
        s.execute("place.load", &json!({"files": files})).unwrap();
        s.execute("place.cycle", &json!({"dir": 1})).unwrap();
        assert_eq!(loaded_names(&s), ["1.png", "2.png", "0.png"]);
        s.execute("place.cycle", &json!({"dir": -1})).unwrap();
        s.execute("place.cycle", &json!({"dir": -1})).unwrap();
        assert_eq!(loaded_names(&s), ["2.png", "0.png", "1.png"]);
        assert!(s.execute("place.cycle", &json!({"dir": 2})).is_err());
        assert!(s.execute("place.cycle", &json!({})).is_err());
    }

    #[test]
    fn consecutive_path_placements_create_distinct_graphics() {
        let images = [image_file_with_color(30).unwrap(), image_file_with_color(31).unwrap(), image_file_with_color(32).unwrap()];
        let mut session = Session::new();
        session.execute("file.new", &json!({"pages": 3, "facingPages": false})).unwrap();
        let mut placements = Vec::new();
        let mut originals = Vec::new();

        for ((spread, x, y), image) in [(0, 0.0, 0.0), (1, 70.0, 90.0), (2, 150.0, 210.0)].into_iter().zip(&images) {
            let placed = session.execute("file.place", &json!({"path": image.path(), "spread": spread, "x": x, "y": y})).unwrap();
            let id = ItemId(placed["id"].as_u64().unwrap());
            assert!(
                placements.iter().all(|previous: &Value| previous["id"] != placed["id"]),
                "each explicit placement needs a distinct frame: {placed}"
            );
            let document = &session.doc().unwrap().doc;
            let item = document.item(id).unwrap();
            assert_eq!(item.bounds(), Rect::new(x, y, x + 40.0, y + 20.0));
            assert!(document.spreads[spread].items.iter().any(|item| item.id == id));
            originals.push(serde_json::to_value(item).unwrap());
            placements.push(placed);
        }

        let document = &session.doc().unwrap().doc;
        assert_eq!(document.spreads.iter().flat_map(|spread| &spread.items).filter(|item| matches!(item.content, Content::Graphic(_))).count(), 3);
        assert_eq!(document.assets.len(), 3);
        for (placed, original) in placements.iter().zip(originals) {
            assert_eq!(serde_json::to_value(document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap()).unwrap(), original);
        }
        let links = session.execute("links.list", &json!({})).unwrap();
        assert_eq!(links.as_array().unwrap().len(), 3);
        for (placed, image) in placements.into_iter().zip(&images) {
            let row = links.as_array().unwrap().iter().find(|row| row["asset"] == placed["asset"]).unwrap();
            assert_eq!(row["path"], json!(image.path()));
            assert_eq!(row["uses"].as_array().unwrap().len(), 1);
            assert_eq!(row["uses"][0]["id"], placed["id"]);
        }
    }

    #[test]
    fn a_locked_frame_named_outright_is_not_replaced() {
        let image = image_file_with_color(30).unwrap();
        let mut session = Session::new();
        session.execute("file.new", &json!({})).unwrap();
        let frame = session.execute("frame.create", &json!({"rect": [36, 36, 136, 136]})).unwrap()["id"].as_u64().unwrap();
        session.execute("object.lock", &json!({"ids": [frame]})).unwrap();
        assert!(session.execute("file.place", &json!({"path": image.path(), "frame": frame})).is_err());
        let document = &session.doc().unwrap().doc;
        assert!(matches!(document.item(ItemId(frame)).unwrap().content, Content::Unassigned), "the locked frame stays empty");
        session.execute("object.unlockAll", &json!({})).unwrap();
        session.execute("file.place", &json!({"path": image.path(), "frame": frame})).unwrap();
        assert!(matches!(session.doc().unwrap().doc.item(ItemId(frame)).unwrap().content, Content::Graphic(_)));
    }

    #[test]
    fn place_load_remembers_the_fingerprint_captured_for_its_link() {
        let image = image_file().unwrap();
        let mut session = Session::new();
        session.execute("file.new", &json!({})).unwrap();
        let load = |session: &mut Session| {
            let loaded = session.execute("place.load", &json!({"path": image.path()})).unwrap();
            session.doc().unwrap().doc.assets[&AssetId(loaded["asset"].as_u64().unwrap())].clone()
        };

        // Written just now: another write in the same second would keep its time, so the time
        // can't vouch for the bytes later: only the size is kept, with a time no file has.
        let asset = load(&mut session);
        assert_eq!(asset.link_fingerprint.map(|f| f.mtime), Some(crate::cmd::links::UNVERIFIED_MTIME));
        assert_eq!(asset.link.as_deref(), image.path().to_str());

        // A file that has been as it is for a while is remembered by its size and time.
        image.as_file().set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60)).unwrap();
        let expected = crate::cmd::datamerge::fingerprint_from(&std::fs::metadata(image.path()).unwrap());
        session.execute("file.new", &json!({})).unwrap();
        assert_eq!(load(&mut session).link_fingerprint, Some(expected));
    }

    #[test]
    fn individual_placement_parameters_bypass_selected_frames() {
        let image = image_file().unwrap();
        for graphic in [false, true] {
            for (key, value, expected) in [
                ("x", 0, Rect::new(0.0, 36.0, 40.0, 56.0)),
                ("y", 0, Rect::new(36.0, 0.0, 76.0, 20.0)),
                ("spread", 0, Rect::new(36.0, 36.0, 76.0, 56.0)),
                ("width", 0, Rect::ZERO),
                ("width", 80, Rect::new(36.0, 36.0, 116.0, 76.0)),
            ] {
                let mut session = Session::new();
                session.execute("file.new", &json!({})).unwrap();
                let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap();
                if graphic {
                    session.execute("file.place", &json!({"path": image.path()})).unwrap();
                }
                let id = ItemId(selected["id"].as_u64().unwrap());
                let original = serde_json::to_value(session.doc().unwrap().doc.item(id).unwrap()).unwrap();
                let mut params = json!({"path": image.path()});
                params[key] = json!(value);

                let result = session.execute("file.place", &params);
                if key == "width" && value == 0 {
                    assert!(result.is_err(), "zero width must be rejected, graphic={graphic}");
                    continue;
                }
                let placed = result.unwrap();

                assert_ne!(placed["id"], selected["id"], "{key}={value}, graphic={graphic}");
                let document = &session.doc().unwrap().doc;
                assert_eq!(serde_json::to_value(document.item(id).unwrap()).unwrap(), original);
                let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap();
                assert_eq!(item.bounds(), expected);
                let Content::Graphic(content) = &item.content else { panic!("placed frame must be graphic") };
                let [scale_x, _, _, scale_y, _, _] = content.xf.as_coeffs();
                assert!(scale_x > 0.0 && scale_y > 0.0);
            }
        }
    }

    fn assert_implicit_placement_preserves_geometry(command: &str, params: Value) -> std::result::Result<(), Box<dyn std::error::Error>> {
        let image = image_file()?;
        let mut session = Session::new();
        session.execute("file.new", &json!({}))?;
        let selected = session.execute(command, &params)?;
        session.execute("object.stroke", &json!({"weight": 6}))?;
        let id = ItemId(selected["id"].as_u64().ok_or("missing selected item id")?);
        let original = serde_json::to_value(session.doc()?.doc.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?)?;

        let placed = session.execute("file.place", &json!({"path": image.path()}))?;

        assert_ne!(placed["id"], selected["id"], "{command}");
        let document = &session.doc()?.doc;
        assert_eq!(serde_json::to_value(document.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?)?, original, "{command}");
        let placed_id = ItemId(placed["id"].as_u64().ok_or("missing placed item id")?);
        let item = document.item(placed_id).ok_or(designcraft_doc::DocError::NoItem(placed_id))?;
        assert_eq!(item.bounds(), Rect::new(36.0, 36.0, 76.0, 56.0));
        assert!(matches!(item.content, Content::Graphic(_)));
        assert_eq!(document.spreads[0].items.len(), 2);
        Ok(())
    }

    #[test]
    fn implicit_placement_preserves_selected_line() {
        assert_implicit_placement_preserves_geometry("line.create", json!({"a": [18, 600], "b": [594, 600]})).unwrap();
    }

    #[test]
    fn implicit_placement_preserves_selected_straight_open_path() {
        assert_implicit_placement_preserves_geometry(
            "path.create",
            json!({"anchors": [{"p": [20, 30]}, {"p": [80, 90]}, {"p": [140, 150]}], "closed": false}),
        )
        .unwrap();
    }

    /// Paths with an area take the image: a closed empty frame, and an open V as before.
    #[test]
    fn implicit_placement_fills_selected_frames_and_open_paths_with_an_area() {
        let image = image_file().unwrap();
        for (command, params) in [
            ("frame.create", json!({"rect": [100, 120, 200, 220]})),
            ("path.create", json!({"anchors": [{"p": [20, 30]}, {"p": [80, 90]}, {"p": [140, 30]}], "closed": false})),
        ] {
            let mut session = Session::new();
            session.execute("file.new", &json!({})).unwrap();
            let selected = session.execute(command, &params).unwrap();

            let placed = session.execute("file.place", &json!({"path": image.path()})).unwrap();

            assert_eq!(placed["id"], selected["id"], "{command}");
            let document = &session.doc().unwrap().doc;
            assert!(matches!(document.item(ItemId(selected["id"].as_u64().unwrap())).unwrap().content, Content::Graphic(_)), "{command}");
            assert_eq!(document.spreads[0].items.len(), 1, "{command}");
        }
    }

    /// A `width` x `height` PNG with a pHYs chunk of `ppm` pixels per meter on both axes, or none.
    fn png_with_density(width: u32, height: u32, ppm: Option<u32>) -> std::io::Result<tempfile::NamedTempFile> {
        fn crc32(data: &[u8]) -> u32 {
            let mut crc = 0xFFFF_FFFFu32;
            for &b in data {
                crc ^= b as u32;
                for _ in 0..8 {
                    crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
                }
            }
            !crc
        }
        let pixels = [30, 90, 180, 255].repeat((width * height) as usize);
        let png = designcraft_render::Rendered { width, height, pixels }.to_png();
        assert_eq!(&png[12..16], b"IHDR");
        let mut bytes = png[..33].to_vec();
        if let Some(ppm) = ppm {
            let mut phys = Vec::new();
            phys.extend_from_slice(&ppm.to_be_bytes());
            phys.extend_from_slice(&ppm.to_be_bytes());
            phys.push(1);
            bytes.extend_from_slice(&(phys.len() as u32).to_be_bytes());
            bytes.extend_from_slice(b"pHYs");
            bytes.extend_from_slice(&phys);
            let mut c = b"pHYs".to_vec();
            c.extend_from_slice(&phys);
            bytes.extend_from_slice(&crc32(&c).to_be_bytes());
        }
        bytes.extend_from_slice(&png[33..]);
        let file = tempfile::Builder::new().suffix(".png").tempfile()?;
        std::fs::write(file.path(), bytes)?;
        Ok(file)
    }

    #[test]
    fn placed_photo_honors_its_embedded_resolution() {
        // #1991: a placed graphic's embedded density sets its size (600 dpi: 40 px place
        // 4.8 pt wide), instead of a pixel always becoming a point.
        let file = png_with_density(40, 20, Some(23622)).unwrap();
        let mut session = Session::new();
        session.execute("file.new", &json!({})).unwrap();
        let placed = session.execute("file.place", &json!({"path": file.path(), "x": 10.0, "y": 20.0})).unwrap();
        let document = &session.doc().unwrap().doc;
        let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap();
        let b = item.bounds();
        assert!((b.x0 - 10.0).abs() < 1e-9 && (b.y0 - 20.0).abs() < 1e-9, "{b:?}");
        assert!((b.width() - 4.8).abs() < 0.01 && (b.height() - 2.4).abs() < 0.01, "{b:?}");
    }

    /// File › Place, then a click: an 11 x 17 in image (330 x 510 px at 30 ppi) comes in at
    /// 792 x 1224 pt, keeps that size through a save and reopen, and an image with no stored
    /// resolution comes in at 72 ppi (330 x 510 pt).
    #[test]
    fn a_clicked_image_keeps_its_print_size_through_save_and_reopen() {
        // 1181 pixels per meter is 29.9974 ppi.
        let (w, h) = (330.0 * 72.0 / (1181.0 * 0.0254), 510.0 * 72.0 / (1181.0 * 0.0254));
        for (ppm, (ew, eh)) in [(Some(1181), (w, h)), (None, (330.0, 510.0))] {
            let image = png_with_density(330, 510, ppm).unwrap();
            let mut session = Session::new();
            session.execute("file.new", &json!({})).unwrap();
            session.execute("file.place", &json!({"path": image.path(), "loadCursor": true})).unwrap();
            session.execute("place.drop", &json!({"x": 0, "y": 0})).unwrap();
            // The bounds and natural size of the document's one placed graphic.
            let shown = |session: &Session| {
                let doc = &session.doc().unwrap().doc;
                let graphics: Vec<_> = doc
                    .all_items()
                    .into_iter()
                    .filter_map(|id| doc.item(id))
                    .filter_map(|item| match &item.content {
                        Content::Graphic(g) => Some((item.bounds(), g.size)),
                        _ => None,
                    })
                    .collect();
                assert_eq!(graphics.len(), 1, "{graphics:?}");
                graphics[0]
            };
            let (b, size) = shown(&session);
            assert!((b.width() - ew).abs() < 1e-6 && (b.height() - eh).abs() < 1e-6, "{ppm:?}: {b:?}");
            assert!((size.0 - ew).abs() < 1e-6 && (size.1 - eh).abs() < 1e-6, "{ppm:?}: {size:?}");

            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("placed.designcraft");
            session.execute("file.save", &json!({"path": path.to_string_lossy()})).unwrap();
            let mut reopened = Session::new();
            reopened.execute("file.open", &json!({"path": path.to_string_lossy()})).unwrap();
            assert_eq!(shown(&reopened), (b, size), "{ppm:?}");
        }
    }

    #[test]
    fn explicit_frame_wins_over_placement_and_selection() {
        let image = image_file().unwrap();
        let mut session = Session::new();
        session.execute("file.new", &json!({})).unwrap();
        let target = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap();
        let selected = session.execute("frame.create", &json!({"rect": [300, 320, 400, 420]})).unwrap();

        let placed =
            session.execute("file.place", &json!({"path": image.path(), "frame": target["id"], "x": 0, "y": 0, "spread": 99, "width": 80})).unwrap();

        assert_eq!(placed["id"], target["id"]);
        let document = &session.doc().unwrap().doc;
        let item = document.item(ItemId(target["id"].as_u64().unwrap())).unwrap();
        assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0));
        assert!(matches!(item.content, Content::Graphic(_)));
        assert!(matches!(document.item(ItemId(selected["id"].as_u64().unwrap())).unwrap().content, Content::Unassigned));
        assert_eq!(document.spreads[0].items.len(), 2);
    }

    fn assert_width_rejected(width: Value) -> std::result::Result<(), Box<dyn std::error::Error>> {
        let image = image_file()?;
        for graphic in [false, true] {
            for explicit_frame in [false, true] {
                let mut session = Session::new();
                session.execute("file.new", &json!({}))?;
                let target = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]}))?;
                if graphic {
                    session.execute("file.place", &json!({"path": image.path()}))?;
                }
                let mut params = json!({"path": image.path(), "width": width});
                if explicit_frame {
                    params["frame"] = target["id"].clone();
                    session.execute("frame.create", &json!({"rect": [300, 320, 400, 420]}))?;
                }
                let before = session.doc()?;
                let document = before.doc.clone();
                let selection = before.selection.clone();
                let revision = before.revision;
                let assets = document.assets.len();

                let result = session.execute("file.place", &params);

                assert!(
                    matches!(&result, Err(crate::EngineError::BadParams { .. })),
                    "width={width}, graphic={graphic}, explicit_frame={explicit_frame}: expected BadParams, got {result:?}"
                );
                let error = result.err().ok_or_else(|| crate::EngineError::Other("expected placement error".into()))?;
                let crate::EngineError::BadParams { cmd, msg } = error else { return Err(error.into()) };
                assert_eq!(cmd, "file.place");
                assert!(msg.contains("width") && msg.contains("finite") && msg.contains("greater than zero"), "{msg}");
                let after = session.doc()?;
                assert!(std::sync::Arc::ptr_eq(&document, &after.doc));
                assert_eq!(after.selection, selection);
                assert_eq!(after.revision, revision);
                assert_eq!(after.doc.assets.len(), assets);
            }
        }
        Ok(())
    }

    #[test]
    fn width_rejected_when_zero() {
        assert_width_rejected(json!(0)).unwrap();
    }

    #[test]
    fn width_rejected_when_negative() {
        assert_width_rejected(json!(-80)).unwrap();
    }

    #[test]
    fn width_rejected_when_non_numeric() {
        for width in [json!("80"), json!(true), json!([80]), json!({"value": 80})] {
            assert_width_rejected(width).unwrap();
        }
    }

    fn assert_null_placement_uses_selection(keys: &[&str]) -> std::result::Result<(), Box<dyn std::error::Error>> {
        let image = image_file()?;
        let previous_image = image_file_with_color(31)?;
        for graphic in [false, true] {
            let mut session = Session::new();
            session.execute("file.new", &json!({}))?;
            let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]}))?;
            let previous = graphic.then(|| session.execute("file.place", &json!({"path": previous_image.path()}))).transpose()?;
            let mut params = json!({"path": image.path()});
            for key in keys {
                params[*key] = Value::Null;
            }

            let placed = session.execute("file.place", &params)?;

            assert_eq!(placed["id"], selected["id"], "keys={keys:?}, graphic={graphic}");
            if let Some(previous) = previous {
                assert_ne!(placed["asset"], previous["asset"]);
            }
            let document = &session.doc()?.doc;
            let id = ItemId(selected["id"].as_u64().ok_or_else(|| crate::EngineError::Other("frame.create returned no numeric id".into()))?);
            let item = document.item(id).ok_or(designcraft_doc::DocError::NoItem(id))?;
            assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0));
            assert!(matches!(&item.content, Content::Graphic(_)), "placed frame must be graphic");
            let Content::Graphic(content) = &item.content else {
                return Err(crate::EngineError::Other("placed frame must be graphic".into()).into());
            };
            assert_eq!(json!(content.asset.0), placed["asset"]);
            assert_eq!(document.spreads[0].items.len(), 1);
        }
        Ok(())
    }

    #[test]
    fn selection_used_when_x_null() {
        assert_null_placement_uses_selection(&["x"]).unwrap();
    }

    #[test]
    fn selection_used_when_y_null() {
        assert_null_placement_uses_selection(&["y"]).unwrap();
    }

    #[test]
    fn selection_used_when_spread_null() {
        assert_null_placement_uses_selection(&["spread"]).unwrap();
    }

    #[test]
    fn selection_used_when_width_null() {
        assert_null_placement_uses_selection(&["width"]).unwrap();
    }

    #[test]
    fn selection_used_when_all_placement_parameters_null() {
        assert_null_placement_uses_selection(&["x", "y", "spread", "width"]).unwrap();
    }

    #[test]
    fn implicit_placement_fills_empty_and_replaces_graphic_selection() {
        let image = image_file().unwrap();
        let previous_image = image_file_with_color(31).unwrap();
        for graphic in [false, true] {
            let mut session = Session::new();
            session.execute("file.new", &json!({})).unwrap();
            let selected = session.execute("frame.create", &json!({"rect": [100, 120, 200, 220]})).unwrap();
            let previous = graphic.then(|| session.execute("file.place", &json!({"path": previous_image.path()})).unwrap());

            let placed = session.execute("file.place", &json!({"path": image.path()})).unwrap();

            assert_eq!(placed["id"], selected["id"]);
            if let Some(previous) = previous {
                assert_ne!(placed["asset"], previous["asset"]);
            }
            let document = &session.doc().unwrap().doc;
            let item = document.item(ItemId(placed["id"].as_u64().unwrap())).unwrap();
            assert_eq!(item.bounds(), Rect::new(100.0, 120.0, 200.0, 220.0));
            let Content::Graphic(content) = &item.content else { panic!("placed frame must be graphic") };
            assert_eq!(json!(content.asset.0), placed["asset"]);
            assert_eq!(document.spreads[0].items.len(), 1);
        }
    }
}

#[cfg(test)]
mod pdf_crop_tests {
    use serde_json::json;

    use crate::Session;

    #[test]
    fn place_pdf_cropped_to_its_trim_box() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();
        let b64 = s.execute("file.exportPdf", &json!({"bleed": true})).unwrap()["base64"].as_str().unwrap().to_string();
        let mut t = Session::new();
        t.execute("file.new", &json!({})).unwrap();
        let size = |t: &mut Session, crop: &str| {
            t.execute("edit.deselectAll", &json!({})).unwrap();
            let r = t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": crop, "width": 630, "x": 0, "y": 0})).unwrap();
            let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
            t.doc().unwrap().doc.item(id).unwrap().bounds()
        };
        let full = size(&mut t, "crop");
        let trim = size(&mut t, "trim");
        assert!((full.width() - 630.0).abs() < 1e-6, "{full:?}");
        assert!((trim.width() - 612.0).abs() < 1e-3 && (trim.height() - 792.0).abs() < 1e-3, "{trim:?}");
        assert!(t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "nope"})).is_err());
    }

    /// Placing with `trim` stores the choice; the graphic spans the trim box and draws only it,
    /// even in a frame larger than the graphic.
    #[test]
    fn a_pdf_placed_with_its_trim_box_stores_and_draws_that_box() {
        // Letter with a 9 pt bleed: black in the bleed's top-left corner and a black square inside.
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();
        for rect in [[-9, -9, 0, 0], [10, 10, 30, 30]] {
            let id = s.execute("frame.create", &json!({"rect": rect})).unwrap()["id"].clone();
            s.execute("object.fill", &json!({"ids": [id], "swatch": "[Black]"})).unwrap();
        }
        let b64 = s.execute("file.exportPdf", &json!({"bleed": true})).unwrap()["base64"].as_str().unwrap().to_string();

        let mut t = Session::new();
        t.execute("file.new", &json!({})).unwrap();
        // `width` is the whole page's (630 pt with its bleed): half size.
        let r = t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "trim", "width": 315, "x": 100, "y": 100})).unwrap();
        let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
        let d = t.doc().unwrap().doc.clone();
        let it = d.item(id).unwrap();
        let g = it.graphic().unwrap().clone();
        let a = &d.assets[&g.asset];
        assert_eq!(a.pdf_crop, designcraft_doc::PdfCrop::Trim);
        let b = a.shown_box().unwrap();
        let want = [9.0 / 630.0, 9.0 / 810.0, 621.0 / 630.0, 801.0 / 810.0];
        assert!(b.iter().zip(want).all(|(x, y)| (x - y).abs() < 1e-4), "{b:?}");
        assert!((g.size.0 - 612.0).abs() < 1e-3 && (g.size.1 - 792.0).abs() < 1e-3, "{:?}", g.size);
        let shown = (it.xf * g.xf).transform_rect_bbox(designcraft_geom::Rect::new(0.0, 0.0, g.size.0, g.size.1));
        let fb = it.bounds();
        for (x, y) in [(shown.x0, 100.0), (shown.y0, 100.0), (shown.x1, 406.0), (shown.y1, 496.0), (fb.x1, 406.0), (fb.y1, 496.0)] {
            assert!((x - y).abs() < 1e-3, "{shown:?} {fb:?}");
        }

        // A frame larger than the graphic still shows only the trim box.
        t.edit(|d, _| {
            d.item_mut(id).unwrap().path = designcraft_geom::shapes::rectangle(designcraft_geom::Rect::new(90.0, 90.0, 416.0, 506.0));
            Ok(())
        })
        .unwrap();
        let d = t.doc().unwrap().doc.clone();
        let mut rr = designcraft_render::Renderer::new();
        rr.threads = 0;
        let img = rr.render_page(&d, &t.cache, 0, 1.0, false, &Default::default()).unwrap();
        let dark = |x: u32, y: u32| img.pixel(x, y)[0] < 60;
        // The page sits at 95.5: its bleed corner (95.5–100) is cut off, the square (105–115) shows
        // where it is on the page.
        assert!(!dark(97, 97), "the bleed is outside the trim box");
        assert!(!dark(103, 103), "the page is offset by its bleed");
        assert!(dark(110, 110), "the square inside the trim box");
    }

    #[test]
    fn placed_pdf_keeps_its_exact_page_size() {
        // A 100.4 x 50.4 pt page placed 100.4 pt wide is 50.4 pt tall, not stretched to whole points.
        let mut s = Session::new();
        s.execute("file.new", &json!({"width": 100.4, "height": 50.4, "pages": 1})).unwrap();
        let b64 = s.execute("file.exportPdf", &json!({})).unwrap()["base64"].as_str().unwrap().to_string();
        let mut t = Session::new();
        t.execute("file.new", &json!({})).unwrap();
        let r = t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "width": 100.4, "x": 0, "y": 0})).unwrap();
        let id = designcraft_doc::ItemId(r["id"].as_u64().unwrap());
        let d = &t.doc().unwrap().doc;
        let it = d.item(id).unwrap();
        let b = it.bounds();
        assert!((b.width() - 100.4).abs() < 1e-3 && (b.height() - 50.4).abs() < 1e-3, "{b:?}");
        let designcraft_doc::Content::Graphic(g) = &it.content else { panic!("not a graphic") };
        assert!((g.size.0 - 100.4).abs() < 1e-3 && (g.size.1 - 50.4).abs() < 1e-3, "{:?}", g.size);
    }
}

#[cfg(test)]
mod layout_place_tests {
    use serde_json::json;

    use crate::Session;

    #[test]
    fn place_a_page_of_an_idml_file_as_a_group() {
        let mut a = Session::new();
        a.execute("file.new", &json!({"pages": 2})).unwrap();
        a.execute("frame.create", &json!({"rect": [100, 100, 200, 150], "content": "text", "text": "From page one", "caret": false})).unwrap();
        a.execute("frame.create", &json!({"rect": [300, 400, 350, 450]})).unwrap();
        let idml = designcraft_idml::export_idml(&a.doc().unwrap().doc);
        let b64 = super::base64_encode(&idml);
        let mut b = Session::new();
        b.execute("file.new", &json!({})).unwrap();
        let r = b.execute("file.place", &json!({"base64": b64, "name": "src.idml", "layoutPage": 1, "x": 0, "y": 0})).unwrap();
        assert_eq!(r["items"], 2);
        let d = &b.doc().unwrap().doc;
        let g = d.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap();
        assert_eq!(g.children().len(), 2, "one group");
        let bb = g.bounds();
        assert!((bb.x0 - 100.0).abs() < 1e-6 && (bb.y0 - 100.0).abs() < 1e-6, "page top-left at 0,0: {bb:?}");
        assert!(d.stories.values().any(|st| st.text == "From page one"), "stories come along");
        assert!(b.execute("file.place", &json!({"base64": b64, "name": "src.idml", "layoutPage": 2})).is_err(), "page 2 is empty");
    }
}

#[cfg(test)]
mod nested_frame_tests {
    use std::sync::Arc;

    use designcraft_doc::{Content, Item, ItemId, Shape, SpreadRef};
    use designcraft_geom::{Affine, Rect, shapes};
    use serde_json::json;

    use crate::Session;

    fn png(red: u8) -> String {
        let png = designcraft_render::Rendered { width: 40, height: 20, pixels: [red, 90, 30, 255].repeat(800) }.to_png();
        super::super::base64_encode(&png)
    }

    /// A graphic placed into a frame holding an image pasted into it (how a document from InDesign
    /// keeps a photo) replaces the image and fills the frame, which keeps its size.
    #[test]
    fn placing_into_a_frame_with_a_nested_image_replaces_it() {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        let first = s.execute("file.place", &json!({"base64": png(200), "name": "old.png", "x": 0, "y": 0})).unwrap();
        let old = ItemId(first["id"].as_u64().unwrap());
        let frame = s
            .edit(|d, _| {
                let mut image = (*d.item(old).unwrap()).clone();
                d.remove_item(old)?;
                image.xf = Affine::translate((-20.0, -20.0));
                let id = ItemId(d.alloc());
                let mut frame = Item::new(id, image.layer, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 90.0)));
                frame.xf = Affine::translate((100.0, 100.0));
                frame.content = Content::Group { items: vec![Arc::new(image)] };
                d.insert_item(SpreadRef::Doc(0), frame, None)?;
                Ok(id)
            })
            .unwrap();
        s.execute("selection.set", &json!({"ids": [frame.0]})).unwrap();
        s.execute("file.place", &json!({"base64": png(20), "name": "new.png"})).unwrap();
        let d = &s.doc().unwrap().doc;
        let it = d.item(frame).unwrap();
        let Content::Graphic(g) = &it.content else { panic!("the frame holds the new graphic: {:?}", it.content) };
        assert_eq!(d.assets[&g.asset].name, "new.png");
        assert_eq!(it.inner_bounds(), Rect::new(0.0, 0.0, 60.0, 90.0), "the frame keeps its size");
        assert_eq!(d.spreads[0].items.len(), 1, "no new object");
    }
}

#[cfg(test)]
mod cursor_cap_tests {
    use serde_json::{Value, json};

    use super::MAX_LOADED_IMAGES;
    use crate::Session;

    fn png() -> String {
        let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png();
        super::super::base64_encode(&png)
    }

    /// A session whose place cursor holds `held` images, loaded without decoding each of them.
    fn holding(held: usize) -> Session {
        let mut s = Session::new();
        s.execute("file.new", &json!({})).unwrap();
        s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap();
        let first = s.loaded.unwrap();
        s.loaded_queue = std::iter::repeat_n(first, held - 1).collect();
        s
    }

    fn count(s: &Session) -> usize {
        super::loaded_count(s)
    }

    /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing.
    #[test]
    fn appending_stops_at_the_cap_on_the_whole_cursor() {
        let image = png();
        let single = json!({"base64": image, "name": "a.png", "append": true});
        let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true});
        let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true});
        for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] {
            let mut s = holding(MAX_LOADED_IMAGES);
            let assets = s.doc().unwrap().doc.assets.len();
            assert!(s.execute(command, params).is_err(), "{command} {params}");
            assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}");
            assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}");
        }
        // One over, as a batch.
        let mut s = holding(MAX_LOADED_IMAGES - 1);
        assert!(s.execute("place.load", &two).is_err());
        assert_eq!(count(&s), MAX_LOADED_IMAGES - 1);
    }

    /// The last places up to the cap load, and an unreadable batch reports the cap before decoding.
    #[test]
    fn appending_up_to_the_cap_still_loads() {
        let image = png();
        for params in
            [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})]
        {
            let mut s = holding(MAX_LOADED_IMAGES - 1);
            s.execute("place.load", &params).unwrap();
            assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}");
        }
        let mut s = holding(MAX_LOADED_IMAGES);
        let error =
            s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string();
        assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}");
    }

    /// Without `append` the new images replace the cursor, so what it holds doesn't count.
    #[test]
    fn replacing_a_full_cursor_is_not_capped() {
        let image = png();
        let mut s = holding(MAX_LOADED_IMAGES);
        let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap();
        assert_eq!(result["loaded"], true);
        assert_eq!(count(&s), 1);
        let mut s = holding(MAX_LOADED_IMAGES);
        s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap();
        assert_eq!(count(&s), 1);
    }
}