From 6b12720ccca4b4704f3bda5143e2e7064de79600 Mon Sep 17 00:00:00 2001 From: Jesus <8483156+jespinolao@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:23:20 -0300 Subject: [PATCH 1/6] Tests: Ctrl+C on Windows does not leave the SVG to a text-only write COPYCLIP hands the selection's SVG to the GUI toolkit's clipboard write, which puts it on the system clipboard as text only. Drawing programs read SVG from the clipboard under its own format, `image/svg+xml`; pasted as text it arrives as text or not at all. The new test fails on Windows: "the SVG went to the clipboard as text only". Refs #2018 Co-Authored-By: Claude Opus 5.5 --- src/app/commands/blocks.rs | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/app/commands/blocks.rs b/src/app/commands/blocks.rs index 00d7eb94d6..e16e61301e 100644 --- a/src/app/commands/blocks.rs +++ b/src/app/commands/blocks.rs @@ -3392,3 +3392,56 @@ mod tests { ); } } + +/// Ctrl+C puts the selection on the system clipboard as SVG for other +/// programs (#2018). On Windows they look for it under the registered +/// `image/svg+xml` format; text alone is pasted as text or not at all. +#[cfg(all(test, target_os = "windows"))] +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); + assert!( + writes.is_empty(), + "the SVG went to the clipboard as text only: {:?}", + writes + .iter() + .map(|write| write.chars().take(60).collect::()) + .collect::>() + ); + } +} From 3fcb19a48f5cf5aa7090eb842f7f4c3f247e436f Mon Sep 17 00:00:00 2001 From: Jesus <8483156+jespinolao@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:25:18 -0300 Subject: [PATCH 2/6] Ctrl+C on Windows puts the SVG under image/svg+xml as well as text Drawing programs read SVG from the clipboard under the SVG MIME type, which Windows has as a registered clipboard format; the GUI toolkit writes text only, so the SVG that COPYCLIP, CUTCLIP and COPYBASE put there for other programs was pasted as text or not at all. On Windows, `sys::clipboard_svg::write` now opens the clipboard once and puts the markup there as CF_UNICODETEXT and, as UTF-8, under `image/svg+xml`. If that write fails, or on other platforms, the toolkit writes the text as before. Tests record the write instead of touching the system clipboard; the test checks both formats. Refs #2018 Co-Authored-By: Claude Opus 5.5 --- src/app/commands/blocks.rs | 18 ++++- src/sys.rs | 1 + src/sys/clipboard_svg.rs | 143 +++++++++++++++++++++++++++++++++++++ 3 files changed, 161 insertions(+), 1 deletion(-) create mode 100644 src/sys/clipboard_svg.rs diff --git a/src/app/commands/blocks.rs b/src/app/commands/blocks.rs index e16e61301e..f69807adad 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() + } } } @@ -3435,6 +3442,15 @@ mod svg_clipboard_format_tests { 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(|(f, _)| f.as_str()).collect(); + assert_eq!(formats, ["CF_UNICODETEXT", "image/svg+xml"]); + let svg = std::str::from_utf8(&written[0][1].1).expect("UTF-8 markup"); + assert!( + svg.starts_with(" bool { + #[cfg(test)] + { + test_record::record(svg); + cfg!(target_os = "windows") + } + #[cfg(all(not(test), target_os = "windows"))] + { + windows::write(svg) + } + #[cfg(all(not(test), not(target_os = "windows")))] + { + let _ = svg; + false + } +} + +/// Tests leave the system clipboard alone: on Windows 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; + + thread_local! { + static WRITES: RefCell)>>> = const { RefCell::new(Vec::new()) }; + } + + pub(super) fn record(svg: &str) { + if !cfg!(target_os = "windows") { + return; + } + let text: Vec = svg + .encode_utf16() + .chain([0]) + .flat_map(u16::to_le_bytes) + .collect(); + WRITES.with(|writes| { + writes.borrow_mut().push(vec![ + ("CF_UNICODETEXT".to_owned(), text), + (super::SVG_FORMAT.to_owned(), svg.as_bytes().to_vec()), + ]) + }); + } + + /// 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 + } + + pub fn write(svg: &str) -> 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; + } + let text: Vec = svg + .encode_utf16() + .chain([0]) + .flat_map(u16::to_le_bytes) + .collect(); + let name: Vec = super::SVG_FORMAT.encode_utf16().chain([0]).collect(); + // SAFETY: the clipboard is open; it is closed before returning. + let written = unsafe { + EmptyClipboard() != 0 + && set(u32::from(CF_UNICODETEXT), &text) + && set(RegisterClipboardFormatW(name.as_ptr()), svg.as_bytes()) + }; + // SAFETY: this function opened the clipboard. + unsafe { + CloseClipboard(); + } + written + } +} From 795ec4309e7a710ffc74dc11ed0eb1c38e3cf403 Mon Sep 17 00:00:00 2001 From: Jesus <8483156+jespinolao@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:42:29 -0300 Subject: [PATCH 3/6] Tests: the copied SVG reads at its size in mm at one unit per pixel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The SVG put on the clipboard has width and height in millimetres and a viewBox in drawing units, so its user unit is a millimetre. A reader that takes the user unit as a CSS pixel, as SVG does by default and as drawing programs do when they paste, gets a 60 x 40 drawing at 15.875 x 10.583 mm. The new test fails: "a 60 × 40 mm drawing reads as 15.875 × 10.583 mm". Refs #2018 Co-Authored-By: Claude Opus 5.5 --- src/io/svg_clipboard.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/io/svg_clipboard.rs b/src/io/svg_clipboard.rs index c78fe7cb42..a7937d459c 100644 --- a/src/io/svg_clipboard.rs +++ b/src/io/svg_clipboard.rs @@ -99,4 +99,41 @@ mod tests { // 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" + ); + } } From 5e85289c62f8ff32267ab259d2f3372492f1d834 Mon Sep 17 00:00:00 2001 From: Jesus <8483156+jespinolao@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:44:54 -0300 Subject: [PATCH 4/6] The copied SVG pastes at its size in millimetres The SVG for other programs had its coordinates in drawing units and its size in millimetres, so its user unit was a millimetre. Drawing programs take the user unit as a CSS pixel when they paste, and pasted a 60 x 40 drawing at 15.9 x 10.6 mm. The coordinates and the viewBox are now written in CSS pixels (96 per inch); width and height stay in millimetres. A reader of either gets one drawing unit as one millimetre. The stroke stays 1 user unit, now one pixel. Pasting the SVG into OCS fits the picture to the view and does not depend on its units. The test of a line's path moves to pixel coordinates. Refs #2018 Co-Authored-By: Claude Opus 5.5 --- src/io/svg_clipboard.rs | 38 +++++++++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/src/io/svg_clipboard.rs b/src/io/svg_clipboard.rs index a7937d459c..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,12 +105,23 @@ 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. From c79fe6ee36f1ae9dde2d7d86e5676e0081dde77c Mon Sep 17 00:00:00 2001 From: Jesus <8483156+jespinolao@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:09:42 -0300 Subject: [PATCH 5/6] Tests: Ctrl+C on Linux does not leave the SVG to a text-only write The COPYCLIP test also runs on Linux, where the toolkit writes the clipboard as text too. There it expects UTF8_STRING, text/plain;charset=utf-8 and image/svg+xml in one write; on Windows, CF_UNICODETEXT and image/svg+xml as before. On Linux the test fails: "the SVG went to the clipboard as text only". Refs #2018 Co-Authored-By: Claude Opus 5.5 --- src/app/commands/blocks.rs | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/app/commands/blocks.rs b/src/app/commands/blocks.rs index f69807adad..4ff74c9e17 100644 --- a/src/app/commands/blocks.rs +++ b/src/app/commands/blocks.rs @@ -3401,9 +3401,10 @@ mod tests { } /// Ctrl+C puts the selection on the system clipboard as SVG for other -/// programs (#2018). On Windows they look for it under the registered -/// `image/svg+xml` format; text alone is pasted as text or not at all. -#[cfg(all(test, target_os = "windows"))] +/// 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; @@ -3444,9 +3445,23 @@ mod svg_clipboard_format_tests { 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(|(f, _)| f.as_str()).collect(); - assert_eq!(formats, ["CF_UNICODETEXT", "image/svg+xml"]); - let svg = std::str::from_utf8(&written[0][1].1).expect("UTF-8 markup"); + 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(" Date: Mon, 23 Nov 2026 16:09:42 -0300 Subject: [PATCH 6/6] Ctrl+C on Linux puts the SVG under image/svg+xml as well as text On Linux the toolkit writes the clipboard as text only, so drawing programs got the SVG a copy puts there for them as text, or not at all. `sys::clipboard_svg` now owns the X11 CLIPBOARD selection from a thread of its own, made at the first copy: an input-only window that answers TARGETS and serves the markup as UTF8_STRING, text/plain;charset=utf-8 and image/svg+xml. Under Wayland, XWayland hands the selection on to Wayland programs with the same targets. When another program takes the clipboard the copy is dropped. With no X server, or if taking the selection fails, the toolkit writes the text as before. `formats` lists what one copy writes on each platform; the Windows and X11 writers and the test record all use it. x11rb 0.13 is already in the tree through the toolkit's clipboard; it is now a Linux dependency of the app as well. Refs #2018 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + Cargo.toml | 2 + src/sys/clipboard_svg.rs | 316 ++++++++++++++++++++++++++++++++++----- 3 files changed, 278 insertions(+), 41 deletions(-) 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/sys/clipboard_svg.rs b/src/sys/clipboard_svg.rs index e46491734b..9783e9be19 100644 --- a/src/sys/clipboard_svg.rs +++ b/src/sys/clipboard_svg.rs @@ -3,60 +3,83 @@ //! //! 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, which Windows has as a registered clipboard format. +//! MIME type: a registered clipboard format on Windows, a selection target +//! on X11 (which XWayland hands on to Wayland programs). -/// The registered clipboard format SVG is read from. +/// The clipboard format, or selection target, SVG is read from. pub const SVG_FORMAT: &str = "image/svg+xml"; -/// Put `svg` on the system clipboard as SVG and as text, in one write. -/// `false` when this platform has no such write here; the caller then puts -/// the text there through the GUI toolkit. +/// 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(svg); - cfg!(target_os = "windows") + test_record::record(formats); + true } #[cfg(all(not(test), target_os = "windows"))] { - windows::write(svg) + windows::write(&formats) + } + #[cfg(all(not(test), target_os = "linux"))] + { + x11::write(formats) } - #[cfg(all(not(test), not(target_os = "windows")))] + #[cfg(all(not(test), not(any(target_os = "windows", target_os = "linux"))))] { - let _ = svg; + let _ = formats; false } } -/// Tests leave the system clipboard alone: on Windows each write is kept -/// here, per thread, as the formats it would have put there. +/// 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()) }; + static WRITES: RefCell> = const { RefCell::new(Vec::new()) }; } - pub(super) fn record(svg: &str) { - if !cfg!(target_os = "windows") { - return; - } - let text: Vec = svg - .encode_utf16() - .chain([0]) - .flat_map(u16::to_le_bytes) - .collect(); - WRITES.with(|writes| { - writes.borrow_mut().push(vec![ - ("CF_UNICODETEXT".to_owned(), text), - (super::SVG_FORMAT.to_owned(), svg.as_bytes().to_vec()), - ]) - }); + 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)>> { + pub fn take() -> Vec { WRITES.with(|writes| std::mem::take(&mut *writes.borrow_mut())) } } @@ -108,7 +131,17 @@ mod windows { true } - pub fn write(svg: &str) -> bool { + /// 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 { @@ -122,18 +155,11 @@ mod windows { if !open { return false; } - let text: Vec = svg - .encode_utf16() - .chain([0]) - .flat_map(u16::to_le_bytes) - .collect(); - let name: Vec = super::SVG_FORMAT.encode_utf16().chain([0]).collect(); // SAFETY: the clipboard is open; it is closed before returning. - let written = unsafe { - EmptyClipboard() != 0 - && set(u32::from(CF_UNICODETEXT), &text) - && set(RegisterClipboardFormatW(name.as_ptr()), svg.as_bytes()) - }; + let written = unsafe { EmptyClipboard() != 0 } + && formats + .iter() + .all(|(name, bytes)| set(format_id(name), bytes)); // SAFETY: this function opened the clipboard. unsafe { CloseClipboard(); @@ -141,3 +167,211 @@ mod windows { 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 + } +}