Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ libloading = "0.8"
windows-sys = { version = "0.61", features = ["Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", "Win32_UI_HiDpi", "Win32_UI_Input", "Win32_UI_Input_KeyboardAndMouse", "Win32_System_LibraryLoader", "Win32_System_Threading", "Win32_Security", "Win32_System_Com", "Win32_System_Com_StructuredStorage", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_Ole", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_Storage_FileSystem", "Win32_Foundation", "Win32_Graphics_Printing", "Win32_Graphics_Gdi", "Win32_Storage_Xps", "Win32_Globalization", "Win32_Security_Authentication_Identity", "Win32_UI_Controls_Dialogs"] }

[target.'cfg(target_os = "linux")'.dependencies]
# The X11 CLIPBOARD selection, for the SVG a copy puts there (#2018).
x11rb = "0.13"
ashpd = { version = "0.13.13", default-features = false, features = ["async-io", "settings", "wayland"] }

# For `src/bin/ocs_launcher.rs` only (the .app's real CFBundleExecutable,
Expand Down
86 changes: 85 additions & 1 deletion src/app/commands/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,14 @@ impl OpenCADStudio {
}
#[cfg(not(target_arch = "wasm32"))]
{
iced::clipboard::write(svg).discard()
// Where the platform has a registered SVG format, the markup
// goes there as well as text, in one write; drawing programs
// read it from there (#2018). Elsewhere the toolkit writes text.
if crate::sys::clipboard_svg::write(&svg) {
Task::none()
} else {
iced::clipboard::write(svg).discard()
}
}
}

Expand Down Expand Up @@ -3392,3 +3399,80 @@ mod tests {
);
}
}

/// Ctrl+C puts the selection on the system clipboard as SVG for other
/// programs (#2018). They look for it under the `image/svg+xml` format (a
/// registered clipboard format on Windows, a selection target on X11);
/// text alone is pasted as text or not at all.
#[cfg(all(test, any(target_os = "windows", target_os = "linux")))]
mod svg_clipboard_format_tests {
use crate::app::OpenCADStudio;
use document::entities::Line;
use document::EntityType;

/// The clipboard writes a task leaves to the GUI toolkit, which writes
/// text only.
fn toolkit_clipboard_writes(task: iced::Task<crate::app::Message>) -> Vec<String> {
use iced::futures::StreamExt;
let mut writes = Vec::new();
let Some(mut stream) = iced_runtime::task::into_stream(task) else {
return writes;
};
while let Some(action) = iced::futures::executor::block_on(stream.next()) {
if let iced_runtime::Action::Clipboard(iced_runtime::clipboard::Action::Write {
content,
..
}) = action
{
writes.push(format!("{content:?}"));
}
}
writes
}

#[test]
fn copyclip_does_not_leave_the_svg_to_a_text_only_write() {
let mut app = OpenCADStudio::new_for_test();
app.automation_op(r#"{"op":"new"}"#);
let i = app.active_tab;
let line = app.tabs[i]
.scene
.add_entity(EntityType::Line(Line::from_coords(
0.0, 0.0, 0.0, 40.0, 20.0, 0.0,
)));
app.tabs[i].scene.select_entity(line, true);
let task = app.dispatch_command("COPYCLIP");
let writes = toolkit_clipboard_writes(task);
let written = crate::sys::clipboard_svg::test_record::take();
assert_eq!(written.len(), 1, "one write of the system clipboard");
let formats: Vec<&str> = written[0]
.iter()
.map(|(format, _)| format.as_ref())
.collect();
if cfg!(target_os = "windows") {
assert_eq!(formats, ["CF_UNICODETEXT", "image/svg+xml"]);
} else {
assert_eq!(
formats,
["UTF8_STRING", "text/plain;charset=utf-8", "image/svg+xml"]
);
}
let (_, svg) = written[0]
.iter()
.find(|(format, _)| *format == "image/svg+xml")
.expect("the SVG format");
let svg = std::str::from_utf8(svg).expect("UTF-8 markup");
assert!(
svg.starts_with("<?xml") && svg.contains("<svg"),
"{svg:.60}"
);
assert!(
writes.is_empty(),
"the SVG went to the clipboard as text only: {:?}",
writes
.iter()
.map(|write| write.chars().take(60).collect::<String>())
.collect::<Vec<_>>()
);
}
}
75 changes: 70 additions & 5 deletions src/io/svg_clipboard.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
//! The selection as SVG for the system clipboard, so other programs paste
//! it as editable paths: each object's outline as a stroked path in its
//! colour, one drawing unit to one millimetre, Y pointing up as drawn.
//!
//! The coordinates are written in CSS pixels, SVG's own user unit, with the
//! size in millimetres: drawing programs take the user unit as a pixel when
//! they paste, and read the size from `width` and `height` otherwise. Both
//! give one drawing unit as one millimetre.

use std::fmt::Write;

use crate::scene::{Scene, WireModel};
use document::Handle;

/// CSS pixels (1/96 in) in a millimetre: SVG user units per drawing unit.
const PX_PER_MM: f64 = 96.0 / 25.4;

fn point(wire: &WireModel, index: usize) -> [f64; 2] {
let high = wire.points[index];
let low = wire.points_low.get(index).unwrap_or([0.0; 3]);
Expand Down Expand Up @@ -45,7 +53,13 @@ pub fn wires_svg(wires: &[&WireModel]) -> Option<String> {
}
min = [min[0].min(x), min[1].min(y)];
max = [max[0].max(x), max[1].max(y)];
let _ = write!(path, "{}{} {} ", if pen_down { "L" } else { "M" }, x, -y);
let _ = write!(
path,
"{}{} {} ",
if pen_down { "L" } else { "M" },
x * PX_PER_MM,
-y * PX_PER_MM
);
pen_down = true;
}
if path.is_empty() {
Expand Down Expand Up @@ -73,8 +87,11 @@ pub fn wires_svg(wires: &[&WireModel]) -> Option<String> {
}
let (width, height) = ((max[0] - min[0]).max(1e-6), (max[1] - min[1]).max(1e-6));
Some(format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}mm\" height=\"{height}mm\" viewBox=\"{} {} {width} {height}\">\n<g fill=\"none\" stroke-width=\"1\" stroke-linecap=\"round\" stroke-linejoin=\"round\" vector-effect=\"non-scaling-stroke\" style=\"vector-effect:non-scaling-stroke\">\n{body}</g>\n</svg>\n",
min[0], -max[1],
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}mm\" height=\"{height}mm\" viewBox=\"{} {} {} {}\">\n<g fill=\"none\" stroke-width=\"1\" stroke-linecap=\"round\" stroke-linejoin=\"round\" vector-effect=\"non-scaling-stroke\" style=\"vector-effect:non-scaling-stroke\">\n{body}</g>\n</svg>\n",
min[0] * PX_PER_MM,
-max[1] * PX_PER_MM,
width * PX_PER_MM,
height * PX_PER_MM,
))
}

Expand All @@ -88,15 +105,63 @@ mod tests {
wire.points = vec![[0.0, 0.0, 0.0], [10.0, 5.0, 0.0]];
wire.color = [1.0, 0.0, 0.0, 1.0];
let svg = wires_svg(&[&wire]).unwrap();
// 10 × 5 mm; the coordinates in CSS pixels, 96 to the inch.
let px = |mm: f64| mm * (96.0 / 25.4);
assert!(
svg.contains(r#"width="10mm" height="5mm" viewBox="0 -5 10 5""#),
svg.contains(&format!(
r#"width="10mm" height="5mm" viewBox="0 {} {} {}""#,
-px(5.0),
px(10.0),
px(5.0)
)),
"{svg}"
);
assert!(
svg.contains(r##"<path d="M0 -0 L10 -5" stroke="#ff0000"/>"##),
svg.contains(&format!(
r##"<path d="M0 -0 L{} {}" stroke="#ff0000"/>"##,
px(10.0),
-px(5.0)
)),
"{svg}"
);
// And reads back as geometry.
assert!(crate::io::svg_import::read(svg.as_bytes(), [100.0, 100.0]).is_ok());
}

/// The size an SVG reader gets when it takes the user unit as a CSS
/// pixel (1/96 in), as SVG does by default and as drawing programs do
/// when they paste: `width` × `height` in millimetres.
fn size_at_one_unit_per_px(svg: &str) -> [f64; 2] {
let attribute = |name: &str| {
let start = svg.find(&format!(" {name}=\"")).unwrap() + name.len() + 3;
let end = start + svg[start..].find('"').unwrap();
svg[start..end].to_owned()
};
let view_box: Vec<f64> = attribute("viewBox")
.split_whitespace()
.map(|v| v.parse().unwrap())
.collect();
let mm_per_px = 25.4 / 96.0;
[view_box[2] * mm_per_px, view_box[3] * mm_per_px]
}

#[test]
fn a_reader_taking_svg_units_as_pixels_gets_the_size_in_millimetres() {
let mut wire = WireModel::default();
wire.points = vec![
[0.0, 0.0, 0.0],
[60.0, 0.0, 0.0],
[60.0, 40.0, 0.0],
[0.0, 40.0, 0.0],
[0.0, 0.0, 0.0],
];
wire.color = [0.0, 0.0, 1.0, 1.0];
let svg = wires_svg(&[&wire]).unwrap();
assert!(svg.contains(r#"width="60mm" height="40mm""#), "{svg}");
let [width, height] = size_at_one_unit_per_px(&svg);
assert!(
(width - 60.0).abs() < 1e-6 && (height - 40.0).abs() < 1e-6,
"a 60 × 40 mm drawing reads as {width:.3} × {height:.3} mm"
);
}
}
1 change: 1 addition & 0 deletions src/sys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// (wasm) build must handle differently or skip.

pub mod clipboard_link;
pub mod clipboard_svg;
pub mod startup_times;
pub mod ui_font;

Expand Down
Loading
Loading