idevice/services/core_device/
pasteboard_service.rs1use std::borrow::Cow;
19
20use crate::{
21 IdeviceError, ReadWrite, RemoteXpcClient, obf, xpc,
22 xpc::{Dictionary, XPCObject},
23};
24
25use super::CoreDeviceError;
26
27pub const GENERAL_PASTEBOARD: &str = "general";
28
29const UTI_UTF8_PLAIN_TEXT: &str = "public.utf8-plain-text";
30const UTI_PLAIN_TEXT: &str = "public.plain-text";
31const UTI_TEXT: &str = "public.text";
32
33const TEXT_UTIS: [&str; 3] = [UTI_UTF8_PLAIN_TEXT, UTI_PLAIN_TEXT, UTI_TEXT];
34
35pub const UTI_PNG: &str = "public.png";
38pub const UTI_JPEG: &str = "public.jpeg";
39pub const UTI_TIFF: &str = "public.tiff";
40
41const IMAGE_UTIS: [&str; 3] = [UTI_PNG, UTI_JPEG, UTI_TIFF];
42
43#[derive(Debug, Clone, Copy)]
47pub enum DataInclusionPolicy {
48 AllResolved,
51 AllPromised,
53 MatchSource,
55 PromiseSecondary,
57 Threshold(i64),
59}
60
61impl DataInclusionPolicy {
62 fn to_xpc(self) -> XPCObject {
63 let (key, value) = match self {
64 DataInclusionPolicy::AllResolved => ("allResolved", Dictionary::new()),
65 DataInclusionPolicy::AllPromised => ("allPromised", Dictionary::new()),
66 DataInclusionPolicy::MatchSource => ("matchSource", Dictionary::new()),
67 DataInclusionPolicy::PromiseSecondary => ("promiseSecondary", Dictionary::new()),
68 DataInclusionPolicy::Threshold(bytes) => {
69 let mut inner = Dictionary::new();
70 inner.insert("bytes".into(), XPCObject::Int64(bytes));
71 ("thresholdData", inner)
72 }
73 };
74 let mut d = Dictionary::new();
75 d.insert(key.into(), XPCObject::Dictionary(value));
76 XPCObject::Dictionary(d)
77 }
78}
79
80#[derive(Debug, Clone)]
82pub enum PasteboardPayload {
83 Inline(Vec<u8>),
85 Promised { size: Option<i64> },
88 Error(String),
90}
91
92#[derive(Debug, Clone)]
94pub struct PasteboardEntry {
95 pub uti: String,
96 pub payload: PasteboardPayload,
97}
98
99#[derive(Debug, Clone)]
102pub struct PasteboardItem {
103 pub index: usize,
106 pub types: Vec<String>,
108 pub data: Vec<PasteboardEntry>,
110}
111
112#[derive(Debug, Clone)]
114pub struct PasteboardSnapshot {
115 pub pasteboard_name: Option<String>,
117 pub change_count: Option<i64>,
119 pub items: Vec<PasteboardItem>,
120}
121
122#[derive(Debug, Clone)]
125pub struct PromisedItem {
126 pub item_index: i64,
127 pub uti: String,
128 pub size: Option<i64>,
129}
130
131impl PasteboardSnapshot {
132 fn from_message(msg: &plist::Value) -> Result<Self, CoreDeviceError> {
135 let dict = msg
136 .as_dictionary()
137 .ok_or(CoreDeviceError::MalformedField("(root)"))?;
138 let snapshot = dict
141 .get("pasteboard")
142 .and_then(|p| p.as_dictionary())
143 .unwrap_or(dict);
144
145 let metadata = snapshot.get("metadata").and_then(|m| m.as_dictionary());
146 let pasteboard_name = metadata
147 .and_then(|m| m.get("pasteboardName"))
148 .and_then(|n| n.as_string())
149 .map(str::to_string);
150 let change_count = metadata
151 .and_then(|m| m.get("changeCount"))
152 .and_then(|c| c.as_signed_integer());
153
154 let items = snapshot
155 .get("items")
156 .and_then(|i| i.as_array())
157 .map(|arr| {
158 arr.iter()
159 .enumerate()
160 .map(|(index, item)| parse_item(index, item))
161 .collect()
162 })
163 .unwrap_or_default();
164
165 Ok(PasteboardSnapshot {
166 pasteboard_name,
167 change_count,
168 items,
169 })
170 }
171
172 pub fn text(&self) -> Option<String> {
174 for item in &self.items {
175 for uti in TEXT_UTIS {
176 if let Some(entry) = item.data.iter().find(|e| e.uti == uti)
177 && let PasteboardPayload::Inline(bytes) = &entry.payload
178 && let Ok(text) = String::from_utf8(bytes.clone())
179 {
180 return Some(text);
181 }
182 }
183 }
184 None
185 }
186
187 pub fn image(&self) -> Option<(&'static str, Vec<u8>)> {
193 for item in &self.items {
194 for uti in IMAGE_UTIS {
195 if let Some(entry) = item.data.iter().find(|e| e.uti == uti)
196 && let PasteboardPayload::Inline(bytes) = &entry.payload
197 {
198 return Some((uti, bytes.clone()));
199 }
200 }
201 }
202 None
203 }
204
205 pub fn promised_items(&self) -> Vec<PromisedItem> {
208 let mut out = Vec::new();
209 for item in &self.items {
210 for entry in &item.data {
211 if let PasteboardPayload::Promised { size } = entry.payload {
212 out.push(PromisedItem {
213 item_index: item.index as i64,
214 uti: entry.uti.clone(),
215 size,
216 });
217 }
218 }
219 }
220 out
221 }
222}
223
224fn parse_item(index: usize, item: &plist::Value) -> PasteboardItem {
225 let dict = item.as_dictionary();
226 let types = dict
227 .and_then(|d| d.get("types"))
228 .and_then(|t| t.as_array())
229 .map(|arr| {
230 arr.iter()
231 .filter_map(|v| v.as_string().map(str::to_string))
232 .collect()
233 })
234 .unwrap_or_default();
235
236 let data = dict
237 .and_then(|d| d.get("data"))
238 .and_then(|d| d.as_dictionary())
239 .map(|map| {
240 map.iter()
241 .map(|(uti, datum)| PasteboardEntry {
242 uti: uti.clone(),
243 payload: parse_payload(datum),
244 })
245 .collect()
246 })
247 .unwrap_or_default();
248
249 PasteboardItem { index, types, data }
250}
251
252fn parse_payload(datum: &plist::Value) -> PasteboardPayload {
253 let Some(d) = datum.as_dictionary() else {
254 return PasteboardPayload::Promised { size: None };
255 };
256 if let Some(bytes) = d.get("data").and_then(|v| v.as_data()) {
257 PasteboardPayload::Inline(bytes.to_vec())
258 } else if let Some(err) = d.get("error") {
259 PasteboardPayload::Error(format!("{err:?}"))
260 } else {
261 PasteboardPayload::Promised {
262 size: d.get("size").and_then(|s| s.as_signed_integer()),
263 }
264 }
265}
266
267#[derive(Debug)]
268pub struct PasteboardServiceClient<R: ReadWrite> {
269 inner: RemoteXpcClient<R>,
270}
271
272#[cfg(feature = "rsd")]
273impl crate::RsdService for PasteboardServiceClient<Box<dyn ReadWrite>> {
274 fn rsd_service_name() -> Cow<'static, str> {
275 obf!("com.apple.coredevice.pasteboardservice")
276 }
277
278 async fn from_stream(stream: Box<dyn ReadWrite>) -> Result<Self, IdeviceError> {
279 let mut inner = RemoteXpcClient::new(stream).await?;
280 inner.do_handshake().await?;
281 Ok(Self { inner })
282 }
283}
284
285impl<R: ReadWrite> PasteboardServiceClient<R> {
286 pub fn new(inner: RemoteXpcClient<R>) -> Self {
287 Self { inner }
288 }
289
290 pub async fn get(&mut self, pasteboard_name: &str) -> Result<PasteboardSnapshot, IdeviceError> {
293 self.get_with_policy(pasteboard_name, DataInclusionPolicy::AllResolved)
294 .await
295 }
296
297 pub async fn get_with_policy(
302 &mut self,
303 pasteboard_name: &str,
304 policy: DataInclusionPolicy,
305 ) -> Result<PasteboardSnapshot, IdeviceError> {
306 let msg = xpc!({
307 "command": "PULL",
308 "pasteboardName": pasteboard_name,
309 "dataPolicy": policy.to_xpc(),
310 });
311
312 self.inner.send_object(msg, true).await?;
313 let reply = self.inner.recv().await?;
314 Ok(PasteboardSnapshot::from_message(&reply)?)
315 }
316
317 pub async fn set_text(
319 &mut self,
320 text: &str,
321 pasteboard_name: &str,
322 ) -> Result<(), IdeviceError> {
323 let mut data = Dictionary::new();
324 for uti in TEXT_UTIS {
325 data.insert(uti.into(), xpc!({ "data": text.as_bytes() }));
326 }
327
328 let msg = xpc!({
329 "command": "SET",
330 "pasteboardName": pasteboard_name,
331 "items": [{
332 "types": TEXT_UTIS.to_vec(),
333 "data": XPCObject::Dictionary(data),
334 }],
335 "sourceMetadata": XPCObject::Null,
336 });
337
338 self.inner.send_object(msg, true).await?;
339 self.inner.recv().await?;
341 Ok(())
342 }
343
344 pub async fn set_image(
347 &mut self,
348 bytes: &[u8],
349 uti: &str,
350 pasteboard_name: &str,
351 ) -> Result<(), IdeviceError> {
352 let mut data = Dictionary::new();
353 data.insert(uti.into(), xpc!({ "data": bytes }));
354
355 let msg = xpc!({
356 "command": "SET",
357 "pasteboardName": pasteboard_name,
358 "items": [{
359 "types": vec![uti],
360 "data": XPCObject::Dictionary(data),
361 }],
362 "sourceMetadata": XPCObject::Null,
363 });
364
365 self.inner.send_object(msg, true).await?;
366 self.inner.recv().await?;
368 Ok(())
369 }
370
371 pub async fn resolve(
378 &mut self,
379 pasteboard_name: &str,
380 item_index: i64,
381 uti: &str,
382 ) -> Result<Option<Vec<u8>>, IdeviceError> {
383 let reply = self.resolve_raw(pasteboard_name, item_index, uti).await?;
384 Ok(reply
385 .as_dictionary()
386 .and_then(|d| d.get("data"))
387 .and_then(|d| d.as_data())
388 .map(|d| d.to_vec()))
389 }
390
391 pub async fn resolve_raw(
394 &mut self,
395 pasteboard_name: &str,
396 item_index: i64,
397 uti: &str,
398 ) -> Result<plist::Value, IdeviceError> {
399 let msg = xpc!({
400 "command": "RESOLVE",
401 "pasteboardName": pasteboard_name,
402 "itemIndex": item_index,
403 "type": uti,
404 });
405
406 self.inner.send_object(msg, true).await?;
407 self.inner.recv().await
408 }
409
410 pub async fn set_change_notifications(
419 &mut self,
420 enable: bool,
421 pasteboard_name: &str,
422 policy: Option<DataInclusionPolicy>,
423 ) -> Result<(), IdeviceError> {
424 let data_policy = policy.map(|p| p.to_xpc()).unwrap_or(XPCObject::Null);
425 let msg = xpc!({
426 "command": "AUTONOTIFY",
427 "enable": enable,
428 "pasteboardName": pasteboard_name,
429 "dataPolicy": data_policy,
430 });
431
432 self.inner.send_object(msg, false).await
433 }
434
435 pub async fn recv_push(&mut self) -> Result<PasteboardSnapshot, IdeviceError> {
442 let push = self.inner.recv_root().await?;
443 Ok(PasteboardSnapshot::from_message(&push)?)
444 }
445}