1#![cfg_attr(
2 test,
3 allow(
4 clippy::disallowed_methods,
5 clippy::string_slice,
6 reason = "in a test these are the assertion, not a hazard"
7 )
8)]
9
10use std::sync::{Arc, OnceLock};
23
24mod caps;
25#[cfg(unix)]
26pub mod chooser_service;
27#[cfg(unix)]
28pub mod chosen;
29#[cfg(any(test, feature = "test-support"))]
30pub mod conformance;
31pub mod portal;
32#[cfg(any(unix, windows))]
33pub mod shell;
34#[cfg(not(any(unix, windows)))]
35#[path = "shell_absent.rs"]
36pub mod shell;
37#[cfg(not(target_arch = "wasm32"))]
38mod unattended;
39pub mod web_policy;
40
41#[cfg(target_os = "macos")]
42pub mod confined;
43#[cfg(target_os = "macos")]
44mod macos;
45#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
46mod web;
47#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
48pub use web::download;
49#[cfg(windows)]
50mod windows;
51#[cfg(all(target_os = "linux", feature = "portal-client"))]
52mod xdg;
53
54pub use caps::{Availability, Feature, Unsupported, availability, available};
55
56use portal::{
57 LaunchChannel, LaunchOutcome, LaunchRequest, MultiChannel, MultiOutcome, OpenFileChannel,
58 OpenFileOutcome, PickRequest, PortalChannel, PortalOutcome, SaveChannel,
59};
60
61pub trait FilePicker: Send + Sync {
62 fn pick(&self, request: PickRequest) -> PortalChannel;
65 fn pick_multiple(&self, request: PickRequest) -> MultiChannel;
66
67 fn open_handle(&self, request: PickRequest) -> OpenFileChannel {
73 let _ = request;
74 answered(OpenFileOutcome::Failed(UNAVAILABLE.to_string()))
75 }
76
77 fn reopen(&self, reference: &std::path::Path, write: bool) -> OpenFileChannel {
82 let _ = (reference, write);
83 answered(OpenFileOutcome::Failed(
84 "This host cannot open the file again once it is chosen.".to_string(),
85 ))
86 }
87
88 fn save_file(&self, request: PickRequest) -> OpenFileChannel {
89 let _ = request;
90 let (tx, rx) = std::sync::mpsc::channel();
91 let _ = tx.send(OpenFileOutcome::Failed(
92 "this host answers Save with a path; use `PickRequest::send`".to_string(),
93 ));
94 rx
95 }
96 fn launch(&self, request: LaunchRequest) -> LaunchChannel;
97 fn save_destination(&self, request: PickRequest) -> portal::DestinationChannel {
98 if request.suggested_name().is_none() {
99 return portal::DestinationChannel::answered(portal::DestinationOutcome::Failed(
100 "only a Save chooser chooses where to save".to_owned(),
101 ));
102 }
103 portal::DestinationChannel::from_path(self.pick(request))
104 }
105 fn save_contents(&self, request: PickRequest, bytes: Vec<u8>) -> SaveChannel {
106 let destination = request
107 .suggested_name()
108 .is_some()
109 .then(|| self.pick(request));
110 crate::portal::write_picked(destination, bytes)
111 }
112}
113
114pub trait UriOpener: Send + Sync {
115 fn open(&self, uri: &str) -> std::io::Result<()>;
116}
117
118#[cfg(not(target_arch = "wasm32"))]
119pub fn unattended_picker(directory: std::path::PathBuf) -> Option<Arc<dyn FilePicker>> {
120 unattended::SaveDirectoryPicker::new(directory)
121 .map(|picker| Arc::new(picker) as Arc<dyn FilePicker>)
122}
123
124#[cfg(not(target_arch = "wasm32"))]
129pub fn inherited_shell_picker(elsewhere: Arc<dyn FilePicker>) -> Option<Arc<dyn FilePicker>> {
130 shell::inherited_picker(elsewhere)
131}
132
133#[cfg(not(target_arch = "wasm32"))]
134pub fn inherited_shell_opener(elsewhere: Arc<dyn UriOpener>) -> Option<Arc<dyn UriOpener>> {
135 shell::inherited_opener(elsewhere)
136}
137
138pub fn system_picker() -> Arc<dyn FilePicker> {
139 #[cfg(all(target_os = "linux", feature = "portal-client"))]
140 return Arc::new(xdg::PortalFilePicker);
141 #[cfg(target_os = "macos")]
142 return match confined::from_env() {
143 Some(confined) => confined as Arc<dyn FilePicker>,
144 None => Arc::new(macos::PanelFilePicker),
145 };
146 #[cfg(windows)]
147 return Arc::new(windows::WindowsFilePicker);
148 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
149 return Arc::new(web::PageFiles);
150 #[allow(
151 unreachable_code,
152 reason = "a target without choosers, or an app process whose host holds one"
153 )]
154 unavailable_picker()
155}
156
157pub fn system_opener() -> Arc<dyn UriOpener> {
158 Arc::new(SystemOpener)
159}
160
161struct SystemOpener;
162
163impl UriOpener for SystemOpener {
164 fn open(&self, uri: &str) -> std::io::Result<()> {
165 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
166 if let Err(error) = url::Url::parse(uri) {
167 return Err(std::io::Error::new(
168 std::io::ErrorKind::InvalidInput,
169 format!("bad URI: {error}"),
170 ));
171 }
172 #[cfg(all(target_os = "linux", feature = "portal-client"))]
173 return xdg::open_uri(uri);
174 #[cfg(all(target_os = "linux", not(feature = "portal-client")))]
177 return open::that_detached(uri);
178 #[cfg(target_os = "macos")]
179 return macos::open_uri(uri);
180 #[cfg(windows)]
181 return open::that_detached(uri);
182 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
183 return web::open_uri(uri);
184 #[allow(unreachable_code, reason = "a target without a URI handler")]
185 UnavailableOpener.open(uri)
186 }
187}
188
189pub fn unavailable_picker() -> Arc<dyn FilePicker> {
190 Arc::new(UnavailableFilePicker)
191}
192
193pub fn unavailable_opener() -> Arc<dyn UriOpener> {
194 Arc::new(UnavailableOpener)
195}
196
197const UNAVAILABLE: &str = "Choosing files isn't available here";
198
199struct UnavailableFilePicker;
200
201fn answered<T>(outcome: T) -> std::sync::mpsc::Receiver<T> {
202 let (tx, rx) = std::sync::mpsc::channel();
203 let _ = tx.send(outcome);
204 rx
205}
206
207impl FilePicker for UnavailableFilePicker {
208 fn pick(&self, _request: PickRequest) -> PortalChannel {
209 answered(PortalOutcome::Failed(UNAVAILABLE.to_string()))
210 }
211
212 fn pick_multiple(&self, _request: PickRequest) -> MultiChannel {
213 answered(MultiOutcome::Failed(UNAVAILABLE.to_string()))
214 }
215
216 fn launch(&self, _request: LaunchRequest) -> LaunchChannel {
217 answered(LaunchOutcome::Failed(UNAVAILABLE.to_string()))
218 }
219
220 fn save_destination(&self, _request: PickRequest) -> portal::DestinationChannel {
221 portal::DestinationChannel::answered(portal::DestinationOutcome::Failed(
222 UNAVAILABLE.to_string(),
223 ))
224 }
225
226 fn save_contents(&self, _request: PickRequest, _bytes: Vec<u8>) -> SaveChannel {
227 answered(portal::SaveOutcome::Failed(UNAVAILABLE.to_string()))
228 }
229}
230
231struct UnavailableOpener;
232
233impl UriOpener for UnavailableOpener {
234 fn open(&self, _uri: &str) -> std::io::Result<()> {
235 Err(std::io::Error::new(
236 std::io::ErrorKind::Unsupported,
237 "Opening links isn't available here",
238 ))
239 }
240}
241
242#[derive(Clone, Copy)]
243pub struct Resolver {
244 pub picker: fn() -> Arc<dyn FilePicker>,
245 pub opener: fn() -> Arc<dyn UriOpener>,
246}
247
248static RESOLVER: OnceLock<Resolver> = OnceLock::new();
249
250pub fn install_resolver(resolver: Resolver) {
251 let _ = RESOLVER.set(resolver);
252}
253
254pub(crate) fn current_picker() -> Arc<dyn FilePicker> {
255 RESOLVER
256 .get()
257 .map_or_else(unavailable_picker, |resolver| (resolver.picker)())
258}
259
260pub(crate) fn current_opener() -> Arc<dyn UriOpener> {
261 RESOLVER
262 .get()
263 .map_or_else(unavailable_opener, |resolver| (resolver.opener)())
264}
265
266#[cfg(any(
267 all(target_os = "linux", feature = "portal-client"),
268 target_os = "macos",
269 windows
270))]
271pub(crate) enum PortalFailure {
272 Cancelled,
273 Failed(String),
274}
275
276#[cfg(any(
277 all(target_os = "linux", feature = "portal-client"),
278 target_os = "macos",
279 windows
280))]
281impl PortalFailure {
282 fn into_single(self) -> PortalOutcome {
283 match self {
284 PortalFailure::Cancelled => PortalOutcome::Cancelled,
285 PortalFailure::Failed(e) => PortalOutcome::Failed(e),
286 }
287 }
288 fn into_multi(self) -> MultiOutcome {
289 match self {
290 PortalFailure::Cancelled => MultiOutcome::Cancelled,
291 PortalFailure::Failed(e) => MultiOutcome::Failed(e),
292 }
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299
300 tilo_test_env::scenario! {
301 fn without_a_desktop_every_service_answers_instead_of_hanging;
302
303 phase unavailable_services_conform;
304 {
305 conformance::check_picker_contract(&*unavailable_picker());
306 conformance::check_opener_contract(&*unavailable_opener());
307 }
308
309 phase the_system_backends_answer_bad_requests_without_a_desktop;
310 {
311 conformance::check_picker_contract(&*system_picker());
312 conformance::check_opener_contract(&*system_opener());
313 }
314
315 phase without_a_resolver_requests_fail_rather_than_hang;
316 {
317 let outcome = PickRequest::open("Open", "Open").send().recv().unwrap();
318 assert!(matches!(outcome, PortalOutcome::Failed(_)));
319 assert!(portal::open_uri("https://example.invalid").is_err());
320 }
321 }
322
323 #[cfg(all(target_os = "linux", not(feature = "portal-client")))]
327 #[test]
328 fn an_app_process_chooses_only_through_its_session() {
329 let outcome = system_picker()
330 .pick(PickRequest::open("Open", "Open"))
331 .recv()
332 .unwrap();
333 assert!(
334 matches!(outcome, PortalOutcome::Failed(_)),
335 "an app process holds no portal"
336 );
337 }
338}