diff --git a/crates/canvas-pilot/src/clipboard.rs b/crates/canvas-pilot/src/clipboard.rs index 33d8efc..ad14b23 100644 --- a/crates/canvas-pilot/src/clipboard.rs +++ b/crates/canvas-pilot/src/clipboard.rs @@ -63,14 +63,14 @@ pub fn encode(layout: &Layout, indices: &[usize], summary: &str) -> Result Result { } let payload: Payload = serde_json::from_str(json).map_err(|e| format!("Invalid Canvas Pilot clipboard: {e}"))?; - if payload.format != "canvas-pilot.layers" || payload.version != 1 { + if payload.format != "canvas-pilot.layers" || !matches!(payload.version, 1 | 2) { return Err( - "Unsupported Canvas Pilot clipboard format/version; expected version 1.".into(), + "Unsupported Canvas Pilot clipboard format/version; expected version 1 or 2.".into(), ); } if payload.layers.is_empty() || payload.layers.len() > 256 { @@ -102,6 +102,7 @@ pub fn parse(json: &str) -> Result { layer.bounds.validate()?; layer.appearance.validate(layer.bounds)?; shapes.push(DetectedShape { + name: (payload.version == 2).then(|| layer.name.clone()), id: layer.name, geometry: layer.bounds, outline: [0.; 2], @@ -111,7 +112,7 @@ pub fn parse(json: &str) -> Result { appearance: Some(layer.appearance), }); } - Ok(ImportDocument { shapes, svg: false, note: "Canvas Pilot layer values include exact crop, fit and blanking. Source assignments, names and device links stay unchanged.".into() }) + Ok(ImportDocument { shapes, svg: false, note: "Canvas Pilot layer values include exact crop, fit and blanking. Names can be applied separately; source assignments and device links stay unchanged.".into() }) } impl Layout { /// Apply geometry and optional appearance atomically, preserving selection and source identity. @@ -123,6 +124,32 @@ impl Layout { crop_fit: bool, masks: bool, ) -> Result<(), String> { + self.apply_mapped_clipboard_with_names(values, zooms, appearances, crop_fit, masks, &[]) + } + /// Apply optional explicit names in the same atomic edit as geometry/appearance. + pub fn apply_mapped_clipboard_with_names( + &mut self, + values: &[(usize, Geometry)], + zooms: &[(usize, f64)], + appearances: &[(usize, Appearance)], + crop_fit: bool, + masks: bool, + names: &[(usize, String)], + ) -> Result<(), String> { + let mut named = std::collections::BTreeSet::new(); + for (i, name) in names { + if *i >= self.layers.len() + || !self.selectable(*i) + || !values.iter().any(|(target, _)| target == i) + || !named.insert(*i) + || name.trim().is_empty() + || name.chars().count() > 128 + { + return Err( + "Each name needs one editable destination and 1–128 characters.".into(), + ); + } + } let mut seen = std::collections::BTreeSet::new(); for &(i, a) in appearances { if i >= self.layers.len() || !self.selectable(i) { @@ -161,6 +188,9 @@ impl Layout { draft.formats.masks[i] = appearance.mask.validate()?; } } + for (i, name) in names { + draft.info[*i].name = name.trim().to_owned(); + } self.finish_drag(); let before = self.snapshot(); self.restore(draft.snapshot()); diff --git a/crates/canvas-pilot/src/device.rs b/crates/canvas-pilot/src/device.rs index 132ad61..91dd3b6 100644 --- a/crates/canvas-pilot/src/device.rs +++ b/crates/canvas-pilot/src/device.rs @@ -111,6 +111,7 @@ impl Screen { return Err("Duplicate device layer selection".into()); } shapes.push(DetectedShape { + name: None, id, geometry: layer.geometry, outline: [0.0; 2], diff --git a/crates/canvas-pilot/src/geometry_formats.rs b/crates/canvas-pilot/src/geometry_formats.rs index 5147919..fe9100c 100644 --- a/crates/canvas-pilot/src/geometry_formats.rs +++ b/crates/canvas-pilot/src/geometry_formats.rs @@ -117,6 +117,7 @@ fn document( return Err("The geometry background must cover the complete canvas.".into()); } detected.push(DetectedShape { + name: crate::import::source_name(Some(&shape.name)), id: if shape.name.is_empty() { shape.id } else { @@ -428,6 +429,16 @@ pub(crate) fn parse_dxf(text: &str) -> Result { pub(crate) fn parse_dxf_bytes(bytes: &[u8]) -> Result { let tags = craft_dxf::parse_with_limit(bytes, MAX_EXCHANGE_BYTES / 4) .map_err(|e| format!("Invalid DXF: {e}"))?; + let cad_names: std::collections::HashMap<_, _> = craft_dxf::model::records(&tags) + .iter() + .filter(|r| r.kind == "LAYER") + .filter_map(craft_dxf::model::Layer::read) + .map(|layer| { + let name = crate::import::source_name(layer.description.as_deref()) + .unwrap_or_else(|| layer.name.clone()); + (layer.name, name) + }) + .collect(); let values: Vec<_> = tags.iter().map(|tag| (tag.code, tag.str())).collect(); let pairs: Vec<_> = values .iter() @@ -541,7 +552,7 @@ pub(crate) fn parse_dxf_bytes(bytes: &[u8]) -> Result { .map(|value| value.round() as i64); layers.push(JsonShape { id: id.into(), - name: String::new(), + name: cad_names.get(id).cloned().unwrap_or_else(|| id.to_owned()), role: if id == "midra-background" { "background" } else { diff --git a/crates/canvas-pilot/src/gui.rs b/crates/canvas-pilot/src/gui.rs index 5e39c11..541bbb0 100644 --- a/crates/canvas-pilot/src/gui.rs +++ b/crates/canvas-pilot/src/gui.rs @@ -136,6 +136,7 @@ struct Paste { include_zoom: bool, include_crop_fit: bool, include_masks: bool, + include_names: bool, include_outline: bool, closing: bool, error: String, @@ -210,6 +211,12 @@ impl Paste { } } } + fn names_available(&self) -> bool { + self.shapes + .iter() + .zip(&self.ignored) + .any(|(s, ignored)| !ignored && s.name.is_some()) + } fn appearance_available(&self) -> bool { self.shapes .iter() @@ -259,12 +266,27 @@ impl Paste { } }) .collect(); - layout.apply_mapped_clipboard( + let names: Vec<_> = self + .shapes + .iter() + .enumerate() + .filter_map(|(row, s)| { + if !self.include_names || self.ignored[row] { + None + } else { + s.name + .clone() + .map(|name| (self.mapping[row].unwrap(), name)) + } + }) + .collect(); + layout.apply_mapped_clipboard_with_names( &values, &zooms, &appearances, self.include_crop_fit, self.include_masks, + &names, ) } fn destination_count_warning(&self, layout: &Layout) -> Option { @@ -278,11 +300,12 @@ impl Paste { fn values(&self, layout: &Layout) -> Result, String> { if !self.include_size && !self.include_position + && !(self.include_names && self.names_available()) && !(self.include_zoom && self.zoom_available()) && !((self.include_crop_fit || self.include_masks) && self.appearance_available()) { return Err( - "Choose at least one available geometry or appearance value to paste.".into(), + "Choose at least one available geometry, appearance or name value to paste.".into(), ); } let count = self.ignored.iter().filter(|v| !**v).count(); @@ -740,6 +763,7 @@ impl Editor { include_zoom: true, include_crop_fit: true, include_masks: true, + include_names: false, include_outline: false, closing: false, error: String::new(), @@ -1189,6 +1213,9 @@ impl Editor { ui.checkbox(&mut p.include_position,"Position"); if p.zoom_available() { ui.checkbox(&mut p.include_zoom,"Crop zoom"); } }); + if p.names_available() { + ui.checkbox(&mut p.include_names, "Rename destination layers").on_hover_text("Use supplied source names. Unnamed items and destination folders stay unchanged."); + } if p.appearance_available() { let summary = match (p.include_crop_fit, p.include_masks) { (true, true) => "Appearance · crop, fit and blanking", @@ -1209,7 +1236,7 @@ impl Editor { } egui::CollapsingHeader::new("Import details").show(ui, |ui| { ui.label(&p.note); - ui.small(if p.appearance_available() { "Source assignments, layer names, device links and input proposals are not imported. Crop & fit requires matching source dimensions." } else { "Source format, crop offsets, colors and outline appearance are not imported." }); + ui.small(if p.appearance_available() { "Source assignments, device links and input proposals are not imported. Crop & fit requires matching source dimensions." } else { "Source format, crop offsets, colors and outline appearance are not imported." }); }); if !p.include_size {ui.small("Outline adjustment requires Format. Position uses the source top-left when enabled.");} ui.separator(); @@ -1246,6 +1273,10 @@ impl Editor { } }); }); + if p.include_names { + if let Some(name) = &shape.name { ui.label(format!("New name: {name}")); } + else { ui.small("No source name; destination name stays unchanged."); } + } egui::CollapsingHeader::new("Geometry · before / after").show(ui, |ui| { ui.small(bounds(shape.geometry)); if let Some(a) = shape.appearance { ui.small(format!("Fit: {} · crop L/R/T/B: {} / {} / {} / {} px", a.fit.map(|f| f.label()).unwrap_or("Normal crop"), a.crop.left, a.crop.right, a.crop.top, a.crop.bottom)); ui.small(format!("Blanking L/R/T/B: {:.2}% / {:.2}% / {:.2}% / {:.2}%", a.mask.left*100., a.mask.right*100., a.mask.top*100., a.mask.bottom*100.)); } @@ -1277,7 +1308,7 @@ impl Editor { ui.colored_label(palette.amber,e); } ui.horizontal(|ui| { - if apply_button(ui,"Import mapped values", valid.is_ok() && (preview.layers()!=self.layout.layers() || preview.formats()!=self.layout.formats())).clicked() { + if apply_button(ui,"Import mapped values", valid.is_ok() && (preview.layers()!=self.layout.layers() || preview.formats()!=self.layout.formats() || (0..preview.layers().len()).any(|i| preview.layer_info(i).name != self.layout.layer_info(i).name))).clicked() { match p.apply(&mut self.layout) {Ok(())=>{self.sync();close=true;},Err(e)=>p.error=e} } if ui.button("Cancel").clicked() {close=true;} @@ -6607,6 +6638,66 @@ mod tests { assert_eq!(app.layout.layers()[1], g); } #[test] + fn mixed_named_and_unnamed_imports_leave_unnamed_destinations_alone() { + let mut app = Editor::default(); + app.layout.select(Some(0)); + app.open_paste(r#""#.into()); + let p = app.paste.as_mut().unwrap(); + p.set_scope(ImportScope::All, &app.layout); + p.mapping = vec![Some(0), Some(1)]; + p.include_size = false; + p.include_position = false; + p.include_names = true; + let before = canvas_pilot::project::Project::from_layout(&app.layout); + p.apply(&mut app.layout).unwrap(); + assert_eq!(app.layout.layer_info(0).name, "Presenter"); + assert_eq!(app.layout.layer_info(1).name, before.layers[1].name); + app.layout.undo(); + assert_eq!( + canvas_pilot::project::Project::from_layout(&app.layout), + before + ); + p.ignored[0] = true; + assert!(!p.names_available()); + assert!(p.apply(&mut app.layout).is_err()); + } + #[test] + fn paste_review_renames_only_when_requested_and_supports_name_only_undo() { + let ctx = egui::Context::default(); + let mut app = Editor::default(); + app.layout + .rename_layer(0, "Presenter", "Source folder") + .unwrap(); + app.layout + .rename_layer(1, "Old name", "Destination folder") + .unwrap(); + app.layout.select(Some(1)); + let before = canvas_pilot::project::Project::from_layout(&app.layout); + let text = canvas_pilot::clipboard::encode(&app.layout, &[0], "Summary").unwrap(); + app.open_paste(text); + let p = app.paste.as_mut().unwrap(); + assert!(p.names_available()); + assert!(!p.include_names); + p.include_size = false; + p.include_position = false; + p.include_crop_fit = false; + p.include_masks = false; + assert!(p.apply(&mut app.layout).is_err()); + frame(&mut app, &ctx, vec![]); + click_text(&mut app, &ctx, "Rename destination layers"); + assert!(app.paste.as_ref().unwrap().include_names); + click_text(&mut app, &ctx, "Import mapped values"); + assert!(app.paste.is_none()); + assert_eq!(app.layout.layer_info(1).name, "Presenter"); + assert_eq!(app.layout.layer_info(1).folder, "Destination folder"); + assert_eq!(app.layout.layers()[1], before.layers[1].bounds); + app.layout.undo(); + assert_eq!( + canvas_pilot::project::Project::from_layout(&app.layout), + before + ); + } + #[test] fn copy_and_review_preserve_all_fit_modes_and_allow_mask_only_paste() { use canvas_pilot::formats::{Crop, LayerFit, Mask}; for fit in [ diff --git a/crates/canvas-pilot/src/import.rs b/crates/canvas-pilot/src/import.rs index ee0308b..beaf04b 100644 --- a/crates/canvas-pilot/src/import.rs +++ b/crates/canvas-pilot/src/import.rs @@ -6,6 +6,8 @@ use std::str::FromStr; #[derive(Clone, Debug)] pub struct DetectedShape { pub id: String, + /// Explicit source name; generated review identifiers are not names. + pub name: Option, pub geometry: Geometry, pub outline: [f64; 2], pub background: bool, @@ -96,6 +98,7 @@ pub fn parse_values(text: &str) -> Result { shapes: parse_drawio(text)? .into_iter() .map(|s| DetectedShape { + name: s.name, id: s.id, geometry: s.geometry, outline: [s.stroke_width; 2], @@ -176,6 +179,7 @@ fn parse_midra_values(text: &str) -> Result { } .validate()?; shapes.push(DetectedShape { + name: None, id: id.into(), geometry, outline: [0.0; 2], @@ -511,7 +515,23 @@ fn walk( }) .map(str::to_owned) .unwrap_or_else(|| format!("{tag} {}", out.len() + 1)); + let name = node + .ancestors() + .filter(|n| *n == node || n.has_tag_name("g")) + .find_map(|n| { + source_name(n.attribute(("http://www.inkscape.org/namespaces/inkscape", "label"))) + .or_else(|| { + source_name( + n.children() + .find(|c| c.has_tag_name("title")) + .and_then(|c| c.text()), + ) + }) + .or_else(|| source_name(n.attribute("data-name"))) + .or_else(|| source_name(n.attribute("id"))) + }); out.push(DetectedShape { + name, id, geometry, outline: [stroke * matrix.x.abs(), stroke * matrix.y.abs()], @@ -609,6 +629,7 @@ fn drawio_svg_shapes( } let background = id == "midra-background"; out.push(DetectedShape { + name: None, id: id.to_owned(), geometry, outline: [stroke * cell_matrix.x.abs(), stroke * cell_matrix.y.abs()], @@ -736,3 +757,31 @@ pub fn parse_svg(text: &str) -> Result { ), }) } + +/// Keep supplied names separate from generated mapping identifiers. +pub(crate) fn source_name(value: Option<&str>) -> Option { + value + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) +} +/// Draw.io HTML labels are read as inert XML text when well formed. +pub(crate) fn drawio_name(value: Option<&str>, html: bool) -> Option { + let value = value?; + if !html || !value.contains('<') { + return source_name(Some(value)); + } + let wrapped = format!(""); + let doc = roxmltree::Document::parse(&wrapped).ok()?; + let text = doc + .descendants() + .filter(|n| n.is_text()) + .filter(|n| { + !n.ancestors() + .any(|p| matches!(p.tag_name().name(), "script" | "style")) + }) + .filter_map(|n| n.text()) + .collect::>() + .join(" "); + source_name(Some(&text)) +} diff --git a/crates/canvas-pilot/src/lib.rs b/crates/canvas-pilot/src/lib.rs index 450fa36..e71d0d4 100644 --- a/crates/canvas-pilot/src/lib.rs +++ b/crates/canvas-pilot/src/lib.rs @@ -2123,6 +2123,7 @@ impl Layout { #[derive(Clone, Debug)] pub struct DrawioShape { pub id: String, + pub name: Option, pub geometry: Geometry, /// Effective visible outline thickness, in diagram pixels (default 1). pub stroke_width: f64, @@ -2289,6 +2290,7 @@ pub fn parse_drawio(input: &str) -> Result, String> { } .validate()?; result.push(DrawioShape { + name: import::drawio_name(cell.attribute("value"), styles.get("html") == Some(&"1")), id: id.to_owned(), geometry, stroke_width, diff --git a/crates/canvas-pilot/src/vendor_formats.rs b/crates/canvas-pilot/src/vendor_formats.rs index f394f2f..581baff 100644 --- a/crates/canvas-pilot/src/vendor_formats.rs +++ b/crates/canvas-pilot/src/vendor_formats.rs @@ -10,6 +10,7 @@ use std::{io::Read, sync::Arc}; fn shape(name: String, geometry: Geometry, background: bool) -> Result { Ok(DetectedShape { + name: crate::import::source_name(Some(&name)), id: name, geometry: geometry.validate()?, outline: [0.0; 2], diff --git a/crates/canvas-pilot/tests/clipboard.rs b/crates/canvas-pilot/tests/clipboard.rs index 7a14c64..f74ab2d 100644 --- a/crates/canvas-pilot/tests/clipboard.rs +++ b/crates/canvas-pilot/tests/clipboard.rs @@ -166,7 +166,7 @@ fn clipboard_schema_is_bounded_versioned_and_never_falls_back_on_invalid_payload let (_, json) = text.rsplit_once(clipboard::MARKER).unwrap(); let good: serde_json::Value = serde_json::from_str(json).unwrap(); for (pointer, value) in [ - ("/version", serde_json::json!(2)), + ("/version", serde_json::json!(3)), ("/format", serde_json::json!("other")), ("/layers/0/appearance/fit", serde_json::json!("unknown")), ("/layers/0/appearance/input_size/0", serde_json::json!(0)), @@ -214,3 +214,127 @@ fn documented_fixture_and_multiple_layers_preserve_fractional_bounds() { assert_eq!(shape.zoom, Some(2.)); assert!(shape.appearance.is_none()); } + +#[test] +fn names_are_explicit_optional_atomic_and_preserve_identity_and_folders() { + let (mut layout, _) = copied(None); + layout + .rename_layer(0, "Caméra & ", "Sources") + .unwrap(); + layout + .rename_layer(1, "Destination", "Keep this folder") + .unwrap(); + let text = clipboard::encode(&layout, &[0], "Summary").unwrap(); + let shape = parse_values(&text).unwrap().shapes.remove(0); + assert_eq!(shape.name.as_deref(), Some("Caméra & ")); + let legacy = include_str!("../../../docs/interfaces/canvas-pilot-clipboard-v1.example.txt"); + assert!(parse_values(legacy).unwrap().shapes[0].name.is_none()); + let current = include_str!("../../../docs/interfaces/canvas-pilot-clipboard-v2.example.txt"); + assert_eq!( + parse_values(current).unwrap().shapes[0].name.as_deref(), + Some("Presenter") + ); + let before = Project::from_layout(&layout); + let g = layout.layers()[1]; + layout + .apply_mapped_clipboard_with_names( + &[(1, g)], + &[], + &[], + false, + false, + &[(1, shape.name.unwrap())], + ) + .unwrap(); + assert_eq!(layout.layer_info(1).name, "Caméra & "); + assert_eq!(layout.layer_info(1).folder, "Keep this folder"); + assert_eq!(layout.layer_info(1).id, before.layers[1].id); + layout.undo(); + assert_eq!(Project::from_layout(&layout), before); + for names in [ + vec![(1, "".into())], + vec![(1, "x".repeat(129))], + vec![(1, "One".into()), (1, "Two".into())], + vec![(999, "No".into())], + ] { + assert!( + layout + .apply_mapped_clipboard_with_names(&[(1, g)], &[], &[], false, false, &names) + .is_err() + ); + assert_eq!(Project::from_layout(&layout), before); + } +} + +#[test] +fn external_names_survive_exchange_without_promoting_generated_ids() { + use canvas_pilot::{ + exchange::Options, + interchange::{self, Codec}, + }; + let mut layout = Layout::default(); + layout.rename_layer(0, "Caméra & wide", "").unwrap(); + let project = Project::from_layout(&layout); + for codec in Codec::available() + .into_iter() + .filter(|c| *c != Codec::Illustrator) + { + let bytes = + interchange::export(&project, &[project.layers[0].id], codec, Options::default()) + .unwrap(); + let pages = interchange::import(&bytes, &format!("test.{}", codec.extension())).unwrap(); + assert_eq!( + pages[0].document.shapes[0].name.as_deref(), + Some("Caméra & wide"), + "{codec:?}" + ); + } + for (svg, name) in [ + ( + r#""#, + None, + ), + ( + r#""#, + Some("Camera"), + ), + ( + r#"Presenter"#, + Some("Presenter"), + ), + ] { + assert_eq!(parse_values(svg).unwrap().shapes[0].name.as_deref(), name); + } + let xml = |value: &str, style: &str| { + format!( + r#""# + ) + }; + for (value, style, name) in [ + ("", "html=0", None), + ("Caméra & wide", "html=0", Some("Caméra & wide")), + ("<b>Presenter</b>", "html=1", Some("Presenter")), + ] { + assert_eq!( + parse_values(&xml(value, style)).unwrap().shapes[0] + .name + .as_deref(), + name + ); + } +} + +#[test] +fn svg_group_names_and_labels_are_used_but_document_titles_are_not() { + let svg = r#"Document titleOther title"#; + let names: Vec<_> = parse_values(svg) + .unwrap() + .shapes + .into_iter() + .map(|s| s.name) + .collect(); + assert_eq!( + names, + vec![Some("Camera".into()), Some("Lectern".into()), None] + ); +} diff --git a/docs/canvas-pilot/changelog.md b/docs/canvas-pilot/changelog.md index ac04935..7a58d2c 100644 --- a/docs/canvas-pilot/changelog.md +++ b/docs/canvas-pilot/changelog.md @@ -4,6 +4,12 @@ ## Unreleased +- Import/paste can optionally rename destination layers from supplied editor names, + with proposed names shown before applying and a name-only mode. Folders and IDs + stay unchanged; renames undo with geometry/appearance in one step. Clipboard v2 + stores actual names and still reads v1. Added name round trips across supported + codecs (Illustrator conversion remains conditional on the external converter). + - Copy layer values now includes an exact, versioned clipboard payload for crop edges/offsets, all fit modes and blanking. Paste reviews Crop & fit and Blanking separately, keeps source/device mappings unchanged, and rejects incompatible diff --git a/docs/canvas-pilot/guide/advanced-exchange.md b/docs/canvas-pilot/guide/advanced-exchange.md index 7e3c270..71de91a 100644 --- a/docs/canvas-pilot/guide/advanced-exchange.md +++ b/docs/canvas-pilot/guide/advanced-exchange.md @@ -19,7 +19,8 @@ means a supported exchange format exported with extra parameters and reopened th | Layer position and size | ✅ | ✅ | ✅ | | Full-precision saved coordinates | ✅ | ❌ [1](#editing-notes) | ✅ | | Output screen resolution | ✅ | ❌ | ✅ | -| Layer names and stacking order | ✅ | ❌ | ✅ | +| Layer names | ✅ | ✅ · opt-in, when supplied | ✅ | +| Stacking order | ✅ | ❌ | ✅ | | Folders, collapsed folders, visibility and locks | ✅ | ❌ | ✅ [2](#editing-notes) | | Source formats, assignments and shared input relationships | ✅ | ❌ | ✅ [2](#editing-notes) | | Input crop edges | ✅ | ❌ | ✅ | @@ -53,6 +54,7 @@ For a complete editable backup, **Save project** remains the recommended choice. Canvas Pilot’s **Copy layer values** also preserves exact geometry, crop edges, offsets, fit and blanking through the clipboard. Its mapping review offers an optional **Appearance** group; source assignments and device links remain unchanged. +The separate **Rename destination layers** option applies supplied source names. See [clipboard preservation and limits](files.md#canvas-pilot-layer-clipboard). This is separate from plain geometry import and export snapshot restoration. diff --git a/docs/canvas-pilot/guide/files.md b/docs/canvas-pilot/guide/files.md index fd7b841..49fe596 100644 --- a/docs/canvas-pilot/guide/files.md +++ b/docs/canvas-pilot/guide/files.md @@ -42,7 +42,7 @@ to 16 MiB; a failed document leaves the batch unapplied and reports its filename zoom** when present. Available values start enabled. Unchecked values retain destination settings; resizing may adjust its existing crop. Outline bounds are offered only when the source includes an outline. At least one available - geometry or appearance value must be enabled. + geometry, appearance or name value must be enabled. 5. Click **Import mapped values** to update the mapped layers in one undo step. Cancel leaves all layers unchanged. Invalid geometry blocks the whole batch, without partial changes. @@ -50,6 +50,35 @@ to 16 MiB; a failed document leaves the batch unapplied and reports its filename The workspace supports 1–256 layers; the import review handles all selected layers rather than choosing one rectangle from a larger clipboard selection. +### Rename destination layers + +Enable **Rename destination layers** in the mapping review to use names from the +copied or imported shapes. It starts unchecked and appears only when included +items have names. The review shows each proposed name. To rename only, uncheck +Position, Format and any appearance options. Unnamed items keep their current +names; folders, layer IDs, stacking order and device links remain unchanged. +Names must contain 1–128 characters. An invalid name blocks the whole operation; +renaming and geometry/appearance changes undo together. + +| Source | Names used when available | +| --- | --- | +| Canvas Pilot clipboard | Actual layer name, without the displayed ID prefix; new copies only | +| SVG, including Figma/Illustrator SVG text | Inkscape label, shape title, `data-name`, then explicit SVG ID; nearest named group if the shape has none | +| draw.io XML | Cell label; supported well-formed HTML labels are reduced to plain text | +| Geometry JSON / CSV | `name` field | +| HTML geometry | `data-name` attribute | +| PowerPoint | Shape name | +| Figma / FigCraft file | Node name | +| DXF / DWG | CAD layer description, otherwise CAD layer name | +| Illustrator file | Names retained by its SVG conversion | + +An editor may omit names or emit generated SVG IDs. Review the proposed names +before applying them. Canvas Pilot never turns its own generated review labels +(such as “rect 1”) into names. Draw.io-rendered SVG cell IDs and older Canvas Pilot +clipboard labels are not treated as source names. File names and document titles +are not layer names. This works within the existing supported geometry profiles; +it does not add support for arbitrary artwork. + ### Canvas Pilot layer clipboard **Copy layer values** preserves exact geometry, crop edges and offsets, all fit diff --git a/docs/canvas-pilot/guide/format-matrix.md b/docs/canvas-pilot/guide/format-matrix.md index b46f1ba..1cf7481 100644 --- a/docs/canvas-pilot/guide/format-matrix.md +++ b/docs/canvas-pilot/guide/format-matrix.md @@ -33,24 +33,24 @@ See the [advanced feature matrix](advanced-exchange.md) for every saved feature. ## File exchange matrix All eleven exchange formats import and export layer positions and sizes. Geometry -import maps boxes to **existing destination layers**: it keeps their names, source -settings and device links, and does not change the output resolution. File names -and layer labels can help identify the boxes; they do not rename destinations. +import maps boxes to **existing destination layers**: it keeps their source +settings and device links, and does not change the output resolution. Names stay +unchanged unless you enable **Rename destination layers** in the import review. -| File | Import | Export | Layer names in export | Background picture [1](#file-notes) | Crop/mask preview pictures [1](#file-notes) | Extra settings snapshot | -| --- | :---: | :---: | :---: | :---: | :---: | :---: | -| Canvas Pilot project (`.pilot.json`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| SVG (`.svg`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | -| draw.io (`.drawio`, XML) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | -| Geometry JSON (`.json`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | -| HTML / CSS (`.html`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | -| PowerPoint (`.pptx`) [3](#file-notes) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | -| FigCraft file (`.figcraft`) [3](#file-notes) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | -| Geometry CSV (`.csv`) | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ [4](#file-notes) | -| DXF (`.dxf`) | ✅ | ✅ | ✅ [2](#file-notes) | ❌ | ❌ | ✅ [4](#file-notes) | -| Figma file (`.fig`) [3](#file-notes) | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | -| DWG (`.dwg`) [3](#file-notes) | ✅ | ✅ | ✅ [2](#file-notes) | ❌ | ❌ | ❌ | -| Illustrator file (`.ai`) [3](#file-notes) | ✅ | ✅ | ✅ [2](#file-notes) | ✅ | ✅ | ❌ | +| File | Import | Export | Layer names in export | Rename on import [5](#file-notes) | Background picture [1](#file-notes) | Crop/mask preview pictures [1](#file-notes) | Extra settings snapshot | +| --- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +| Canvas Pilot project (`.pilot.json`) | ✅ | ✅ | ✅ | ✅ · restored | ✅ | ✅ | ✅ | +| SVG (`.svg`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | +| draw.io (`.drawio`, XML) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | +| Geometry JSON (`.json`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | +| HTML / CSS (`.html`) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | +| PowerPoint (`.pptx`) [3](#file-notes) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | +| FigCraft file (`.figcraft`) [3](#file-notes) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ [4](#file-notes) | +| Geometry CSV (`.csv`) | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ [4](#file-notes) | +| DXF (`.dxf`) | ✅ | ✅ | ✅ [2](#file-notes) | ✅ | ❌ | ❌ | ✅ [4](#file-notes) | +| Figma file (`.fig`) [3](#file-notes) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | +| DWG (`.dwg`) [3](#file-notes) | ✅ | ✅ | ✅ [2](#file-notes) | ✅ | ❌ | ❌ | ❌ | +| Illustrator file (`.ai`) [3](#file-notes) | ✅ | ✅ | ✅ [2](#file-notes) | ✅ | ✅ | ✅ | ❌ | ### File notes @@ -65,6 +65,11 @@ and layer labels can help identify the boxes; they do not rename destinations. **Project → Restore parameters from export…**; ordinary geometry import never applies it. External applications may strip it or leave it stale after edits. +5. **Rename on import:** projects restore saved names. For geometry exchange this is opt-in, using names actually present in the file. SVG and + Illustrator conversion use labels, titles or explicit IDs; CAD prefers layer + descriptions, then CAD layer names. Unnamed items keep their destination names. + See [renaming from imports](files.md#rename-destination-layers). + Exports use one screen-sized canvas, slide, frame or artboard. PPTX import offers a slide picker; FIG / FIGCRAFT offer page/frame choices; Illustrator offers artboards. Draw.io supports single-page files, including compressed files. These are supported @@ -80,10 +85,10 @@ applies to Illustrator and draw.io. “Paste” below means **into Canvas Pilot* | Clipboard path | Paste positions and sizes | Copy out in this format | Rename destination layers | Crop zoom | Crop edges / offsets, fit and masks | | --- | :---: | :---: | :---: | :---: | :---: | -| Canvas Pilot **Copy layer values**, all fit modes | ✅ | ✅ | ❌ | ✅ | ✅ | -| Figma **SVG text** copy/paste | ✅ | ❌ | ❌ | ❌ | ❌ | -| Illustrator **SVG text** copy/paste | ✅ | ❌ | ❌ | ❌ | ❌ | -| draw.io diagram XML copy/paste | ✅ | ❌ | ❌ | ❌ | ❌ | +| Canvas Pilot **Copy layer values**, all fit modes | ✅ | ✅ | ✅ | ✅ | ✅ | +| Figma **SVG text** copy/paste | ✅ | ❌ | ✅ [names](files.md#rename-destination-layers) | ❌ | ❌ | +| Illustrator **SVG text** copy/paste | ✅ | ❌ | ✅ [names](files.md#rename-destination-layers) | ❌ | ❌ | +| draw.io diagram XML copy/paste | ✅ | ❌ | ✅ [names](files.md#rename-destination-layers) | ❌ | ❌ | | SVG file contents pasted as text | ✅ | ❌ | ❌ | ❌ | ❌ | | Geometry JSON / CSV file contents pasted as text | ✅ | ❌ | ❌ | ❌ | ❌ | | Canvas Pilot HTML / ASCII DXF file contents pasted as text | ✅ | ❌ | ❌ | ❌ | ❌ | @@ -97,7 +102,7 @@ is available. PowerPoint and QCAD use file exchange in this workflow. Paste opens a mapping review with separate **Position** and **Format** (width/height) choices. Canvas Pilot copies also offer an **Appearance** group with **Crop & fit** and **Blanking**. Crop edges preserve normal zoom/offsets and all explicit fit -modes; masks retain their proportions. Names identify rows without renaming them. +modes; masks retain their proportions. Enable **Rename destination layers** to apply supplied names; it starts unchecked. Crop & fit requires matching source dimensions after input crop; it never changes source assignments or device mappings. If dimensions differ, match the local source diff --git a/docs/interfaces/canvas-pilot-clipboard-v2.example.txt b/docs/interfaces/canvas-pilot-clipboard-v2.example.txt new file mode 100644 index 0000000..9ccc2b5 --- /dev/null +++ b/docs/interfaces/canvas-pilot-clipboard-v2.example.txt @@ -0,0 +1,42 @@ +01 / Presenter — visible box (device container unverified) +Horizontal: 440 px +Vertical: 361 px +Width: 640 px +Height: 360 px +Crop zoom: 200 % + +Canvas Pilot layer data: +{ + "format": "canvas-pilot.layers", + "version": 2, + "layers": [ + { + "name": "Presenter", + "bounds": { + "x": 120.125, + "y": 180.5, + "width": 640.0, + "height": 360.0 + }, + "appearance": { + "input_size": [ + 1920.0, + 1080.0 + ], + "crop": { + "left": 600.0, + "right": 360.0, + "top": 240.0, + "bottom": 300.0 + }, + "fit": null, + "mask": { + "left": 0.125, + "right": 0.0625, + "top": 0.25, + "bottom": 0.125 + } + } + } + ] +} \ No newline at end of file diff --git a/docs/interfaces/canvas-pilot-clipboard.md b/docs/interfaces/canvas-pilot-clipboard.md index 1f5b462..2d968cf 100644 --- a/docs/interfaces/canvas-pilot-clipboard.md +++ b/docs/interfaces/canvas-pilot-clipboard.md @@ -1,4 +1,4 @@ -# Canvas Pilot layer clipboard, version 1 +# Canvas Pilot layer clipboard, version 2 Implementation: `clipboard.rs`, `import.rs` and the shared paste review in `gui.rs`. This is a Canvas Pilot clipboard representation, not a device protocol or a native @@ -20,7 +20,8 @@ escaping. The summary is informational: editing it does not override the JSON. Readers validate the payload and never fall back to rounded geometry when it is invalid. Raw legacy summaries without this delimiter still use the existing parser. -See the [complete example](canvas-pilot-clipboard-v1.example.txt). +See the [current example](canvas-pilot-clipboard-v2.example.txt) and +[legacy v1 example](canvas-pilot-clipboard-v1.example.txt). ## JSON schema and validation @@ -31,9 +32,9 @@ No URLs, file paths, commands, images or arbitrary application state are evaluat | Field | Meaning | | --- | --- | | `format` | Exactly `canvas-pilot.layers` | -| `version` | Integer `1`; unknown versions reject the whole paste | +| `version` | Integer `2`; readers also accept `1`; other versions reject the whole paste | | `layers` | Ordered array of copied layers; selection order follows document order | -| `layers[].name` | Nonblank label, at most 256 characters; identifies review rows, never renames destinations | +| `layers[].name` | In v2, the actual layer name without an ID prefix; nonblank, at most 256 characters to read, 1–128 to apply. In v1, a review label only | | `layers[].bounds` | `x`, `y`, `width`, `height`: full-precision screen pixels; top-left coordinates, finite within ±1,000,000 and positive dimensions up to 1,000,000 | | `layers[].appearance.input_size` | Two positive finite effective source dimensions in pixels, after local input crop; validated by the existing source-size limits | | `layers[].appearance.crop` | `left`, `right`, `top`, `bottom`: nonnegative finite effective-source pixel crop edges, leaving positive width/height | @@ -49,7 +50,8 @@ mask proportions do not become source-pixel crops. All data enters the existing destination mapping review. Position and Format are independent. An **Appearance** group offers **Crop & fit** and **Blanking**, enabled -initially for this payload. An appearance-only paste is valid. External geometry +initially for this payload. Appearance-only and name-only pastes are valid. **Rename destination layers** is +off by default, copies v2 names only, and leaves folders/IDs unchanged. External geometry formats have no such payload; older normal-crop summaries offer their legacy zoom control instead. Ignored items do not affect availability or mapped values. @@ -69,7 +71,7 @@ writes are never part of paste. Copying and opening the review are read-only. ## Omissions and compatibility -Destination names, folders, identity, visibility, locks, pivots, source formats, +Folders, identity, visibility, locks, pivots, source formats, input crop, shared source relationships, device links, input proposals, captures, references and workspace settings are not copied by this representation. Only the recorded source dimensions accompany crop for compatibility validation. Use a @@ -78,7 +80,9 @@ project or embedded export snapshot for the wider state. Existing normal-crop summaries remain readable, with optional zoom and their historical integer geometry. Old advanced-container summaries are not upgraded implicitly because they lack the crop/source information needed to reconstruct -appearance. New copies of all fit modes contain the v1 payload. Older application +appearance. New copies of all fit modes contain the v2 payload. V1 stays readable for geometry +and appearance; its names may include display ID prefixes and are not offered for +renaming. V1-only readers reject v2 with an unsupported-version error. Older application versions do not support the appended payload; remove the payload only when intentionally exchanging the legacy normal-crop geometry/zoom subset. diff --git a/docs/interfaces/canvas-pilot-exchange.md b/docs/interfaces/canvas-pilot-exchange.md index ce377e7..d3028e4 100644 --- a/docs/interfaces/canvas-pilot-exchange.md +++ b/docs/interfaces/canvas-pilot-exchange.md @@ -225,7 +225,7 @@ UTF-8 SVG; SVG namespace and optional XLink namespace. Root attributes: Each layer is a `` (plain) or `` (placeholder), with `id="layer-N"`, `data-midra-role="layer"`, `x`, `y`, `width`, `height`. A `` carries its name -for external viewers; Midra import does not rename destinations. Images use +for external viewers and optional destination renaming. Images use `xlink:href="data:image/png;base64,..."` and `preserveAspectRatio="none"`. The optional background is an `<image>` with `data-midra-role="background"` and full-page bounds. No visible text geometry, transforms, clipping or CSS is needed. @@ -365,7 +365,7 @@ changes when still eligible. Clipboard text and per-item geometry details are collapsed, read-only previews. These review choices are session-only and do not change any file schema. Import with size and position enabled restores the rounded geometry in one Undo step. Output -screen resolution is not imported. Mapped names, sources and Midra links stay with +screen resolution is not imported. Mapped sources and Midra links stay with the destination layers. File replacement retains the existing explicit overwrite confirmation and atomic-write path. @@ -456,3 +456,24 @@ to the container, including transparent margins for Centered or small 1:1 conten Project v15 also preserves normalized layer masks in embedded snapshots. Placeholder artwork blanks pixels transparently without resampling. Plain rectangle geometry continues to omit mask appearance; use project JSON for exact round trips. + + +## Optional destination naming + +Geometry import now offers **Rename destination layers**, off by default. Names +are separate from generated review identifiers. SVG uses a shape's Inkscape label, +child title, `data-name`, or explicit ID, with the nearest named group as fallback. +Draw.io XML uses `value` (plain text, or inert text extracted from well-formed XML +markup for HTML labels); malformed markup supplies no name. Draw.io-rendered SVG +cell identifiers are not promoted to names. JSON/CSV use `name`, HTML uses +`data-name`, PPTX uses shape names and FIG/FIGCRAFT uses node names. DXF/DWG reads +CAD layer descriptions with layer names as fallback. Illustrator depends on the +SVG conversion preserving labels. No exchange file schema changes are needed. + +A supplied name is trimmed and must contain 1–128 characters when applied; longer +names may still be read for geometry-only imports. Unnamed or excluded items do +not rename anything. Names never alter identity, folders, order, source assignments +or device links. A names-only edit is supported, and geometry/appearance/names +commit atomically as one undo step. Invalid or stale mappings, locked destinations +or invalid selected names reject the entire batch. The [clipboard contract](canvas-pilot-clipboard.md) +versions the separate Canvas Pilot clipboard name semantics.