Preserve crop, fit and blanking in layer clipboard

This commit is contained in:
Dandaedre 2026-11-16 12:50:37 +01:00
parent 52d467fb99
commit c628a2b4c5
16 changed files with 729 additions and 32 deletions

View File

@ -26,6 +26,7 @@ Versioned examples and sanitized fixtures remain beside their contracts and in
| [Project](docs/interfaces/canvas-pilot.md) | Project schema, versions and migrations |
| [Settings](docs/interfaces/canvas-pilot-settings.md) | User preferences and settings compatibility |
| [Recovery](docs/interfaces/canvas-pilot-recovery.md) | Recovery storage and restoration |
| [Layer clipboard](docs/interfaces/canvas-pilot-clipboard.md) | Versioned geometry, crop, fit and blanking payload |
| [Geometry exchange](docs/interfaces/canvas-pilot-exchange.md) | Precision, omissions and round trips |
| [Extra parameters](docs/interfaces/midra-extra-parameters.md) | Embedded project snapshots |
| [Device adapters](docs/interfaces/device-adapters.md) | Shared representation and family-specific behavior |

View File

@ -0,0 +1,170 @@
//! Versioned clipboard appearance, separate from geometry-only external imports.
use crate::{
Geometry, Layout,
formats::{self, Crop, LayerFit, Mask},
import::{DetectedShape, ImportDocument},
};
use serde::{Deserialize, Serialize};
pub const MARKER: &str = "\n\nCanvas Pilot layer data:\n";
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Appearance {
pub input_size: [f64; 2],
pub crop: Crop,
#[serde(deserialize_with = "required_fit")]
pub fit: Option<LayerFit>,
pub mask: Mask,
}
fn required_fit<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<LayerFit>, D::Error> {
Option::<LayerFit>::deserialize(d)
}
impl Appearance {
fn validate(self, bounds: Geometry) -> Result<(), String> {
formats::validate_size(self.input_size)?;
self.mask.validate()?;
let retained = self.crop.remaining(self.input_size)?;
if let Some(fit) = self.fit {
fit.image(retained, bounds)?;
} else {
formats::mapping(self.input_size, [bounds.width, bounds.height], self.crop)?;
}
Ok(())
}
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Layer {
name: String,
bounds: Geometry,
appearance: Appearance,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Payload {
format: String,
version: u32,
layers: Vec<Layer>,
}
/// Append exact, locale-independent values to the readable clipboard summary.
pub fn encode(layout: &Layout, indices: &[usize], summary: &str) -> Result<String, String> {
if indices.is_empty() || indices.len() > 256 {
return Err("Copy between 1 and 256 layers.".into());
}
let mut layers = Vec::new();
for &i in indices {
let bounds = *layout.layers().get(i).ok_or("Invalid copied layer")?;
let appearance = Appearance {
input_size: layout.formats().input(i)?,
crop: layout.formats().advanced[i],
fit: layout.formats().layer_fit[i],
mask: layout.formats().masks[i],
};
bounds.validate()?;
appearance.validate(bounds)?;
layers.push(Layer {
name: layout.layer_label(i),
bounds,
appearance,
});
}
let json = serde_json::to_string_pretty(&Payload {
format: "canvas-pilot.layers".into(),
version: 1,
layers,
})
.map_err(|e| e.to_string())?;
let text = format!("{summary}{MARKER}{json}");
if text.len() > crate::exchange::MAX_EXCHANGE_BYTES {
return Err("Clipboard exceeds 16 MiB.".into());
}
Ok(text)
}
pub fn parse(json: &str) -> Result<ImportDocument, String> {
if json.len() > crate::exchange::MAX_EXCHANGE_BYTES {
return Err("Clipboard exceeds 16 MiB.".into());
}
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 {
return Err(
"Unsupported Canvas Pilot clipboard format/version; expected version 1.".into(),
);
}
if payload.layers.is_empty() || payload.layers.len() > 256 {
return Err("Clipboard must contain 1–256 layers.".into());
}
let mut shapes = Vec::new();
for layer in payload.layers {
if layer.name.trim().is_empty() || layer.name.chars().count() > 256 {
return Err("Invalid clipboard layer name.".into());
}
layer.bounds.validate()?;
layer.appearance.validate(layer.bounds)?;
shapes.push(DetectedShape {
id: layer.name,
geometry: layer.bounds,
outline: [0.; 2],
background: false,
background_only: false,
zoom: None,
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() })
}
impl Layout {
/// Apply geometry and optional appearance atomically, preserving selection and source identity.
pub fn apply_mapped_clipboard(
&mut self,
values: &[(usize, Geometry)],
zooms: &[(usize, f64)],
appearances: &[(usize, Appearance)],
crop_fit: bool,
masks: bool,
) -> Result<(), String> {
let mut seen = std::collections::BTreeSet::new();
for &(i, a) in appearances {
if i >= self.layers.len() || !self.selectable(i) {
return Err("Clipboard destination must be an editable layer.".into());
}
if !values.iter().any(|(target, _)| *target == i) || !seen.insert(i) {
return Err("Each clipboard appearance must map to one imported layer.".into());
}
if zooms.iter().any(|(target, _)| *target == i) {
return Err("Choose full crop and fit or legacy zoom, not both.".into());
}
if crop_fit {
let input = self.formats.input(i)?;
if input
.iter()
.zip(a.input_size)
.any(|(v, expected)| (v - expected).abs() > 1e-8)
{
return Err("Crop & fit requires matching source dimensions after input crop. Match the destination source or uncheck Crop & fit.".into());
}
}
}
let mut draft = self.clone();
draft.apply_mapped_import_with_zoom(values, zooms)?;
for &(i, appearance) in appearances {
if crop_fit {
appearance.validate(draft.layers[i]).map_err(|error| {
format!(
"Cannot paste Crop & fit: {error} Include Format or uncheck Crop & fit."
)
})?;
draft.formats.advanced[i] = appearance.crop;
draft.formats.layer_fit[i] = appearance.fit;
}
if masks {
draft.formats.masks[i] = appearance.mask.validate()?;
}
}
self.finish_drag();
let before = self.snapshot();
self.restore(draft.snapshot());
self.remember(before);
Ok(())
}
}

View File

@ -117,6 +117,7 @@ impl Screen {
background: false,
background_only: false,
zoom: None,
appearance: None,
});
}
Ok(ImportDocument {

View File

@ -127,6 +127,7 @@ fn document(
background,
background_only: background,
zoom: None,
appearance: None,
});
}
if backgrounds > 1

View File

@ -134,6 +134,8 @@ struct Paste {
include_size: bool,
include_position: bool,
include_zoom: bool,
include_crop_fit: bool,
include_masks: bool,
include_outline: bool,
closing: bool,
error: String,
@ -208,6 +210,12 @@ impl Paste {
}
}
}
fn appearance_available(&self) -> bool {
self.shapes
.iter()
.zip(&self.ignored)
.any(|(s, ignored)| !ignored && s.appearance.is_some())
}
fn zoom_available(&self) -> bool {
self.shapes
.iter()
@ -239,7 +247,25 @@ impl Paste {
} else {
Vec::new()
};
layout.apply_mapped_import_with_zoom(&values, &zooms)
let appearances: Vec<_> = self
.shapes
.iter()
.enumerate()
.filter_map(|(row, shape)| {
if self.ignored[row] {
None
} else {
shape.appearance.map(|a| (self.mapping[row].unwrap(), a))
}
})
.collect();
layout.apply_mapped_clipboard(
&values,
&zooms,
&appearances,
self.include_crop_fit,
self.include_masks,
)
}
fn destination_count_warning(&self, layout: &Layout) -> Option<String> {
let count = self.ignored.iter().filter(|ignored| !**ignored).count();
@ -253,9 +279,10 @@ impl Paste {
if !self.include_size
&& !self.include_position
&& !(self.include_zoom && self.zoom_available())
&& !((self.include_crop_fit || self.include_masks) && self.appearance_available())
{
return Err(
"Choose at least one available value to paste: format, position or zoom.".into(),
"Choose at least one available geometry or appearance value to paste.".into(),
);
}
let count = self.ignored.iter().filter(|v| !**v).count();
@ -711,6 +738,8 @@ impl Editor {
include_size: true,
include_position: true,
include_zoom: true,
include_crop_fit: true,
include_masks: true,
include_outline: false,
closing: false,
error: String::new(),
@ -895,7 +924,7 @@ impl Editor {
Err(e) => self.error = e,
}
}
fn copy(&self, ctx: &egui::Context) {
fn copy(&mut self, ctx: &egui::Context) {
let entries: Vec<_> = self
.layout
.selected_indices()
@ -920,7 +949,14 @@ impl Editor {
})
.collect();
if !entries.is_empty() {
ctx.copy_text(entries.join("\n\n"));
match canvas_pilot::clipboard::encode(
&self.layout,
&self.layout.selected_indices(),
&entries.join("\n\n"),
) {
Ok(text) => ctx.copy_text(text),
Err(error) => self.error = error,
}
}
}
fn shortcuts(&mut self, ctx: &egui::Context) {
@ -1153,6 +1189,18 @@ impl Editor {
ui.checkbox(&mut p.include_position,"Position");
if p.zoom_available() { ui.checkbox(&mut p.include_zoom,"Crop zoom"); }
});
if p.appearance_available() {
let summary = match (p.include_crop_fit, p.include_masks) {
(true, true) => "Appearance · crop, fit and blanking",
(true, false) => "Appearance · crop and fit",
(false, true) => "Appearance · blanking",
(false, false) => "Appearance · keep destination",
};
egui::CollapsingHeader::new(summary).id_salt("paste-appearance").show(ui, |ui| {
ui.checkbox(&mut p.include_crop_fit, "Crop & fit").on_hover_text("Copy exact crop edges, offsets and fit mode. Source dimensions after input crop must match; source assignments remain unchanged.");
ui.checkbox(&mut p.include_masks, "Blanking").on_hover_text("Copy the four proportional mask edges without resizing the layer.");
});
}
ui.small("Unchecked values keep the destination settings. Format changes may adjust existing crops to fit.");
if p.shapes.iter().any(|s|s.outline.iter().any(|v|*v>0.0)) {
ui.indent("outline-option", |ui| {
@ -1161,7 +1209,7 @@ impl Editor {
}
egui::CollapsingHeader::new("Import details").show(ui, |ui| {
ui.label(&p.note);
ui.small("Source format, crop offsets, colors and outline appearance are not imported.");
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." });
});
if !p.include_size {ui.small("Outline adjustment requires Format. Position uses the source top-left when enabled.");}
ui.separator();
@ -1200,6 +1248,7 @@ impl Editor {
});
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.)); }
if let Some(zoom) = shape.zoom { ui.small(format!("Crop zoom: {:.1}%", zoom * 100.0)); }
if let Some(target)=p.mapping[row].filter(|&i| i < self.layout.layers().len()) {
let before=self.layout.layers()[target];
@ -1757,7 +1806,7 @@ impl Editor {
12.0,
palette.muted,
);
ink.button(0.0, 808.0, w, "Copy position values", true);
ink.button(0.0, 808.0, w, "Copy layer values", true);
if click(ui, &ink, [0.0, 808.0, w, 34.0], "copy-values") {
self.copy(ui.ctx());
}
@ -2230,7 +2279,7 @@ impl Editor {
palette.text,
);
}
ink.button(0.0, 552.0, w, "Copy selected positions", true);
ink.button(0.0, 552.0, w, "Copy selected layer values", true);
if click(ui, ink, [0.0, 552.0, w, 34.0], "copy-selected") {
self.copy(ui.ctx());
}
@ -6557,6 +6606,90 @@ mod tests {
assert!(output.platform_output.commands.iter().any(|c|matches!(c,egui::OutputCommand::CopyText(text) if text.contains("Width: 300 px") && text.contains("Height: 251 px"))));
assert_eq!(app.layout.layers()[1], g);
}
#[test]
fn copy_and_review_preserve_all_fit_modes_and_allow_mask_only_paste() {
use canvas_pilot::formats::{Crop, LayerFit, Mask};
for fit in [
None,
Some(LayerFit::OneToOne),
Some(LayerFit::Centered),
Some(LayerFit::Fullscreen),
Some(LayerFit::Cropped),
] {
let ctx = egui::Context::default();
let mut app = Editor::default();
app.layout.select(Some(0));
app.layout
.set_layer_fit(
0,
fit,
Crop {
left: 40.25,
right: 60.5,
top: 15.125,
bottom: 25.25,
},
)
.unwrap();
app.layout
.set_mask(
0,
Mask {
left: 0.1,
right: 0.2,
top: 0.05,
bottom: 0.15,
},
)
.unwrap();
let output = ctx.run(egui::RawInput::default(), |ctx| app.copy(ctx));
let text = output
.platform_output
.commands
.iter()
.find_map(|c| match c {
egui::OutputCommand::CopyText(text) => Some(text.clone()),
_ => None,
})
.unwrap();
app.layout.select(Some(1));
app.open_paste(text.clone());
let p = app.paste.take().unwrap();
assert!(p.appearance_available());
assert!(!p.zoom_available());
p.apply(&mut app.layout).unwrap();
assert_eq!(app.layout.formats().layer_fit[1], fit);
assert_eq!(
app.layout.formats().advanced[1],
app.layout.formats().advanced[0]
);
assert_eq!(app.layout.formats().masks[1], app.layout.formats().masks[0]);
app.layout.undo();
let before = app.project();
app.open_paste(text);
let p = app.paste.as_mut().unwrap();
p.include_position = false;
p.include_size = false;
click_text(&mut app, &ctx, "Appearance · crop, fit and blanking");
click_text(&mut app, &ctx, "Crop & fit");
assert!(!app.paste.as_ref().unwrap().include_crop_fit);
click_text(&mut app, &ctx, "Import mapped values");
assert!(app.paste.is_none());
assert_eq!(app.layout.layers()[1], before.layers[1].bounds);
assert_eq!(
app.layout.formats().advanced[1],
before.layers[1].advanced_crop
);
assert_eq!(
app.layout.formats().layer_fit[1],
before.layers[1].layer_fit
);
assert_eq!(app.layout.formats().masks[1], app.layout.formats().masks[0]);
app.layout.undo();
assert_eq!(app.project(), before);
}
}
#[test]
fn resize_choice_survives_deselection_and_single_layer_gestures() {
for mode in [ResizeMode::Same, ResizeMode::Mirror, ResizeMode::Opposite] {

View File

@ -11,6 +11,7 @@ pub struct DetectedShape {
pub background: bool,
pub background_only: bool,
pub zoom: Option<f64>,
pub appearance: Option<crate::clipboard::Appearance>,
}
impl DetectedShape {
pub fn paste_geometry(
@ -56,6 +57,9 @@ pub fn parse_values(text: &str) -> Result<ImportDocument, String> {
if text.len() > crate::exchange::MAX_EXCHANGE_BYTES {
return Err("Import text exceeds 16 MiB.".into());
}
if let Some((_, json)) = text.rsplit_once(crate::clipboard::MARKER) {
return crate::clipboard::parse(json);
}
if let Some(geometry) = crate::exchange_metadata::geometry_text(text)? {
return parse_values(&geometry);
}
@ -98,6 +102,7 @@ pub fn parse_values(text: &str) -> Result<ImportDocument, String> {
background: s.background,
background_only: s.background,
zoom: None,
appearance: None,
})
.collect(),
svg: false,
@ -177,6 +182,7 @@ fn parse_midra_values(text: &str) -> Result<ImportDocument, String> {
background: false,
background_only: false,
zoom,
appearance: None,
});
}
Ok(ImportDocument {
@ -512,6 +518,7 @@ fn walk(
background,
background_only: background && (tag == "image" || marked_background),
zoom: None,
appearance: None,
});
if out.iter().filter(|s| !s.background_only).count() > 256 || out.len() > 257 {
return Err("Import is limited to 256 rectangles.".into());
@ -608,6 +615,7 @@ fn drawio_svg_shapes(
background,
background_only: background,
zoom: None,
appearance: None,
});
if out.iter().filter(|shape| !shape.background_only).count() > 256 || out.len() > 257 {
return Err("Import is limited to 256 rectangles.".into());

View File

@ -1,4 +1,5 @@
//! Layer geometry, reversible edits and bounded imports.
pub mod clipboard;
pub mod device;
pub mod device_capture;
pub mod device_send;

View File

@ -16,6 +16,7 @@ fn shape(name: String, geometry: Geometry, background: bool) -> Result<DetectedS
background,
background_only: background,
zoom: None,
appearance: None,
})
}
fn page(name: String, shapes: Vec<DetectedShape>, note: String) -> Result<Page, String> {

View File

@ -0,0 +1,216 @@
use canvas_pilot::{
Layout,
clipboard::{self, Appearance},
formats::{Crop, Framing, LayerFit, Mask},
import::parse_values,
project::Project,
};
fn copied(fit: Option<LayerFit>) -> (Layout, String) {
let mut layout = Layout::default();
layout
.set_layer_fit(
0,
fit,
Crop {
left: 40.25,
right: 70.5,
top: 20.125,
bottom: 35.75,
},
)
.unwrap();
if fit.is_none() {
layout
.set_framing(
0,
Framing {
zoom: 2.25,
offset: [17.125, -8.75],
},
)
.unwrap();
}
layout
.set_mask(
0,
Mask {
left: 0.125,
right: 0.0625,
top: 0.25,
bottom: 0.125,
},
)
.unwrap();
let text = clipboard::encode(&layout, &[0], "Readable values").unwrap();
(layout, text)
}
#[test]
fn every_fit_roundtrips_exact_crop_mask_and_offset_with_atomic_undo() {
for fit in [
None,
Some(LayerFit::OneToOne),
Some(LayerFit::Centered),
Some(LayerFit::Fullscreen),
Some(LayerFit::Cropped),
] {
let (mut layout, text) = copied(fit);
let shape = parse_values(&text).unwrap().shapes.remove(0);
let before = Project::from_layout(&layout);
let a = shape.appearance.unwrap();
assert_eq!(a.fit, fit);
assert_eq!(a.crop, layout.formats().advanced[0]);
layout
.apply_mapped_clipboard(&[(1, shape.geometry)], &[], &[(1, a)], true, true)
.unwrap();
let after = Project::from_layout(&layout);
assert_eq!(layout.formats().advanced[1], layout.formats().advanced[0]);
assert_eq!(layout.formats().layer_fit[1], fit);
assert_eq!(layout.formats().masks[1], layout.formats().masks[0]);
if fit.is_none() {
assert_eq!(
layout.formats().mapping(1, shape.geometry).unwrap(),
layout.formats().mapping(0, shape.geometry).unwrap()
);
}
assert_eq!(after.inputs, before.inputs);
assert_eq!(after.layers[1].source_id, before.layers[1].source_id);
assert_eq!(after.layers[1].device_link, before.layers[1].device_link);
assert_eq!(after.layers[1].name, before.layers[1].name);
let second = clipboard::encode(&layout, &[1], "Second copy").unwrap();
assert_eq!(parse_values(&second).unwrap().shapes[0].appearance, Some(a));
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout.redo();
assert_eq!(Project::from_layout(&layout), after);
}
}
#[test]
fn appearance_can_be_applied_independently_and_source_mismatch_is_atomic() {
let (mut layout, text) = copied(Some(LayerFit::Fullscreen));
let a = parse_values(&text).unwrap().shapes[0].appearance.unwrap();
let before = Project::from_layout(&layout);
let g = layout.layers()[1];
let incompatible = Appearance {
input_size: [1000., 500.],
..a
};
assert!(
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, incompatible)], true, true)
.unwrap_err()
.contains("matching source dimensions")
);
assert_eq!(Project::from_layout(&layout), before);
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, incompatible)], false, true)
.unwrap();
assert_eq!(layout.formats().masks[1], a.mask);
assert_eq!(layout.formats().advanced[1], before.layers[1].advanced_crop);
assert_eq!(layout.formats().layer_fit[1], before.layers[1].layer_fit);
layout.undo();
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, a)], true, false)
.unwrap();
assert_eq!(layout.formats().layer_fit[1], a.fit);
assert_eq!(layout.formats().masks[1], before.layers[1].mask);
layout.undo();
let mut invalid = a;
invalid.mask.left = 2.;
assert!(
layout
.apply_mapped_clipboard(&[(0, g), (1, g)], &[], &[(0, a), (1, invalid)], true, true)
.is_err()
);
assert_eq!(Project::from_layout(&layout), before);
assert!(
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, a), (1, a)], true, true)
.is_err()
);
assert!(
layout
.apply_mapped_clipboard(&[(1, g)], &[(1, 2.)], &[(1, a)], true, true)
.is_err()
);
assert!(
layout
.apply_mapped_clipboard(&[(999, g)], &[], &[(999, a)], true, true)
.is_err()
);
layout.set_locked(1, true);
assert!(
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, a)], true, true)
.is_err()
);
}
#[test]
fn normal_crop_requires_matching_aspect_and_does_not_silently_reframe() {
let (mut layout, text) = copied(None);
let a = parse_values(&text).unwrap().shapes[0].appearance.unwrap();
let before = Project::from_layout(&layout);
let mut g = layout.layers()[1];
g.width = g.height;
assert!(
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, a)], true, true)
.unwrap_err()
.contains("Include Format")
);
assert_eq!(Project::from_layout(&layout), before);
}
#[test]
fn clipboard_schema_is_bounded_versioned_and_never_falls_back_on_invalid_payload() {
let (layout, text) = copied(None);
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)),
("/format", serde_json::json!("other")),
("/layers/0/appearance/fit", serde_json::json!("unknown")),
("/layers/0/appearance/input_size/0", serde_json::json!(0)),
("/layers/0/appearance/crop/left", serde_json::json!(-1)),
("/layers/0/appearance/mask/top", serde_json::json!(1.5)),
("/layers", serde_json::json!([])),
] {
let mut invalid = good.clone();
*invalid.pointer_mut(pointer).unwrap() = value;
assert!(
parse_values(&format!("Readable text{}{invalid}", clipboard::MARKER)).is_err(),
"{pointer}"
);
}
for field in ["fit", "crop", "mask", "input_size"] {
let mut invalid = good.clone();
invalid["layers"][0]["appearance"]
.as_object_mut()
.unwrap()
.remove(field);
assert!(clipboard::parse(&invalid.to_string()).is_err());
}
let mut invalid = good.clone();
invalid["layers"][0]["device_link"] = serde_json::json!({});
assert!(clipboard::parse(&invalid.to_string()).is_err());
invalid = good.clone();
invalid["layers"] = serde_json::json!(vec![good["layers"][0].clone(); 257]);
assert!(clipboard::parse(&invalid.to_string()).is_err());
assert!(parse_values(&format!("{text}garbage")).is_err());
assert!(clipboard::encode(&layout, &[], "").is_err());
assert!(clipboard::encode(&layout, &[999], "").is_err());
assert!(parse_values(&"x".repeat(canvas_pilot::exchange::MAX_EXCHANGE_BYTES + 1)).is_err());
}
#[test]
fn documented_fixture_and_multiple_layers_preserve_fractional_bounds() {
let fixture = include_str!("../../../docs/interfaces/canvas-pilot-clipboard-v1.example.txt");
let shape = parse_values(fixture).unwrap().shapes.remove(0);
assert_eq!(shape.geometry.x, 120.125);
assert_eq!(shape.appearance.unwrap().crop.left, 600.);
let (layout, _) = copied(None);
let multi = clipboard::encode(&layout, &[0, 1], "Readable values").unwrap();
assert_eq!(parse_values(&multi).unwrap().shapes.len(), 2);
let legacy = "Old — visible box (device container unverified)\nHorizontal: 320 px\nVertical: 180 px\nWidth: 640 px\nHeight: 360 px\nCrop zoom: 200 %";
let shape = parse_values(legacy).unwrap().shapes.remove(0);
assert_eq!(shape.zoom, Some(2.));
assert!(shape.appearance.is_none());
}

View File

@ -4,6 +4,11 @@
## Unreleased
- 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
dimensions atomically. Legacy normal-crop/zoom text remains readable.
- Prepared issue drafts for all untracked stretch goals and linked the existing
adapter issue. Gitea publication awaits a token with issue permissions.

View File

@ -48,6 +48,14 @@ means a supported exchange format exported with extra parameters and reopened th
For a complete editable backup, **Save project** remains the recommended choice.
## Copying layer appearance
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.
See [clipboard preservation and limits](files.md#canvas-pilot-layer-clipboard).
This is separate from plain geometry import and export snapshot restoration.
## Saved input corrections
In the advanced input controls, explicitly choose **Save staged input edits as a

View File

@ -61,15 +61,15 @@ not affect device links or source assignments. All document edits support Undo.
**Zoom to selection** frames the entire selection. A view warning appears only when a visible layer is completely out of view; select it in the layer list to frame it. The inspector separately flags layers partly or entirely beyond the output screen and suggests alignment or position edits. A divider separates view tools from Undo/Redo. Hover an icon for its label.
Camera changes do not modify coordinates. Off-screen layers retain their exact
coordinates, display a warning and remain selectable through the layer list.
- **Copy position values** (or **Copy selected positions** for multiple layers)
copies labeled plain text with each selected layer's center position and
dimensions. **Ctrl/Cmd-C** does the same when the viewport has focus. These
values can be pasted back using **Ctrl/Cmd-V** or **Paste layer(s) values**, with
the usual destination mapping and exact layer-count requirement. Center values
are converted back to top-left bounds; whole-pixel export rounding still applies
(an odd width/height can produce a half-pixel top-left). Source formats and crop
offsets are not copied. Crop zoom is included separately as a percentage and
can be toggled on paste. This is not a native WebRCS clipboard payload.
- **Copy layer values** (or **Copy selected layer values** for multiple layers)
copies a readable position summary plus exact geometry, crop, fit and blanking.
**Ctrl/Cmd-C** does the same when the viewport has focus. Paste with
**Ctrl/Cmd-V** or **Paste layer(s) values**, then review the destination mapping.
**Appearance** lets you choose **Crop & fit** and **Blanking** independently;
source assignments and device links stay unchanged. Crop & fit requires matching
source dimensions after input crop. See [layer clipboard](files.md#canvas-pilot-layer-clipboard)
for the paste options and compatibility details. This is not a native WebRCS
clipboard payload.
Right-click a layer for **Source properties**, **Layer properties**, **Crop properties**, **Configure capture**,
**Adjust layer crop**, alignment, **Copy layer values**, **Paste layer values**, and lock/hide actions.

View File

@ -36,15 +36,13 @@ to 16 MiB; a failed document leaves the batch unapplied and reports its filename
item** to skip an item. Each included item must map to a different destination;
fewer source items than destinations are fine. Duplicate or missing mappings
block import. Other layers stay unchanged.
4. Choose independently what to paste: **Format (width / height)**, **Position**,
and **Crop zoom**. Zoom is enabled only when present in the data (new Midra
clipboard values include it; older copies, draw.io and SVG do not). All
available values are initially enabled. Unchecked values retain destination
settings; format-only paste keeps its top-left position. Choose **Include
outline in bounds** if the layer should cover the rectangle's outline too.
Zoom applies to the resulting layer size; existing crop offsets clamp if
necessary. Mixed batches keep destination zoom where the source lacks it.
At least one available value must be enabled.
4. Choose **Format (width / height)** and **Position** independently. For Canvas
Pilot copies, expand **Appearance** to choose **Crop & fit** and **Blanking**;
the collapsed heading shows what will be applied. Legacy text offers **Crop
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.
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.
@ -52,6 +50,27 @@ 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.
### Canvas Pilot layer clipboard
**Copy layer values** preserves exact geometry, crop edges and offsets, all fit
modes and blanking masks. The clipboard still begins with readable values; an
appended versioned payload holds the exact data. Editing only the readable summary
does not change what Canvas Pilot pastes.
To copy only appearance, uncheck Position and Format. Expand **Appearance** to
choose Crop & fit, Blanking, or both. Source assignments, device mappings and
input settings stay unchanged. Crop & fit requires matching source dimensions
after local input crop; normal crop also needs compatible box proportions. The
review explains mismatches before allowing import. Match the source dimensions,
include Format, or uncheck Crop & fit as appropriate. Blanking works independently
of source dimensions. A failed batch changes nothing; a successful paste undoes
in one step.
Older normal-crop text remains supported, with its optional zoom. It cannot supply
missing offsets or masks. The new full payload needs a current Canvas Pilot
version; use a project or snapshot for references, inputs and other document state.
See the [clipboard contract and example](../../interfaces/canvas-pilot-clipboard.md).
### SVG bounds
SVG import accepts square-corner rectangles and simple closed rectangular

View File

@ -80,7 +80,7 @@ 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**, normal crop | ✅ | ✅ | ❌ | ✅ | ❌ |
| Canvas Pilot **Copy layer values**, all fit modes | ✅ | ✅ | ❌ | ✅ | ✅ |
| Figma **SVG text** copy/paste | ✅ | ❌ | ❌ | ❌ | ❌ |
| Illustrator **SVG text** copy/paste | ✅ | ❌ | ❌ | ❌ | ❌ |
| draw.io diagram XML copy/paste | ✅ | ❌ | ❌ | ❌ | ❌ |
@ -94,12 +94,16 @@ Figma SVG, Illustrator SVG and draw.io XML clipboard paths have been manually re
or HTML clipboard payload. Use the corresponding file path if no supported text
is available. PowerPoint and QCAD use file exchange in this workflow.
Paste opens a mapping review with separate **Position**, **Format** (width/height)
and, when present, **Crop zoom** choices. Names in copied values identify rows;
they do not rename destination layers. Zoom alone does not reproduce the original
crop offsets or source settings. Older Canvas Pilot values may omit zoom.
**Advanced-fit container values are not the normal-crop paste format**; use a
project or supported snapshot to retain those modes.
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.
Crop & fit requires matching source dimensions after input crop; it never changes
source assignments or device mappings. If dimensions differ, match the local source
or uncheck Crop & fit. Blanking can be pasted independently. Older clipboard text
still offers **Crop zoom** when present, without full crop offsets or fit/masks.
See [clipboard preservation and limits](files.md#canvas-pilot-layer-clipboard).
SVG and draw.io imports can optionally include supported outline widths in the
bounds. Colors, text styling and artwork are not applied to the destination.

View File

@ -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": 1,
"layers": [
{
"name": "01 / 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
}
}
}
]
}

View File

@ -0,0 +1,87 @@
# Canvas Pilot layer clipboard, version 1
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
clipboard format for other applications. It changes no project/file schema.
## Text envelope
**Copy layer values** and viewport Ctrl/Cmd-C emit the existing readable summary
(center coordinates and dimensions in rounded screen pixels; normal crop zoom as
percent), followed by this exact delimiter:
```text
\n\nCanvas Pilot layer data:\n
```
The escapes above represent actual newlines. The remainder is UTF-8 JSON. The last
literal delimiter identifies the payload; names inside JSON use standard JSON
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).
## JSON schema and validation
Objects reject unknown fields. All listed fields are required, including nullable
`fit`. The maximum complete text size is 16 MiB; layers must contain 1–256 entries.
No URLs, file paths, commands, images or arbitrary application state are evaluated.
| Field | Meaning |
| --- | --- |
| `format` | Exactly `canvas-pilot.layers` |
| `version` | Integer `1`; unknown 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[].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 |
| `layers[].appearance.fit` | `null` for normal crop/zoom, or `one_to_one`, `centered`, `fullscreen`, `cropped` |
| `layers[].appearance.mask` | `left`, `right`, `top`, `bottom`: finite fractions of the layer container, each 0–1; opposite sums must be at most 1, with fully blank axes allowed |
Normal crop must match the visible-box aspect and supported 1–100 zoom range.
Offsets and zoom are derived from crop and bounds rather than stored twice.
Advanced modes apply crop before fit. Values are not display-rounded in JSON;
mask proportions do not become source-pixel crops.
## Applying a paste
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
formats have no such payload; older normal-crop summaries offer their legacy zoom
control instead. Ignored items do not affect availability or mapped values.
Crop & fit requires the destination's effective source dimensions to match the
recorded dimensions within 1e-8 pixels per axis. It copies exact crop and mode;
it does not adapt different inputs silently. Normal-crop aspect must also match
the resulting box. Mismatches block the batch with guidance to include Format,
match the local source dimensions, or disable Crop & fit. Blanking can be applied
independently across different input sizes because it is container-relative.
Unchecked appearance fields remain unchanged, except that a selected Format change
may reframe existing crop under the editor's normal resize rules.
Mappings must be unique, visible, unlocked and still refer to the reviewed layer
identities. Apply is atomic and one undo step: malformed data, duplicate mappings,
incompatible crops or invalid masks cannot partially change the document. Device
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,
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
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
versions do not support the appended payload; remove the payload only when
intentionally exchanging the legacy normal-crop geometry/zoom subset.
Regression tests cover every mode, crop offsets, fractional values, masks,
independent appearance controls, legacy summaries, invalid schemas, source/aspect
mismatches, locked destinations, whole-batch rollback and undo/redo.