diff --git a/crates/platform/src/clipboard/offer/macos.rs b/crates/platform/src/clipboard/offer/macos.rs index 8b2add51d..7faa00a61 100644 --- a/crates/platform/src/clipboard/offer/macos.rs +++ b/crates/platform/src/clipboard/offer/macos.rs @@ -1 +1,118 @@ //! The offer on macOS. +//! +//! arboard writes first (it clears the pasteboard); the types it doesn't hold are added to the +//! item it wrote. The pasteboard's change count after the write tells a later call whether the +//! copy is still ours, so no marker is written. + +use objc2_app_kit::NSPasteboard; +use objc2_foundation::{NSData, NSString}; + +use super::{Plan, Primary, arboard_write}; +use crate::clipboard::types::{ClipboardError, HTML, MATHML, PNG, RTF, TEXT, URI_LIST}; + +/// RTF's pasteboard type (`NSPasteboardTypeRTF`, whose extern static needs `unsafe` to read, +/// which this crate forbids). The other standard types are named the same way. +const RTF_TYPE: &str = "public.rtf"; +/// The MathML types (W3C MathML 3 §6.2.4): presentation markup, and the generic type for +/// readers that only know that one. +const MATHML_TYPES: [&str; 2] = ["public.mathml.presentation", "public.mathml"]; +/// Most types looked at. +const MAX_TYPES: usize = 128; + +/// The pasteboard's change count recorded after this process's last write. +pub(super) struct State { + change: Option, +} + +impl State { + pub(super) fn new() -> Self { + Self { change: None } + } + + /// Nothing this process wrote is on offer any more. + pub(super) fn forget(&mut self) { + self.change = None; + } +} + +pub(super) fn write(handle: &mut arboard::Clipboard, state: &mut State, plan: &Plan<'_>, _owner: &[u8]) -> Result { + let (index, primary) = arboard_write(handle, plan)?; + let board = NSPasteboard::generalPasteboard(); + // A type that can't be added is logged: what arboard wrote still carries the copy. + let data = |name: &str, bytes: &[u8]| { + if !board.setData_forType(Some(&NSData::with_bytes(bytes)), &NSString::from_str(name)) { + log::warn!("clipboard: couldn't add {name}"); + } + }; + let string = |name: &str, text: &str| { + if !board.setString_forType(&NSString::from_str(text), &NSString::from_str(name)) { + log::warn!("clipboard: couldn't add {name}"); + } + }; + match primary { + Primary::Rich => { + if let Some(rtf) = &plan.rtf { + data(RTF_TYPE, rtf.text.as_bytes()); + } + if let Some(mathml) = &plan.mathml { + for name in MATHML_TYPES { + string(name, &mathml.text); + } + } + } + Primary::Picture => { + if let Some(png) = plan.picture.as_ref().and_then(|picture| picture.png) { + data("public.png", png); + } + if let Some(html) = &plan.html { + string("public.html", &html.text); + } + } + } + state.change = Some(board.changeCount()); + Ok(index) +} + +pub(super) fn rtf(_state: &mut State, limit: u64) -> Result>, ClipboardError> { + let Some(data) = NSPasteboard::generalPasteboard().dataForType(&NSString::from_str(RTF_TYPE)) else { return Ok(None) }; + if data.len() as u64 > limit { + return Err(ClipboardError::TooLarge { limit }); + } + Ok(Some(data.to_vec())) +} + +/// The MIME type a pasteboard type is read as, for [`formats`]; `None` for types nothing reads. +fn mime(name: &str) -> Option<&'static str> { + match name { + "public.utf8-plain-text" => Some(TEXT), + "public.html" => Some(HTML), + "public.png" | "public.tiff" => Some(PNG), + "public.file-url" => Some(URI_LIST), + RTF_TYPE => Some(RTF), + name if MATHML_TYPES.contains(&name) => Some(MATHML), + _ => None, + } +} + +/// The pasteboard's types, and the MIME type of each a read takes. `types` lists the formats on +/// offer; no item's data is fetched. +pub(super) fn formats(_state: &mut State) -> Vec { + let Some(types) = NSPasteboard::generalPasteboard().types() else { return Vec::new() }; + let mut names = Vec::new(); + for offered in types.iter().take(MAX_TYPES) { + let name = offered.to_string(); + let mime = mime(&name); + names.push(name); + if let Some(mime) = mime + && !names.iter().any(|offered| offered == mime) + { + names.push(mime.to_owned()); + } + } + names +} + +pub(super) fn owns(state: &mut State, _owner: &[u8]) -> Option { + let Some(recorded) = state.change else { return Some(false) }; + Some(NSPasteboard::generalPasteboard().changeCount() == recorded) +} diff --git a/crates/platform/src/clipboard/offer/mod.rs b/crates/platform/src/clipboard/offer/mod.rs index 96b167fd0..4eaca682c 100644 --- a/crates/platform/src/clipboard/offer/mod.rs +++ b/crates/platform/src/clipboard/offer/mod.rs @@ -1,29 +1,132 @@ //! What the system clipboard offers and how it is written, per platform. +//! +//! arboard writes the bitmap, or the HTML with its text, or the text, on every desktop platform. +//! What it can't hold goes beside it where the platform lets a second writer add formats: on +//! Windows and macOS RTF, MathML and (beside a bitmap) PNG and HTML, after arboard's write; on +//! Wayland everything in one offer. On X11 arboard owns the selection and serves only its own +//! targets, so a copy there carries text and HTML, or the bitmap, alone. Reading another +//! program's RTF works on all four. #[cfg(target_os = "macos")] mod macos; +#[cfg(test)] +mod tests; #[cfg(all(unix, not(target_os = "macos")))] mod unix; #[cfg(windows)] mod windows; -use super::backend::Decode; -use super::types::{ClipboardError, Flavor}; +#[cfg(target_os = "macos")] +use self::macos as platform; +#[cfg(all(unix, not(target_os = "macos")))] +use self::unix as platform; +#[cfg(windows)] +use self::windows as platform; + +use std::borrow::Cow; + +use super::backend::{Decode, system_error}; +use super::convert::rgba8_image; +use super::types::{ClipboardError, ClipboardImage, Flavor, HTML, MATHML, PNG, RGBA8, RTF, TEXT}; /// The platform's offer state: the cached X11 `TARGETS` connection and the macOS change count recorded at a write. pub(super) struct Offer { - _state: (), + state: platform::State, } impl Offer { /// An offer with nothing cached. pub(super) fn new() -> Self { - Self { _state: () } + Self { state: platform::State::new() } + } +} + +/// One text-like flavour a write offers, with its index in the caller's flavours. +struct Part<'a> { + index: usize, + text: Cow<'a, str>, +} + +/// The bitmap a write offers: its pixels for arboard and, when the caller gave one, its PNG +/// bytes for the platforms that take an encoded picture beside them. +struct Picture<'a> { + index: usize, + pixels: ClipboardImage, + png: Option<&'a [u8]>, +} + +/// What a write puts on the clipboard: the first flavour of each kind among the caller's. +struct Plan<'a> { + text: Option>, + html: Option>, + rtf: Option>, + mathml: Option>, + picture: Option>, +} + +/// Which of a plan's two shapes a write takes: arboard holds a bitmap or rich text, not both. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Primary { + Picture, + Rich, +} + +impl<'a> Plan<'a> { + fn new(flavors: &'a [Flavor], decode: Option<&Decode>) -> Self { + let part = |mime: &str| { + flavors.iter().enumerate().find(|(_, flavor)| flavor.mime == mime).map(|(index, flavor)| Part { index, text: String::from_utf8_lossy(&flavor.data) }) + }; + let png = flavors.iter().find(|flavor| flavor.mime == PNG).map(|flavor| flavor.data.as_slice()); + let picture = flavors.iter().enumerate().find_map(|(index, flavor)| { + let pixels = match &*flavor.mime { + RGBA8 => rgba8_image(&flavor.data), + PNG => decode.and_then(|decode| decode(&flavor.data)), + _ => None, + }?; + pixels.is_whole().then_some(Picture { index, pixels, png }) + }); + Self { text: part(TEXT), html: part(HTML), rtf: part(RTF), mathml: part(MATHML), picture } + } + + /// The shape of the write: whichever of the bitmap and the HTML or text the caller put first. + fn primary(&self) -> Option { + let rich = [&self.html, &self.text].into_iter().flatten().map(|part| part.index).min(); + match (self.picture.as_ref().map(|picture| picture.index), rich) { + (Some(picture), Some(rich)) if rich < picture => Some(Primary::Rich), + (Some(_), _) => Some(Primary::Picture), + (None, Some(_)) => Some(Primary::Rich), + (None, None) => None, + } + } +} + +/// arboard's part of a write: the bitmap, else the HTML with its text, else the text. Answers +/// the index of the flavour it wrote and the shape it took. +fn arboard_write(handle: &mut arboard::Clipboard, plan: &Plan<'_>) -> Result<(usize, Primary), ClipboardError> { + match plan.primary().ok_or(ClipboardError::NoFormat)? { + Primary::Picture => { + let picture = plan.picture.as_ref().ok_or(ClipboardError::NoFormat)?; + let pixels = &picture.pixels; + handle + .set_image(arboard::ImageData { width: pixels.width as usize, height: pixels.height as usize, bytes: Cow::Borrowed(&pixels.rgba) }) + .map_err(system_error)?; + Ok((picture.index, Primary::Picture)) + } + Primary::Rich => match (&plan.html, &plan.text) { + (Some(html), alt) => { + handle.set_html(html.text.clone(), alt.as_ref().map(|text| text.text.clone())).map_err(system_error)?; + Ok((html.index, Primary::Rich)) + } + (None, Some(text)) => { + handle.set_text(text.text.clone()).map_err(system_error)?; + Ok((text.index, Primary::Rich)) + } + (None, None) => Err(ClipboardError::NoFormat), + }, } } /// Every flavour the platform can hold in one offer, tagged with `owner`; the index of the first one written. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 pub(super) fn write( handle: &mut arboard::Clipboard, offer: &mut Offer, @@ -31,34 +134,78 @@ pub(super) fn write( decode: Option<&Decode>, owner: &[u8], ) -> Result { - let _ = (handle, offer, flavors, decode, owner); - todo!("pf.C-P7") + if flavors.is_empty() { + offer.state.forget(); + handle.clear().map_err(system_error)?; + return Ok(0); + } + platform::write(handle, &mut offer.state, &Plan::new(flavors, decode), owner) } /// The clipboard's RTF text, at most `limit` bytes of it. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 pub(super) fn read_rtf(offer: &mut Offer, limit: u64) -> Result, ClipboardError> { - let _ = (offer, limit); - todo!("pf.C-P7") + let Some(bytes) = platform::rtf(&mut offer.state, limit)? else { return Ok(None) }; + // RTF is 7-bit by the spec; stray 8-bit bytes become replacement characters. Windows + // programs NUL-terminate it. + let text = String::from_utf8_lossy(&bytes); + let text = text.trim_end_matches('\0'); + Ok(text.trim_start().starts_with("{\\rtf").then(|| text.to_owned())) } /// The MIME names of the formats on offer. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 pub(super) fn formats(offer: &mut Offer) -> Vec { - let _ = offer; - todo!("pf.C-P7") + platform::formats(&mut offer.state) } /// Whether the offer holds one of `mimes`. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 pub(super) fn has(offer: &mut Offer, mimes: &[&str]) -> bool { - let _ = (offer, mimes); - todo!("pf.C-P7") + let offered = formats(offer); + #[cfg(all(unix, not(target_os = "macos")))] + let holds = unix::offered_has; + #[cfg(any(windows, target_os = "macos"))] + let holds = named_has; + mimes.iter().any(|&mime| holds(&offered, mime)) } /// Whether this process owns the clipboard, by the `owner` marker; `None` when the platform cannot tell. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 pub(super) fn owns(offer: &mut Offer, owner: &[u8]) -> Option { - let _ = (offer, owner); - todo!("pf.C-P7") + platform::owns(&mut offer.state, owner) +} + +/// Whether `offered`, as Windows and macOS `formats` name the standard formats (by the MIME +/// type each is read as), holds `mime`. Any bitmap is listed as `image/png`. +#[cfg(any(windows, target_os = "macos"))] +fn named_has(offered: &[String], mime: &str) -> bool { + use super::types::BITMAP; + let mime = match mime { + BITMAP | RGBA8 => PNG, + mime => mime, + }; + offered.iter().any(|name| name == mime) +} + +/// `fragment` wrapped as a CF_HTML clipboard payload. +/// +/// Offsets are zero-padded byte offsets from the start of the payload; `EndHTML` excludes the +/// trailing NUL. +#[cfg(any(windows, test))] +fn wrap_cf_html(fragment: &str) -> Vec { + let version = "Version:0.9"; + let start_html = "\r\nStartHTML:"; + let end_html = "\r\nEndHTML:"; + let start_fragment = "\r\nStartFragment:"; + let end_fragment = "\r\nEndFragment:"; + let before = "\r\n\r\n\r\n\r\n"; + let after = "\r\n\r\n\r\n\0"; + // Each offset is written as ten digits. + let header = version.len() + start_html.len() + 10 + end_html.len() + 10 + start_fragment.len() + 10 + end_fragment.len() + 10; + // `before` opens with a line break, so the document starts two bytes after the header. + let html_at = header + 2; + let fragment_at = header + before.len(); + let fragment_end = fragment_at + fragment.len(); + let html_end = fragment_end + after.len() - 1; + format!( + "{version}{start_html}{html_at:010}{end_html}{html_end:010}{start_fragment}{fragment_at:010}{end_fragment}{fragment_end:010}{before}{fragment}{after}" + ) + .into_bytes() } diff --git a/crates/platform/src/clipboard/offer/tests.rs b/crates/platform/src/clipboard/offer/tests.rs new file mode 100644 index 000000000..cd667d8f6 --- /dev/null +++ b/crates/platform/src/clipboard/offer/tests.rs @@ -0,0 +1,28 @@ +//! The offer's format boundary: the CF_HTML header. + +use super::wrap_cf_html; + +fn field(data: &[u8], name: &str) -> usize { + let at = data.windows(name.len()).position(|window| window == name.as_bytes()).expect("field") + name.len(); + std::str::from_utf8(&data[at..at + 10]).expect("offset digits").parse().expect("offset") +} + +#[test] +fn cf_html_offsets_delimit_the_fragment_bytes() { + let fragment = "

Olá, 世界 — café

"; + let data = wrap_cf_html(fragment); + + let start_html = field(&data, "StartHTML:"); + let end_html = field(&data, "EndHTML:"); + let start_fragment = field(&data, "StartFragment:"); + let end_fragment = field(&data, "EndFragment:"); + + assert!(start_html < start_fragment, "HTML starts before its fragment"); + assert!(start_fragment < end_fragment, "fragment has a positive length"); + assert!(end_fragment < end_html, "fragment ends inside the document"); + assert_eq!(&data[start_html..start_html + "".len()], b""); + assert_eq!(&data[start_fragment..end_fragment], fragment.as_bytes()); + assert_eq!(end_fragment - start_fragment, fragment.len(), "offsets count UTF-8 bytes"); + assert_eq!(&data[end_html..], b"\0", "EndHTML excludes the trailing NUL"); + assert_eq!(end_html, data.len() - 1); +} diff --git a/crates/platform/src/clipboard/offer/unix.rs b/crates/platform/src/clipboard/offer/unix.rs index 9d3349157..6965f8d68 100644 --- a/crates/platform/src/clipboard/offer/unix.rs +++ b/crates/platform/src/clipboard/offer/unix.rs @@ -1,22 +1,365 @@ //! The offer on Linux and the BSDs. +//! +//! Wayland when `WAYLAND_DISPLAY` is set and the compositor has a data-control protocol, else +//! X11: the order arboard picks its own backend in. On Wayland a write is one offer from +//! `wl_clipboard_rs::copy` with the owner marker in it; on X11 arboard owns the selection, and +//! ownership is the selection owner being the window arboard set. + +use std::io::Read; + +use wl_clipboard_rs::copy::{self, MimeSource, Options, Source}; +use wl_clipboard_rs::paste::{self, ClipboardType, Seat, get_contents, get_mime_types_ordered}; + +use super::{Plan, Primary, arboard_write}; +use crate::clipboard::types::{BITMAP, ClipboardError, HTML, MATHML, PNG, RGBA8, RTF, TEXT, URI_LIST}; + +/// The Wayland text type the copy's text goes under; wl-clipboard-rs serves the plain-text +/// aliases from the first text type offered. +const UTF8_TEXT: &str = "text/plain;charset=utf-8"; +/// The MIME type of the owner marker in a Wayland offer. +const OWNER_MIME: &str = "application/x-craft-clipboard-owner"; +/// RTF types a clipboard may offer, best first. +const RTF_MIMES: [&str; 3] = ["text/rtf", "application/rtf", "text/richtext"]; +/// Most formats looked at, so a hostile owner's list can't make the app allocate without end. +const MAX_TYPES: usize = 128; + +/// How this process's last write can be recognised later. +#[derive(Clone, Copy)] +enum Mark { + /// Nothing this process wrote is on offer. + Nothing, + /// A write that carries no marker and recorded no selection owner, so ownership can't be told. + Unmarked, + /// An X11 write; the window that owned the selection after it. + X11(u32), +} + +/// The cached X11 connection for `TARGETS` and the selection owner, and how the last write +/// can be recognised. +pub(super) struct State { + x11: Option, + mark: Mark, +} + +impl State { + pub(super) fn new() -> Self { + Self { x11: None, mark: Mark::Nothing } + } + + /// Nothing this process wrote is on offer any more. + pub(super) fn forget(&mut self) { + self.mark = Mark::Nothing; + } + + fn targets(&mut self) -> Option<&x11::Targets> { + if self.x11.is_none() { + self.x11 = x11::Targets::connect(); + } + self.x11.as_ref() + } +} /// Whether the target or MIME names in `offered` contain a format that can be read as `mime`. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 +/// Text includes the X11 text targets; a bitmap is `image/png`, the only bitmap arboard reads +/// on Linux. pub(super) fn offered_has(offered: &[String], mime: &str) -> bool { - let _ = (offered, mime); - todo!("pf.C-P7") + let any = |names: &[&str]| offered.iter().any(|offer| names.iter().any(|name| offer.eq_ignore_ascii_case(name))); + match mime { + TEXT => any(&["text/plain", UTF8_TEXT, "UTF8_STRING", "STRING", "TEXT"]), + HTML => any(&[HTML]), + RTF => rtf_target(offered).is_some(), + MATHML => any(&[MATHML]), + BITMAP | RGBA8 => any(&[PNG]), + URI_LIST => any(&[URI_LIST]), + _ => false, + } } /// The target that carries RTF among `offered`. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 pub(super) fn rtf_target(offered: &[String]) -> Option<&'static str> { - let _ = offered; - todo!("pf.C-P7") + RTF_MIMES.into_iter().find(|mime| offered.iter().any(|offer| offer == mime)) } /// Whether a read of `len` bytes with `remaining` left under `cap` is complete. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 pub(super) fn complete(len: usize, remaining: usize, cap: usize) -> bool { - let _ = (len, remaining, cap); - todo!("pf.C-P7") + remaining == 0 && len <= cap +} + +/// The Wayland offer's MIME types, best first; `None` outside Wayland or without a data-control +/// protocol, where X11 answers. +fn wayland_types() -> Option> { + std::env::var_os("WAYLAND_DISPLAY")?; + match get_mime_types_ordered(ClipboardType::Regular, Seat::Unspecified) { + Ok(mut types) => { + types.truncate(MAX_TYPES); + Some(types) + } + // Nothing is copied. + Err(paste::Error::NoSeats | paste::Error::ClipboardEmpty | paste::Error::NoMimeType) => Some(Vec::new()), + Err(error) => { + log::debug!("no Wayland data control for the clipboard, using X11: {error}"); + None + } + } +} + +/// One Wayland MIME type's bytes, at most `limit` of them. +fn wayland_read(mime: &str, limit: u64) -> Result>, ClipboardError> { + let (pipe, _) = match get_contents(ClipboardType::Regular, Seat::Unspecified, paste::MimeType::Specific(mime)) { + Ok(contents) => contents, + Err(paste::Error::NoSeats | paste::Error::ClipboardEmpty | paste::Error::NoMimeType) => return Ok(None), + Err(error) => return Err(ClipboardError::Other(error.to_string())), + }; + let mut out = Vec::new(); + pipe.take(limit.saturating_add(1)).read_to_end(&mut out).map_err(|error| ClipboardError::Other(error.to_string()))?; + if out.len() as u64 > limit { + return Err(ClipboardError::TooLarge { limit }); + } + Ok(Some(out)) +} + +/// The plan as one Wayland offer with the owner marker; `None` when the plan needs arboard (a +/// bitmap given as pixels only: this crate has no PNG encoder, arboard has) or offers nothing. +fn wayland_write(plan: &Plan<'_>, owner: &[u8]) -> Result, ClipboardError> { + let text = |part: &Option>, mime: &'static str| part.as_ref().map(|part| (part.index, mime, part.text.as_bytes().to_vec())); + let parts: Vec<(usize, &str, Vec)> = match plan.primary() { + Some(Primary::Picture) => { + let Some((index, png)) = plan.picture.as_ref().and_then(|picture| Some((picture.index, picture.png?))) else { return Ok(None) }; + [Some((index, PNG, png.to_vec())), text(&plan.html, HTML), text(&plan.text, UTF8_TEXT)].into_iter().flatten().collect() + } + // The text first: the plain-text aliases serve the first text type offered. + _ => [text(&plan.text, UTF8_TEXT), text(&plan.html, HTML), text(&plan.rtf, RTF), text(&plan.mathml, MATHML)].into_iter().flatten().collect(), + }; + let Some(first) = parts.iter().map(|&(index, _, _)| index).min() else { return Ok(None) }; + let source = |mime: &str, data: Vec| MimeSource { source: Source::Bytes(data.into()), mime_type: copy::MimeType::Specific(mime.into()) }; + let mut sources: Vec = parts.into_iter().map(|(_, mime, data)| source(mime, data)).collect(); + sources.push(source(OWNER_MIME, owner.to_vec())); + Options::new().copy_multi(sources).map_err(|error| ClipboardError::Other(error.to_string()))?; + Ok(Some(first)) +} + +pub(super) fn write(handle: &mut arboard::Clipboard, state: &mut State, plan: &Plan<'_>, owner: &[u8]) -> Result { + let wayland = wayland_types().is_some(); + if wayland && let Some(index) = wayland_write(plan, owner)? { + state.forget(); + return Ok(index); + } + let (index, _) = arboard_write(handle, plan)?; + // On Wayland arboard's offer carries no marker, and on X11 the owner may be unreadable: + // `owns` can't tell then, and the caller compares content. + let recorded = if wayland { None } else { state.targets().and_then(x11::Targets::owner) }; + state.mark = recorded.map_or(Mark::Unmarked, Mark::X11); + Ok(index) +} + +pub(super) fn rtf(state: &mut State, limit: u64) -> Result>, ClipboardError> { + if let Some(types) = wayland_types() { + return match rtf_target(&types) { + Some(mime) => wayland_read(mime, limit), + None => Ok(None), + }; + } + let offered = state.targets().map(x11::Targets::offered).unwrap_or_default(); + match rtf_target(&offered) { + Some(target) => x11::read(target, limit), + None => Ok(None), + } +} + +pub(super) fn formats(state: &mut State) -> Vec { + if let Some(types) = wayland_types() { + return types; + } + state.targets().map(x11::Targets::offered).unwrap_or_default() +} + +pub(super) fn owns(state: &mut State, owner: &[u8]) -> Option { + if let Some(types) = wayland_types() { + if matches!(state.mark, Mark::Unmarked) { + return None; + } + if !types.iter().any(|mime| mime == OWNER_MIME) { + return Some(false); + } + return match wayland_read(OWNER_MIME, owner.len() as u64) { + Ok(marker) => Some(marker.is_some_and(|marker| marker == owner)), + // A marker longer than ours is another process's. + Err(ClipboardError::TooLarge { .. }) => Some(false), + Err(_) => None, + }; + } + let recorded = match state.mark { + Mark::Nothing => return Some(false), + Mark::Unmarked => return None, + Mark::X11(recorded) => recorded, + }; + let current = state.targets()?.owner(); + Some(current == Some(recorded)) +} + +/// The X11 CLIPBOARD selection: its owner's `TARGETS` on a cached connection, and its content +/// read into a property of a hidden window, neither of which arboard offers. +mod x11 { + use std::time::{Duration, Instant}; + + use x11rb::connection::Connection; + use x11rb::protocol::Event; + use x11rb::protocol::xproto::{Atom, AtomEnum, ConnectionExt, CreateWindowAux, EventMask, GetPropertyReply, Window, WindowClass}; + use x11rb::rust_connection::RustConnection; + use x11rb::{COPY_DEPTH_FROM_PARENT, COPY_FROM_PARENT, CURRENT_TIME, NONE}; + + use crate::clipboard::types::ClipboardError; + + /// How long a `TARGETS` request waits for the owner. The probe's worker waits, not the UI. + const ANSWER_WAIT: Duration = Duration::from_millis(250); + /// How long a content read waits for the selection's owner, in all. + const READ_WAIT: Duration = Duration::from_secs(1); + /// Most targets looked at: a longer list is cut short, not refused. + const MAX_TARGETS: u32 = super::MAX_TYPES as u32; + + fn atom(conn: &RustConnection, name: &[u8]) -> Option { + conn.intern_atom(false, name).ok()?.reply().ok().map(|reply| reply.atom) + } + + /// A connection and a window that receive the clipboard owner's `TARGETS` answer. + pub(super) struct Targets { + conn: RustConnection, + window: Window, + clipboard: Atom, + targets: Atom, + property: Atom, + } + + impl Targets { + pub(super) fn connect() -> Option { + let (conn, screen) = RustConnection::connect(None).ok()?; + let root = conn.setup().roots.get(screen)?.root; + let window = conn.generate_id().ok()?; + conn.create_window( + COPY_DEPTH_FROM_PARENT, + window, + root, + 0, + 0, + 1, + 1, + 0, + WindowClass::INPUT_OUTPUT, + 0, + &CreateWindowAux::new().event_mask(EventMask::PROPERTY_CHANGE), + ) + .ok()?; + let (clipboard, targets, property) = (atom(&conn, b"CLIPBOARD")?, atom(&conn, b"TARGETS")?, atom(&conn, b"CRAFT_CLIPBOARD_TARGETS")?); + Some(Self { conn, window, clipboard, targets, property }) + } + + /// The target names the CLIPBOARD owner offers; none when nobody owns it or answers. + pub(super) fn offered(&self) -> Vec { + self.ask().unwrap_or_default() + } + + /// The window that owns the CLIPBOARD selection; `None` when nobody does. + pub(super) fn owner(&self) -> Option { + let reply = self.conn.get_selection_owner(self.clipboard).ok()?.reply().ok()?; + (reply.owner != NONE).then_some(reply.owner) + } + + fn ask(&self) -> Option> { + self.conn.delete_property(self.window, self.property).ok()?; + self.conn.convert_selection(self.window, self.clipboard, self.targets, self.property, CURRENT_TIME).ok()?; + self.conn.flush().ok()?; + let end = Instant::now() + ANSWER_WAIT; + while Instant::now() < end { + match self.conn.poll_for_event().ok()? { + Some(Event::SelectionNotify(event)) if event.requestor == self.window && event.selection == self.clipboard => { + if event.property == NONE { + return None; + } + let reply = self.conn.get_property(true, self.window, self.property, AtomEnum::ATOM, 0, MAX_TARGETS).ok()?.reply().ok()?; + // The name requests go out together; their answers are collected after. + let cookies: Vec<_> = + reply.value32()?.take(MAX_TARGETS as usize).filter_map(|atom| self.conn.get_atom_name(atom).ok()).collect(); + return Some( + cookies.into_iter().filter_map(|cookie| cookie.reply().ok()).filter_map(|name| String::from_utf8(name.name).ok()).collect(), + ); + } + Some(_) => {} + None => std::thread::sleep(Duration::from_millis(1)), + } + } + None + } + } + + /// A hidden window the selection's owner writes a conversion into. + struct Reader { + conn: RustConnection, + window: Window, + clipboard: Atom, + property: Atom, + deadline: Instant, + } + + impl Reader { + fn new() -> Option { + let (conn, screen) = RustConnection::connect(None).ok()?; + let root = conn.setup().roots.get(screen)?.root; + let window = conn.generate_id().ok()?; + conn.create_window(COPY_DEPTH_FROM_PARENT, window, root, 0, 0, 1, 1, 0, WindowClass::INPUT_ONLY, COPY_FROM_PARENT, &CreateWindowAux::new()) + .ok()?; + let (clipboard, property) = (atom(&conn, b"CLIPBOARD")?, atom(&conn, b"CRAFT_CLIPBOARD_PASTE")?); + Some(Self { conn, window, clipboard, property, deadline: Instant::now() + READ_WAIT }) + } + + /// The selection converted to `target`, read as at most one unit past `cap` bytes so a + /// larger value shows in its length or `bytes_after`; `None` when the owner refuses or + /// doesn't answer in time. + fn convert(&self, target: Atom, cap: usize) -> Option { + self.conn.convert_selection(self.window, self.clipboard, target, self.property, CURRENT_TIME).ok()?; + self.conn.flush().ok()?; + loop { + // Checked every time round, so a stream of other events can't keep us here. + if Instant::now() >= self.deadline { + return None; + } + match self.conn.poll_for_event().ok()? { + Some(Event::SelectionNotify(event)) if event.requestor == self.window => { + if event.property == NONE { + return None; + } + break; + } + Some(_) => {} + None => std::thread::sleep(Duration::from_millis(5)), + } + } + // In 32-bit units. + let units = u32::try_from(cap / 4 + 1).unwrap_or(u32::MAX); + self.conn.get_property(true, self.window, self.property, AtomEnum::ANY, 0, units).ok()?.reply().ok() + } + } + + impl Drop for Reader { + fn drop(&mut self) { + let _ = self.conn.destroy_window(self.window); + let _ = self.conn.flush(); + } + } + + /// The CLIPBOARD selection as `target`, at most `limit` bytes. Copies too large to send at + /// once arrive in pieces (INCR), which aren't read: nothing then. + pub(super) fn read(target: &str, limit: u64) -> Result>, ClipboardError> { + let cap = usize::try_from(limit).unwrap_or(usize::MAX); + let Some(reader) = Reader::new() else { return Ok(None) }; + let (Some(target), Some(incr)) = (atom(&reader.conn, target.as_bytes()), atom(&reader.conn, b"INCR")) else { return Ok(None) }; + let Some(reply) = reader.convert(target, cap) else { return Ok(None) }; + if reply.type_ == incr { + log::debug!("the clipboard owner sends its content in pieces (INCR), which isn't read"); + return Ok(None); + } + if !super::complete(reply.value.len(), usize::try_from(reply.bytes_after).unwrap_or(usize::MAX), cap) { + return Err(ClipboardError::TooLarge { limit }); + } + Ok(Some(reply.value)) + } } diff --git a/crates/platform/src/clipboard/offer/windows.rs b/crates/platform/src/clipboard/offer/windows.rs index fe4ab7529..643974906 100644 --- a/crates/platform/src/clipboard/offer/windows.rs +++ b/crates/platform/src/clipboard/offer/windows.rs @@ -1,8 +1,168 @@ //! The offer on Windows. +//! +//! arboard writes first and empties the clipboard; the formats it doesn't hold are added after +//! it without emptying, each with `clipboard-win`, and the owner marker last. -/// `fragment` wrapped as a CF_HTML clipboard payload. -#[allow(dead_code)] // P3(platform-w2): pf.C-P7 -pub(super) fn wrap_cf_html(fragment: &str) -> Vec { - let _ = fragment; - todo!("pf.C-P7") +use clipboard_win::{Clipboard, EnumFormats, formats as cf, raw}; + +use super::{Plan, Primary, arboard_write, wrap_cf_html}; +use crate::clipboard::types::{ClipboardError, HTML, MATHML, PNG, RTF, TEXT, URI_LIST}; + +/// The registered format the owner marker goes under. +const OWNER_FORMAT: &str = "Craft Clipboard Owner"; +/// RTF's registered format. +const RTF_FORMAT: &str = "Rich Text Format"; +/// HTML's registered format (CF_HTML). +const HTML_FORMAT: &str = "HTML Format"; +/// The encoded picture's registered format. +const PNG_FORMAT: &str = "PNG"; +/// The clipboard format names for MathML that Windows programs read (W3C MathML 3 §6.2.4; Office +/// reads and writes both). +const MATHML_FORMATS: [&str; 2] = ["MathML", "MathML Presentation"]; +/// Most formats looked at. +const MAX_FORMATS: usize = 64; + +/// The owner marker is on the clipboard itself; only a write that couldn't add it is recorded. +pub(super) struct State { + unmarked: bool, +} + +impl State { + pub(super) fn new() -> Self { + Self { unmarked: false } + } + + /// Emptying the clipboard removes the marker with everything else. + pub(super) fn forget(&mut self) { + self.unmarked = false; + } +} + +fn open() -> Result { + Clipboard::new_attempts(10).map_err(|_| ClipboardError::Busy) +} + +fn register(name: &str) -> Option { + raw::register_format(name).map(|format| format.get()) +} + +/// Adds `bytes` under the registered format `name` beside what is there. A format that can't be +/// added is logged: what arboard wrote still carries the copy. Whether it was added. +fn add(name: &str, bytes: &[u8]) -> bool { + let Some(format) = register(name) else { + log::warn!("clipboard: couldn't register {name}"); + return false; + }; + if let Err(error) = raw::set_without_clear(format, bytes) { + log::warn!("clipboard: {name}: {error}"); + return false; + } + true +} + +pub(super) fn write(handle: &mut arboard::Clipboard, state: &mut State, plan: &Plan<'_>, owner: &[u8]) -> Result { + let (index, primary) = arboard_write(handle, plan)?; + // Until the marker is on the clipboard, `owns` can't tell and the caller compares content. + state.unmarked = true; + let _open = match open() { + Ok(open) => open, + Err(error) => { + log::warn!("clipboard: couldn't open it to add formats beside arboard's: {error}"); + return Ok(index); + } + }; + match primary { + Primary::Rich => { + if let Some(rtf) = &plan.rtf { + // NUL-terminated, as is usual. + let bytes: Vec = rtf.text.as_bytes().iter().copied().chain(std::iter::once(0)).collect(); + add(RTF_FORMAT, &bytes); + } + if let Some(mathml) = &plan.mathml { + // UTF-16LE text with its terminating NUL, as Windows text formats have. + let bytes: Vec = mathml.text.encode_utf16().chain(std::iter::once(0)).flat_map(u16::to_le_bytes).collect(); + for name in MATHML_FORMATS { + add(name, &bytes); + } + } + } + Primary::Picture => { + if let Some(png) = plan.picture.as_ref().and_then(|picture| picture.png) { + add(PNG_FORMAT, png); + } + if let Some(html) = &plan.html { + add(HTML_FORMAT, &wrap_cf_html(&html.text)); + } + } + } + state.unmarked = !add(OWNER_FORMAT, owner); + Ok(index) +} + +pub(super) fn rtf(_state: &mut State, limit: u64) -> Result>, ClipboardError> { + let Some(format) = register(RTF_FORMAT) else { return Ok(None) }; + let _open = open()?; + if !raw::is_format_avail(format) { + return Ok(None); + } + // Checked before the copy, so a hostile owner's size never becomes an allocation. + let Some(size) = raw::size(format) else { return Ok(None) }; + if size.get() as u64 > limit { + return Err(ClipboardError::TooLarge { limit }); + } + let mut out = Vec::new(); + raw::get_vec(format, &mut out).map_err(|error| ClipboardError::Other(error.to_string()))?; + Ok(Some(out)) +} + +/// The MIME type a format is read as, for [`formats`]; `None` for formats nothing reads. +fn mime(format: u32, name: Option<&str>) -> Option<&'static str> { + match format { + cf::CF_UNICODETEXT => Some(TEXT), + cf::CF_HDROP => Some(URI_LIST), + cf::CF_DIB | cf::CF_DIBV5 => Some(PNG), + _ => match name? { + HTML_FORMAT => Some(HTML), + PNG_FORMAT => Some(PNG), + RTF_FORMAT => Some(RTF), + name if MATHML_FORMATS.contains(&name) => Some(MATHML), + _ => None, + }, + } +} + +/// The registered and standard names of the formats on offer, and the MIME type of each format +/// a read takes. No content is read. +pub(super) fn formats(_state: &mut State) -> Vec { + let Ok(_open) = open() else { return Vec::new() }; + let mut names = Vec::new(); + for format in EnumFormats::new().take(MAX_FORMATS) { + let name = raw::format_name_big(format); + let mime = mime(format, name.as_deref()); + names.extend(name); + if let Some(mime) = mime + && !names.iter().any(|offered| offered == mime) + { + names.push(mime.to_owned()); + } + } + names +} + +pub(super) fn owns(state: &mut State, owner: &[u8]) -> Option { + if state.unmarked { + return None; + } + let format = register(OWNER_FORMAT)?; + let _open = open().ok()?; + if !raw::is_format_avail(format) { + return Some(false); + } + // A marker longer than ours is another process's; it is never copied. + if raw::size(format).is_some_and(|size| size.get() > owner.len()) { + return Some(false); + } + let mut out = Vec::new(); + raw::get_vec(format, &mut out).ok()?; + Some(out == owner) }