diff --git a/Cargo.lock b/Cargo.lock index 049e016d89..9d7ab478d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -100,6 +100,7 @@ dependencies = [ "web-sys", "windows-sys 0.61.2", "winresource", + "x11rb", "zip 8.6.0", ] diff --git a/Cargo.toml b/Cargo.toml index 1d6f16c792..5ed65fbf32 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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, diff --git a/src/app/commands/blocks.rs b/src/app/commands/blocks.rs index 00d7eb94d6..4ff74c9e17 100644 --- a/src/app/commands/blocks.rs +++ b/src/app/commands/blocks.rs @@ -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() + } } } @@ -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) -> Vec { + 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("()) + .collect::>() + ); + } +} diff --git a/src/io/svg_clipboard.rs b/src/io/svg_clipboard.rs index c78fe7cb42..e336d5e99e 100644 --- a/src/io/svg_clipboard.rs +++ b/src/io/svg_clipboard.rs @@ -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]); @@ -45,7 +53,13 @@ pub fn wires_svg(wires: &[&WireModel]) -> Option { } 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() { @@ -73,8 +87,11 @@ pub fn wires_svg(wires: &[&WireModel]) -> Option { } let (width, height) = ((max[0] - min[0]).max(1e-6), (max[1] - min[1]).max(1e-6)); Some(format!( - "\n\n\n{body}\n\n", - min[0], -max[1], + "\n\n\n{body}\n\n", + min[0] * PX_PER_MM, + -max[1] * PX_PER_MM, + width * PX_PER_MM, + height * PX_PER_MM, )) } @@ -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##""##), + svg.contains(&format!( + r##""##, + 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 = 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" + ); + } } diff --git a/src/sys.rs b/src/sys.rs index 26a532de96..601b28bef4 100644 --- a/src/sys.rs +++ b/src/sys.rs @@ -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; diff --git a/src/sys/clipboard_svg.rs b/src/sys/clipboard_svg.rs new file mode 100644 index 0000000000..9783e9be19 --- /dev/null +++ b/src/sys/clipboard_svg.rs @@ -0,0 +1,377 @@ +//! The selection as SVG on the system clipboard, under the format other +//! programs read SVG from. +//! +//! The GUI toolkit writes text only. Drawing programs paste SVG markup that +//! arrives as text as text, or not at all; they look for it under the SVG +//! MIME type: a registered clipboard format on Windows, a selection target +//! on X11 (which XWayland hands on to Wayland programs). + +/// The clipboard format, or selection target, SVG is read from. +pub const SVG_FORMAT: &str = "image/svg+xml"; + +/// The formats one copy puts on this platform's clipboard, with their +/// bytes: the markup as text, and as SVG. Empty where this module does not +/// write the clipboard. +pub fn formats(svg: &str) -> Vec<(&'static str, Vec)> { + if cfg!(target_os = "windows") { + let text: Vec = svg + .encode_utf16() + .chain([0]) + .flat_map(u16::to_le_bytes) + .collect(); + vec![ + ("CF_UNICODETEXT", text), + (SVG_FORMAT, svg.as_bytes().to_vec()), + ] + } else if cfg!(target_os = "linux") { + vec![ + ("UTF8_STRING", svg.as_bytes().to_vec()), + ("text/plain;charset=utf-8", svg.as_bytes().to_vec()), + (SVG_FORMAT, svg.as_bytes().to_vec()), + ] + } else { + Vec::new() + } +} + +/// Put `svg` on the system clipboard in all its `formats`, in one write. +/// `false` when this platform has no such write, or it failed; the caller +/// then puts the text there through the GUI toolkit. +pub fn write(svg: &str) -> bool { + let formats = formats(svg); + if formats.is_empty() { + return false; + } + #[cfg(test)] + { + test_record::record(formats); + true + } + #[cfg(all(not(test), target_os = "windows"))] + { + windows::write(&formats) + } + #[cfg(all(not(test), target_os = "linux"))] + { + x11::write(formats) + } + #[cfg(all(not(test), not(any(target_os = "windows", target_os = "linux"))))] + { + let _ = formats; + false + } +} + +/// Tests leave the system clipboard alone: each write is kept here, per +/// thread, as the formats it would have put there. +#[cfg(test)] +pub mod test_record { + use std::cell::RefCell; + + type Write = Vec<(&'static str, Vec)>; + + thread_local! { + static WRITES: RefCell> = const { RefCell::new(Vec::new()) }; + } + + pub(super) fn record(formats: Write) { + WRITES.with(|writes| writes.borrow_mut().push(formats)); + } + + /// The writes made on this thread so far, each as (format, bytes). + pub fn take() -> Vec { + WRITES.with(|writes| std::mem::take(&mut *writes.borrow_mut())) + } +} + +#[cfg(all(not(test), target_os = "windows"))] +mod windows { + use windows_sys::Win32::Foundation::{GlobalFree, HGLOBAL}; + use windows_sys::Win32::System::DataExchange::{ + CloseClipboard, EmptyClipboard, OpenClipboard, RegisterClipboardFormatW, SetClipboardData, + }; + use windows_sys::Win32::System::Memory::{ + GlobalAlloc, GlobalLock, GlobalUnlock, GMEM_MOVEABLE, + }; + use windows_sys::Win32::System::Ole::CF_UNICODETEXT; + + /// A movable global block holding `bytes`, as the clipboard takes data. + fn global(bytes: &[u8]) -> Option { + // SAFETY: the block is as long as `bytes`; it is written while + // locked and freed if it cannot be locked. + unsafe { + let handle = GlobalAlloc(GMEM_MOVEABLE, bytes.len().max(1)); + if handle.is_null() { + return None; + } + let data = GlobalLock(handle) as *mut u8; + if data.is_null() { + GlobalFree(handle); + return None; + } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len()); + GlobalUnlock(handle); + Some(handle) + } + } + + /// Hand `bytes` to the open clipboard under `format`. The clipboard owns + /// the block once it is set; otherwise it is freed here. + fn set(format: u32, bytes: &[u8]) -> bool { + let Some(handle) = global(bytes) else { + return false; + }; + // SAFETY: the clipboard is open and emptied by this process. + unsafe { + if SetClipboardData(format, handle).is_null() { + GlobalFree(handle); + return false; + } + } + true + } + + /// The clipboard's number for a format of [`super::formats`]. + fn format_id(name: &str) -> u32 { + if name == "CF_UNICODETEXT" { + return u32::from(CF_UNICODETEXT); + } + let name: Vec = name.encode_utf16().chain([0]).collect(); + // SAFETY: `name` is NUL-terminated. + unsafe { RegisterClipboardFormatW(name.as_ptr()) } + } + + pub fn write(formats: &[(&str, Vec)]) -> bool { + // Another program may hold the clipboard for a moment. + let mut open = false; + for _ in 0..10 { + // SAFETY: closed again below. + if unsafe { OpenClipboard(std::ptr::null_mut()) } != 0 { + open = true; + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + if !open { + return false; + } + // SAFETY: the clipboard is open; it is closed before returning. + let written = unsafe { EmptyClipboard() != 0 } + && formats + .iter() + .all(|(name, bytes)| set(format_id(name), bytes)); + // SAFETY: this function opened the clipboard. + unsafe { + CloseClipboard(); + } + written + } +} + +#[cfg(all(not(test), target_os = "linux"))] +mod x11 { + //! The CLIPBOARD selection of the X server, owned by a thread of this + //! process while it holds the copy. Under Wayland, XWayland hands the + //! selection on to Wayland programs with the same targets. + + use std::sync::{Arc, Mutex, OnceLock}; + + use x11rb::connection::Connection; + use x11rb::protocol::xproto::{ + AtomEnum, ConnectionExt, CreateWindowAux, EventMask, PropMode, SelectionNotifyEvent, + SelectionRequestEvent, WindowClass, SELECTION_NOTIFY_EVENT, + }; + use x11rb::protocol::Event; + use x11rb::rust_connection::RustConnection; + use x11rb::wrapper::ConnectionExt as _; + use x11rb::CURRENT_TIME; + + /// A target of the selection and its bytes. + type Target = (u32, Arc<[u8]>); + + /// What the selection serves: the targets of the last copy, `None` + /// once another program owns the clipboard. + type Served = Arc>>>; + + struct Owner { + conn: Arc, + window: u32, + clipboard: u32, + served: Served, + } + + fn atom(conn: &RustConnection, name: &str) -> Option { + Some( + conn.intern_atom(false, name.as_bytes()) + .ok()? + .reply() + .ok()? + .atom, + ) + } + + /// The window that owns the selection and the thread that answers for + /// it, made at the first copy. `None` with no X server to talk to. + fn owner() -> Option<&'static Owner> { + static OWNER: OnceLock> = OnceLock::new(); + OWNER + .get_or_init(|| { + let (conn, screen) = x11rb::connect(None).ok()?; + let conn = Arc::new(conn); + let root = conn.setup().roots.get(screen)?.root; + let window = conn.generate_id().ok()?; + conn.create_window( + 0, + window, + root, + 0, + 0, + 1, + 1, + 0, + WindowClass::INPUT_ONLY, + 0, + &CreateWindowAux::new(), + ) + .ok()?; + let clipboard = atom(&conn, "CLIPBOARD")?; + let targets = atom(&conn, "TARGETS")?; + conn.flush().ok()?; + let served: Served = Arc::new(Mutex::new(None)); + let (thread_conn, thread_served) = (conn.clone(), served.clone()); + std::thread::Builder::new() + .name("svg-clipboard".into()) + .spawn(move || serve(&thread_conn, window, clipboard, targets, &thread_served)) + .ok()?; + Some(Owner { + conn, + window, + clipboard, + served, + }) + }) + .as_ref() + } + + /// Answer requests for the selection until the connection closes. + fn serve(conn: &RustConnection, window: u32, clipboard: u32, targets: u32, served: &Served) { + while let Ok(event) = conn.wait_for_event() { + match event { + // Another program took the clipboard. A copy made since took + // it back, so ask who owns it now. + Event::SelectionClear(event) if event.selection == clipboard => { + let ours = conn + .get_selection_owner(clipboard) + .ok() + .and_then(|cookie| cookie.reply().ok()) + .is_some_and(|reply| reply.owner == window); + if !ours { + if let Ok(mut served) = served.lock() { + *served = None; + } + } + } + Event::SelectionRequest(event) => { + let formats = served.lock().ok().and_then(|s| s.clone()); + let _ = answer(conn, clipboard, targets, &event, formats.as_deref()); + } + _ => {} + } + } + } + + /// Put the requested target on the requestor's property, or the list of + /// targets for TARGETS, and tell it whether that worked. It is told in + /// either case, so it never waits for an answer that does not come. + fn answer( + conn: &RustConnection, + clipboard: u32, + targets: u32, + event: &SelectionRequestEvent, + formats: Option<&[Target]>, + ) -> Result<(), Box> { + // Clients of the old protocol name no property: the target is it. + let property = if event.property == u32::from(AtomEnum::NONE) { + event.target + } else { + event.property + }; + let put = || -> Result> { + let Some(formats) = formats.filter(|_| event.selection == clipboard) else { + return Ok(false); + }; + if event.target == targets { + let mut list: Vec = formats.iter().map(|(target, _)| *target).collect(); + list.push(targets); + conn.change_property32( + PropMode::REPLACE, + event.requestor, + property, + AtomEnum::ATOM, + &list, + )? + .check()?; + return Ok(true); + } + let Some((target, bytes)) = formats.iter().find(|(target, _)| *target == event.target) + else { + return Ok(false); + }; + conn.change_property8(PropMode::REPLACE, event.requestor, property, *target, bytes)? + .check()?; + Ok(true) + }; + let property = if put().unwrap_or(false) { + property + } else { + AtomEnum::NONE.into() + }; + conn.send_event( + false, + event.requestor, + EventMask::NO_EVENT, + SelectionNotifyEvent { + response_type: SELECTION_NOTIFY_EVENT, + sequence: event.sequence, + time: event.time, + requestor: event.requestor, + selection: event.selection, + target: event.target, + property, + }, + )?; + conn.flush()?; + Ok(()) + } + + pub fn write(formats: Vec<(&'static str, Vec)>) -> bool { + let Some(owner) = owner() else { + return false; + }; + let Some(formats) = formats + .into_iter() + .map(|(name, bytes)| Some((atom(&owner.conn, name)?, Arc::from(bytes)))) + .collect::>>() + else { + return false; + }; + let Ok(mut served) = owner.served.lock() else { + return false; + }; + *served = Some(formats); + drop(served); + let owned = owner + .conn + .set_selection_owner(owner.window, owner.clipboard, CURRENT_TIME) + .ok() + .and_then(|_| owner.conn.get_selection_owner(owner.clipboard).ok()) + .and_then(|cookie| cookie.reply().ok()) + .is_some_and(|reply| reply.owner == owner.window); + if !owned { + if let Ok(mut served) = owner.served.lock() { + *served = None; + } + } + owned + } +}