Skip to main content

idevice/services/core_device/
pasteboard_service.rs

1//! Read/write the device pasteboard via the
2//! `com.apple.coredevice.pasteboardservice` RemoteXPC service.
3//!
4//! Unlike the DDI features, the service speaks XPC dicts directly: the
5//! `command` field drives dispatch. Six verbs exist (request -> reply):
6//!
7//! * `PULL`  -> `PULL_REPLY`  read the pasteboard
8//! * `SET`   -> `SET_REPLY`   replace the pasteboard
9//! * `RESOLVE` -> `DATA`      fetch the bytes of a promised item
10//! * `AUTONOTIFY` + `PUSH`    subscribe to change notifications (clipboard sync)
11//!
12//! A `PasteboardItem` is `{types: [UTI], data: {UTI: PasteboardItemData}}`. A
13//! `PasteboardItemData` encodes as `{data: <bytes>}` when its bytes are inline,
14//! `{size: <Int64>}` when the item is *promised* (fetch later with `RESOLVE`),
15//! or `{error: ...}` when resolution failed. These map to
16//! [`PasteboardPayload`].
17
18use 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
35/// Image UTIs we recognise on the pasteboard, in priority order. PNG first
36/// (lossless, what we write back), then JPEG and TIFF.
37pub 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/// `PasteboardDataInclusionPolicy` tells the device whether to inline item
44/// bytes in a `PULL`/`PUSH` snapshot or hand them back as promises to fetch
45/// with `RESOLVE`.
46#[derive(Debug, Clone, Copy)]
47pub enum DataInclusionPolicy {
48    /// Resolve and inline every item's bytes. Simplest for callers; can be
49    /// expensive for large items.
50    AllResolved,
51    /// Promise every item; fetch bytes on demand with [`resolve`](PasteboardServiceClient::resolve).
52    AllPromised,
53    /// Mirror whatever the source set on the device.
54    MatchSource,
55    /// Resolve the primary item, promise the rest.
56    PromiseSecondary,
57    /// Inline items smaller than `bytes`, promise the rest.
58    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/// The bytes (or absence thereof) for one UTI of a [`PasteboardItem`].
81#[derive(Debug, Clone)]
82pub enum PasteboardPayload {
83    /// The bytes were inlined in the snapshot.
84    Inline(Vec<u8>),
85    /// The item is promised: fetch with [`PasteboardServiceClient::resolve`].
86    /// `size` is the device's advertised byte count when known.
87    Promised { size: Option<i64> },
88    /// The device reported an error resolving this UTI, rendered for diagnostics.
89    Error(String),
90}
91
92/// One UTI's payload within a [`PasteboardItem`].
93#[derive(Debug, Clone)]
94pub struct PasteboardEntry {
95    pub uti: String,
96    pub payload: PasteboardPayload,
97}
98
99/// A single pasteboard item: its declared UTIs (in priority order) and the
100/// payload for each.
101#[derive(Debug, Clone)]
102pub struct PasteboardItem {
103    /// Position in the snapshot — the `item_index` to pass to
104    /// [`PasteboardServiceClient::resolve`].
105    pub index: usize,
106    /// Declared UTIs in priority order.
107    pub types: Vec<String>,
108    /// Per-UTI payloads.
109    pub data: Vec<PasteboardEntry>,
110}
111
112/// A parsed `PULL_REPLY`/`PUSH` pasteboard snapshot.
113#[derive(Debug, Clone)]
114pub struct PasteboardSnapshot {
115    /// The pasteboard the snapshot is for, e.g. [`GENERAL_PASTEBOARD`].
116    pub pasteboard_name: Option<String>,
117    /// Monotonic change counter; bumps on every pasteboard mutation.
118    pub change_count: Option<i64>,
119    pub items: Vec<PasteboardItem>,
120}
121
122/// A promised (not-inlined) `(item, UTI)` pair to fetch with
123/// [`PasteboardServiceClient::resolve`].
124#[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    /// Parse a `PULL_REPLY`/`PUSH` message. Both nest the snapshot under a
133    /// `pasteboard` key; a bare snapshot dict is also accepted.
134    fn from_message(msg: &plist::Value) -> Result<Self, CoreDeviceError> {
135        let dict = msg
136            .as_dictionary()
137            .ok_or(CoreDeviceError::MalformedField("(root)"))?;
138        // PULL_REPLY/PUSH nest the snapshot under "pasteboard"; tolerate a bare
139        // snapshot too.
140        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    /// Best-effort UTF-8 text: the first text UTI carrying inline bytes.
173    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    /// Best-effort image bytes: the first image UTI (PNG/JPEG/TIFF, in priority
188    /// order) carrying inline bytes, returned with the UTI that produced them so
189    /// the caller knows the encoding. Promised items are skipped — pull with
190    /// [`DataInclusionPolicy::AllResolved`] (the default for [`get`](PasteboardServiceClient::get))
191    /// to inline them, or fetch with [`resolve`](PasteboardServiceClient::resolve).
192    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    /// The promised (not-inlined) entries, each fetchable with
206    /// [`PasteboardServiceClient::resolve`].
207    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    /// Pull `pasteboard_name` with every item's bytes inlined
291    /// ([`DataInclusionPolicy::AllResolved`]).
292    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    /// Pull `pasteboard_name` with an explicit data-inclusion `policy`. Use a
298    /// promising policy plus [`PasteboardSnapshot::promised_items`] +
299    /// [`resolve`](Self::resolve) to avoid transferring large items you don't
300    /// need.
301    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    /// Replace the contents of `pasteboard_name` with a single UTF-8 `text` value.
318    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        // Drain the SET_REPLY ack; it carries no information we surface.
340        self.inner.recv().await?;
341        Ok(())
342    }
343
344    /// Replace the contents of `pasteboard_name` with a single image item of the
345    /// given `uti` (e.g. [`UTI_PNG`]) and its encoded `bytes`.
346    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        // Drain the SET_REPLY ack; it carries no information we surface.
367        self.inner.recv().await?;
368        Ok(())
369    }
370
371    /// Fetch the bytes of a promised item (`RESOLVE` -> `DATA`). `item_index` is
372    /// the item's position in the snapshot and `uti` is the type to resolve.
373    ///
374    /// Returns `None` when the device can't fulfil the promise — e.g. the
375    /// snapshot was superseded by a newer pasteboard change, or the data is no
376    /// longer available (the `DATA` reply carries a null `data`).
377    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    /// Like [`resolve`](Self::resolve) but returns the raw `DATA` reply for
392    /// callers that need to inspect it (e.g. an `error` instead of `data`).
393    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    /// Subscribe to (or, with `enable = false`, unsubscribe from) pasteboard
411    /// change notifications. While subscribed the device pushes `PUSH` snapshots
412    /// as the pasteboard changes; read them with [`recv_push`](Self::recv_push).
413    ///
414    /// `policy` controls whether the pushed snapshots carry inline bytes.
415    ///
416    /// The request is sent one-way: the device does not reply on the reply
417    /// channel, it just begins pushing `PUSH` messages on the root channel.
418    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    /// Block for the next `PUSH` change-notification snapshot from the device.
436    /// Only meaningful after [`set_change_notifications`](Self::set_change_notifications)
437    /// with `enable = true`.
438    ///
439    /// Pushes arrive on the root channel (not the reply channel that
440    /// request/reply verbs use), so this reads from there.
441    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}