Skip to main content

tilo_dialogs/
portal.rs

1//! The file-chooser and URI-opening vocabulary: requests, outcomes and the URI
2//! to path rule every backend shares.
3//!
4//! An app never draws its own file picker and never keys open or save off an
5//! environment variable: it goes through the portal, so the host desktop
6//! provides the chooser. On Tilo the picker is also where the per-workspace
7//! sandbox file-access prompt lives, which makes this module the file-access
8//! security boundary; a per-app copy would be a second, drifting definition of
9//! which URIs may become paths. The URI mapping goes through
10//! [`url::Url::to_file_path`], never a prefix strip that turns a remote host
11//! into a relative path.
12//!
13//! The round trip opens a real host window, so it never runs on the UI thread:
14//! [`PickRequest::send`] hands the request to the host's [`crate::FilePicker`],
15//! which answers over an [`std::sync::mpsc`] channel the app drains once per
16//! frame.
17#![allow(
18    clippy::disallowed_methods,
19    reason = "native host runner: portal and file dialogs block on their own thread"
20)]
21
22mod destination;
23mod uri;
24pub use destination::{DestinationChannel, DestinationOutcome, SaveDestination};
25pub use uri::open_uri_scoped;
26#[cfg(any(test, feature = "test-support"))]
27pub use uri::{ScopedUriFixture, scoped_uri_fixture};
28
29pub trait EffectCheck: Send + 'static {
30    fn with_effect<R>(&self, effect: impl FnOnce() -> Result<R, String>) -> Result<R, String>;
31}
32
33use std::fs::File;
34#[cfg(any(unix, windows))]
35use std::fs::OpenOptions;
36use std::path::{Path, PathBuf};
37use std::sync::mpsc::Receiver;
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum PortalOutcome {
41    Opened(PathBuf),
42    Cancelled,
43    Failed(String),
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum MultiOutcome {
48    Selected(Vec<PathBuf>),
49    Cancelled,
50    Failed(String),
51}
52
53pub type PortalChannel = Receiver<PortalOutcome>;
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub enum LaunchOutcome {
57    Opened,
58    Failed(String),
59}
60
61pub type LaunchChannel = Receiver<LaunchOutcome>;
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub(crate) enum LaunchKind {
65    Open,
66    Reveal,
67}
68
69#[derive(Debug, Clone)]
70pub struct LaunchRequest {
71    pub(crate) path: PathBuf,
72    pub(crate) kind: LaunchKind,
73    pub(crate) thread_name: String,
74}
75
76impl LaunchRequest {
77    pub fn open(path: impl Into<PathBuf>) -> Self {
78        Self {
79            path: path.into(),
80            kind: LaunchKind::Open,
81            thread_name: "tilo-portal-open-path".into(),
82        }
83    }
84
85    pub fn reveal(path: impl Into<PathBuf>) -> Self {
86        Self {
87            path: path.into(),
88            kind: LaunchKind::Reveal,
89            thread_name: "tilo-portal-reveal-path".into(),
90        }
91    }
92
93    #[must_use]
94    pub fn thread_name(mut self, name: &str) -> Self {
95        self.thread_name = name.to_string();
96        self
97    }
98
99    pub fn send(self) -> LaunchChannel {
100        crate::current_picker().launch(self)
101    }
102
103    pub fn path(&self) -> &Path {
104        &self.path
105    }
106
107    pub fn is_reveal(&self) -> bool {
108        self.kind == LaunchKind::Reveal
109    }
110
111    pub fn worker_name(&self) -> &str {
112        &self.thread_name
113    }
114}
115
116/// Open a file or folder again by the reference a choice answered
117/// ([`ChosenHandle::reference`]): what a window restored on the file it showed does.
118pub fn reopen(reference: &Path, write: bool) -> OpenFileChannel {
119    crate::current_picker().reopen(reference, write)
120}
121
122pub fn open_uri(uri: &str) -> std::io::Result<()> {
123    open_uri_with(&*crate::current_opener(), uri)
124}
125
126pub fn send_open_uri(uri: &str) -> LaunchChannel {
127    let (tx, rx) = std::sync::mpsc::channel();
128    let opener = crate::current_opener();
129    let uri = uri.to_string();
130    let refused = tx.clone();
131    let spawned =
132        tilo_rt::background::Background::current().spawn("tilo-portal-open-uri", move || {
133            let _ = tx.send(match open_uri_with(&*opener, &uri) {
134                Ok(()) => LaunchOutcome::Opened,
135                Err(error) => LaunchOutcome::Failed(error.to_string()),
136            });
137        });
138    if spawned.is_err() {
139        let _ = refused.send(LaunchOutcome::Failed(
140            "this host runs no background work".to_owned(),
141        ));
142    }
143    rx
144}
145
146pub fn open_uri_detached(uri: &str) {
147    let opener = crate::current_opener();
148    let uri = uri.to_string();
149    let spawned =
150        tilo_rt::background::Background::current().spawn("tilo-portal-open-uri", move || {
151            if let Err(error) = open_uri_with(&*opener, &uri) {
152                tracing::warn!("failed to open {uri:?}: {error}");
153            }
154        });
155    if spawned.is_err() {
156        tracing::warn!("not opening a URI: this host runs no background work");
157    }
158}
159
160pub fn open_uri_with(opener: &dyn crate::UriOpener, uri: &str) -> std::io::Result<()> {
161    if uri.contains('\0') {
162        return Err(std::io::Error::new(
163            std::io::ErrorKind::InvalidInput,
164            "URI contains NUL",
165        ));
166    }
167    opener.open(uri)
168}
169
170pub struct OpenedFile {
171    /// The file a native host opened.
172    file: Option<File>,
173    /// The bytes a page chose, where there are no descriptors to hand.
174    bytes: Option<Vec<u8>>,
175    display_name: String,
176    /// What the chooser answers that reopens the same file: the documents-store path of a file a
177    /// sandboxed app was given. `None` only for a host that answers a file it cannot name again.
178    reference: Option<PathBuf>,
179    /// What a save commits when its file is finished: renaming the chosen file over the one the
180    /// person sees, so a save replaces it whole or not at all.
181    commit: Option<Box<dyn FnOnce() + Send>>,
182}
183
184impl std::fmt::Debug for OpenedFile {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        f.debug_struct("OpenedFile")
187            .field("file", &self.file)
188            .field("bytes", &self.bytes.as_ref().map(Vec::len))
189            .field("display_name", &self.display_name)
190            .field("reference", &self.reference)
191            .field("commit", &self.commit.is_some())
192            .finish()
193    }
194}
195
196impl OpenedFile {
197    #[must_use]
198    pub fn display_name(&self) -> &str {
199        &self.display_name
200    }
201
202    /// What the chooser answers to reopen the same file ([`crate::shell::ShellLink::reopen`]).
203    #[must_use]
204    pub fn reference(&self) -> Option<&Path> {
205        self.reference.as_deref()
206    }
207
208    /// The file, and the commit that finishes a save when it is dropped.
209    #[must_use]
210    pub fn into_file(self) -> PickedFile {
211        self.into_held()
212    }
213
214    /// The opened file and what names it again.
215    #[must_use]
216    pub fn into_parts(self) -> (PickedFile, Option<PathBuf>) {
217        let reference = self.reference.clone();
218        (self.into_held(), reference)
219    }
220
221    fn into_held(self) -> PickedFile {
222        let Self {
223            file,
224            bytes,
225            display_name: _,
226            reference: _,
227            commit,
228        } = self;
229        PickedFile {
230            file,
231            bytes: bytes.map(std::io::Cursor::new),
232            commit,
233        }
234    }
235}
236
237/// A file a chooser opened, kept until what writes it is done: dropping it finishes a save. A
238/// native host hands a descriptor; a page hands the bytes it read.
239pub struct PickedFile {
240    file: Option<File>,
241    bytes: Option<std::io::Cursor<Vec<u8>>>,
242    commit: Option<Box<dyn FnOnce() + Send>>,
243}
244
245impl PickedFile {
246    /// The open file. A page has none: its choice is the bytes it read.
247    #[cfg(not(target_arch = "wasm32"))]
248    #[allow(
249        clippy::expect_used,
250        reason = "a native host always opened a file; only a page holds bytes instead"
251    )]
252    fn file(&self) -> &File {
253        self.file
254            .as_ref()
255            .expect("a native host opens a file; a page holds its bytes")
256    }
257
258    /// The file itself, without finishing a save when it goes.
259    #[must_use]
260    #[allow(
261        clippy::expect_used,
262        reason = "a native host always opened a file; only a page holds bytes instead"
263    )]
264    pub fn into_std(mut self) -> File {
265        self.commit = None;
266        let file = self
267            .file
268            .take()
269            .expect("a native host opens a file; a page holds its bytes");
270        std::mem::forget(self);
271        file
272    }
273}
274
275impl std::fmt::Debug for PickedFile {
276    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
277        f.debug_struct("PickedFile")
278            .field("file", &self.file)
279            .field(
280                "bytes",
281                &self.bytes.as_ref().map(|bytes| bytes.get_ref().len()),
282            )
283            .field("commit", &self.commit.is_some())
284            .finish()
285    }
286}
287
288impl Drop for PickedFile {
289    fn drop(&mut self) {
290        if let Some(commit) = self.commit.take() {
291            commit();
292        }
293    }
294}
295
296impl std::io::Read for PickedFile {
297    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
298        match (&mut self.file, &mut self.bytes) {
299            (Some(file), _) => std::io::Read::read(file, buf),
300            (None, Some(bytes)) => std::io::Read::read(bytes, buf),
301            (None, None) => Err(no_file()),
302        }
303    }
304}
305
306impl std::io::Write for PickedFile {
307    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
308        match (&mut self.file, &mut self.bytes) {
309            (Some(file), _) => std::io::Write::write(file, buf),
310            (None, Some(bytes)) => std::io::Write::write(bytes, buf),
311            (None, None) => Err(no_file()),
312        }
313    }
314
315    fn flush(&mut self) -> std::io::Result<()> {
316        match (&mut self.file, &mut self.bytes) {
317            (Some(file), _) => std::io::Write::flush(file),
318            (None, Some(bytes)) => std::io::Write::flush(bytes),
319            (None, None) => Err(no_file()),
320        }
321    }
322}
323
324impl std::io::Seek for PickedFile {
325    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
326        match (&mut self.file, &mut self.bytes) {
327            (Some(file), _) => std::io::Seek::seek(file, pos),
328            (None, Some(bytes)) => std::io::Seek::seek(bytes, pos),
329            (None, None) => Err(no_file()),
330        }
331    }
332}
333
334#[cfg(unix)]
335impl std::os::fd::AsRawFd for PickedFile {
336    fn as_raw_fd(&self) -> std::os::fd::RawFd {
337        std::os::fd::AsRawFd::as_raw_fd(self.file())
338    }
339}
340
341fn no_file() -> std::io::Error {
342    std::io::Error::new(
343        std::io::ErrorKind::Unsupported,
344        "this host holds no open file",
345    )
346}
347
348impl PickedFile {
349    /// Metadata of the file a native host opened; a page's bytes hold none.
350    pub fn metadata(&self) -> std::io::Result<std::fs::Metadata> {
351        match &self.file {
352            Some(file) => file.metadata(),
353            None => Err(no_file()),
354        }
355    }
356
357    /// A file a page chose: its bytes, held as the file's content.
358    #[must_use]
359    pub fn from_bytes(bytes: Vec<u8>) -> Self {
360        Self {
361            file: None,
362            bytes: Some(std::io::Cursor::new(bytes)),
363            commit: None,
364        }
365    }
366}
367
368#[derive(Debug)]
369pub enum OpenFileOutcome {
370    Opened(OpenedFile),
371    Cancelled,
372    Failed(String),
373}
374
375pub type OpenFileChannel = Receiver<OpenFileOutcome>;
376
377pub type MultiChannel = Receiver<MultiOutcome>;
378
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub enum WallpaperTarget {
381    Background,
382    Lockscreen,
383    Both,
384}
385
386pub type WallpaperChannel = Receiver<Result<(), String>>;
387
388pub fn send_set_wallpaper(file: File, target: WallpaperTarget) -> WallpaperChannel {
389    #[cfg(all(target_os = "linux", feature = "portal-client"))]
390    {
391        crate::xdg::set_wallpaper(file, target)
392    }
393    #[cfg(all(target_os = "linux", not(feature = "portal-client")))]
394    {
395        let _ = (file, target);
396        let (tx, rx) = std::sync::mpsc::channel();
397        let _ = tx.send(Err(
398            "setting the wallpaper needs the desktop portal client".to_string()
399        ));
400        rx
401    }
402    #[cfg(not(target_os = "linux"))]
403    {
404        let _ = (file, target);
405        let (tx, rx) = std::sync::mpsc::channel();
406        let _ = tx.send(Err(
407            "setting the wallpaper needs the desktop portal build".to_string()
408        ));
409        rx
410    }
411}
412
413#[derive(Debug, Clone, Default, PartialEq, Eq)]
414pub struct FileFilter {
415    pub(crate) name: String,
416    pub(crate) globs: Vec<String>,
417    pub(crate) mimetypes: Vec<String>,
418}
419
420impl FileFilter {
421    pub fn new(name: &str) -> Self {
422        Self {
423            name: name.to_string(),
424            ..Default::default()
425        }
426    }
427
428    #[must_use]
429    pub fn globs(&self) -> &[String] {
430        &self.globs
431    }
432
433    #[must_use]
434    pub fn glob(mut self, g: &str) -> Self {
435        self.globs.push(g.to_string());
436        self
437    }
438
439    #[must_use]
440    pub fn mimetype(mut self, m: &str) -> Self {
441        self.mimetypes.push(m.to_string());
442        self
443    }
444
445    pub fn all_files() -> Self {
446        Self::new("All files").glob("*")
447    }
448
449    #[must_use]
450    pub fn mimetypes(&self) -> &[String] {
451        &self.mimetypes
452    }
453
454    pub fn name(&self) -> &str {
455        &self.name
456    }
457}
458
459pub const SAVE_DIRECTORY_ENV: &str = "TILO_SAVE_DIRECTORY";
460
461pub const WRITABLE_DIRECTORY_CHOICE: &str = "tilo-writable-directory";
462
463#[derive(Debug, Clone, PartialEq, Eq)]
464pub enum PickKind {
465    Open { multiple: bool },
466    Directory,
467    Save { suggested_name: String },
468}
469
470#[derive(Debug, Clone)]
471pub struct PickRequest {
472    pub(crate) title: String,
473    pub(crate) accept_label: String,
474    pub(crate) thread_name: String,
475    pub(crate) filters: Vec<FileFilter>,
476    pub(crate) kind: PickKind,
477    pub(crate) max_contents_bytes: Option<usize>,
478    pub(crate) initial_directory: Option<PathBuf>,
479    writable_directory: bool,
480}
481
482impl PickRequest {
483    pub fn open(title: &str, accept_label: &str) -> Self {
484        Self::new(title, accept_label, PickKind::Open { multiple: false })
485    }
486
487    pub fn open_multiple(title: &str, accept_label: &str) -> Self {
488        Self::new(title, accept_label, PickKind::Open { multiple: true })
489    }
490
491    pub fn directory(title: &str, accept_label: &str) -> Self {
492        Self::new(title, accept_label, PickKind::Directory)
493    }
494
495    pub fn writable_directory(title: &str, accept_label: &str) -> Self {
496        Self {
497            writable_directory: true,
498            ..Self::directory(title, accept_label)
499        }
500    }
501
502    pub fn is_writable_directory(&self) -> bool {
503        self.writable_directory
504    }
505
506    pub fn save(title: &str, accept_label: &str, suggested_name: &str) -> Self {
507        Self::new(
508            title,
509            accept_label,
510            PickKind::Save {
511                suggested_name: suggested_name.to_string(),
512            },
513        )
514    }
515
516    fn new(title: &str, accept_label: &str, kind: PickKind) -> Self {
517        Self {
518            title: title.to_string(),
519            accept_label: accept_label.to_string(),
520            thread_name: "tilo-portal".to_string(),
521            filters: Vec::new(),
522            kind,
523            max_contents_bytes: None,
524            initial_directory: None,
525            writable_directory: false,
526        }
527    }
528
529    #[must_use]
530    pub fn initial_directory(mut self, directory: impl Into<PathBuf>) -> Self {
531        self.initial_directory = Some(directory.into());
532        self
533    }
534
535    pub fn directory_hint(&self) -> Option<&Path> {
536        self.initial_directory.as_deref()
537    }
538
539    /// Bound what the app reads of a choice into memory: an Open read past this fails rather
540    /// than growing without limit. A folder's files count together.
541    #[must_use]
542    pub fn max_contents_bytes(mut self, limit: usize) -> Self {
543        self.max_contents_bytes = Some(limit);
544        self
545    }
546
547    #[must_use]
548    pub fn contents_byte_limit(&self) -> Option<usize> {
549        self.max_contents_bytes
550    }
551
552    #[must_use]
553    pub fn thread_name(mut self, name: &str) -> Self {
554        self.thread_name = name.to_string();
555        self
556    }
557
558    #[must_use]
559    pub fn filter(mut self, f: FileFilter) -> Self {
560        self.filters.push(f);
561        self
562    }
563
564    #[must_use]
565    pub fn all_files(self) -> Self {
566        self.filter(FileFilter::all_files())
567    }
568
569    pub fn title(&self) -> &str {
570        &self.title
571    }
572
573    pub fn is_multiple(&self) -> bool {
574        matches!(self.kind, PickKind::Open { multiple: true })
575    }
576
577    pub fn is_open(&self) -> bool {
578        matches!(self.kind, PickKind::Open { .. })
579    }
580
581    pub fn filter_names(&self) -> Vec<&str> {
582        self.filters.iter().map(FileFilter::name).collect()
583    }
584
585    pub fn suggested_name(&self) -> Option<&str> {
586        match &self.kind {
587            PickKind::Save { suggested_name } => Some(suggested_name.as_str()),
588            PickKind::Open { .. } | PickKind::Directory => None,
589        }
590    }
591
592    pub fn accept_label(&self) -> &str {
593        &self.accept_label
594    }
595
596    pub fn filters(&self) -> &[FileFilter] {
597        &self.filters
598    }
599
600    pub fn is_directory(&self) -> bool {
601        matches!(self.kind, PickKind::Directory)
602    }
603
604    pub fn kind(&self) -> &PickKind {
605        &self.kind
606    }
607
608    pub fn worker_name(&self) -> &str {
609        &self.thread_name
610    }
611
612    pub fn send(self) -> PortalChannel {
613        crate::current_picker().pick(self)
614    }
615
616    pub fn send_scoped(self, scope: impl EffectCheck) -> PortalChannel {
617        #[cfg(any(test, feature = "test-support"))]
618        if let Some(backend) = scoped_picker_fixture_backend() {
619            return scoped_pick_worker(scope, move || backend(self));
620        }
621        let files = crate::current_picker();
622        scoped_pick_worker(scope, move || {
623            files.pick(self).recv().unwrap_or_else(|_| {
624                PortalOutcome::Failed("The file chooser closed before you chose. Try again.".into())
625            })
626        })
627    }
628
629    /// The SDK's handle path only: an app reads a chosen file or walks a chosen folder through
630    /// [`ChosenHandle`].
631    #[doc(hidden)]
632    pub fn send_open_handle(self) -> OpenFileChannel {
633        crate::current_picker().open_handle(self)
634    }
635
636    pub fn send_save_file(self) -> OpenFileChannel {
637        crate::current_picker().save_file(self)
638    }
639
640    pub fn send_multiple(self) -> MultiChannel {
641        crate::current_picker().pick_multiple(self)
642    }
643
644    /// The SDK's save path only: an app saves through `EffectCx::choose_destination`,
645    /// whose job waits for the answer and tells the person when the chooser fails.
646    #[doc(hidden)]
647    pub fn send_save_destination(self) -> DestinationChannel {
648        crate::current_picker().save_destination(self)
649    }
650}
651
652#[derive(Debug, Clone, PartialEq, Eq)]
653pub enum SaveOutcome {
654    Saved,
655    Cancelled,
656    Failed(String),
657}
658
659pub type SaveChannel = Receiver<SaveOutcome>;
660
661const CHOOSER_GONE: &str = "The file chooser closed before you chose. Try again.";
662
663pub(crate) fn write_picked(destination: Option<PortalChannel>, bytes: Vec<u8>) -> SaveChannel {
664    let (tx, rx) = std::sync::mpsc::channel();
665    let Some(destination) = destination else {
666        let _ = tx.send(SaveOutcome::Failed(
667            "only a Save chooser saves contents".to_owned(),
668        ));
669        return rx;
670    };
671    let refused = tx.clone();
672    let spawned =
673        tilo_rt::background::Background::current().spawn("tilo-portal-write", move || {
674            let _ = tx.send(match destination.recv() {
675                Ok(PortalOutcome::Opened(path)) => match std::fs::write(&path, bytes) {
676                    Ok(()) => SaveOutcome::Saved,
677                    Err(error) => SaveOutcome::Failed(format!("{}: {error}", path.display())),
678                },
679                Ok(PortalOutcome::Cancelled) => SaveOutcome::Cancelled,
680                Ok(PortalOutcome::Failed(reason)) => SaveOutcome::Failed(reason),
681                Err(_) => SaveOutcome::Failed(CHOOSER_GONE.to_owned()),
682            });
683        });
684    if spawned.is_err() {
685        let _ = refused.send(SaveOutcome::Failed(
686            "this host runs no background work".to_owned(),
687        ));
688    }
689    rx
690}
691
692fn scoped_pick_worker(
693    scope: impl EffectCheck,
694    pick: impl FnOnce() -> PortalOutcome + Send + 'static,
695) -> PortalChannel {
696    let (sender, receiver) = std::sync::mpsc::channel();
697    let failed = sender.clone();
698    let spawned = tilo_rt::background::Background::current().spawn("ui-portal-scoped", move || {
699        let outcome = scope
700            .with_effect(|| Ok(pick()))
701            .unwrap_or_else(PortalOutcome::Failed);
702        let _ = sender.send(outcome);
703    });
704    if spawned.is_err() {
705        let _ = failed.send(PortalOutcome::Failed(
706            "this host runs no background work for a scoped chooser".into(),
707        ));
708    }
709    receiver
710}
711
712#[cfg(any(windows, target_os = "android"))]
713pub fn spawn_worker(name: &str, work: impl FnOnce() + Send + 'static) {
714    let _ = std::thread::Builder::new()
715        .name(name.to_string())
716        .spawn(work);
717}
718
719#[cfg(any(unix, windows))]
720pub fn to_local_path(uri: &url::Url) -> Option<PathBuf> {
721    use std::path::Component;
722
723    if !matches!(uri.host_str(), None | Some("" | "localhost")) {
724        return None;
725    }
726    let path = uri.to_file_path().ok()?;
727    if !path.is_absolute() {
728        return None;
729    }
730    #[cfg(windows)]
731    if !matches!(path.components().next(), Some(Component::Prefix(prefix))
732        if matches!(prefix.kind(), std::path::Prefix::Disk(_)))
733    {
734        return None;
735    }
736
737    if path
738        .components()
739        .any(|c| matches!(c, Component::ParentDir | Component::CurDir))
740    {
741        return None;
742    }
743
744    let segments = uri.path_segments()?.filter(|s| !s.is_empty()).count();
745    let components = path
746        .components()
747        .filter(|c| matches!(c, Component::Normal(_)))
748        .count();
749    #[cfg(windows)]
750    let components = components.checked_add(1)?;
751    if components != segments {
752        return None;
753    }
754
755    Some(path)
756}
757
758#[cfg(not(any(unix, windows)))]
759#[must_use]
760pub fn to_local_path(_uri: &url::Url) -> Option<PathBuf> {
761    None
762}
763
764pub fn map_uri(uris: &[url::Url]) -> PortalOutcome {
765    let Some(uri) = uris.first() else {
766        return PortalOutcome::Cancelled;
767    };
768    match to_local_path(uri) {
769        Some(path) => PortalOutcome::Opened(path),
770        None => PortalOutcome::Failed(format!("not a local file: {uri}")),
771    }
772}
773
774pub fn map_uris(uris: &[url::Url]) -> MultiOutcome {
775    if uris.is_empty() {
776        return MultiOutcome::Cancelled;
777    }
778    let paths: Vec<PathBuf> = uris.iter().filter_map(to_local_path).collect();
779    if paths.is_empty() {
780        return MultiOutcome::Failed(match uris {
781            [only] => format!("not a local file: {only}"),
782            _ => "no local files in selection".to_string(),
783        });
784    }
785    MultiOutcome::Selected(paths)
786}
787
788#[cfg(any(target_os = "linux", target_os = "macos", windows))]
789#[cfg_attr(
790    any(target_os = "linux", windows),
791    allow(
792        dead_code,
793        reason = "a Linux host opens chosen files by descriptor; the others by URI"
794    )
795)]
796pub(crate) fn open_selected_uri(uri: &url::Url) -> OpenFileOutcome {
797    let Some(path) = to_local_path(uri) else {
798        return OpenFileOutcome::Failed(format!("not a local file: {uri}"));
799    };
800    match open_regular_file(&path) {
801        Ok(file) => OpenFileOutcome::Opened(OpenedFile::at(file, &path)),
802        Err(error) => OpenFileOutcome::Failed(format!("could not open selected file: {error}")),
803    }
804}
805
806pub(crate) fn file_name_of(path: &Path) -> String {
807    path.file_name()
808        .map(|name| name.to_string_lossy().into_owned())
809        .filter(|name| !name.is_empty())
810        .unwrap_or_else(|| "selected file".to_string())
811}
812
813/// The files under a chosen folder, walked through the folder's own descriptor: what an app's
814/// folder chooser hands on, never a host path. Each is named by where it stands in the folder,
815/// symlinks and pipes are skipped, and the walk stops with an error once more than `limit` bytes
816/// would be read.
817#[cfg(unix)]
818#[allow(
819    clippy::too_many_lines,
820    reason = "one walk keeps the descriptor discipline a reader checks in one place"
821)]
822pub fn walk_chosen_folder(folder: &File, limit: usize) -> Result<Vec<(String, Vec<u8>)>, String> {
823    use std::os::fd::{AsRawFd as _, FromRawFd as _};
824
825    /// The most files one folder choice hands over.
826    const MAX_FILES: usize = 10_000;
827
828    struct Dir(*mut libc::DIR);
829    impl Drop for Dir {
830        fn drop(&mut self) {
831            // SAFETY: the directory stream was opened by `fdopendir` and is closed once.
832            unsafe { libc::closedir(self.0) };
833        }
834    }
835
836    fn walk(
837        fd: std::os::fd::RawFd,
838        prefix: &str,
839        limit: &mut usize,
840        out: &mut Vec<(String, Vec<u8>)>,
841    ) -> Result<(), String> {
842        // SAFETY: duplicating a descriptor this walk owns; the copy is closed by `Dir`.
843        let dup = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 3) };
844        if dup < 0 {
845            return Err("the chosen folder can't be read".to_owned());
846        }
847        // SAFETY: `dup` is a fresh descriptor to a directory, and `fdopendir` takes it over.
848        let raw = unsafe { libc::fdopendir(dup) };
849        if raw.is_null() {
850            // SAFETY: `fdopendir` failed, so the descriptor is still this call's to close.
851            unsafe { libc::close(dup) };
852            return Err("the chosen folder can't be read".to_owned());
853        }
854        let dir = Dir(raw);
855        loop {
856            // SAFETY: `readdir` reads the stream; the entry it answers is valid until the next
857            // call, and is copied out before one.
858            let entry = unsafe { libc::readdir(dir.0) };
859            if entry.is_null() {
860                break;
861            }
862            // SAFETY: `d_name` is a NUL-terminated name inside the entry.
863            let name = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) }
864                .to_string_lossy()
865                .into_owned();
866            if name == "." || name == ".." {
867                continue;
868            }
869            let Ok(cname) = std::ffi::CString::new(name.as_str()) else {
870                continue;
871            };
872            let relative = if prefix.is_empty() {
873                name.clone()
874            } else {
875                format!("{prefix}/{name}")
876            };
877            if out.len() >= MAX_FILES {
878                return Err("the chosen folder holds too many files".to_owned());
879            }
880            // The entry's own type, or the file's when the filesystem does not say.
881            let mut kind = unsafe { (*entry).d_type };
882            if kind == libc::DT_UNKNOWN {
883                // SAFETY: `fstatat` writes the buffer it is given, for the name at `fd`.
884                let mut stat = unsafe { std::mem::zeroed::<libc::stat>() };
885                let asked = unsafe {
886                    libc::fstatat(fd, cname.as_ptr(), &raw mut stat, libc::AT_SYMLINK_NOFOLLOW)
887                };
888                if asked != 0 {
889                    continue;
890                }
891                kind = if stat.st_mode & libc::S_IFMT == libc::S_IFDIR {
892                    libc::DT_DIR
893                } else if stat.st_mode & libc::S_IFMT == libc::S_IFREG {
894                    libc::DT_REG
895                } else {
896                    libc::DT_LNK
897                };
898            }
899            if kind == libc::DT_DIR {
900                // SAFETY: opening a name inside the chosen folder, never following a link out.
901                let sub = unsafe {
902                    libc::openat(
903                        fd,
904                        cname.as_ptr(),
905                        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
906                    )
907                };
908                if sub < 0 {
909                    continue;
910                }
911                let walked = walk(sub, &relative, limit, out);
912                // SAFETY: the descriptor was opened by this walk and nothing else holds it.
913                unsafe { libc::close(sub) };
914                walked?;
915            } else if kind == libc::DT_REG {
916                // SAFETY: opening a regular name inside the chosen folder, never a link.
917                let file = unsafe {
918                    libc::openat(
919                        fd,
920                        cname.as_ptr(),
921                        libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
922                    )
923                };
924                if file < 0 {
925                    continue;
926                }
927                // SAFETY: `file` is a fresh descriptor this walk owns.
928                let mut file = unsafe { File::from_raw_fd(file) };
929                let Ok(metadata) = file.metadata() else {
930                    continue;
931                };
932                if !metadata.is_file() {
933                    continue;
934                }
935                let size = usize::try_from(metadata.len()).unwrap_or(usize::MAX);
936                if size > *limit {
937                    return Err(
938                        "Those files are too large for the app to read. Choose fewer or smaller files."
939                            .to_owned(),
940                    );
941                }
942                let mut bytes = Vec::with_capacity(size);
943                if std::io::Read::read_to_end(&mut file, &mut bytes).is_err() {
944                    continue;
945                }
946                *limit = limit.saturating_sub(bytes.len());
947                out.push((relative, bytes));
948            }
949        }
950        Ok(())
951    }
952
953    let mut limit = limit;
954    let mut out = Vec::new();
955    walk(folder.as_raw_fd(), "", &mut limit, &mut out)?;
956    Ok(out)
957}
958
959/// [`walk_chosen_folder`] on Windows: the folder the handle is open on, walked by its final
960/// path. Links and junctions are skipped, never followed out of the folder.
961#[cfg(windows)]
962pub fn walk_chosen_folder(folder: &File, limit: usize) -> Result<Vec<(String, Vec<u8>)>, String> {
963    use std::os::windows::io::AsRawHandle as _;
964    use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;
965
966    /// The most files one folder choice hands over.
967    const MAX_FILES: usize = 10_000;
968
969    fn walk(
970        dir: &Path,
971        prefix: &str,
972        limit: &mut usize,
973        out: &mut Vec<(String, Vec<u8>)>,
974    ) -> Result<(), String> {
975        let entries =
976            std::fs::read_dir(dir).map_err(|_| "the chosen folder can't be read".to_owned())?;
977        for entry in entries.flatten() {
978            let name = entry.file_name().to_string_lossy().into_owned();
979            let relative = if prefix.is_empty() {
980                name.clone()
981            } else {
982                format!("{prefix}/{name}")
983            };
984            if out.len() >= MAX_FILES {
985                return Err("the chosen folder holds too many files".to_owned());
986            }
987            // The entry itself, never what a link or junction points at.
988            let Ok(kind) = entry.file_type() else {
989                continue;
990            };
991            if kind.is_symlink() {
992                continue;
993            }
994            if kind.is_dir() {
995                walk(&entry.path(), &relative, limit, out)?;
996            } else if kind.is_file() {
997                let Ok(mut file) = File::open(entry.path()) else {
998                    continue;
999                };
1000                let Ok(metadata) = file.metadata() else {
1001                    continue;
1002                };
1003                let size = usize::try_from(metadata.len()).unwrap_or(usize::MAX);
1004                if size > *limit {
1005                    return Err(
1006                        "Those files are too large for the app to read. Choose fewer or smaller files."
1007                            .to_owned(),
1008                    );
1009                }
1010                let mut bytes = Vec::with_capacity(size);
1011                if std::io::Read::read_to_end(&mut file, &mut bytes).is_err() {
1012                    continue;
1013                }
1014                *limit = limit.saturating_sub(bytes.len());
1015                out.push((relative, bytes));
1016            }
1017        }
1018        Ok(())
1019    }
1020
1021    let mut wide = vec![0_u16; 32_768];
1022    // SAFETY: the folder's live handle and a buffer of the length given.
1023    let length = unsafe {
1024        GetFinalPathNameByHandleW(
1025            folder.as_raw_handle(),
1026            wide.as_mut_ptr(),
1027            u32::try_from(wide.len()).unwrap_or(u32::MAX),
1028            0,
1029        )
1030    };
1031    let length = usize::try_from(length).unwrap_or(usize::MAX);
1032    if length == 0 || length >= wide.len() {
1033        return Err("the chosen folder can't be read".to_owned());
1034    }
1035    wide.truncate(length);
1036    let path =
1037        PathBuf::from(<std::ffi::OsString as std::os::windows::ffi::OsStringExt>::from_wide(&wide));
1038    let mut limit = limit;
1039    let mut out = Vec::new();
1040    walk(&path, "", &mut limit, &mut out)?;
1041    Ok(out)
1042}
1043
1044/// The chosen folder `path`, kept open for reading: what a host hands an app that walks a folder
1045/// it was given. Opening the folder itself, never a link to one.
1046#[cfg(unix)]
1047pub fn open_directory_handle(path: &Path) -> std::io::Result<File> {
1048    use std::os::unix::fs::OpenOptionsExt;
1049
1050    let file = OpenOptions::new()
1051        .read(true)
1052        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
1053        .open(path)?;
1054    if !file.metadata()?.is_dir() {
1055        return Err(std::io::Error::new(
1056            std::io::ErrorKind::InvalidInput,
1057            "selected path is not a folder",
1058        ));
1059    }
1060    Ok(file)
1061}
1062
1063#[cfg(windows)]
1064pub fn open_directory_handle(path: &Path) -> std::io::Result<File> {
1065    use std::os::windows::fs::OpenOptionsExt as _;
1066    use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
1067
1068    let file = OpenOptions::new()
1069        .read(true)
1070        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
1071        .open(path)?;
1072    if !file.metadata()?.is_dir() {
1073        return Err(std::io::Error::new(
1074            std::io::ErrorKind::InvalidInput,
1075            "selected path is not a folder",
1076        ));
1077    }
1078    Ok(file)
1079}
1080
1081#[cfg(not(any(unix, windows)))]
1082#[allow(
1083    clippy::unnecessary_wraps,
1084    reason = "a page opens no folder, and answers the same fallible call"
1085)]
1086pub fn open_directory_handle(_path: &Path) -> std::io::Result<File> {
1087    Err(std::io::Error::new(
1088        std::io::ErrorKind::Unsupported,
1089        "this host opens no folders",
1090    ))
1091}
1092
1093/// Where the chooser names what it answers with: every reference is a path under it, whether the
1094/// choice is a file of a workspace's tree or one kept in the device's records.
1095pub const DOCUMENTS_DIR: &str = "/run/tilo/chosen";
1096
1097/// Whether `path` names a chosen document rather than a file on the host: what a sandboxed app
1098/// is handed, and what a session holding the choices can reopen after a restart.
1099#[must_use]
1100pub fn is_document_reference(path: &Path) -> bool {
1101    let Some(rest) = path.strip_prefix(DOCUMENTS_DIR).ok() else {
1102        return false;
1103    };
1104    let mut parts = rest.components();
1105    // A token names the document; at least the document's own name follows it.
1106    matches!(parts.next(), Some(std::path::Component::Normal(_)))
1107        && matches!(parts.next(), Some(std::path::Component::Normal(_)))
1108}
1109
1110pub fn save_sibling(destination: &Path) -> Option<PathBuf> {
1111    let name = destination.file_name()?;
1112    let mut sibling = std::ffi::OsString::from(".");
1113    sibling.push(name);
1114    sibling.push(".tilo-save");
1115    Some(destination.with_file_name(sibling))
1116}
1117
1118pub fn replace_saved(destination: &Path, bytes: &[u8]) -> std::io::Result<()> {
1119    use std::io::Write as _;
1120    let sibling = save_sibling(destination).ok_or_else(|| {
1121        std::io::Error::new(
1122            std::io::ErrorKind::InvalidInput,
1123            "the destination names no file",
1124        )
1125    })?;
1126    let written = File::create(&sibling)
1127        .and_then(|mut file| file.write_all(bytes).and_then(|()| file.sync_all()))
1128        .and_then(|()| std::fs::rename(&sibling, destination));
1129    if written.is_err() {
1130        let _ = std::fs::remove_file(&sibling);
1131    }
1132    written
1133}
1134
1135#[cfg(unix)]
1136pub fn open_regular_file(path: &Path) -> std::io::Result<File> {
1137    use std::os::unix::fs::OpenOptionsExt;
1138
1139    let file = OpenOptions::new()
1140        .read(true)
1141        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
1142        .open(path)?;
1143    if !file.metadata()?.file_type().is_file() {
1144        return Err(std::io::Error::new(
1145            std::io::ErrorKind::InvalidInput,
1146            "selected path is not a regular file",
1147        ));
1148    }
1149    Ok(file)
1150}
1151
1152#[cfg(windows)]
1153pub fn open_regular_file(path: &Path) -> std::io::Result<File> {
1154    use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
1155    use windows_sys::Win32::Storage::FileSystem::{
1156        FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT,
1157    };
1158    let file = OpenOptions::new()
1159        .read(true)
1160        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
1161        .open(path)?;
1162    let metadata = file.metadata()?;
1163    if !metadata.is_file() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
1164        return Err(std::io::Error::new(
1165            std::io::ErrorKind::InvalidInput,
1166            "selected path is not a regular file",
1167        ));
1168    }
1169    Ok(file)
1170}
1171
1172impl OpenedFile {
1173    #[must_use]
1174    pub fn new(file: File, display_name: impl Into<String>) -> Self {
1175        Self {
1176            file: Some(file),
1177            bytes: None,
1178            display_name: display_name.into(),
1179            reference: None,
1180            commit: None,
1181        }
1182    }
1183
1184    /// A file opened at `path` on a host whose files have paths: the path names it again.
1185    #[must_use]
1186    pub fn at(file: File, path: &Path) -> Self {
1187        Self {
1188            file: Some(file),
1189            bytes: None,
1190            display_name: file_name_of(path),
1191            reference: Some(path.to_path_buf()),
1192            commit: None,
1193        }
1194    }
1195
1196    /// A file a page chose: the bytes it read, named by the name the chooser answered. A page
1197    /// keeps no descriptor, so the bytes are the handle's form.
1198    #[must_use]
1199    pub fn from_bytes(bytes: Vec<u8>, display_name: impl Into<String>, reference: PathBuf) -> Self {
1200        Self {
1201            file: None,
1202            bytes: Some(bytes),
1203            display_name: display_name.into(),
1204            reference: Some(reference),
1205            commit: None,
1206        }
1207    }
1208
1209    /// A file or folder the chooser reopened by its reference, called what the chooser calls it.
1210    #[cfg(any(unix, windows))]
1211    #[must_use]
1212    pub(crate) fn named(file: File, display_name: impl Into<String>, reference: PathBuf) -> Self {
1213        Self {
1214            file: Some(file),
1215            bytes: None,
1216            display_name: display_name.into(),
1217            reference: Some(reference),
1218            commit: None,
1219        }
1220    }
1221
1222    /// What a save commits when its file is finished: renaming the file it writes over the one
1223    /// the person chose, so it is replaced whole or not at all.
1224    #[cfg(any(unix, windows))]
1225    #[must_use]
1226    pub(crate) fn keeping(
1227        file: File,
1228        display_name: impl Into<String>,
1229        reference: PathBuf,
1230        commit: impl FnOnce() + Send + 'static,
1231    ) -> Self {
1232        Self {
1233            file: Some(file),
1234            bytes: None,
1235            display_name: display_name.into(),
1236            reference: Some(reference),
1237            commit: Some(Box::new(commit)),
1238        }
1239    }
1240}
1241
1242/// A chosen file or folder, kept open: what a host hands an app for a file it reads in place.
1243#[derive(Debug)]
1244pub struct ChosenHandle {
1245    file: PickedFile,
1246    reference: PathBuf,
1247    name: String,
1248}
1249
1250impl ChosenHandle {
1251    /// A handle on a file the host keeps open, named by what reopens it.
1252    #[must_use]
1253    pub fn new(file: File, reference: PathBuf, name: impl Into<String>) -> Self {
1254        Self {
1255            file: PickedFile {
1256                file: Some(file),
1257                bytes: None,
1258                commit: None,
1259            },
1260            reference,
1261            name: name.into(),
1262        }
1263    }
1264
1265    /// [`Self::new`] for the file a chooser answered, with what finishes it when it goes.
1266    #[must_use]
1267    pub fn from_picked(file: PickedFile, reference: PathBuf, name: impl Into<String>) -> Self {
1268        Self {
1269            file,
1270            reference,
1271            name: name.into(),
1272        }
1273    }
1274
1275    /// The opened file, or the opened folder. A page has none: its choice is the bytes it read.
1276    #[cfg(not(target_arch = "wasm32"))]
1277    #[must_use]
1278    pub fn file(&self) -> &File {
1279        self.file.as_ref()
1280    }
1281
1282    #[must_use]
1283    pub fn into_file(self) -> PickedFile {
1284        self.file
1285    }
1286
1287    /// What the chooser answers to reopen the same file or folder.
1288    #[must_use]
1289    pub fn reference(&self) -> &Path {
1290        &self.reference
1291    }
1292
1293    #[must_use]
1294    pub fn name(&self) -> &str {
1295        &self.name
1296    }
1297}
1298
1299#[cfg(not(target_arch = "wasm32"))]
1300impl PickedFile {
1301    fn as_ref(&self) -> &File {
1302        self.file()
1303    }
1304}
1305
1306impl PortalOutcome {
1307    pub fn path(&self) -> Option<&Path> {
1308        match self {
1309            PortalOutcome::Opened(p) => Some(p.as_path()),
1310            _ => None,
1311        }
1312    }
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318
1319    fn u(s: &str) -> url::Url {
1320        #[cfg(windows)]
1321        let s = &s
1322            .replace("file:///", "file:///C:/")
1323            .replace("file://localhost/", "file://localhost/C:/");
1324        url::Url::parse(s).unwrap()
1325    }
1326
1327    fn local_path(s: &str) -> PathBuf {
1328        #[cfg(windows)]
1329        return PathBuf::from(format!("C:{s}"));
1330        #[cfg(not(windows))]
1331        PathBuf::from(s)
1332    }
1333
1334    tilo_test_env::scenario! {
1335        fn a_request_records_what_the_app_asked_for_and_an_outcome_what_was_picked;
1336
1337        phase writable_directory_is_explicit_and_preserves_directory_shape;
1338        {
1339            let read = PickRequest::directory("Read folder", "Choose");
1340            let write = PickRequest::writable_directory("Import into folder", "Import here");
1341            assert!(!read.is_writable_directory());
1342            assert!(write.is_writable_directory());
1343            assert!(write.is_directory());
1344            assert!(!write.is_open());
1345            assert!(!write.is_multiple());
1346            assert_eq!(write.suggested_name(), None);
1347            assert_eq!(write.accept_label(), "Import here");
1348        }
1349
1350        phase directory_request_is_single_select_and_has_no_filename;
1351        {
1352            let request = PickRequest::directory("Choose folder", "Choose");
1353            assert!(!request.is_multiple());
1354            assert_eq!(request.suggested_name(), None);
1355            assert!(matches!(request.kind, PickKind::Directory));
1356        }
1357
1358        phase directory_hint_preserves_the_requested_folder_without_granting_it;
1359        {
1360            let home = local_path("/Users/you/Recognized home");
1361            let request =
1362                PickRequest::directory("Allow this folder", "Allow").initial_directory(home.clone());
1363            assert_eq!(request.directory_hint(), Some(home.as_path()));
1364            assert!(request.is_directory());
1365            assert_eq!(request.suggested_name(), None);
1366            assert_eq!(
1367                PickRequest::directory("Choose", "Allow").directory_hint(),
1368                None
1369            );
1370        }
1371
1372        phase launch_request_records_open_and_reveal_without_changing_the_path;
1373        {
1374            let open = LaunchRequest::open("/tmp/archive.zip");
1375            assert_eq!(open.path, Path::new("/tmp/archive.zip"));
1376            assert_eq!(open.kind, LaunchKind::Open);
1377            let reveal = LaunchRequest::reveal("/tmp/archive.zip");
1378            assert_eq!(reveal.path, Path::new("/tmp/archive.zip"));
1379            assert_eq!(reveal.kind, LaunchKind::Reveal);
1380        }
1381
1382        phase outcome_path_accessor_reports_only_a_real_pick;
1383        {
1384            assert_eq!(
1385                PortalOutcome::Opened(PathBuf::from("/tmp/a")).path(),
1386                Some(Path::new("/tmp/a"))
1387            );
1388            assert_eq!(PortalOutcome::Cancelled.path(), None);
1389            assert_eq!(PortalOutcome::Failed("x".into()).path(), None);
1390        }
1391
1392        phase builder_records_the_per_app_delta;
1393        {
1394            let r = PickRequest::open("Insert image", "Insert")
1395                .thread_name("wp-portal-open")
1396                .filter(
1397                    FileFilter::new("Images")
1398                        .glob("*.png")
1399                        .mimetype("image/png"),
1400                )
1401                .all_files();
1402            assert_eq!(r.title(), "Insert image");
1403            assert!(!r.is_multiple());
1404            assert_eq!(r.filters.len(), 2);
1405            assert_eq!(r.filters[0].name(), "Images");
1406            assert_eq!(r.filters[0].globs, ["*.png"]);
1407            assert_eq!(r.filters[0].mimetypes, ["image/png"]);
1408            assert_eq!(
1409                r.filters[1],
1410                FileFilter::all_files(),
1411                "escape hatch is last"
1412            );
1413            assert_eq!(r.thread_name, "wp-portal-open");
1414
1415            assert!(PickRequest::open_multiple("Import contacts", "Import").is_multiple());
1416            let s = PickRequest::save("Export contacts", "Export", "contacts.vcf");
1417            assert!(!s.is_multiple());
1418            assert_eq!(
1419                s.kind,
1420                PickKind::Save {
1421                    suggested_name: "contacts.vcf".into()
1422                }
1423            );
1424        }
1425    }
1426
1427    tilo_test_env::scenario! {
1428        fn a_file_uri_becomes_a_local_path_only_when_it_names_one;
1429
1430        phase rejects_a_uri_that_names_a_remote_host;
1431        {
1432            let uri = u("file://evil-host.example.com/etc/passwd");
1433
1434            assert_eq!(
1435                to_local_path(&uri),
1436                None,
1437                "a foreign host is not a local path"
1438            );
1439            assert!(
1440                matches!(
1441                    map_uri(std::slice::from_ref(&uri)),
1442                    PortalOutcome::Failed(_)
1443                ),
1444                "a foreign-host URI must not become an openable path"
1445            );
1446            assert!(matches!(map_uris(&[uri]), MultiOutcome::Failed(_)));
1447        }
1448
1449        phase a_rejected_host_never_yields_a_relative_path;
1450        {
1451            for s in [
1452                "file://evil-host.example.com/etc/passwd",
1453                "file://192.0.2.1/srv/secret",
1454                "https://example.com/remote.png",
1455                "smb://fileserver/share/doc.odt",
1456            ] {
1457                let out = map_uri(&[u(s)]);
1458                if let PortalOutcome::Opened(p) = &out {
1459                    panic!("{s} was accepted as {p:?}");
1460                }
1461                assert!(matches!(out, PortalOutcome::Failed(_)), "{s} must fail");
1462            }
1463        }
1464
1465        phase localhost_is_the_local_machine;
1466        {
1467            assert_eq!(
1468                map_uri(&[u("file://localhost/home/alice/a.mkv")]),
1469                PortalOutcome::Opened(local_path("/home/alice/a.mkv"))
1470            );
1471        }
1472
1473        phase percent_escapes_in_filenames_are_decoded;
1474        {
1475            assert_eq!(
1476                map_uri(&[u("file:///home/alice/My%20Clip.mp4")]),
1477                PortalOutcome::Opened(local_path("/home/alice/My Clip.mp4"))
1478            );
1479            assert_eq!(
1480                map_uri(&[u("file:///home/alice/%C3%A9t%C3%A9%20caf%C3%A9.mp3")]),
1481                PortalOutcome::Opened(local_path("/home/alice/été café.mp3"))
1482            );
1483            assert_eq!(
1484                map_uri(&[u("file:///home/alice/a%23b%3Fc%25d.txt")]),
1485                PortalOutcome::Opened(local_path("/home/alice/a#b?c%d.txt"))
1486            );
1487        }
1488
1489        phase a_plus_in_a_path_stays_a_plus;
1490        {
1491            assert_eq!(
1492                map_uri(&[u("file:///home/alice/my+song.mp3")]),
1493                PortalOutcome::Opened(local_path("/home/alice/my+song.mp3"))
1494            );
1495        }
1496
1497        phase an_escaped_separator_does_not_become_a_new_path_component;
1498        {
1499            assert_eq!(
1500                to_local_path(&u("file:///home/alice/a%2Fb.txt")),
1501                None,
1502                "an escaped separator must not add a path component"
1503            );
1504            assert!(matches!(
1505                map_uri(&[u("file:///home/alice/a%2Fb.txt")]),
1506                PortalOutcome::Failed(_)
1507            ));
1508        }
1509
1510        phase a_parent_hop_hidden_inside_one_segment_is_rejected;
1511        {
1512            for s in [
1513                "file:///home/alice/%2E%2E%2F%2E%2E%2Fetc/shadow",
1514                "file:///var/workspace/%2E%2E%2Fetc/shadow",
1515            ] {
1516                assert_eq!(to_local_path(&u(s)), None, "{s} must not resolve");
1517                assert!(matches!(map_uri(&[u(s)]), PortalOutcome::Failed(_)), "{s}");
1518            }
1519        }
1520
1521        phase a_dot_dot_segment_is_resolved_by_uri_normalisation_not_smuggled;
1522        {
1523            let uri = u("file:///home/alice/%2E%2E/%2E%2E/etc/shadow");
1524            assert_eq!(
1525                to_local_path(&uri),
1526                Some(local_path("/etc/shadow")),
1527                "the URI normalises on parse"
1528            );
1529            assert_eq!(to_local_path(&uri), Some(local_path("/etc/shadow")));
1530        }
1531
1532        phase ordinary_nested_paths_still_resolve;
1533        {
1534            for (uri, want) in [
1535                ("file:///a.txt", "/a.txt"),
1536                (
1537                    "file:///home/alice/Documents/report.pdf",
1538                    "/home/alice/Documents/report.pdf",
1539                ),
1540                (
1541                    "file:///var/workspace/deep/er/still/x.odp",
1542                    "/var/workspace/deep/er/still/x.odp",
1543                ),
1544                (
1545                    "file:///home/alice/dot.name.with.dots.tar.gz",
1546                    "/home/alice/dot.name.with.dots.tar.gz",
1547                ),
1548            ] {
1549                assert_eq!(
1550                    to_local_path(&u(uri)),
1551                    Some(local_path(want)),
1552                    "{uri} must resolve normally"
1553                );
1554            }
1555        }
1556
1557        phase workspace_paths_resolve_through_the_fuse_mount;
1558        {
1559            assert_eq!(
1560                map_uri(&[u("file:///var/workspace/media/a.mkv")]),
1561                PortalOutcome::Opened(local_path("/var/workspace/media/a.mkv"))
1562            );
1563        }
1564    }
1565
1566    #[cfg(windows)]
1567    #[test]
1568    fn windows_drive_paths_roundtrip_without_accepting_unc_or_escaped_separators() {
1569        let uri = url::Url::parse("file:///C:/Users/Alice/My%20notes.txt").unwrap();
1570        assert_eq!(
1571            to_local_path(&uri),
1572            Some(PathBuf::from("C:/Users/Alice/My notes.txt"))
1573        );
1574        for rejected in [
1575            "file://server/share/notes.txt",
1576            "file:///C:/Users/Alice/a%5Cb.txt",
1577            "file:///C:/Users/Alice/a%2Fb.txt",
1578            "file:///Users/Alice/notes.txt",
1579        ] {
1580            assert_eq!(
1581                to_local_path(&url::Url::parse(rejected).unwrap()),
1582                None,
1583                "{rejected}"
1584            );
1585        }
1586    }
1587
1588    tilo_test_env::scenario! {
1589        fn a_selection_maps_to_the_local_files_it_names;
1590
1591        phase empty_is_cancel;
1592        {
1593            assert_eq!(map_uri(&[]), PortalOutcome::Cancelled);
1594            assert_eq!(map_uris(&[]), MultiOutcome::Cancelled);
1595        }
1596
1597        phase single_takes_the_first_local_file;
1598        {
1599            let uris = [
1600                u("file:///home/alice/photo.png"),
1601                u("file:///home/alice/other.png"),
1602            ];
1603            assert_eq!(
1604                map_uri(&uris),
1605                PortalOutcome::Opened(local_path("/home/alice/photo.png"))
1606            );
1607        }
1608
1609        phase multi_collects_every_local_file;
1610        {
1611            let uris = [
1612                u("file:///home/alice/work.vcf"),
1613                u("file:///home/alice/family.vcard"),
1614            ];
1615            assert_eq!(
1616                map_uris(&uris),
1617                MultiOutcome::Selected(vec![
1618                    local_path("/home/alice/work.vcf"),
1619                    local_path("/home/alice/family.vcard"),
1620                ])
1621            );
1622        }
1623
1624        phase multi_skips_remote_but_keeps_local;
1625        {
1626            let uris = [
1627                u("https://example.com/remote.vcf"),
1628                u("file:///home/alice/local.vcf"),
1629            ];
1630            assert_eq!(
1631                map_uris(&uris),
1632                MultiOutcome::Selected(vec![local_path("/home/alice/local.vcf")]),
1633                "a mixed multi-selection keeps the files the user can actually read"
1634            );
1635        }
1636
1637        phase multi_all_remote_is_failure;
1638        {
1639            assert!(matches!(
1640                map_uris(&[
1641                    u("https://example.com/a.vcf"),
1642                    u("https://example.com/b.vcf")
1643                ]),
1644                MultiOutcome::Failed(_)
1645            ));
1646        }
1647    }
1648
1649    tilo_test_env::scenario! {
1650        #[cfg(any(target_os = "linux", target_os = "macos", windows))]
1651        fn descriptor_open_holds_the_file_it_opened_and_refuses_a_directory;
1652
1653        phase descriptor_open_retains_the_opened_file_and_a_separate_display_name;
1654        {
1655            use std::io::{Read, Write};
1656
1657            let dir = tempfile::tempdir().unwrap();
1658            let path = dir.path().join("original-installer.msi");
1659            let mut source = File::create(&path).unwrap();
1660            source.write_all(b"installer bytes").unwrap();
1661            source.flush().unwrap();
1662            let uri = url::Url::from_file_path(&path).unwrap();
1663
1664            let opened = match open_selected_uri(&uri) {
1665                OpenFileOutcome::Opened(opened) => opened,
1666                OpenFileOutcome::Cancelled | OpenFileOutcome::Failed(_) => {
1667                    panic!("regular temporary file must open")
1668                }
1669            };
1670            assert_eq!(opened.display_name(), "original-installer.msi");
1671            std::fs::remove_file(&path).unwrap();
1672            std::fs::write(&path, b"replacement bytes").unwrap();
1673            let mut contents = String::new();
1674            let mut file = opened.into_file();
1675            file.read_to_string(&mut contents).unwrap();
1676            assert_eq!(contents, "installer bytes");
1677        }
1678
1679        phase descriptor_open_refuses_a_non_regular_file;
1680        {
1681            let dir = tempfile::tempdir().unwrap();
1682            let uri = url::Url::from_file_path(dir.path()).unwrap();
1683
1684            assert!(matches!(
1685                open_selected_uri(&uri),
1686                OpenFileOutcome::Failed(_)
1687            ));
1688        }
1689    }
1690
1691    #[cfg(unix)]
1692    #[test]
1693    fn descriptor_open_refuses_a_symlink() {
1694        use std::os::unix::fs::symlink;
1695
1696        let dir = tempfile::tempdir().unwrap();
1697        let target = dir.path().join("installer.exe");
1698        std::fs::write(&target, b"installer bytes").unwrap();
1699        let link = dir.path().join("selected.exe");
1700        symlink(&target, &link).unwrap();
1701        let uri = url::Url::from_file_path(&link).unwrap();
1702
1703        assert!(matches!(
1704            open_selected_uri(&uri),
1705            OpenFileOutcome::Failed(_)
1706        ));
1707    }
1708}
1709#[cfg(any(test, feature = "test-support"))]
1710type ScopedPickerBackend = std::sync::Arc<dyn Fn(PickRequest) -> PortalOutcome + Send + Sync>;
1711#[cfg(any(test, feature = "test-support"))]
1712thread_local! {
1713    static SCOPED_PICKER_FIXTURE: std::cell::RefCell<Option<ScopedPickerBackend>> = const { std::cell::RefCell::new(None) };
1714}
1715#[cfg(any(test, feature = "test-support"))]
1716pub struct ScopedPickerFixture {
1717    _owner_thread: std::marker::PhantomData<std::rc::Rc<()>>,
1718}
1719#[cfg(any(test, feature = "test-support"))]
1720pub fn scoped_picker_fixture(backend: ScopedPickerBackend) -> Result<ScopedPickerFixture, String> {
1721    SCOPED_PICKER_FIXTURE.with(|current| {
1722        let mut current = current.borrow_mut();
1723        if current.is_some() {
1724            return Err("this UI thread already owns a picker fixture".into());
1725        }
1726        *current = Some(backend);
1727        Ok(ScopedPickerFixture {
1728            _owner_thread: std::marker::PhantomData,
1729        })
1730    })
1731}
1732#[cfg(any(test, feature = "test-support"))]
1733fn scoped_picker_fixture_backend() -> Option<ScopedPickerBackend> {
1734    SCOPED_PICKER_FIXTURE.with(|current| current.borrow().clone())
1735}
1736#[cfg(any(test, feature = "test-support"))]
1737impl Drop for ScopedPickerFixture {
1738    fn drop(&mut self) {
1739        SCOPED_PICKER_FIXTURE.with(|current| *current.borrow_mut() = None);
1740    }
1741}
1742
1743#[cfg(test)]
1744#[test]
1745fn writer_scoped_picker_fixture_is_thread_local_and_released_by_guard() {
1746    use std::sync::Arc;
1747    assert!(scoped_picker_fixture_backend().is_none());
1748    let guard = scoped_picker_fixture(Arc::new(|_| PortalOutcome::Cancelled)).unwrap();
1749    assert!(scoped_picker_fixture_backend().is_some());
1750    assert!(scoped_picker_fixture(Arc::new(|_| PortalOutcome::Cancelled)).is_err());
1751    assert!(
1752        std::thread::spawn(|| scoped_picker_fixture_backend().is_none())
1753            .join()
1754            .unwrap()
1755    );
1756    drop(guard);
1757    assert!(scoped_picker_fixture_backend().is_none());
1758}