Offer outline-inclusive bounds for draw.io paste

This commit is contained in:
Dandaedre 2026-11-13 11:48:32 +01:00
parent 3b7e4250a8
commit d752d9b118
4 changed files with 248 additions and 29 deletions

View File

@ -17,6 +17,7 @@ struct Paste {
shapes: Vec<DrawioShape>,
choice: usize,
include_size: bool,
include_outline: bool,
error: String,
}
impl Paste {
@ -86,6 +87,7 @@ impl Editor {
shapes: Vec::new(),
choice: 0,
include_size: true,
include_outline: false,
error: String::new(),
};
if !p.text.is_empty() {
@ -254,36 +256,50 @@ impl Editor {
&mut p.include_size,
"Include size / format (otherwise position only)",
);
let before = self.layout.layers()[p.target];
let mut after = p.shapes[p.choice].geometry;
let shape = &p.shapes[p.choice];
ui.add_enabled(
p.include_size && shape.stroke_width > 0.0,
egui::Checkbox::new(&mut p.include_outline, "Include outline in bounds"),
);
if !p.include_size {
after.width = before.width;
after.height = before.height;
ui.small("Outline adjustment requires size import; position-only uses the original top-left.");
} else if shape.stroke_width == 0.0 {
ui.small("No visible outline to include.");
} else {
ui.small(format!("Outline: {} px · extends {} px beyond each edge. Center stays unchanged.", number(shape.stroke_width), number(shape.stroke_width / 2.0)));
}
ui.separator();
ui.columns(2, |cols| {
cols[0].label("Before");
cols[0].label(bounds(before));
cols[1].label("After");
cols[1].label(bounds(after));
});
if after.outside() {
ui.colored_label(
AMBER,
"This rectangle extends outside the screen. Its coordinates are preserved.",
);
}
ui.label("Geometry only; source format, colors and stroke are not imported.");
if ui
.add(egui::Button::new("Apply to selected target").fill(PURPLE))
.clicked()
{
match self.layout.apply(p.target, after) {
Ok(()) => {
self.sync();
close = true;
let before = self.layout.layers()[p.target];
match shape.paste_geometry(before, p.include_size, p.include_outline) {
Ok(after) => {
ui.separator();
ui.columns(2, |cols| {
cols[0].label("Before");
cols[0].label(bounds(before));
cols[1].label("After");
cols[1].label(bounds(after));
});
if after.outside() {
ui.colored_label(
AMBER,
"This rectangle extends outside the screen. Its coordinates are preserved.",
);
}
Err(e) => p.error = e,
ui.label("Bounds only; source format, colors and outline appearance are not imported.");
if ui
.add(egui::Button::new("Apply to selected target").fill(PURPLE))
.clicked()
{
match self.layout.apply(p.target, after) {
Ok(()) => {
self.sync();
close = true;
}
Err(e) => p.error = e,
}
}
}
Err(error) => {
ui.colored_label(AMBER, error);
}
}
}
@ -987,4 +1003,54 @@ mod tests {
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn outline_checkbox_changes_preview_then_applies_as_one_undo_step() {
let mut app = Editor::default();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let before = *app.layout.layers();
frame(
&mut app,
&ctx,
vec![egui::Event::Paste(
include_str!("../tests/fixtures/drawio-rectangle.txt").into(),
)],
);
assert!(!app.paste.as_ref().unwrap().include_outline);
for text in ["Include outline in bounds", "Apply to selected target"] {
let output = frame(&mut app, &ctx, vec![]);
let pos = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::epaint::Shape::Text(t) if t.galley.job.text == text => {
Some(t.pos + Vec2::new(20.0, 6.0))
}
_ => None,
})
.expect("paste control rendered");
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(pos), mouse(pos, true)],
);
frame(&mut app, &ctx, vec![mouse(pos, false)]);
if text == "Include outline in bounds" {
assert!(app.paste.as_ref().unwrap().include_outline);
assert_eq!(*app.layout.layers(), before);
}
}
assert!(app.paste.is_none());
assert_eq!(
app.layout.layers()[1],
Geometry {
x: 9.5,
y: 268.5,
width: 950.0,
height: 536.58
}
);
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
}
}

View File

@ -213,6 +213,30 @@ impl Layout {
pub struct DrawioShape {
pub id: String,
pub geometry: Geometry,
/// Effective visible outline thickness, in diagram pixels (default 1).
pub stroke_width: f64,
}
impl DrawioShape {
/// Outline expansion applies only when importing size; position-only keeps
/// the original draw.io top-left and the destination layer dimensions.
pub fn paste_geometry(
&self,
before: Geometry,
include_size: bool,
include_outline: bool,
) -> Result<Geometry, String> {
let mut g = self.geometry;
if !include_size {
g.width = before.width;
g.height = before.height;
} else if include_outline {
g.x -= self.stroke_width / 2.0;
g.y -= self.stroke_width / 2.0;
g.width += self.stroke_width;
g.height += self.stroke_width;
}
g.validate()
}
}
/// Read raw or once-percent-encoded mxGraphModel XML. Values map 1:1 to pixels.
@ -274,6 +298,7 @@ pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
.into(),
);
}
let mut styles = HashMap::new();
for entry in cell
.attribute("style")
.unwrap_or("")
@ -283,12 +308,31 @@ pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
let (key, value) = entry
.split_once('=')
.ok_or("Named/inherited draw.io styles are unsupported.")?;
styles.insert(key, value);
if (key == "shape" && value != "rectangle")
|| (matches!(key, "rotation" | "flipH" | "flipV") && value != "0")
{
return Err("Only unrotated rectangles are supported; remove shape transforms before copying.".into());
}
}
let style_number = |key, default: f64, max: f64| -> Result<f64, String> {
let value = styles.get(key).map_or(Ok(default), |s| {
s.parse::<f64>().map_err(|_| format!("Invalid {key}."))
})?;
if !value.is_finite() || !(0.0..=max).contains(&value) {
return Err(format!("Invalid {key}: expected 0–{max}."));
}
Ok(value)
};
let width = style_number("strokeWidth", 1.0, 1_000_000.0)?;
let stroke_opacity = style_number("strokeOpacity", 100.0, 100.0)?;
let opacity = style_number("opacity", 100.0, 100.0)?;
let hidden = styles
.get("strokeColor")
.is_some_and(|c| matches!(*c, "none" | "transparent"))
|| stroke_opacity == 0.0
|| opacity == 0.0;
let stroke_width = if hidden { 0.0 } else { width };
let geometries: Vec<_> = cell.children().filter(|n| n.is_element()).collect();
if geometries.len() != 1 || !geometries[0].has_tag_name("mxGeometry") {
return Err("Expected one plain geometry per rectangle.".into());
@ -315,6 +359,7 @@ pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
result.push(DrawioShape {
id: id.to_owned(),
geometry,
stroke_width,
});
}
if result.is_empty() {

View File

@ -242,3 +242,93 @@ fn offscreen_placement_is_preserved_and_nudging_keeps_size() {
assert_eq!(a.width, 945.0);
assert!(a.outside());
}
#[test]
fn outline_expands_sample_without_moving_center_and_position_only_is_unadjusted() {
let shape = parse_drawio(SAMPLE).unwrap().remove(0);
assert_eq!(shape.stroke_width, 5.0);
let before = Geometry {
x: 100.0,
y: 200.0,
width: 300.0,
height: 250.0,
};
assert_eq!(shape.paste_geometry(before, true, false).unwrap(), g());
let outlined = shape.paste_geometry(before, true, true).unwrap();
assert_eq!(
outlined,
Geometry {
x: 9.5,
y: 268.5,
width: 950.0,
height: 536.58
}
);
assert_eq!(outlined.center(), g().center());
assert_eq!(
shape.paste_geometry(before, false, true).unwrap(),
Geometry {
x: 12.0,
y: 271.0,
..before
}
);
}
#[test]
fn default_fractional_and_hidden_outlines_are_handled() {
for (style, width) in [
("", 1.0),
("strokeWidth=0.5;", 0.5),
("strokeWidth=0;", 0.0),
("strokeWidth=5;strokeColor=none;", 0.0),
("strokeWidth=5;strokeColor=transparent;", 0.0),
("strokeWidth=5;strokeOpacity=0;", 0.0),
("strokeWidth=5;opacity=0;", 0.0),
("strokeWidth=2;strokeWidth=6;", 6.0),
] {
let shape = parse_drawio(&vertex(r#"<mxGeometry width="10" height="20"/>"#, style))
.unwrap()
.remove(0);
assert_eq!(shape.stroke_width, width, "{style}");
let result = shape.paste_geometry(g(), true, true).unwrap();
assert_eq!(result.x, -width / 2.0);
assert_eq!(result.width, 10.0 + width);
assert_eq!(result.center(), [5.0, 10.0]);
}
}
#[test]
fn invalid_outline_settings_and_expansion_beyond_limits_are_refused() {
for style in [
"strokeWidth=NaN;",
"strokeWidth=-1;",
"strokeWidth=inf;",
"strokeWidth=huge;",
"strokeOpacity=101;",
"opacity=-1;",
] {
assert!(parse_drawio(&vertex(r#"<mxGeometry width="10" height="20"/>"#, style)).is_err());
}
let shape = parse_drawio(&vertex(
r#"<mxGeometry width="1000000" height="20"/>"#,
"strokeWidth=5;",
))
.unwrap()
.remove(0);
assert!(shape.paste_geometry(g(), true, false).is_ok());
assert!(shape.paste_geometry(g(), true, true).is_err());
}
#[test]
fn each_pasted_rectangle_keeps_its_own_outline_width() {
let data = xml(
r#"<mxCell id="2" vertex="1" parent="1" style="strokeWidth=2;"><mxGeometry width="10" height="20"/></mxCell><mxCell id="3" vertex="1" parent="1" style="strokeWidth=8;"><mxGeometry width="30" height="40"/></mxCell>"#,
);
let shapes = parse_drawio(&data).unwrap();
assert_eq!(
shapes[0].paste_geometry(g(), true, true).unwrap().width,
12.0
);
assert_eq!(
shapes[1].paste_geometry(g(), true, true).unwrap().width,
38.0
);
}

View File

@ -19,7 +19,9 @@ cargo run --locked -p midra-layout
were copied, choose one explicitly; the importer does not guess a mapping to
the two layers.
4. Leave **Include size / format** checked to import width and height along with
position, or uncheck it for position only. Click **Apply to selected target**.
position, or uncheck it for position only. Choose **Include outline in bounds**
if the layer should cover the rectangle's outline too, then click
**Apply to selected target**. The before/after preview updates with your choice.
The first adapter accepts raw or once-percent-encoded `mxGraphModel` XML, like
[the supplied clipboard fixture](../crates/midra-layout/tests/fixtures/drawio-rectangle.txt).
@ -32,7 +34,23 @@ is **484.5, 536.79**. The visible box has its exact imported ratio; it is not ro
or coerced into a 16:9 preset. “Format” here means the visible rectangle's width,
height and aspect, not native source format or advanced cropping.
The adapter ignores colors, stroke width, text, style aspect locks and other
**Include outline in bounds** is off by default on each paste. For an outline of
width `s`, enabling it subtracts `s/2` from X and Y and adds `s` to width and
height, preserving the center. This follows the half-stroke expansion in
[mxGraph's bounding-box calculation](https://github.com/jgraph/mxgraph/blob/master/javascript/src/js/shape/mxShape.js).
Your sample's 5 px outline gives **950 × 536.58 at (9.5, 268.5)**. Only the bounds
are imported; no border is drawn or configured on the device.
The option is disabled for position-only paste: that mode uses the original
geometry's top-left and keeps the target layer's dimensions. Zero-width,
`strokeColor=none`/`transparent`, zero stroke opacity and zero overall opacity
produce no outline expansion. A missing width uses the standard 1 px default;
the detected width is shown in the preview. Each rectangle in a multi-object
paste uses its own width. Shadows, sketch effects and raster antialiasing fringes
are not included. Invalid thickness/opacity values or bounds beyond the
application limits are rejected without changing the document.
The adapter otherwise ignores colors, text, style aspect locks and other
appearance settings. It currently rejects grouped/nested geometry, connections,
nonrectangular shapes, relative coordinates, alternate bounds, rotated/flipped
objects, named/inherited styles, wrapped objects and compressed `.drawio` files.