Skip to main content

day_part_clipboard/
content.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! One clipboard item with alternate MIME representations, including arbitrary bytes.
5use std::{future::Future, pin::Pin, sync::Arc};
6
7/// One MIME representation. Bytes are encoded content, never a native image handle.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct Representation {
10    pub mime: String,
11    pub bytes: Arc<Vec<u8>>,
12}
13impl Representation {
14    pub fn new(mime: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
15        Self {
16            mime: mime.into(),
17            bytes: Arc::new(bytes.into()),
18        }
19    }
20}
21/// Alternative representations of ONE logical item, ordered by preference.
22#[derive(Clone, Debug, Default, PartialEq, Eq)]
23pub struct Content(pub Vec<Representation>);
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Error {
26    Unsupported,
27    Unavailable,
28    InvalidData,
29    TooLarge,
30}
31impl std::fmt::Display for Error {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        write!(f, "clipboard: {self:?}")
34    }
35}
36impl std::error::Error for Error {}
37pub type ClipboardFuture<T> = Pin<Box<dyn Future<Output = Result<T, Error>>>>;
38/// Resource limit applied before allocating clipboard content from another application.
39pub const MAX_BYTES: usize = 64 * 1024 * 1024;
40
41impl Content {
42    /// Check the content against the limits every platform arm enforces before a write.
43    ///
44    /// # Errors
45    ///
46    /// [`Error::InvalidData`] when there are no representations, more than 32, a malformed MIME
47    /// type, or the same type twice. [`Error::TooLarge`] when the bytes total more than
48    /// [`MAX_BYTES`].
49    pub fn validate(&self) -> Result<(), Error> {
50        if self.0.is_empty() || self.0.len() > 32 {
51            return Err(Error::InvalidData);
52        }
53        let mut total = 0usize;
54        let mut types = std::collections::HashSet::new();
55        for r in &self.0 {
56            if !valid_mime(&r.mime) || !types.insert(&r.mime) {
57                return Err(Error::InvalidData);
58            }
59            total = total.checked_add(r.bytes.len()).ok_or(Error::TooLarge)?;
60            if total > MAX_BYTES {
61                return Err(Error::TooLarge);
62            }
63        }
64        Ok(())
65    }
66}
67pub(crate) fn valid_mime(m: &str) -> bool {
68    m.len() <= 255
69        && m.split_once('/')
70            .is_some_and(|(a, b)| !a.is_empty() && !b.is_empty() && !b.contains('/'))
71        && m.bytes()
72            .all(|c| c.is_ascii_alphanumeric() || b"/!#$&^_.+-".contains(&c))
73}
74/// Read the first available type in caller preference order. Empty and denied are distinct.
75/// Start this call from a user action; browsers capture the live paste event immediately.
76pub fn read(preferred: &[&str]) -> ClipboardFuture<Option<Representation>> {
77    if preferred.is_empty() || preferred.iter().any(|m| !valid_mime(m)) {
78        return Box::pin(std::future::ready(Err(Error::InvalidData)));
79    }
80    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
81    {
82        super::web_content::read(preferred)
83    }
84    #[cfg(target_os = "ios")]
85    {
86        // UIPasteboard may wait for an external provider or paste authorization. Returning
87        // a ready future after a synchronous read still blocks the caller's UI thread.
88        let preferred: Vec<String> = preferred.iter().map(|m| (*m).to_owned()).collect();
89        let read = day_async::spawn_blocking(move || {
90            objc2::rc::autoreleasepool(|_| {
91                let preferred: Vec<&str> = preferred.iter().map(String::as_str).collect();
92                super::imp::read_content(&preferred)
93            })
94        });
95        Box::pin(async move { read.await.map_err(|_| Error::Unavailable)? })
96    }
97    #[cfg(not(any(target_os = "ios", all(target_family = "wasm", target_os = "unknown"))))]
98    {
99        Box::pin(std::future::ready(super::imp::read_content(preferred)))
100    }
101}
102/// Replace the clipboard with alternate representations. Returns the types actually written;
103/// platforms with restricted formats may accept a subset. Cut only after this succeeds.
104/// No previous-copy fallback is used: an empty/denied clipboard never resurrects stale data.
105#[allow(
106    clippy::needless_pass_by_value,
107    reason = "public signature; only some platform arms consume the content, so the finding differs per target"
108)]
109pub fn write(content: Content) -> ClipboardFuture<Vec<String>> {
110    if let Err(e) = content.validate() {
111        return Box::pin(std::future::ready(Err(e)));
112    }
113    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
114    {
115        super::web_content::write(content)
116    }
117    #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
118    {
119        Box::pin(std::future::ready(super::imp::write_content(&content)))
120    }
121}
122
123// Internal bridge wire format: count, then (MIME length, byte length, MIME, bytes), LE u32.
124// It is transport only, never a replacement for standard system clipboard representations.
125#[allow(dead_code)]
126pub(crate) fn pack(content: &Content) -> Vec<u8> {
127    let mut out = (content.0.len() as u32).to_le_bytes().to_vec();
128    for r in &content.0 {
129        out.extend_from_slice(&(r.mime.len() as u32).to_le_bytes());
130        out.extend_from_slice(&(r.bytes.len() as u32).to_le_bytes());
131        out.extend_from_slice(r.mime.as_bytes());
132        out.extend_from_slice(&r.bytes);
133    }
134    out
135}
136#[allow(dead_code)]
137pub(crate) fn unpack(mut data: &[u8]) -> Result<Content, Error> {
138    fn take<'a>(data: &mut &'a [u8], n: usize) -> Result<&'a [u8], Error> {
139        if n > data.len() {
140            return Err(Error::InvalidData);
141        }
142        let (head, tail) = data.split_at(n);
143        *data = tail;
144        Ok(head)
145    }
146    fn number(data: &mut &[u8]) -> Result<usize, Error> {
147        Ok(u32::from_le_bytes(take(data, 4)?.try_into().unwrap()) as usize)
148    }
149    if data.len() > MAX_BYTES + 32 * 263 + 4 {
150        return Err(Error::TooLarge);
151    }
152    let count = number(&mut data)?;
153    if count > 32 {
154        return Err(Error::InvalidData);
155    }
156    let mut out = Vec::new();
157    for _ in 0..count {
158        let m = number(&mut data)?;
159        let n = number(&mut data)?;
160        let mime = std::str::from_utf8(take(&mut data, m)?)
161            .map_err(|_| Error::InvalidData)?
162            .to_string();
163        let bytes = take(&mut data, n)?.to_vec();
164        out.push(Representation::new(mime, bytes));
165    }
166    if !data.is_empty() {
167        return Err(Error::InvalidData);
168    }
169    let content = Content(out);
170    if !content.0.is_empty() {
171        content.validate()?;
172    }
173    Ok(content)
174}
175
176/// Convert Windows' packed DIB clipboard representation into an encoded BMP file.
177#[cfg(any(windows, test))]
178pub(crate) fn dib_to_bmp(dib: &[u8]) -> Result<Vec<u8>, Error> {
179    if dib.len() < 12 || dib.len() > MAX_BYTES - 14 {
180        return Err(Error::InvalidData);
181    }
182    let u32_at = |at: usize| -> Result<u32, Error> {
183        Ok(u32::from_le_bytes(
184            dib.get(at..at + 4)
185                .ok_or(Error::InvalidData)?
186                .try_into()
187                .unwrap(),
188        ))
189    };
190    let header = u32_at(0)? as usize;
191    let (palette, masks) = if header == 12 {
192        let bits = u16::from_le_bytes([dib[10], dib[11]]);
193        (if bits <= 8 { (1usize << bits) * 3 } else { 0 }, 0)
194    } else if header >= 40 && header <= dib.len() {
195        let bits = u16::from_le_bytes([dib[14], dib[15]]);
196        let colors = u32_at(32)? as usize;
197        let entries = if colors != 0 {
198            colors
199        } else if bits <= 8 {
200            1usize << bits
201        } else {
202            0
203        };
204        let masks = if header == 40 {
205            match u32_at(16)? {
206                3 => 12,
207                6 => 16,
208                _ => 0,
209            }
210        } else {
211            0
212        };
213        (entries.checked_mul(4).ok_or(Error::InvalidData)?, masks)
214    } else {
215        return Err(Error::InvalidData);
216    };
217    let offset = header
218        .checked_add(palette)
219        .and_then(|n| n.checked_add(masks))
220        .ok_or(Error::InvalidData)?;
221    if offset > dib.len() {
222        return Err(Error::InvalidData);
223    }
224    let mut bmp = Vec::with_capacity(dib.len() + 14);
225    bmp.extend_from_slice(b"BM");
226    bmp.extend_from_slice(&((dib.len() + 14) as u32).to_le_bytes());
227    bmp.extend_from_slice(&[0; 4]);
228    bmp.extend_from_slice(&((offset + 14) as u32).to_le_bytes());
229    bmp.extend_from_slice(dib);
230    Ok(bmp)
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236    #[test]
237    fn dib_clipboard_pixels_get_a_bmp_file_header() {
238        let mut dib = vec![0u8; 44];
239        dib[..4].copy_from_slice(&40u32.to_le_bytes());
240        dib[4..8].copy_from_slice(&1u32.to_le_bytes());
241        dib[8..12].copy_from_slice(&1u32.to_le_bytes());
242        dib[12..14].copy_from_slice(&1u16.to_le_bytes());
243        dib[14..16].copy_from_slice(&24u16.to_le_bytes());
244        dib[40..44].copy_from_slice(&[1, 2, 3, 0]);
245        let bmp = dib_to_bmp(&dib).unwrap();
246        assert_eq!(&bmp[..2], b"BM");
247        assert_eq!(&bmp[10..14], &54u32.to_le_bytes());
248        assert_eq!(&bmp[54..], &[1, 2, 3, 0]);
249        assert!(dib_to_bmp(&dib[..20]).is_err());
250        dib[32..36].copy_from_slice(&u32::MAX.to_le_bytes());
251        assert!(dib_to_bmp(&dib).is_err());
252    }
253    #[test]
254    fn binary_content_is_lossless_and_validated() {
255        let c = Content(vec![Representation::new(
256            "application/x-day-test",
257            vec![0, 255, 0, 128],
258        )]);
259        assert_eq!(c.validate(), Ok(()));
260        assert_eq!(&**c.0[0].bytes, &[0, 255, 0, 128]);
261        assert_eq!(
262            Content(vec![c.0[0].clone(), c.0[0].clone()]).validate(),
263            Err(Error::InvalidData)
264        );
265        assert!(!valid_mime("image/png\0"));
266        assert!(!valid_mime("image/png/extra"));
267        assert!(!valid_mime("text/plain; charset=utf-8"));
268        let shared = Arc::new(vec![0; MAX_BYTES / 32 + 1]);
269        let oversized = Content(
270            (0..32)
271                .map(|i| Representation {
272                    mime: format!("application/x-limit-{i}"),
273                    bytes: shared.clone(),
274                })
275                .collect(),
276        );
277        assert_eq!(oversized.validate(), Err(Error::TooLarge));
278        let packet = pack(&c);
279        assert_eq!(unpack(&packet), Ok(c));
280        for end in 0..packet.len() {
281            assert!(unpack(&packet[..end]).is_err());
282        }
283        assert!(unpack(&[255, 255, 255, 255]).is_err());
284    }
285}