diff --git a/crates/engine/src/cmds_file.rs b/crates/engine/src/cmds_file.rs index 5b834a0c..0dd52528 100644 --- a/crates/engine/src/cmds_file.rs +++ b/crates/engine/src/cmds_file.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { label: "Import to Stage…", menu: "File/Import", shortcut: Some("Ctrl+R"), - params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead)}", + params: "{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead), match_stage?: false (SVG only: set the stage to the SVG size rounded up to whole pixels, and place it at the origin unless coordinates are given)}", mutates: true, run: import_to_stage, }, @@ -284,10 +284,14 @@ pub(crate) const MAX_IMPORT_BYTES: u64 = 256 * 1024 * 1024; /// artwork they clip (ADR 0021). Centred on the stage unless `x`/`y` give its top-left corner. pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { let path = PathBuf::from(str_req(p, "path")?); + let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); + let match_stage = opt_bool(p, "match_stage")?.unwrap_or(false); + if match_stage && ext.as_deref() != Some("svg") { + return Err(EngineError::Param("match_stage is only available for SVG drawings".into())); + } if crate::cmds_sound::is_sound(&path) { return crate::cmds_sound::import_to_stage(s, &path); } - let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase); if !matches!(ext.as_deref(), Some("svg" | "png" | "jpg" | "jpeg")) { return Err(EngineError::Param("Import to Stage reads SVG drawings, PNG or JPEG images, and WAV, Ogg Vorbis or MP3 sounds".into())); } @@ -305,15 +309,22 @@ pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { if drawing.is_empty() { return Err(EngineError::State(format!("{} has no shapes AniCraft can import yet. {}", path.display(), drawing.report.summary()))); } - let stage = s.doc.stage; + let mut stage = s.doc.stage; + let (default_x, default_y) = if match_stage { + stage.width = svg_stage_edge(drawing.width)?; + stage.height = svg_stage_edge(drawing.height)?; + (0.0, 0.0) + } else { + ((stage.width as f32 - drawing.width) * 0.5, (stage.height as f32 - drawing.height) * 0.5) + }; // `cx`/`cy` centre it on a point (a drop, ADR 0059); `x`/`y` give its top-left corner. let x = match opt_f32(p, "cx")? { Some(cx) => cx - drawing.width * 0.5, - None => opt_f32(p, "x")?.unwrap_or((stage.width as f32 - drawing.width) * 0.5), + None => opt_f32(p, "x")?.unwrap_or(default_x), }; let y = match opt_f32(p, "cy")? { Some(cy) => cy - drawing.height * 0.5, - None => opt_f32(p, "y")?.unwrap_or((stage.height as f32 - drawing.height) * 0.5), + None => opt_f32(p, "y")?.unwrap_or(default_y), }; let onto_active = match opt_str(p, "layer")? { None | Some("new") => false, @@ -420,6 +431,9 @@ pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { s.layer = lid; (lid, ids, made, Some(fid.0)) }; + if match_stage { + s.doc.stage = stage; + } s.select_only(ids.iter().copied()); Ok(json!({ "layer": layer_id.0, @@ -437,6 +451,16 @@ pub(crate) fn import_to_stage(s: &mut Session, p: &Value) -> Result { })) } +/// A stage has whole-pixel edges. Round up so the imported drawing fits at its original scale. +fn svg_stage_edge(pixels: f32) -> Result { + let edge = pixels.ceil(); + if (1.0..=MAX_STAGE_EDGE as f32).contains(&edge) { + Ok(edge as u32) + } else { + Err(EngineError::Param(format!("the SVG size must fit a stage of up to {MAX_STAGE_EDGE} pixels per edge"))) + } +} + /// An SVG drawing read from `path` (size-checked), with at least one shape. pub(crate) fn read_svg(path: &std::path::Path) -> Result { if crate::vfs::len(path)? > MAX_IMPORT_BYTES { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 342e6942..640cac21 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -431,6 +431,35 @@ fn svg_round_trip_looks_the_same_and_imports_as_one_undo_step() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn svg_import_matches_stage_only_when_requested_and_undoes_together() { + let dir = std::env::temp_dir().join(format!("anicraft-svg-stage-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let svg = dir.join("badge.svg"); + std::fs::write(&svg, r#""#).unwrap(); + let mut s = Session::default(); + run(&mut s, "file.new", json!({"width": 160, "height": 80, "fps": 30})); + let previous = s.doc.stage; + let name = svg.display().to_string(); + run(&mut s, "file.import", json!({"path": name})); + assert_eq!(s.doc.stage, previous); + let centered = s.visible_elements()[0].transform.translation(); + assert!(centered.x > 0.0 && centered.y > 0.0, "the default import still centres the file"); + s.undo().unwrap(); + + let report = run(&mut s, "file.import", json!({"path": name, "match_stage": true})); + let stage = s.doc.stage; + assert_eq!(stage.width, report["width"].as_f64().unwrap().ceil() as u32); + assert_eq!(stage.height, report["height"].as_f64().unwrap().ceil() as u32); + assert_eq!(stage.fps, previous.fps); + let offset = s.visible_elements()[0].transform.translation(); + assert!(offset.x.abs() < 1e-5 && offset.y.abs() < 1e-5, "the SVG starts at the new stage's origin: {offset:?}"); + s.undo().unwrap(); + assert_eq!(s.doc.stage, previous); + assert!(s.visible_elements().is_empty()); + std::fs::remove_dir_all(&dir).unwrap(); +} + #[test] fn animated_gif_export() { let dir = std::env::temp_dir().join(format!("anicraft-gif-{}", std::process::id())); diff --git a/docs/guide/reference/commands.md b/docs/guide/reference/commands.md index 3068d543..dec3df46 100644 --- a/docs/guide/reference/commands.md +++ b/docs/guide/reference/commands.md @@ -23,7 +23,7 @@ This page is generated from the command registry, so it always matches the versi - **Export Frame as PNG…** `file.export_png` · File › Export Parameters: `{path, frame? (in the current scene), scale?}` - **Import to Stage…** `file.import` · File › Import · **Ctrl+R** (macOS **⌘R**) · changes the document - Parameters: `{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead)}` + Parameters: `{path (.svg, .png, .jpg; or a .wav, .ogg or .mp3 sound: onto a new layer at the playhead), x?, y? (top-left on the stage; default: centred), cx?, cy? (centred on that point instead), layer? (new (default) | active: a one-layer drawing goes into the active layer's keyframe at the playhead), match_stage?: false (SVG only: set the stage to the SVG size rounded up to whole pixels, and place it at the origin unless coordinates are given)}` - **Export Frame as SVG…** `file.export_svg` · File › Export Parameters: `{path, frame? (in the current scene), confirm?}` - **Export Video…** `file.export_video` · File › Export