day_part_clipboard/
content.rs1use std::{future::Future, pin::Pin, sync::Arc};
6
7#[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#[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>>>>;
38pub const MAX_BYTES: usize = 64 * 1024 * 1024;
40
41impl Content {
42 pub fn validate(&self) -> Result<(), Error> {
43 if self.0.is_empty() || self.0.len() > 32 {
44 return Err(Error::InvalidData);
45 }
46 let mut total = 0usize;
47 let mut types = std::collections::HashSet::new();
48 for r in &self.0 {
49 if !valid_mime(&r.mime) || !types.insert(&r.mime) {
50 return Err(Error::InvalidData);
51 }
52 total = total.checked_add(r.bytes.len()).ok_or(Error::TooLarge)?;
53 if total > MAX_BYTES {
54 return Err(Error::TooLarge);
55 }
56 }
57 Ok(())
58 }
59}
60pub(crate) fn valid_mime(m: &str) -> bool {
61 m.len() <= 255
62 && m.split_once('/')
63 .is_some_and(|(a, b)| !a.is_empty() && !b.is_empty() && !b.contains('/'))
64 && m.bytes()
65 .all(|c| c.is_ascii_alphanumeric() || b"/!#$&^_.+-".contains(&c))
66}
67pub fn read(preferred: &[&str]) -> ClipboardFuture<Option<Representation>> {
70 if preferred.is_empty() || preferred.iter().any(|m| !valid_mime(m)) {
71 return Box::pin(std::future::ready(Err(Error::InvalidData)));
72 }
73 #[cfg(all(target_family = "wasm", target_os = "unknown"))]
74 {
75 super::web_content::read(preferred)
76 }
77 #[cfg(target_os = "ios")]
78 {
79 let preferred: Vec<String> = preferred.iter().map(|m| (*m).to_owned()).collect();
82 let read = day_async::spawn_blocking(move || {
83 objc2::rc::autoreleasepool(|_| {
84 let preferred: Vec<&str> = preferred.iter().map(String::as_str).collect();
85 super::imp::read_content(&preferred)
86 })
87 });
88 Box::pin(async move { read.await.map_err(|_| Error::Unavailable)? })
89 }
90 #[cfg(not(any(target_os = "ios", all(target_family = "wasm", target_os = "unknown"))))]
91 {
92 Box::pin(std::future::ready(super::imp::read_content(preferred)))
93 }
94}
95pub fn write(content: Content) -> ClipboardFuture<Vec<String>> {
99 if let Err(e) = content.validate() {
100 return Box::pin(std::future::ready(Err(e)));
101 }
102 #[cfg(all(target_family = "wasm", target_os = "unknown"))]
103 {
104 super::web_content::write(content)
105 }
106 #[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
107 {
108 Box::pin(std::future::ready(super::imp::write_content(&content)))
109 }
110}
111
112#[allow(dead_code)]
115pub(crate) fn pack(content: &Content) -> Vec<u8> {
116 let mut out = (content.0.len() as u32).to_le_bytes().to_vec();
117 for r in &content.0 {
118 out.extend_from_slice(&(r.mime.len() as u32).to_le_bytes());
119 out.extend_from_slice(&(r.bytes.len() as u32).to_le_bytes());
120 out.extend_from_slice(r.mime.as_bytes());
121 out.extend_from_slice(&r.bytes);
122 }
123 out
124}
125#[allow(dead_code)]
126pub(crate) fn unpack(mut data: &[u8]) -> Result<Content, Error> {
127 fn take<'a>(data: &mut &'a [u8], n: usize) -> Result<&'a [u8], Error> {
128 if n > data.len() {
129 return Err(Error::InvalidData);
130 }
131 let (head, tail) = data.split_at(n);
132 *data = tail;
133 Ok(head)
134 }
135 fn number(data: &mut &[u8]) -> Result<usize, Error> {
136 Ok(u32::from_le_bytes(take(data, 4)?.try_into().unwrap()) as usize)
137 }
138 if data.len() > MAX_BYTES + 32 * 263 + 4 {
139 return Err(Error::TooLarge);
140 }
141 let count = number(&mut data)?;
142 if count > 32 {
143 return Err(Error::InvalidData);
144 }
145 let mut out = Vec::new();
146 for _ in 0..count {
147 let m = number(&mut data)?;
148 let n = number(&mut data)?;
149 let mime = std::str::from_utf8(take(&mut data, m)?)
150 .map_err(|_| Error::InvalidData)?
151 .to_string();
152 let bytes = take(&mut data, n)?.to_vec();
153 out.push(Representation::new(mime, bytes));
154 }
155 if !data.is_empty() {
156 return Err(Error::InvalidData);
157 }
158 let content = Content(out);
159 if !content.0.is_empty() {
160 content.validate()?;
161 }
162 Ok(content)
163}
164
165#[cfg(any(windows, test))]
167pub(crate) fn dib_to_bmp(dib: &[u8]) -> Result<Vec<u8>, Error> {
168 if dib.len() < 12 || dib.len() > MAX_BYTES - 14 {
169 return Err(Error::InvalidData);
170 }
171 let u32_at = |at: usize| -> Result<u32, Error> {
172 Ok(u32::from_le_bytes(
173 dib.get(at..at + 4)
174 .ok_or(Error::InvalidData)?
175 .try_into()
176 .unwrap(),
177 ))
178 };
179 let header = u32_at(0)? as usize;
180 let (palette, masks) = if header == 12 {
181 let bits = u16::from_le_bytes([dib[10], dib[11]]);
182 (if bits <= 8 { (1usize << bits) * 3 } else { 0 }, 0)
183 } else if header >= 40 && header <= dib.len() {
184 let bits = u16::from_le_bytes([dib[14], dib[15]]);
185 let colors = u32_at(32)? as usize;
186 let entries = if colors != 0 {
187 colors
188 } else if bits <= 8 {
189 1usize << bits
190 } else {
191 0
192 };
193 let masks = if header == 40 {
194 match u32_at(16)? {
195 3 => 12,
196 6 => 16,
197 _ => 0,
198 }
199 } else {
200 0
201 };
202 (entries.checked_mul(4).ok_or(Error::InvalidData)?, masks)
203 } else {
204 return Err(Error::InvalidData);
205 };
206 let offset = header
207 .checked_add(palette)
208 .and_then(|n| n.checked_add(masks))
209 .ok_or(Error::InvalidData)?;
210 if offset > dib.len() {
211 return Err(Error::InvalidData);
212 }
213 let mut bmp = Vec::with_capacity(dib.len() + 14);
214 bmp.extend_from_slice(b"BM");
215 bmp.extend_from_slice(&((dib.len() + 14) as u32).to_le_bytes());
216 bmp.extend_from_slice(&[0; 4]);
217 bmp.extend_from_slice(&((offset + 14) as u32).to_le_bytes());
218 bmp.extend_from_slice(dib);
219 Ok(bmp)
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225 #[test]
226 fn dib_clipboard_pixels_get_a_bmp_file_header() {
227 let mut dib = vec![0u8; 44];
228 dib[..4].copy_from_slice(&40u32.to_le_bytes());
229 dib[4..8].copy_from_slice(&1u32.to_le_bytes());
230 dib[8..12].copy_from_slice(&1u32.to_le_bytes());
231 dib[12..14].copy_from_slice(&1u16.to_le_bytes());
232 dib[14..16].copy_from_slice(&24u16.to_le_bytes());
233 dib[40..44].copy_from_slice(&[1, 2, 3, 0]);
234 let bmp = dib_to_bmp(&dib).unwrap();
235 assert_eq!(&bmp[..2], b"BM");
236 assert_eq!(&bmp[10..14], &54u32.to_le_bytes());
237 assert_eq!(&bmp[54..], &[1, 2, 3, 0]);
238 assert!(dib_to_bmp(&dib[..20]).is_err());
239 dib[32..36].copy_from_slice(&u32::MAX.to_le_bytes());
240 assert!(dib_to_bmp(&dib).is_err());
241 }
242 #[test]
243 fn binary_content_is_lossless_and_validated() {
244 let c = Content(vec![Representation::new(
245 "application/x-day-test",
246 vec![0, 255, 0, 128],
247 )]);
248 assert_eq!(c.validate(), Ok(()));
249 assert_eq!(&**c.0[0].bytes, &[0, 255, 0, 128]);
250 assert_eq!(
251 Content(vec![c.0[0].clone(), c.0[0].clone()]).validate(),
252 Err(Error::InvalidData)
253 );
254 assert!(!valid_mime("image/png\0"));
255 assert!(!valid_mime("image/png/extra"));
256 assert!(!valid_mime("text/plain; charset=utf-8"));
257 let shared = Arc::new(vec![0; MAX_BYTES / 32 + 1]);
258 let oversized = Content(
259 (0..32)
260 .map(|i| Representation {
261 mime: format!("application/x-limit-{i}"),
262 bytes: shared.clone(),
263 })
264 .collect(),
265 );
266 assert_eq!(oversized.validate(), Err(Error::TooLarge));
267 let packet = pack(&c);
268 assert_eq!(unpack(&packet), Ok(c));
269 for end in 0..packet.len() {
270 assert!(unpack(&packet[..end]).is_err());
271 }
272 assert!(unpack(&[255, 255, 255, 255]).is_err());
273 }
274}