Fix clipboard text detection and embedded format fallback
Gitea/canvas-pilot/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-11-18 16:13:34 +01:00
parent 4ab2a2e855
commit 709fdcbb59
7 changed files with 160 additions and 11 deletions

2
Cargo.lock generated
View File

@ -602,7 +602,7 @@ dependencies = [
[[package]]
name = "canvas-pilot"
version = "0.9.69"
version = "0.9.70"
dependencies = [
"base64 0.22.1",
"craft-dwg",

View File

@ -4,7 +4,7 @@ default-members = ["crates/canvas-pilot"]
resolver = "3"
[workspace.package]
version = "0.9.69"
version = "0.9.70"
edition = "2024"
license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot"

View File

@ -82,18 +82,98 @@ pub fn parse_values(text: &str) -> Result<ImportDocument, String> {
if crate::geometry_formats::looks_like_dxf(text) {
return crate::geometry_formats::parse_dxf(text);
}
if text.trim_start().starts_with('<')
&& roxmltree::Document::parse_with_options(text, xml_options())
.is_ok_and(|d| d.root_element().has_tag_name("svg"))
let decoded;
let xml = if text.trim_start().to_ascii_lowercase().starts_with("%3c") {
decoded = crate::decode_percent(text.trim())?;
decoded.as_str()
} else {
text
};
if let Ok(document) = roxmltree::Document::parse_with_options(xml, xml_options()) {
let root = document.root_element();
match root.tag_name().name() {
"svg" => return parse_svg(xml),
"mxGraphModel" | "mxfile" => return parse_drawio_values(xml),
"html" => {
// Explicit Canvas Pilot documents remain strict: do not hide invalid
// versions or lost settings by falling back to incidental artwork.
if root.attribute("data-midra-layout-geometry").is_some() {
return crate::geometry_formats::parse_html(xml);
}
let mut failures = Vec::new();
for (label, tags) in [
("draw.io", &["mxGraphModel", "mxfile"][..]),
("SVG", &["svg"][..]),
] {
let nodes: Vec<_> = root
.descendants()
.filter(|node| {
node.is_element()
&& tags.contains(&node.tag_name().name())
&& !node.ancestors().skip(1).any(|parent| {
parent.is_element() && tags.contains(&parent.tag_name().name())
})
})
.collect();
if nodes.is_empty() {
continue;
}
if nodes.len() != 1 {
failures.push(format!(
"{label}: multiple embedded documents; export a single file instead."
));
continue;
}
let fragment = &xml[nodes[0].range()];
let result = if label == "SVG" {
parse_svg(fragment)
} else {
parse_drawio_values(fragment)
};
match result {
Ok(mut imported)
if imported.shapes.iter().any(|shape| !shape.background_only) =>
{
imported.note = format!(
"Clipboard: used embedded {label}; HTML layout/CSS is not imported. {}{}",
imported.note,
if failures.is_empty() {
String::new()
} else {
format!(
" Earlier candidates were rejected: {}",
failures.join(" | ")
)
}
);
return Ok(imported);
}
Ok(_) => failures.push(format!("{label}: no usable layer geometry.")),
Err(error) => failures.push(format!("{label}: {error}")),
}
}
if !failures.is_empty() {
return Err(format!(
"No supported clipboard representation could be imported. {}",
failures.join(" | ")
));
}
}
_ => {}
}
} else if xml.trim_start().starts_with("<svg")
|| xml.trim_start().starts_with("<?xml") && xml.contains("<svg")
{
return parse_svg(text);
}
if text.trim_start().starts_with('<')
&& roxmltree::Document::parse_with_options(text, xml_options())
.is_ok_and(|d| d.root_element().has_tag_name("html"))
return parse_svg(xml);
} else if xml.trim_start().starts_with("<mxGraphModel")
|| xml.trim_start().starts_with("<mxfile")
{
return crate::geometry_formats::parse_html(text);
return parse_drawio_values(xml);
}
Err("No supported layer geometry found in clipboard text. Copy SVG, draw.io XML or Canvas Pilot values, or import a supported file. For PowerPoint, use Import geometry with the .pptx file; native PowerPoint clipboard objects are not supported.".into())
}
fn parse_drawio_values(text: &str) -> Result<ImportDocument, String> {
Ok(ImportDocument {
shapes: parse_drawio(text)?
.into_iter()

View File

@ -402,3 +402,32 @@ fn explicit_mapping_without_selection_is_atomic_and_preserves_selection() {
.is_err()
);
}
#[test]
fn clipboard_tries_embedded_svg_after_invalid_drawio_candidate() {
let text = r#"<html><body><mxGraphModel/><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect x="10" y="20" width="30" height="40"/></svg></body></html>"#;
let imported = parse_values(text).unwrap();
assert_eq!(imported.shapes.len(), 1);
assert_eq!(imported.shapes[0].geometry.x, 10.);
assert!(imported.note.contains("used embedded SVG"));
assert!(imported.note.contains("rejected"));
}
#[test]
fn clipboard_unknown_text_is_not_misdiagnosed_as_drawio() {
for text in ["PowerPoint slide title and ordinary text", "\u{2060}"] {
let error = parse_values(text).unwrap_err();
assert!(error.contains("native PowerPoint clipboard"));
assert!(!error.contains("Invalid draw.io"));
}
let error =
parse_values("<html><body><mxGraphModel/><svg><path d='M0 0'/></svg></body></html>")
.unwrap_err();
assert!(error.contains("draw.io:"));
assert!(error.contains("SVG:"));
}
#[test]
fn clipboard_keeps_explicit_versions_strict_and_rejects_ambiguous_svg() {
assert!(parse_values(r#"<html data-midra-layout-geometry="99"><svg width="100" height="100"><rect width="30" height="40"/></svg></html>"#).is_err());
let error = parse_values("<html><svg/><svg/></html>").unwrap_err();
assert!(error.contains("multiple embedded documents"));
}

View File

@ -4,6 +4,16 @@
## Unreleased
### v0.9.70
- Stop treating unrecognized clipboard text as draw.io XML. Unsupported text now
explains the supported text formats and PowerPoint’s .pptx file-import route.
- Well-formed HTML supplied as clipboard text can fall back from a rejected
embedded draw.io document to embedded SVG. Rejected candidates are reported in
the review; ambiguous multiple documents and invalid explicit Canvas Pilot
versions remain errors. Native binary clipboard support is unchanged.
### v0.9.69
- Enter now opens crop edit for the selected editable layer using the same rules

View File

@ -202,6 +202,20 @@ styles for predictable results. Files are limited to 16 MiB, 256 rectangles plus
64 levels of nesting. SVG imports retain the same outline and position-only
choices as draw.io imports.
### Clipboard detection and fallback
Paste examines the text supplied by the clipboard. Unrecognized text is not
assumed to be draw.io XML. For well-formed HTML supplied as text, it tries a single
embedded draw.io document, then a single embedded SVG if the first candidate fails.
The review identifies the chosen representation and any rejected candidates.
Only the embedded drawing's coordinates are imported; surrounding HTML layout and
CSS are not. Multiple drawings of the same format require exporting a single file.
This does not enumerate native operating-system clipboard formats. PowerPoint
objects copied inside PowerPoint remain unsupported; use **Import geometry** with
the **.pptx** file. Invalid Canvas Pilot data keeps its specific error rather than
silently dropping settings in a fallback.
### Figma SVG clipboard text
The supplied [Figma SVG sample](../../../crates/canvas-pilot/tests/fixtures/figma-rectangles.svg)

View File

@ -94,3 +94,19 @@ 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.
## External text detection and fallback
The GUI receives egui's text paste event; it does not enumerate OS clipboard MIME
types or consume native PowerPoint/OLE packages. The parser keeps explicit
Canvas Pilot markers and versioned representations strict. Ordinary unsupported
text no longer falls through to the draw.io parser. Raw and percent-encoded
draw.io XML are recognized by their root element.
For well-formed, unversioned HTML text, detection attempts a single outermost
embedded draw.io document, then a single outermost SVG document. A failed or
geometry-empty candidate does not stop the next candidate. The first usable
document enters normal import review with rejected-candidate details. Multiple
documents of the same candidate type are rejected as ambiguous, not partially
imported. HTML layout/CSS is not interpreted. Existing text-size, XML node,
geometry and parser limits remain in force; external resources are never fetched.