Skip to main content

robius_share/
lib.rs

1//! Multi-platform abstractions for showing the system-native share sheet.
2//!
3//! ## Platform behavior
4//! All types and functions in this crate are platform-independent, but native
5//! share APIs don't expose exactly the same payload model on every OS:
6//! * **Android**: sharing uses `Intent.ACTION_SEND` or `ACTION_SEND_MULTIPLE`,
7//!   wrapped in the Android Sharesheet via `Intent.createChooser`.
8//!   * Text, URLs, `content://` attachments, and filesystem path attachments
9//!     are supported.
10//!   * Filesystem path attachments are copied to a shareable MediaStore item on
11//!     Android 10 and newer. On older Android versions, text files can be shared
12//!     as text content, but arbitrary binary path attachments require an app
13//!     `ContentProvider`.
14//!   * **Minimum API level: 26 (Android 8.0).** The bundled Java helper is loaded
15//!     via `InMemoryDexClassLoader`, which requires API 26. Set `minSdk` to at
16//!     least 26 in your app.
17//! * **iOS**: sharing uses `UIActivityViewController`, with text, URLs, and
18//!   filesystem path attachments.
19//! * **macOS**: sharing uses `NSSharingServicePicker`, with text, URLs, and
20//!   filesystem path attachments.
21//! * **Windows**: sharing uses the native WinRT Share UI through
22//!   `DataTransferManager` desktop-window interop, with text, URLs, and
23//!   filesystem path attachments.
24//! * **Linux**: Linux doesn't have a single standardized share sheet, so this
25//!   crate talks to the XDG desktop portal over a minimal D-Bus interface.
26//!   * A single file or URL is shared via the "Open With" app chooser.
27//!   * A mixed payload (multiple items) will open a save files dialog,
28//!     and write each item to the directory chosen by the user.
29//!   * If the d-bus portal doesn't work or isn't available, it falls back to `xdg-open`.
30//!
31//! ## Completion
32//! * On macOS, iOS, and Windows, a successful `share()` means the native share sheet
33//!   was presented.
34//! * On Android and Linux, the share request is fire-and-forget, so a successful
35//!   return value means that the request was dispatched, not that anything was shown.
36//!
37//! ## Examples
38//!
39//! ```no_run
40//! use robius_share::ShareSheet;
41//!
42//! ShareSheet::new()
43//!     .set_title("Share")
44//!     .set_subject("Robius")
45//!     .add_text("Cross-platform native APIs from Rust")
46//!     .add_url("https://robius.rs/")
47//!     .share()
48//!     .expect("failed to show share sheet");
49//! ```
50
51mod error;
52mod sys;
53
54use std::path::Path;
55
56pub use error::{Error, Result};
57use robius_common::FileLocation;
58
59/// A native share sheet builder.
60#[derive(Clone, Debug, Default)]
61pub struct ShareSheet {
62    options: ShareOptions,
63}
64
65impl ShareSheet {
66    /// Creates a new share sheet builder.
67    pub fn new() -> Self {
68        Self::default()
69    }
70
71    /// Sets a share sheet title or chooser prompt, where supported.
72    ///
73    /// On Android this is used as the chooser title. On iOS/macOS, the system
74    /// share sheet might ignore it.
75    #[must_use]
76    pub fn set_title(mut self, title: impl Into<String>) -> Self {
77        self.options.title = Some(title.into());
78        self
79    }
80
81    /// Sets secondary share metadata for receivers that support it.
82    ///
83    /// Some share targets use this as a subject, description, or preview title.
84    /// Many targets ignore it.
85    #[must_use]
86    pub fn set_subject(mut self, subject: impl Into<String>) -> Self {
87        self.options.subject = Some(subject.into());
88        self
89    }
90
91    /// Adds plain text to the share payload.
92    #[must_use]
93    pub fn add_text(mut self, text: impl Into<String>) -> Self {
94        self.options.items.push(ShareItem::Text(text.into()));
95        self
96    }
97
98    /// Adds a web or app URL to the share payload.
99    ///
100    /// On Android this is encoded as shared text, because `ACTION_SEND` has no
101    /// separate URL field.
102    #[must_use]
103    pub fn add_url(mut self, url: impl Into<String>) -> Self {
104        self.options.items.push(ShareItem::Url(url.into()));
105        self
106    }
107
108    /// Adds a filesystem path attachment.
109    ///
110    /// On Android 10 and newer, this copies the file to a shareable MediaStore
111    /// item before launching the chooser. On older Android versions, text files
112    /// can be shared as text content, while arbitrary binary path attachments
113    /// require a host app `ContentProvider`.
114    #[must_use]
115    pub fn add_file<P: AsRef<Path>>(mut self, path: P) -> Self {
116        self.options.items.push(ShareItem::File(SharedFile::from_path(path)));
117        self
118    }
119
120    /// Adds a filesystem path attachment with an explicit MIME type hint.
121    #[must_use]
122    pub fn add_file_with_mime_type<P: AsRef<Path>>(
123        mut self,
124        path: P,
125        mime_type: impl Into<String>,
126    ) -> Self {
127        self.options.items.push(ShareItem::File(
128            SharedFile::from_path(path).set_mime_type(mime_type),
129        ));
130        self
131    }
132
133    /// Adds a platform file/content URI attachment.
134    ///
135    /// This is primarily for Android `content://` URIs that your app already
136    /// owns or received from another platform API. Local `file://` URIs are
137    /// accepted on Android and are copied to a shareable MediaStore item where
138    /// supported.
139    #[must_use]
140    pub fn add_file_uri(mut self, uri: impl Into<String>) -> Self {
141        self.options.items.push(ShareItem::File(SharedFile::from_uri(uri)));
142        self
143    }
144
145    /// Adds a platform file/content URI attachment with an explicit MIME type hint.
146    #[must_use]
147    pub fn add_file_uri_with_mime_type(
148        mut self,
149        uri: impl Into<String>,
150        mime_type: impl Into<String>,
151    ) -> Self {
152        self.options.items.push(ShareItem::File(
153            SharedFile::from_uri(uri).set_mime_type(mime_type),
154        ));
155        self
156    }
157
158    /// Shows the native share sheet.
159    ///
160    /// The returned result only indicates whether the share sheet was presented.
161    /// It does not indicate whether the user chose a target or completed sharing.
162    pub fn share(self) -> Result<()> {
163        self.options.validate()?;
164        sys::share(self.options)
165    }
166}
167
168/// A file attachment in a share payload.
169#[derive(Clone, Debug, PartialEq, Eq)]
170pub struct SharedFile {
171    location: FileLocation,
172    mime_type: Option<String>,
173}
174
175impl SharedFile {
176    /// Creates a file attachment from a filesystem path.
177    pub fn from_path<P: AsRef<Path>>(path: P) -> Self {
178        Self {
179            location: FileLocation::from_path(path),
180            mime_type: None,
181        }
182    }
183
184    /// Creates a file attachment from a platform file/content URI.
185    pub fn from_uri(uri: impl Into<String>) -> Self {
186        Self {
187            location: FileLocation::from_uri(uri),
188            mime_type: None,
189        }
190    }
191
192    /// Sets an explicit MIME type hint for this file attachment.
193    #[must_use]
194    pub fn set_mime_type(mut self, mime_type: impl Into<String>) -> Self {
195        self.mime_type = Some(mime_type.into());
196        self
197    }
198
199    /// Returns this attachment as a filesystem path, if it has one.
200    pub fn path(&self) -> Option<&Path> {
201        self.location.path()
202    }
203
204    /// Returns this attachment as a platform URI, if it has one.
205    pub fn uri(&self) -> Option<&str> {
206        self.location.uri()
207    }
208
209    /// Returns the explicit MIME type hint, if one was set.
210    pub fn mime_type(&self) -> Option<&str> {
211        self.mime_type.as_deref()
212    }
213}
214
215/// A single share payload item.
216#[derive(Clone, Debug, PartialEq, Eq)]
217pub enum ShareItem {
218    /// Plain text content.
219    Text(String),
220    /// A URL to share as a link.
221    Url(String),
222    /// A file attachment.
223    File(SharedFile),
224}
225
226/// Options collected by [`ShareSheet`].
227#[derive(Clone, Debug, Default)]
228pub(crate) struct ShareOptions {
229    pub(crate) title: Option<String>,
230    pub(crate) subject: Option<String>,
231    pub(crate) items: Vec<ShareItem>,
232}
233
234impl ShareOptions {
235    fn validate(&self) -> Result<()> {
236        if self.items.is_empty() {
237            return Err(Error::Empty);
238        }
239
240        for item in &self.items {
241            match item {
242                ShareItem::Text(text) if text.trim().is_empty() => return Err(Error::InvalidItem),
243                ShareItem::Url(url) if url.trim().is_empty() => return Err(Error::InvalidItem),
244                ShareItem::File(file) => match &file.location {
245                    FileLocation::Path(path) if path.as_os_str().is_empty() => {
246                        return Err(Error::InvalidItem);
247                    }
248                    FileLocation::Uri(uri) if uri.trim().is_empty() => {
249                        return Err(Error::InvalidItem);
250                    }
251                    _ if file.mime_type.as_deref().is_some_and(|m| m.trim().is_empty()) => {
252                        return Err(Error::InvalidItem);
253                    }
254                    _ => {}
255                },
256                _ => {}
257            }
258        }
259
260        Ok(())
261    }
262}
263
264pub(crate) fn text_items(options: &ShareOptions) -> Vec<&str> {
265    options
266        .items
267        .iter()
268        .filter_map(|item| match item {
269            ShareItem::Text(text) | ShareItem::Url(text) => Some(text.as_str()),
270            ShareItem::File(_) => None,
271        })
272        .collect()
273}
274
275#[cfg_attr(not(target_os = "android"), allow(dead_code))]
276pub(crate) fn file_items(options: &ShareOptions) -> impl Iterator<Item = &SharedFile> {
277    options.items.iter().filter_map(|item| match item {
278        ShareItem::File(file) => Some(file),
279        _ => None,
280    })
281}
282
283#[cfg_attr(not(target_os = "android"), allow(dead_code))]
284pub(crate) fn shared_text(options: &ShareOptions) -> Option<String> {
285    let mut text = String::new();
286    for item in text_items(options) {
287        if !text.is_empty() {
288            text.push('\n');
289        }
290        text.push_str(item);
291    }
292    (!text.is_empty()).then_some(text)
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn empty_payload_is_invalid() {
301        assert!(matches!(
302            ShareSheet::new().options.validate(),
303            Err(Error::Empty)
304        ));
305    }
306
307    #[test]
308    fn empty_text_url_path_uri_and_mime_type_are_invalid() {
309        let invalid_payloads = [
310            ShareSheet::new().add_text(""),
311            ShareSheet::new().add_url(""),
312            ShareSheet::new().add_file(""),
313            ShareSheet::new().add_file_uri(""),
314            ShareSheet::new().add_file_with_mime_type("share.txt", ""),
315            ShareSheet::new().add_file_uri_with_mime_type("content://robius/share.txt", ""),
316        ];
317
318        for payload in invalid_payloads {
319            assert!(matches!(payload.options.validate(), Err(Error::InvalidItem)));
320        }
321    }
322
323    #[test]
324    fn text_and_urls_are_combined_in_order() {
325        let sheet = ShareSheet::new()
326            .add_text("hello")
327            .add_url("https://robius.rs/")
328            .add_text("goodbye");
329
330        assert_eq!(
331            shared_text(&sheet.options).as_deref(),
332            Some("hello\nhttps://robius.rs/\ngoodbye"),
333        );
334    }
335
336    #[test]
337    fn file_items_preserve_paths_uris_and_mime_types() {
338        let sheet = ShareSheet::new()
339            .add_file_with_mime_type("share.txt", "text/plain")
340            .add_file_uri_with_mime_type("content://robius/share.png", "image/png");
341
342        let files = file_items(&sheet.options).collect::<Vec<_>>();
343        assert_eq!(files.len(), 2);
344        assert_eq!(files[0].path(), Some(Path::new("share.txt")));
345        assert_eq!(files[0].uri(), None);
346        assert_eq!(files[0].mime_type(), Some("text/plain"));
347        assert_eq!(files[1].path(), None);
348        assert_eq!(files[1].uri(), Some("content://robius/share.png"));
349        assert_eq!(files[1].mime_type(), Some("image/png"));
350    }
351
352    #[test]
353    fn valid_builder_options_pass_validation() {
354        let sheet = ShareSheet::new()
355            .set_title("Share")
356            .set_subject("Robius")
357            .add_text("hello")
358            .add_url("https://robius.rs/")
359            .add_file("share.txt")
360            .add_file_uri("content://robius/share.txt");
361
362        assert!(sheet.options.validate().is_ok());
363    }
364}