beffroi-tools/crates/midra-layout/src/lib.rs

1221 lines
42 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Offline layer geometry, reversible edits and bounded draw.io/SVG imports.
use std::collections::HashMap;
pub mod formats;
pub mod import;
pub mod project;
use formats::{Formats, Framing, Source};
/// Presentation only: retain full precision in the document.
pub fn view_pixels(value: f64) -> String {
let rounded = (value * 10.0).round() / 10.0;
format!("{:.1}", if rounded == 0.0 { 0.0 } else { rounded })
}
pub fn export_pixels(value: f64) -> String {
let rounded = value.round();
format!("{:.0}", if rounded == 0.0 { 0.0 } else { rounded })
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ResizeHandle {
Corner(Corner),
Top,
Bottom,
Left,
Right,
}
/// How a handle drag affects selected layers.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum ResizeMode {
#[default]
Individual,
Same,
Mirror,
Opposite,
}
impl ResizeHandle {
pub fn mirrored_horizontally(self) -> Self {
match self {
Self::Left => Self::Right,
Self::Right => Self::Left,
Self::Top | Self::Bottom => self,
Self::Corner(corner) => Self::Corner(match corner {
Corner::TopLeft => Corner::TopRight,
Corner::TopRight => Corner::TopLeft,
Corner::BottomLeft => Corner::BottomRight,
Corner::BottomRight => Corner::BottomLeft,
}),
}
}
pub fn opposite(self) -> Self {
match self {
Self::Top => Self::Bottom,
Self::Bottom => Self::Top,
Self::Left => Self::Right,
Self::Right => Self::Left,
Self::Corner(corner) => Self::Corner(match corner {
Corner::TopLeft => Corner::BottomRight,
Corner::TopRight => Corner::BottomLeft,
Corner::BottomLeft => Corner::TopRight,
Corner::BottomRight => Corner::TopLeft,
}),
}
}
pub fn positions(g: Geometry) -> [(Self, [f64; 2]); 8] {
let [cx, cy] = g.center();
[
(Self::Corner(Corner::TopLeft), [g.x, g.y]),
(Self::Corner(Corner::TopRight), [g.x + g.width, g.y]),
(Self::Corner(Corner::BottomLeft), [g.x, g.y + g.height]),
(
Self::Corner(Corner::BottomRight),
[g.x + g.width, g.y + g.height],
),
(Self::Top, [cx, g.y]),
(Self::Bottom, [cx, g.y + g.height]),
(Self::Left, [g.x, cy]),
(Self::Right, [g.x + g.width, cy]),
]
}
}
fn resized_geometry(
original: Geometry,
handle: ResizeHandle,
delta: [f64; 2],
keep_ratio: bool,
) -> Geometry {
let left = matches!(
handle,
ResizeHandle::Corner(Corner::TopLeft | Corner::BottomLeft) | ResizeHandle::Left
);
let top = matches!(
handle,
ResizeHandle::Corner(Corner::TopLeft | Corner::TopRight) | ResizeHandle::Top
);
let dx = delta[0].round() * if left { -1.0 } else { 1.0 };
let dy = delta[1].round() * if top { -1.0 } else { 1.0 };
let side = !matches!(handle, ResizeHandle::Corner(_));
let horizontal = matches!(handle, ResizeHandle::Left | ResizeHandle::Right);
let (width, height) = if side {
if horizontal {
let width = (original.width + dx).max(if keep_ratio {
(original.width / original.height).max(1.0)
} else {
1.0
});
(
width,
if keep_ratio {
width * original.height / original.width
} else {
original.height
},
)
} else {
let height = (original.height + dy).max(if keep_ratio {
(original.height / original.width).max(1.0)
} else {
1.0
});
(
if keep_ratio {
height * original.width / original.height
} else {
original.width
},
height,
)
}
} else if keep_ratio {
let factor = ((original.width * (original.width + dx)
+ original.height * (original.height + dy))
/ (original.width * original.width + original.height * original.height))
.max((1.0 / original.width).max(1.0 / original.height));
(original.width * factor, original.height * factor)
} else {
(
(original.width + dx).max(1.0),
(original.height + dy).max(1.0),
)
};
anchored_resize(original, handle, width, height)
}
fn anchored_resize(original: Geometry, handle: ResizeHandle, width: f64, height: f64) -> Geometry {
let side = !matches!(handle, ResizeHandle::Corner(_));
let horizontal = matches!(handle, ResizeHandle::Left | ResizeHandle::Right);
let left = matches!(
handle,
ResizeHandle::Left | ResizeHandle::Corner(Corner::TopLeft | Corner::BottomLeft)
);
let top = matches!(
handle,
ResizeHandle::Top | ResizeHandle::Corner(Corner::TopLeft | Corner::TopRight)
);
Geometry {
x: if side && !horizontal {
original.center()[0] - width / 2.0
} else if left {
original.x + original.width - width
} else {
original.x
},
y: if side && horizontal {
original.center()[1] - height / 2.0
} else if top {
original.y + original.height - height
} else {
original.y
},
width,
height,
}
}
/// Visible layer bounds, in output screen pixels. No crop or camera transform.
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Geometry {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
impl Geometry {
pub fn validate(self) -> Result<Self, String> {
if [self.x, self.y, self.width, self.height]
.iter()
.any(|n| !n.is_finite() || n.abs() > 1_000_000.0)
|| self.width <= 0.0
|| self.height <= 0.0
{
return Err("Use finite coordinates within ±1,000,000 px and positive sizes up to 1,000,000 px.".into());
}
Ok(self)
}
pub fn center(self) -> [f64; 2] {
[self.x + self.width / 2.0, self.y + self.height / 2.0]
}
pub fn contains(self, p: [f64; 2]) -> bool {
p[0] >= self.x
&& p[0] <= self.x + self.width
&& p[1] >= self.y
&& p[1] <= self.y + self.height
}
pub fn outside(self) -> bool {
self.outside_on([1920, 1080])
}
pub fn outside_on(self, output: [u32; 2]) -> bool {
self.x < 0.0
|| self.y < 0.0
|| self.x + self.width > output[0] as f64
|| self.y + self.height > output[1] as f64
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Corner {
#[default]
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl Corner {
pub fn offsets(self, g: Geometry) -> [f64; 2] {
self.offsets_on(g, [1920, 1080])
}
pub fn offsets_on(self, g: Geometry, output: [u32; 2]) -> [f64; 2] {
[
if matches!(self, Self::TopRight | Self::BottomRight) {
output[0] as f64 - g.x - g.width
} else {
g.x
},
if matches!(self, Self::BottomLeft | Self::BottomRight) {
output[1] as f64 - g.y - g.height
} else {
g.y
},
]
}
pub fn geometry(self, dx: f64, dy: f64, width: f64, height: f64) -> Result<Geometry, String> {
self.geometry_on(dx, dy, width, height, [1920, 1080])
}
pub fn geometry_on(
self,
dx: f64,
dy: f64,
width: f64,
height: f64,
output: [u32; 2],
) -> Result<Geometry, String> {
Geometry {
x: if matches!(self, Self::TopRight | Self::BottomRight) {
output[0] as f64 - dx - width
} else {
dx
},
y: if matches!(self, Self::BottomLeft | Self::BottomRight) {
output[1] as f64 - dy - height
} else {
dy
},
width,
height,
}
.validate()
}
}
/// Edge or center line to align, without resizing layers.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Alignment {
Left,
Right,
Top,
Bottom,
HorizontalCenter,
VerticalCenter,
}
/// Explicit alignment reference, independent of selection order.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum AlignTarget {
#[default]
Selection,
Screen,
Layer(usize),
}
/// Two-layer document with one undo record per complete gesture/edit.
#[derive(Clone)]
pub struct Layout {
layers: [Geometry; 2],
selected: [bool; 2],
locked: [bool; 2],
visible: [bool; 2],
formats: Formats,
undo: Vec<Snapshot>,
redo: Vec<Snapshot>,
drag: Option<([bool; 2], Snapshot, [f64; 2])>,
content_drag: Option<(usize, Snapshot, [f64; 2])>,
content_resize: Option<Resize>,
pub gesture_error: Option<String>,
resize: Option<Resize>,
}
#[derive(Clone)]
struct Resize {
mode: ResizeMode,
targets: [bool; 2],
index: usize,
handle: ResizeHandle,
before: Snapshot,
start: [f64; 2],
keep_ratio: bool,
}
#[derive(Clone, Copy, PartialEq)]
struct Snapshot {
layers: [Geometry; 2],
formats: Formats,
}
impl Default for Layout {
fn default() -> Self {
Self {
layers: [
Geometry {
x: 120.0,
y: 180.0,
width: 640.0,
height: 360.0,
},
Geometry {
x: 1160.0,
y: 180.0,
width: 640.0,
height: 360.0,
},
],
selected: [false, true],
locked: [false; 2],
visible: [true; 2],
formats: Formats::default(),
content_drag: None,
content_resize: None,
gesture_error: None,
undo: Vec::new(),
redo: Vec::new(),
drag: None,
resize: None,
}
}
}
impl Layout {
fn snapshot(&self) -> Snapshot {
Snapshot {
layers: self.layers,
formats: self.formats,
}
}
fn restore(&mut self, s: Snapshot) {
self.gesture_error = None;
self.layers = s.layers;
self.formats = s.formats;
}
pub fn formats(&self) -> &Formats {
&self.formats
}
pub fn set_output(&mut self, output: [u32; 2]) -> Result<(), String> {
formats::validate_resolution(output)?;
self.finish_drag();
let before = self.snapshot();
self.formats.output = output;
self.remember(before);
Ok(())
}
pub fn set_framing(&mut self, i: usize, framing: Framing) -> Result<(), String> {
if !self.selectable(i) {
return Err("Unlock and show this layer first.".into());
}
let crop = formats::crop_from_framing(
self.formats.input(i)?,
[self.layers[i].width, self.layers[i].height],
framing,
)?;
self.finish_drag();
let before = self.snapshot();
self.formats.advanced[i] = crop;
self.remember(before);
Ok(())
}
pub fn start_content_drag(&mut self, i: usize, point: [f64; 2]) {
self.finish_drag();
if self.selectable(i) && self.selected() == Some(i) {
self.content_drag = Some((i, self.snapshot(), point));
}
}
/// Zoom the content from a corner, leaving the visible layer box unchanged.
pub fn start_content_resize(&mut self, index: usize, corner: Corner, point: [f64; 2]) {
self.finish_drag();
if !self.selectable(index)
|| self.selected() != Some(index)
|| point.iter().any(|v| !v.is_finite())
{
return;
}
self.content_resize = Some(Resize {
mode: ResizeMode::Individual,
targets: self.selected,
index,
handle: ResizeHandle::Corner(corner),
before: self.snapshot(),
start: point,
keep_ratio: true,
});
}
/// Atomic shared-source edit plus visible-box resizing. Explicit acceptance is required for any center adjustment.
pub fn configure(
&mut self,
i: usize,
source_id: usize,
source: Source,
geometry: Geometry,
allow_adjustment: bool,
) -> Result<String, String> {
if !self.selectable(i) || source_id >= 2 {
return Err("Select an editable layer and existing source.".into());
}
source.input()?;
geometry.validate()?;
self.finish_drag();
let before = self.snapshot();
let mut next = before;
next.formats.source_for[i] = source_id;
next.formats.sources[source_id] = source;
next.layers[i] = geometry;
let mut adjustments = Vec::new();
for j in 0..2 {
let affected = j == i
|| (next.formats.source_for[j] == source_id
&& source != before.formats.sources[source_id]);
if !affected {
continue;
}
if self.locked(j) {
return Err(format!(
"Source edit also affects locked layer {}. Unlock it first.",
j + 1
));
}
let (crop, adjusted) = formats::reframed(
before.formats.input(j)?,
[before.layers[j].width, before.layers[j].height],
before.formats.advanced[j],
next.formats.input(j)?,
[next.layers[j].width, next.layers[j].height],
)?;
next.formats.advanced[j] = crop;
if adjusted {
let m = next.formats.mapping(j, next.layers[j])?;
adjustments.push(format!(
"Layer {}: content offsets adjusted to {:.1}, {:.1} px",
j + 1,
m.framing.offset[0],
m.framing.offset[1]
));
}
}
let message = adjustments.join("; ");
if !allow_adjustment && !adjustments.is_empty() {
return Err(format!("Review required: {message}"));
}
self.restore(next);
self.remember(before);
Ok(message)
}
/// Provisional geometry report; deliberately not a verified WebRCS command recipe.
pub fn calculation_report(&self, i: usize) -> Result<String, String> {
self.formatted_report(i, false)
}
pub fn calculation_export(&self, i: usize) -> Result<String, String> {
self.formatted_report(i, true)
}
fn formatted_report(&self, i: usize, export: bool) -> Result<String, String> {
let p = if export { export_pixels } else { view_pixels };
let f = &self.formats;
let g = self.layers[i];
let source = f.sources[f.source_for[i]];
let input = source.input()?;
let m = f.mapping(i, g)?;
let a = f.advanced[i];
let c = source.input_crop;
let projected = Geometry {
x: g.x - m.scale * a.left,
y: g.y - m.scale * a.top,
width: m.scale * input[0],
height: m.scale * input[1],
};
Ok(format!(
"PROVISIONAL GEOMETRY — not a verified device recipe\nSource {} / {} / {} x {}\nInput crop L/R/T/B (native px): {} / {} / {} / {}\nInput resolution: {} x {}\nLayer resolution: {} x {}; visible center: {}, {}\nAdvanced crop L/R/T/B (usable-input px): {} / {} / {} / {}\nCombined native retained region: x {}, y {}, w {}, h {}\nContent zoom: {}%; offsets (output px): {}, {}\nProjected full usable input: {} x {}; center {}, {}\nIntended aspect mode: Centered. Device container, crop units and quantization remain unverified.",
f.source_for[i] + 1,
source.aspect.label(),
source.native[0],
source.native[1],
p(c.left),
p(c.right),
p(c.top),
p(c.bottom),
p(input[0]),
p(input[1]),
p(g.width),
p(g.height),
p(g.center()[0]),
p(g.center()[1]),
p(a.left),
p(a.right),
p(a.top),
p(a.bottom),
p(c.left + a.left),
p(c.top + a.top),
p(m.retained[0]),
p(m.retained[1]),
view_pixels(m.framing.zoom * 100.0),
p(m.framing.offset[0]),
p(m.framing.offset[1]),
p(projected.width),
p(projected.height),
p(projected.center()[0]),
p(projected.center()[1])
))
}
pub fn layers(&self) -> &[Geometry; 2] {
&self.layers
}
pub fn locked(&self, index: usize) -> bool {
self.locked.get(index).copied().unwrap_or(false)
}
pub fn visible(&self, index: usize) -> bool {
self.visible.get(index).copied().unwrap_or(false)
}
fn selectable(&self, index: usize) -> bool {
self.visible(index) && !self.locked(index)
}
/// Editor protection flags do not change geometry or its undo history.
pub fn set_locked(&mut self, index: usize, locked: bool) {
self.cancel_drag();
if let Some(value) = self.locked.get_mut(index) {
*value = locked;
if locked {
self.selected[index] = false;
}
}
}
pub fn set_visible(&mut self, index: usize, visible: bool) {
self.cancel_drag();
if let Some(value) = self.visible.get_mut(index) {
*value = visible;
if !visible {
self.selected[index] = false;
}
}
}
/// A single selected layer, or None for zero/multiple selections.
pub fn selected(&self) -> Option<usize> {
let indices = self.selected_indices();
if indices.len() == 1 {
Some(indices[0])
} else {
None
}
}
pub fn selected_indices(&self) -> Vec<usize> {
(0..2).filter(|i| self.selected[*i]).collect()
}
pub fn selection_mask(&self) -> [bool; 2] {
self.selected
}
pub fn set_selection(&mut self, selected: [bool; 2]) {
self.finish_drag();
self.selected = std::array::from_fn(|i| selected[i] && self.selectable(i));
}
pub fn select(&mut self, index: Option<usize>) {
self.set_selection(std::array::from_fn(|i| index == Some(i)));
}
pub fn toggle(&mut self, index: usize) {
self.finish_drag();
if !self.selectable(index) {
return;
}
if let Some(selected) = self.selected.get_mut(index) {
*selected = !*selected;
}
}
/// Select rectangles intersecting the marquee; base supplies Shift-additive selection.
pub fn select_region(&mut self, start: [f64; 2], end: [f64; 2], base: [bool; 2]) {
let left = start[0].min(end[0]);
let right = start[0].max(end[0]);
let top = start[1].min(end[1]);
let bottom = start[1].max(end[1]);
self.set_selection(std::array::from_fn(|i| {
let g = self.layers[i];
base[i]
|| (g.x <= right && g.x + g.width >= left && g.y <= bottom && g.y + g.height >= top)
}));
}
pub fn selection_bounds(&self) -> Option<Geometry> {
let mut bounds = None::<Geometry>;
for i in self.selected_indices() {
let g = self.layers[i];
bounds = Some(match bounds {
None => g,
Some(b) => {
let x = b.x.min(g.x);
let y = b.y.min(g.y);
Geometry {
x,
y,
width: (b.x + b.width).max(g.x + g.width) - x,
height: (b.y + b.height).max(g.y + g.height) - y,
}
}
});
}
bounds
}
/// Align only selected rectangles; preserve size and the unrelated axis.
pub fn align(&mut self, alignment: Alignment, target: AlignTarget) -> Result<(), String> {
self.align_axes(&[alignment], target)
}
/// Align one or both axes against one reference, with one undo record.
pub fn align_axes(
&mut self,
alignments: &[Alignment],
target: AlignTarget,
) -> Result<(), String> {
self.finish_drag();
let bounds = self.selection_bounds().ok_or("Select layers to align.")?;
let reference = match target {
AlignTarget::Selection => bounds,
AlignTarget::Screen => Geometry {
x: 0.0,
y: 0.0,
width: self.formats.output[0] as f64,
height: self.formats.output[1] as f64,
},
AlignTarget::Layer(i) => *self.layers.get(i).ok_or("Unknown reference layer.")?,
};
let mut next = self.layers;
for i in self.selected_indices() {
if target == AlignTarget::Layer(i) {
continue;
}
let g = &mut next[i];
for alignment in alignments {
match alignment {
Alignment::Left => g.x = reference.x,
Alignment::Right => g.x = reference.x + reference.width - g.width,
Alignment::Top => g.y = reference.y,
Alignment::Bottom => g.y = reference.y + reference.height - g.height,
Alignment::HorizontalCenter => {
g.x = reference.x + (reference.width - g.width) / 2.0
}
Alignment::VerticalCenter => {
g.y = reference.y + (reference.height - g.height) / 2.0
}
}
}
}
self.commit(next)
}
fn commit(&mut self, next: [Geometry; 2]) -> Result<(), String> {
for g in next {
g.validate()?;
}
let before = self.snapshot();
let mut formats = self.formats;
for (i, geometry) in next.iter().enumerate() {
formats.resize(i, self.layers[i], *geometry)?;
}
self.layers = next;
self.formats = formats;
self.remember(before);
Ok(())
}
/// Viewport back-to-front order; selected layers are drawn last.
/// Layer identities and export order remain unchanged.
pub fn viewport_order(&self) -> [usize; 2] {
let mut order = [0, 1];
order.sort_by_key(|i| self.selected[*i]);
order
}
pub fn hit(&self, point: [f64; 2]) -> Option<usize> {
self.viewport_order()
.into_iter()
.rev()
.find(|i| self.selectable(*i) && self.layers[*i].contains(point))
}
fn remember(&mut self, before: Snapshot) {
if before != self.snapshot() {
if self.undo.len() == 100 {
self.undo.remove(0);
}
self.undo.push(before);
self.redo.clear();
}
}
pub fn apply(&mut self, index: usize, geometry: Geometry) -> Result<(), String> {
let geometry = geometry.validate()?;
if index >= 2 {
return Err("Select an existing layer.".into());
}
if !self.selectable(index) {
return Err("Unlock and show the layer before editing it.".into());
}
self.finish_drag();
let mut next = self.layers;
next[index] = geometry;
self.commit(next)
}
/// Apply a one-to-one import to the complete selection, with one undo record.
pub fn apply_import(&mut self, values: &[(usize, Geometry)]) -> Result<(), String> {
let targets = self.selected_indices();
if values.len() != targets.len() || targets.is_empty() {
return Err(format!(
"Layer count mismatch: {} selected, {} imported. Select exactly one destination for each imported rectangle.",
targets.len(),
values.len()
));
}
let mut seen = Vec::new();
let mut next = self.layers;
for (i, g) in values {
if !targets.contains(i) || seen.contains(i) || !self.selectable(*i) {
return Err("Map every selected layer exactly once; duplicate or unselected targets are not allowed.".into());
}
g.validate()?;
seen.push(*i);
next[*i] = *g;
}
self.finish_drag();
self.commit(next)
}
/// Import geometry and optional crop zoom together as one atomic edit.
pub fn apply_import_with_zoom(
&mut self,
values: &[(usize, Geometry)],
zooms: &[(usize, f64)],
) -> Result<(), String> {
let mut draft = self.clone();
draft.apply_import(values)?;
let mut seen = Vec::new();
for &(i, zoom) in zooms {
if !values.iter().any(|(target, _)| *target == i) || seen.contains(&i) {
return Err("Each zoom must map to one imported layer, without duplicates.".into());
}
seen.push(i);
let g = draft.layers[i];
let mut framing = draft.formats.mapping(i, g)?.framing;
let (_, limits) = formats::limits(draft.formats.input(i)?, [g.width, g.height], zoom)?;
framing.zoom = zoom;
for (offset, limit) in framing.offset.iter_mut().zip(limits) {
*offset = offset.clamp(-limit, limit);
}
draft.set_framing(i, framing)?;
}
self.finish_drag();
let before = self.snapshot();
self.restore(draft.snapshot());
self.remember(before);
Ok(())
}
pub fn nudge(&mut self, dx: f64, dy: f64) -> Result<(), String> {
self.finish_drag();
let mut next = self.layers;
for i in self.selected_indices() {
next[i].x += dx;
next[i].y += dy;
}
self.commit(next)
}
pub fn start_drag(&mut self, point: [f64; 2]) {
self.finish_drag();
if let Some(i) = self.hit(point) {
if !self.selected[i] {
self.select(Some(i));
}
self.drag = Some((self.selected, self.snapshot(), point));
} else {
self.select(None);
}
}
/// Resize one selected layer, keeping its opposite corner fixed.
pub fn start_resize(
&mut self,
index: usize,
corner: Corner,
point: [f64; 2],
keep_ratio: bool,
) {
self.start_handle_resize(index, ResizeHandle::Corner(corner), point, keep_ratio);
}
pub fn start_handle_resize(
&mut self,
index: usize,
handle: ResizeHandle,
point: [f64; 2],
keep_ratio: bool,
) {
self.finish_drag();
if !self.selectable(index) || !self.selected[index] {
return;
}
self.select(Some(index));
self.resize = Some(Resize {
mode: ResizeMode::Individual,
targets: self.selected,
index,
handle,
before: self.snapshot(),
start: point,
keep_ratio,
});
}
/// Start proportional resizing from matching or opposite handles, without changing selection.
pub fn start_selected_resize(
&mut self,
index: usize,
handle: ResizeHandle,
point: [f64; 2],
keep_ratio: bool,
mode: ResizeMode,
) -> Result<(), String> {
if mode == ResizeMode::Individual {
self.start_handle_resize(index, handle, point, keep_ratio);
return Ok(());
}
let count = self.selected_indices().len();
if count < 2 || (matches!(mode, ResizeMode::Mirror | ResizeMode::Opposite) && count != 2) {
return Err(
"Select at least two layers for Same handles, or exactly two for Mirror horizontally / Opposite handles."
.into(),
);
}
if !self.selectable(index) || !self.selected.get(index).copied().unwrap_or(false) {
return Err("Resize from a selected, visible, unlocked layer.".into());
}
self.finish_drag();
self.resize = Some(Resize {
mode,
targets: self.selected,
index,
handle,
before: self.snapshot(),
start: point,
keep_ratio,
});
Ok(())
}
pub fn drag_to(&mut self, point: [f64; 2]) {
if point.iter().any(|v| !v.is_finite()) {
return;
}
if let Some(r) = &self.content_resize {
let result = (|| {
let i = r.index;
let g = r.before.layers[i];
let input = r.before.formats.input(i)?;
let m = r.before.formats.mapping(i, g)?;
let crop = r.before.formats.advanced[i];
let full = Geometry {
x: g.x - crop.left * m.scale,
y: g.y - crop.top * m.scale,
width: input[0] * m.scale,
height: input[1] * m.scale,
};
let desired = resized_geometry(
full,
r.handle,
[point[0] - r.start[0], point[1] - r.start[1]],
true,
);
let zoom = (m.framing.zoom * desired.width / full.width).clamp(1.0, 100.0);
let (scale, limits) = formats::limits(input, [g.width, g.height], zoom)?;
let resized = anchored_resize(full, r.handle, input[0] * scale, input[1] * scale);
let center = resized.center();
let layer_center = g.center();
let offset = std::array::from_fn(|axis| {
(center[axis] - layer_center[axis]).clamp(-limits[axis], limits[axis])
});
formats::crop_from_framing(input, [g.width, g.height], Framing { zoom, offset })
})();
match result {
Ok(crop) => {
self.formats.advanced[r.index] = crop;
self.gesture_error = None;
}
Err(e) => self.gesture_error = Some(e),
}
return;
}
if let Some((i, before, start)) = self.content_drag {
if let Ok(m) = before.formats.mapping(i, before.layers[i]) {
let offset = std::array::from_fn(|axis| {
(m.framing.offset[axis] + point[axis] - start[axis])
.clamp(-m.offset_limits[axis], m.offset_limits[axis])
});
if let Ok(crop) = formats::crop_from_framing(
before.formats.input(i).unwrap(),
[before.layers[i].width, before.layers[i].height],
Framing {
zoom: m.framing.zoom,
offset,
},
) {
self.formats.advanced[i] = crop;
}
}
return;
}
if let Some(r) = &self.resize {
let original = r.before.layers[r.index];
let next = resized_geometry(
original,
r.handle,
[point[0] - r.start[0], point[1] - r.start[1]],
r.keep_ratio,
);
let result = (|| {
let mut layers = r.before.layers;
let mut formats = r.before.formats;
let mut sx = next.width / original.width;
let mut sy = next.height / original.height;
if r.mode != ResizeMode::Individual {
for (i, g) in layers.iter().enumerate() {
if r.targets[i] {
sx = sx.max(1.0 / g.width);
sy = sy.max(1.0 / g.height);
}
}
if r.keep_ratio {
sx = sx.max(sy);
sy = sx;
}
}
for (i, geometry) in layers.iter_mut().enumerate() {
if !r.targets[i] {
continue;
}
let before = *geometry;
let handle = if i != r.index {
match r.mode {
ResizeMode::Mirror => r.handle.mirrored_horizontally(),
ResizeMode::Opposite => r.handle.opposite(),
ResizeMode::Individual | ResizeMode::Same => r.handle,
}
} else {
r.handle
};
*geometry = if r.mode == ResizeMode::Individual {
next
} else {
anchored_resize(before, handle, before.width * sx, before.height * sy)
};
geometry.validate()?;
formats.resize(i, before, *geometry)?;
}
Ok::<_, String>((layers, formats))
})();
match result {
Ok((layers, formats)) => {
self.layers = layers;
self.formats = formats;
self.gesture_error = None;
}
Err(e) => self.gesture_error = Some(e),
}
return;
}
if let Some((selected, before, start)) = self.drag {
let mut next = before.layers;
for i in 0..2 {
if selected[i] {
next[i].x += (point[0] - start[0]).round();
next[i].y += (point[1] - start[1]).round();
}
}
if next.iter().all(|g| g.validate().is_ok()) {
self.layers = next;
}
}
}
pub fn dragging(&self) -> bool {
self.drag.is_some()
|| self.resize.is_some()
|| self.content_drag.is_some()
|| self.content_resize.is_some()
}
pub fn finish_drag(&mut self) {
if let Some(r) = self.content_resize.take() {
self.remember(r.before);
}
if let Some((_, before, _)) = self.content_drag.take() {
self.remember(before);
}
if let Some(r) = self.resize.take() {
self.remember(r.before);
}
if let Some((_, before, _)) = self.drag.take() {
self.remember(before);
}
}
pub fn cancel_drag(&mut self) {
if let Some(r) = self.content_resize.take() {
self.restore(r.before);
}
self.gesture_error = None;
if let Some((_, before, _)) = self.content_drag.take() {
self.restore(before);
}
if let Some(r) = self.resize.take() {
self.restore(r.before);
}
if let Some((_, before, _)) = self.drag.take() {
self.restore(before);
}
}
pub fn undo(&mut self) {
self.finish_drag();
if let Some(before) = self.undo.pop() {
self.redo.push(self.snapshot());
self.restore(before);
}
}
pub fn redo(&mut self) {
self.finish_drag();
if let Some(after) = self.redo.pop() {
self.undo.push(self.snapshot());
self.restore(after);
}
}
}
#[derive(Clone, Debug)]
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.
/// Nested, relative, rotated and nonrectangular geometry is intentionally refused.
pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
if input.len() > 1_048_576 {
return Err("Clipboard text exceeds 1 MiB.".into());
}
let input = input.trim();
let decoded;
let xml = if input.starts_with('<') {
input
} else {
decoded = decode_percent(input)?;
decoded.trim()
};
let doc = roxmltree::Document::parse(xml).map_err(|e| format!("Invalid draw.io XML: {e}"))?;
let model = doc.root_element();
if !model.has_tag_name("mxGraphModel") {
return Err("Paste draw.io mxGraphModel XML, not a compressed file or an image.".into());
}
let root = model
.children()
.find(|n| n.has_tag_name("root"))
.ok_or("draw.io root is missing.")?;
let mut cells = HashMap::new();
for n in root.children().filter(|n| n.is_element()) {
if !n.has_tag_name("mxCell") {
return Err("Wrapped objects are not supported yet. Copy plain rectangles.".into());
}
let id = n.attribute("id").ok_or("A cell has no ID.")?;
if cells.insert(id, n).is_some() {
return Err("Duplicate draw.io cell ID.".into());
}
}
let mut result = Vec::new();
for cell in root.children().filter(|n| n.has_tag_name("mxCell")) {
if cell.attribute("edge") == Some("1") {
return Err("Connections are not supported. Copy rectangles only.".into());
}
if cell.attribute("vertex") != Some("1") {
continue;
}
let id = cell.attribute("id").unwrap();
let parent = cell
.attribute("parent")
.and_then(|p| cells.get(p))
.ok_or("Missing parent; grouped/partial geometry is unsupported.")?;
let is_layer = parent.attribute("vertex").is_none()
&& parent
.attribute("parent")
.and_then(|p| cells.get(p))
.is_some_and(|p| {
p.attribute("parent").is_none() && p.attribute("vertex").is_none()
});
if !is_layer {
return Err(
"Grouped or nested rectangles are not supported yet. Ungroup before copying."
.into(),
);
}
let mut styles = HashMap::new();
for entry in cell
.attribute("style")
.unwrap_or("")
.split(';')
.filter(|s| !s.is_empty())
{
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());
}
let g = geometries[0];
if g.attribute("relative").is_some_and(|v| v != "0") || g.children().any(|n| n.is_element())
{
return Err("Relative, offset or alternate bounds are not supported yet.".into());
}
let number = |name, default| -> Result<f64, String> {
g.attribute(name)
.or(default)
.ok_or_else(|| format!("Missing {name}."))?
.parse()
.map_err(|_| format!("Invalid {name}."))
};
let geometry = Geometry {
x: number("x", Some("0"))?,
y: number("y", Some("0"))?,
width: number("width", None)?,
height: number("height", None)?,
}
.validate()?;
result.push(DrawioShape {
id: id.to_owned(),
geometry,
stroke_width,
});
}
if result.is_empty() {
return Err("No rectangles found in the draw.io clipboard.".into());
}
Ok(result)
}
fn decode_percent(input: &str) -> Result<String, String> {
let mut out = Vec::with_capacity(input.len());
let mut bytes = input.bytes();
while let Some(b) = bytes.next() {
if b == b'%' {
let hex = |c: u8| (c as char).to_digit(16).map(|v| v as u8);
let a = bytes
.next()
.and_then(hex)
.ok_or("Invalid percent escape in clipboard.")?;
let b = bytes
.next()
.and_then(hex)
.ok_or("Invalid percent escape in clipboard.")?;
out.push(a * 16 + b);
} else {
out.push(b);
} // '+' is literal in encodeURIComponent, not a space.
}
String::from_utf8(out).map_err(|_| "Clipboard is not valid UTF-8.".into())
}