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/// What one entry of a chosen folder is.
814#[derive(Clone, Copy, Debug, PartialEq, Eq)]
815pub enum ChosenKind {
816    Folder,
817    File,
818    /// A link, a pipe or a device: never followed or read.
819    Other,
820}
821
822/// One entry of a chosen folder, as the folder's own descriptor answers it.
823#[derive(Clone, Debug, PartialEq, Eq)]
824pub struct ChosenEntry {
825    pub name: String,
826    pub kind: ChosenKind,
827    /// Its size in bytes.
828    pub size: u64,
829    /// When its content last changed, in Unix seconds.
830    pub modified: i64,
831}
832
833/// The entries of the folder open at `fd`, read through the descriptor alone: nothing beneath it
834/// is opened, and a link is told as one, never followed. A name that is not text, or an entry
835/// gone between reading the folder and asking about it, is left out.
836///
837/// # Errors
838/// The descriptor is no folder that can be read.
839#[cfg(unix)]
840pub fn chosen_folder_entries(fd: std::os::fd::RawFd) -> Result<Vec<ChosenEntry>, String> {
841    struct Dir(*mut libc::DIR);
842    impl Drop for Dir {
843        fn drop(&mut self) {
844            // SAFETY: the directory stream was opened by `fdopendir` and is closed once.
845            unsafe { libc::closedir(self.0) };
846        }
847    }
848
849    // SAFETY: duplicating a descriptor the caller holds open; the copy is closed by `Dir`.
850    let dup = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 3) };
851    if dup < 0 {
852        return Err("the chosen folder can't be read".to_owned());
853    }
854    // SAFETY: `dup` is a fresh descriptor to a directory, and `fdopendir` takes it over.
855    let raw = unsafe { libc::fdopendir(dup) };
856    if raw.is_null() {
857        // SAFETY: `fdopendir` failed, so the descriptor is still this call's to close.
858        unsafe { libc::close(dup) };
859        return Err("the chosen folder can't be read".to_owned());
860    }
861    let dir = Dir(raw);
862    let mut entries = Vec::new();
863    loop {
864        // SAFETY: `readdir` reads the stream; the entry it answers is valid until the next call,
865        // and is copied out before one.
866        let entry = unsafe { libc::readdir(dir.0) };
867        if entry.is_null() {
868            break;
869        }
870        // SAFETY: `d_name` is a NUL-terminated name inside the entry.
871        let name = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) };
872        if matches!(name.to_bytes(), b"." | b"..") {
873            continue;
874        }
875        let Ok(text) = name.to_str() else {
876            continue;
877        };
878        // SAFETY: `fstatat` writes the buffer it is given, for the name at `fd`.
879        let mut stat = unsafe { std::mem::zeroed::<libc::stat>() };
880        let asked =
881            unsafe { libc::fstatat(fd, name.as_ptr(), &raw mut stat, libc::AT_SYMLINK_NOFOLLOW) };
882        if asked != 0 {
883            continue;
884        }
885        let kind = match stat.st_mode & libc::S_IFMT {
886            libc::S_IFDIR => ChosenKind::Folder,
887            libc::S_IFREG => ChosenKind::File,
888            _ => ChosenKind::Other,
889        };
890        entries.push(ChosenEntry {
891            name: text.to_owned(),
892            kind,
893            size: u64::try_from(stat.st_size).unwrap_or(0),
894            modified: stat.st_mtime,
895        });
896    }
897    Ok(entries)
898}
899
900/// The files under a chosen folder, walked through the folder's own descriptor: what an app's
901/// folder chooser hands on, never a host path. Each is named by where it stands in the folder,
902/// symlinks and pipes are skipped, and the walk stops with an error once more than `limit` bytes
903/// would be read.
904#[cfg(unix)]
905pub fn walk_chosen_folder(folder: &File, limit: usize) -> Result<Vec<(String, Vec<u8>)>, String> {
906    use std::os::fd::{AsRawFd as _, FromRawFd as _};
907
908    /// The most files one folder choice hands over.
909    const MAX_FILES: usize = 10_000;
910
911    fn walk(
912        fd: std::os::fd::RawFd,
913        prefix: &str,
914        limit: &mut usize,
915        out: &mut Vec<(String, Vec<u8>)>,
916    ) -> Result<(), String> {
917        for entry in chosen_folder_entries(fd)? {
918            let Ok(cname) = std::ffi::CString::new(entry.name.as_str()) else {
919                continue;
920            };
921            let relative = if prefix.is_empty() {
922                entry.name.clone()
923            } else {
924                format!("{prefix}/{}", entry.name)
925            };
926            if out.len() >= MAX_FILES {
927                return Err("the chosen folder holds too many files".to_owned());
928            }
929            match entry.kind {
930                ChosenKind::Folder => {
931                    // SAFETY: opening a name inside the chosen folder, never following a link out.
932                    let sub = unsafe {
933                        libc::openat(
934                            fd,
935                            cname.as_ptr(),
936                            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
937                        )
938                    };
939                    if sub < 0 {
940                        continue;
941                    }
942                    let walked = walk(sub, &relative, limit, out);
943                    // SAFETY: the descriptor was opened by this walk and nothing else holds it.
944                    unsafe { libc::close(sub) };
945                    walked?;
946                }
947                ChosenKind::File => {
948                    // SAFETY: opening a regular name inside the chosen folder, never a link.
949                    let file = unsafe {
950                        libc::openat(
951                            fd,
952                            cname.as_ptr(),
953                            libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
954                        )
955                    };
956                    if file < 0 {
957                        continue;
958                    }
959                    // SAFETY: `file` is a fresh descriptor this walk owns.
960                    let mut file = unsafe { File::from_raw_fd(file) };
961                    let Ok(metadata) = file.metadata() else {
962                        continue;
963                    };
964                    if !metadata.is_file() {
965                        continue;
966                    }
967                    let size = usize::try_from(metadata.len()).unwrap_or(usize::MAX);
968                    if size > *limit {
969                        return Err(
970                            "Those files are too large for the app to read. Choose fewer or smaller files."
971                                .to_owned(),
972                        );
973                    }
974                    let mut bytes = Vec::with_capacity(size);
975                    if std::io::Read::read_to_end(&mut file, &mut bytes).is_err() {
976                        continue;
977                    }
978                    *limit = limit.saturating_sub(bytes.len());
979                    out.push((relative, bytes));
980                }
981                ChosenKind::Other => {}
982            }
983        }
984        Ok(())
985    }
986
987    let mut limit = limit;
988    let mut out = Vec::new();
989    walk(folder.as_raw_fd(), "", &mut limit, &mut out)?;
990    Ok(out)
991}
992
993/// [`walk_chosen_folder`] on Windows: the folder the handle is open on, walked by its final
994/// path. Links and junctions are skipped, never followed out of the folder.
995#[cfg(windows)]
996pub fn walk_chosen_folder(folder: &File, limit: usize) -> Result<Vec<(String, Vec<u8>)>, String> {
997    use std::os::windows::io::AsRawHandle as _;
998    use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;
999
1000    /// The most files one folder choice hands over.
1001    const MAX_FILES: usize = 10_000;
1002
1003    fn walk(
1004        dir: &Path,
1005        prefix: &str,
1006        limit: &mut usize,
1007        out: &mut Vec<(String, Vec<u8>)>,
1008    ) -> Result<(), String> {
1009        let entries =
1010            std::fs::read_dir(dir).map_err(|_| "the chosen folder can't be read".to_owned())?;
1011        for entry in entries.flatten() {
1012            let name = entry.file_name().to_string_lossy().into_owned();
1013            let relative = if prefix.is_empty() {
1014                name.clone()
1015            } else {
1016                format!("{prefix}/{name}")
1017            };
1018            if out.len() >= MAX_FILES {
1019                return Err("the chosen folder holds too many files".to_owned());
1020            }
1021            // The entry itself, never what a link or junction points at.
1022            let Ok(kind) = entry.file_type() else {
1023                continue;
1024            };
1025            if kind.is_symlink() {
1026                continue;
1027            }
1028            if kind.is_dir() {
1029                walk(&entry.path(), &relative, limit, out)?;
1030            } else if kind.is_file() {
1031                let Ok(mut file) = File::open(entry.path()) else {
1032                    continue;
1033                };
1034                let Ok(metadata) = file.metadata() else {
1035                    continue;
1036                };
1037                let size = usize::try_from(metadata.len()).unwrap_or(usize::MAX);
1038                if size > *limit {
1039                    return Err(
1040                        "Those files are too large for the app to read. Choose fewer or smaller files."
1041                            .to_owned(),
1042                    );
1043                }
1044                let mut bytes = Vec::with_capacity(size);
1045                if std::io::Read::read_to_end(&mut file, &mut bytes).is_err() {
1046                    continue;
1047                }
1048                *limit = limit.saturating_sub(bytes.len());
1049                out.push((relative, bytes));
1050            }
1051        }
1052        Ok(())
1053    }
1054
1055    let mut wide = vec![0_u16; 32_768];
1056    // SAFETY: the folder's live handle and a buffer of the length given.
1057    let length = unsafe {
1058        GetFinalPathNameByHandleW(
1059            folder.as_raw_handle(),
1060            wide.as_mut_ptr(),
1061            u32::try_from(wide.len()).unwrap_or(u32::MAX),
1062            0,
1063        )
1064    };
1065    let length = usize::try_from(length).unwrap_or(usize::MAX);
1066    if length == 0 || length >= wide.len() {
1067        return Err("the chosen folder can't be read".to_owned());
1068    }
1069    wide.truncate(length);
1070    let path =
1071        PathBuf::from(<std::ffi::OsString as std::os::windows::ffi::OsStringExt>::from_wide(&wide));
1072    let mut limit = limit;
1073    let mut out = Vec::new();
1074    walk(&path, "", &mut limit, &mut out)?;
1075    Ok(out)
1076}
1077
1078/// The chosen folder `path`, kept open for reading: what a host hands an app that walks a folder
1079/// it was given. Opening the folder itself, never a link to one.
1080#[cfg(unix)]
1081pub fn open_directory_handle(path: &Path) -> std::io::Result<File> {
1082    use std::os::unix::fs::OpenOptionsExt;
1083
1084    let file = OpenOptions::new()
1085        .read(true)
1086        .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
1087        .open(path)?;
1088    if !file.metadata()?.is_dir() {
1089        return Err(std::io::Error::new(
1090            std::io::ErrorKind::InvalidInput,
1091            "selected path is not a folder",
1092        ));
1093    }
1094    Ok(file)
1095}
1096
1097#[cfg(windows)]
1098pub fn open_directory_handle(path: &Path) -> std::io::Result<File> {
1099    use std::os::windows::fs::OpenOptionsExt as _;
1100    use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
1101
1102    let file = OpenOptions::new()
1103        .read(true)
1104        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
1105        .open(path)?;
1106    if !file.metadata()?.is_dir() {
1107        return Err(std::io::Error::new(
1108            std::io::ErrorKind::InvalidInput,
1109            "selected path is not a folder",
1110        ));
1111    }
1112    Ok(file)
1113}
1114
1115#[cfg(not(any(unix, windows)))]
1116#[allow(
1117    clippy::unnecessary_wraps,
1118    reason = "a page opens no folder, and answers the same fallible call"
1119)]
1120pub fn open_directory_handle(_path: &Path) -> std::io::Result<File> {
1121    Err(std::io::Error::new(
1122        std::io::ErrorKind::Unsupported,
1123        "this host opens no folders",
1124    ))
1125}
1126
1127/// Where the chooser names what it answers with: every reference is a path under it, whether the
1128/// choice is a file of a workspace's tree or one kept in the device's records.
1129pub const DOCUMENTS_DIR: &str = "/run/tilo/chosen";
1130
1131/// Whether `path` names a chosen document rather than a file on the host: what a sandboxed app
1132/// is handed, and what a session holding the choices can reopen after a restart.
1133#[must_use]
1134pub fn is_document_reference(path: &Path) -> bool {
1135    let Some(rest) = path.strip_prefix(DOCUMENTS_DIR).ok() else {
1136        return false;
1137    };
1138    let mut parts = rest.components();
1139    // A token names the document; at least the document's own name follows it.
1140    matches!(parts.next(), Some(std::path::Component::Normal(_)))
1141        && matches!(parts.next(), Some(std::path::Component::Normal(_)))
1142}
1143
1144pub fn save_sibling(destination: &Path) -> Option<PathBuf> {
1145    let name = destination.file_name()?;
1146    let mut sibling = std::ffi::OsString::from(".");
1147    sibling.push(name);
1148    sibling.push(".tilo-save");
1149    Some(destination.with_file_name(sibling))
1150}
1151
1152pub fn replace_saved(destination: &Path, bytes: &[u8]) -> std::io::Result<()> {
1153    use std::io::Write as _;
1154    let sibling = save_sibling(destination).ok_or_else(|| {
1155        std::io::Error::new(
1156            std::io::ErrorKind::InvalidInput,
1157            "the destination names no file",
1158        )
1159    })?;
1160    let written = File::create(&sibling)
1161        .and_then(|mut file| file.write_all(bytes).and_then(|()| file.sync_all()))
1162        .and_then(|()| std::fs::rename(&sibling, destination));
1163    if written.is_err() {
1164        let _ = std::fs::remove_file(&sibling);
1165    }
1166    written
1167}
1168
1169#[cfg(unix)]
1170pub fn open_regular_file(path: &Path) -> std::io::Result<File> {
1171    use std::os::unix::fs::OpenOptionsExt;
1172
1173    let file = OpenOptions::new()
1174        .read(true)
1175        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
1176        .open(path)?;
1177    if !file.metadata()?.file_type().is_file() {
1178        return Err(std::io::Error::new(
1179            std::io::ErrorKind::InvalidInput,
1180            "selected path is not a regular file",
1181        ));
1182    }
1183    Ok(file)
1184}
1185
1186#[cfg(windows)]
1187pub fn open_regular_file(path: &Path) -> std::io::Result<File> {
1188    use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
1189    use windows_sys::Win32::Storage::FileSystem::{
1190        FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT,
1191    };
1192    let file = OpenOptions::new()
1193        .read(true)
1194        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
1195        .open(path)?;
1196    let metadata = file.metadata()?;
1197    if !metadata.is_file() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
1198        return Err(std::io::Error::new(
1199            std::io::ErrorKind::InvalidInput,
1200            "selected path is not a regular file",
1201        ));
1202    }
1203    Ok(file)
1204}
1205
1206impl OpenedFile {
1207    #[must_use]
1208    pub fn new(file: File, display_name: impl Into<String>) -> Self {
1209        Self {
1210            file: Some(file),
1211            bytes: None,
1212            display_name: display_name.into(),
1213            reference: None,
1214            commit: None,
1215        }
1216    }
1217
1218    /// A file opened at `path` on a host whose files have paths: the path names it again.
1219    #[must_use]
1220    pub fn at(file: File, path: &Path) -> Self {
1221        Self {
1222            file: Some(file),
1223            bytes: None,
1224            display_name: file_name_of(path),
1225            reference: Some(path.to_path_buf()),
1226            commit: None,
1227        }
1228    }
1229
1230    /// A file a page chose: the bytes it read, named by the name the chooser answered. A page
1231    /// keeps no descriptor, so the bytes are the handle's form.
1232    #[must_use]
1233    pub fn from_bytes(bytes: Vec<u8>, display_name: impl Into<String>, reference: PathBuf) -> Self {
1234        Self {
1235            file: None,
1236            bytes: Some(bytes),
1237            display_name: display_name.into(),
1238            reference: Some(reference),
1239            commit: None,
1240        }
1241    }
1242
1243    /// A file or folder the chooser reopened by its reference, called what the chooser calls it.
1244    #[cfg(any(unix, windows))]
1245    #[must_use]
1246    pub(crate) fn named(file: File, display_name: impl Into<String>, reference: PathBuf) -> Self {
1247        Self {
1248            file: Some(file),
1249            bytes: None,
1250            display_name: display_name.into(),
1251            reference: Some(reference),
1252            commit: None,
1253        }
1254    }
1255
1256    /// What a save commits when its file is finished: renaming the file it writes over the one
1257    /// the person chose, so it is replaced whole or not at all.
1258    #[cfg(any(unix, windows))]
1259    #[must_use]
1260    pub(crate) fn keeping(
1261        file: File,
1262        display_name: impl Into<String>,
1263        reference: PathBuf,
1264        commit: impl FnOnce() + Send + 'static,
1265    ) -> Self {
1266        Self {
1267            file: Some(file),
1268            bytes: None,
1269            display_name: display_name.into(),
1270            reference: Some(reference),
1271            commit: Some(Box::new(commit)),
1272        }
1273    }
1274}
1275
1276/// A chosen file or folder, kept open: what a host hands an app for a file it reads in place.
1277#[derive(Debug)]
1278pub struct ChosenHandle {
1279    file: PickedFile,
1280    reference: PathBuf,
1281    name: String,
1282}
1283
1284impl ChosenHandle {
1285    /// A handle on a file the host keeps open, named by what reopens it.
1286    #[must_use]
1287    pub fn new(file: File, reference: PathBuf, name: impl Into<String>) -> Self {
1288        Self {
1289            file: PickedFile {
1290                file: Some(file),
1291                bytes: None,
1292                commit: None,
1293            },
1294            reference,
1295            name: name.into(),
1296        }
1297    }
1298
1299    /// [`Self::new`] for the file a chooser answered, with what finishes it when it goes.
1300    #[must_use]
1301    pub fn from_picked(file: PickedFile, reference: PathBuf, name: impl Into<String>) -> Self {
1302        Self {
1303            file,
1304            reference,
1305            name: name.into(),
1306        }
1307    }
1308
1309    /// The opened file, or the opened folder. A page has none: its choice is the bytes it read.
1310    #[cfg(not(target_arch = "wasm32"))]
1311    #[must_use]
1312    pub fn file(&self) -> &File {
1313        self.file.as_ref()
1314    }
1315
1316    #[must_use]
1317    pub fn into_file(self) -> PickedFile {
1318        self.file
1319    }
1320
1321    /// What the chooser answers to reopen the same file or folder.
1322    #[must_use]
1323    pub fn reference(&self) -> &Path {
1324        &self.reference
1325    }
1326
1327    #[must_use]
1328    pub fn name(&self) -> &str {
1329        &self.name
1330    }
1331}
1332
1333#[cfg(not(target_arch = "wasm32"))]
1334impl PickedFile {
1335    fn as_ref(&self) -> &File {
1336        self.file()
1337    }
1338}
1339
1340impl PortalOutcome {
1341    pub fn path(&self) -> Option<&Path> {
1342        match self {
1343            PortalOutcome::Opened(p) => Some(p.as_path()),
1344            _ => None,
1345        }
1346    }
1347}
1348
1349#[cfg(test)]
1350mod tests {
1351    use super::*;
1352
1353    fn u(s: &str) -> url::Url {
1354        #[cfg(windows)]
1355        let s = &s
1356            .replace("file:///", "file:///C:/")
1357            .replace("file://localhost/", "file://localhost/C:/");
1358        url::Url::parse(s).unwrap()
1359    }
1360
1361    fn local_path(s: &str) -> PathBuf {
1362        #[cfg(windows)]
1363        return PathBuf::from(format!("C:{s}"));
1364        #[cfg(not(windows))]
1365        PathBuf::from(s)
1366    }
1367
1368    tilo_test_env::scenario! {
1369        fn a_request_records_what_the_app_asked_for_and_an_outcome_what_was_picked;
1370
1371        phase writable_directory_is_explicit_and_preserves_directory_shape;
1372        {
1373            let read = PickRequest::directory("Read folder", "Choose");
1374            let write = PickRequest::writable_directory("Import into folder", "Import here");
1375            assert!(!read.is_writable_directory());
1376            assert!(write.is_writable_directory());
1377            assert!(write.is_directory());
1378            assert!(!write.is_open());
1379            assert!(!write.is_multiple());
1380            assert_eq!(write.suggested_name(), None);
1381            assert_eq!(write.accept_label(), "Import here");
1382        }
1383
1384        phase directory_request_is_single_select_and_has_no_filename;
1385        {
1386            let request = PickRequest::directory("Choose folder", "Choose");
1387            assert!(!request.is_multiple());
1388            assert_eq!(request.suggested_name(), None);
1389            assert!(matches!(request.kind, PickKind::Directory));
1390        }
1391
1392        phase directory_hint_preserves_the_requested_folder_without_granting_it;
1393        {
1394            let home = local_path("/Users/you/Recognized home");
1395            let request =
1396                PickRequest::directory("Allow this folder", "Allow").initial_directory(home.clone());
1397            assert_eq!(request.directory_hint(), Some(home.as_path()));
1398            assert!(request.is_directory());
1399            assert_eq!(request.suggested_name(), None);
1400            assert_eq!(
1401                PickRequest::directory("Choose", "Allow").directory_hint(),
1402                None
1403            );
1404        }
1405
1406        phase launch_request_records_open_and_reveal_without_changing_the_path;
1407        {
1408            let open = LaunchRequest::open("/tmp/archive.zip");
1409            assert_eq!(open.path, Path::new("/tmp/archive.zip"));
1410            assert_eq!(open.kind, LaunchKind::Open);
1411            let reveal = LaunchRequest::reveal("/tmp/archive.zip");
1412            assert_eq!(reveal.path, Path::new("/tmp/archive.zip"));
1413            assert_eq!(reveal.kind, LaunchKind::Reveal);
1414        }
1415
1416        phase outcome_path_accessor_reports_only_a_real_pick;
1417        {
1418            assert_eq!(
1419                PortalOutcome::Opened(PathBuf::from("/tmp/a")).path(),
1420                Some(Path::new("/tmp/a"))
1421            );
1422            assert_eq!(PortalOutcome::Cancelled.path(), None);
1423            assert_eq!(PortalOutcome::Failed("x".into()).path(), None);
1424        }
1425
1426        phase builder_records_the_per_app_delta;
1427        {
1428            let r = PickRequest::open("Insert image", "Insert")
1429                .thread_name("wp-portal-open")
1430                .filter(
1431                    FileFilter::new("Images")
1432                        .glob("*.png")
1433                        .mimetype("image/png"),
1434                )
1435                .all_files();
1436            assert_eq!(r.title(), "Insert image");
1437            assert!(!r.is_multiple());
1438            assert_eq!(r.filters.len(), 2);
1439            assert_eq!(r.filters[0].name(), "Images");
1440            assert_eq!(r.filters[0].globs, ["*.png"]);
1441            assert_eq!(r.filters[0].mimetypes, ["image/png"]);
1442            assert_eq!(
1443                r.filters[1],
1444                FileFilter::all_files(),
1445                "escape hatch is last"
1446            );
1447            assert_eq!(r.thread_name, "wp-portal-open");
1448
1449            assert!(PickRequest::open_multiple("Import contacts", "Import").is_multiple());
1450            let s = PickRequest::save("Export contacts", "Export", "contacts.vcf");
1451            assert!(!s.is_multiple());
1452            assert_eq!(
1453                s.kind,
1454                PickKind::Save {
1455                    suggested_name: "contacts.vcf".into()
1456                }
1457            );
1458        }
1459    }
1460
1461    tilo_test_env::scenario! {
1462        fn a_file_uri_becomes_a_local_path_only_when_it_names_one;
1463
1464        phase rejects_a_uri_that_names_a_remote_host;
1465        {
1466            let uri = u("file://evil-host.example.com/etc/passwd");
1467
1468            assert_eq!(
1469                to_local_path(&uri),
1470                None,
1471                "a foreign host is not a local path"
1472            );
1473            assert!(
1474                matches!(
1475                    map_uri(std::slice::from_ref(&uri)),
1476                    PortalOutcome::Failed(_)
1477                ),
1478                "a foreign-host URI must not become an openable path"
1479            );
1480            assert!(matches!(map_uris(&[uri]), MultiOutcome::Failed(_)));
1481        }
1482
1483        phase a_rejected_host_never_yields_a_relative_path;
1484        {
1485            for s in [
1486                "file://evil-host.example.com/etc/passwd",
1487                "file://192.0.2.1/srv/secret",
1488                "https://example.com/remote.png",
1489                "smb://fileserver/share/doc.odt",
1490            ] {
1491                let out = map_uri(&[u(s)]);
1492                if let PortalOutcome::Opened(p) = &out {
1493                    panic!("{s} was accepted as {p:?}");
1494                }
1495                assert!(matches!(out, PortalOutcome::Failed(_)), "{s} must fail");
1496            }
1497        }
1498
1499        phase localhost_is_the_local_machine;
1500        {
1501            assert_eq!(
1502                map_uri(&[u("file://localhost/home/alice/a.mkv")]),
1503                PortalOutcome::Opened(local_path("/home/alice/a.mkv"))
1504            );
1505        }
1506
1507        phase percent_escapes_in_filenames_are_decoded;
1508        {
1509            assert_eq!(
1510                map_uri(&[u("file:///home/alice/My%20Clip.mp4")]),
1511                PortalOutcome::Opened(local_path("/home/alice/My Clip.mp4"))
1512            );
1513            assert_eq!(
1514                map_uri(&[u("file:///home/alice/%C3%A9t%C3%A9%20caf%C3%A9.mp3")]),
1515                PortalOutcome::Opened(local_path("/home/alice/été café.mp3"))
1516            );
1517            assert_eq!(
1518                map_uri(&[u("file:///home/alice/a%23b%3Fc%25d.txt")]),
1519                PortalOutcome::Opened(local_path("/home/alice/a#b?c%d.txt"))
1520            );
1521        }
1522
1523        phase a_plus_in_a_path_stays_a_plus;
1524        {
1525            assert_eq!(
1526                map_uri(&[u("file:///home/alice/my+song.mp3")]),
1527                PortalOutcome::Opened(local_path("/home/alice/my+song.mp3"))
1528            );
1529        }
1530
1531        phase an_escaped_separator_does_not_become_a_new_path_component;
1532        {
1533            assert_eq!(
1534                to_local_path(&u("file:///home/alice/a%2Fb.txt")),
1535                None,
1536                "an escaped separator must not add a path component"
1537            );
1538            assert!(matches!(
1539                map_uri(&[u("file:///home/alice/a%2Fb.txt")]),
1540                PortalOutcome::Failed(_)
1541            ));
1542        }
1543
1544        phase a_parent_hop_hidden_inside_one_segment_is_rejected;
1545        {
1546            for s in [
1547                "file:///home/alice/%2E%2E%2F%2E%2E%2Fetc/shadow",
1548                "file:///var/workspace/%2E%2E%2Fetc/shadow",
1549            ] {
1550                assert_eq!(to_local_path(&u(s)), None, "{s} must not resolve");
1551                assert!(matches!(map_uri(&[u(s)]), PortalOutcome::Failed(_)), "{s}");
1552            }
1553        }
1554
1555        phase a_dot_dot_segment_is_resolved_by_uri_normalisation_not_smuggled;
1556        {
1557            let uri = u("file:///home/alice/%2E%2E/%2E%2E/etc/shadow");
1558            assert_eq!(
1559                to_local_path(&uri),
1560                Some(local_path("/etc/shadow")),
1561                "the URI normalises on parse"
1562            );
1563            assert_eq!(to_local_path(&uri), Some(local_path("/etc/shadow")));
1564        }
1565
1566        phase ordinary_nested_paths_still_resolve;
1567        {
1568            for (uri, want) in [
1569                ("file:///a.txt", "/a.txt"),
1570                (
1571                    "file:///home/alice/Documents/report.pdf",
1572                    "/home/alice/Documents/report.pdf",
1573                ),
1574                (
1575                    "file:///var/workspace/deep/er/still/x.odp",
1576                    "/var/workspace/deep/er/still/x.odp",
1577                ),
1578                (
1579                    "file:///home/alice/dot.name.with.dots.tar.gz",
1580                    "/home/alice/dot.name.with.dots.tar.gz",
1581                ),
1582            ] {
1583                assert_eq!(
1584                    to_local_path(&u(uri)),
1585                    Some(local_path(want)),
1586                    "{uri} must resolve normally"
1587                );
1588            }
1589        }
1590
1591        phase workspace_paths_resolve_through_the_fuse_mount;
1592        {
1593            assert_eq!(
1594                map_uri(&[u("file:///var/workspace/media/a.mkv")]),
1595                PortalOutcome::Opened(local_path("/var/workspace/media/a.mkv"))
1596            );
1597        }
1598    }
1599
1600    #[cfg(windows)]
1601    #[test]
1602    fn windows_drive_paths_roundtrip_without_accepting_unc_or_escaped_separators() {
1603        let uri = url::Url::parse("file:///C:/Users/Alice/My%20notes.txt").unwrap();
1604        assert_eq!(
1605            to_local_path(&uri),
1606            Some(PathBuf::from("C:/Users/Alice/My notes.txt"))
1607        );
1608        for rejected in [
1609            "file://server/share/notes.txt",
1610            "file:///C:/Users/Alice/a%5Cb.txt",
1611            "file:///C:/Users/Alice/a%2Fb.txt",
1612            "file:///Users/Alice/notes.txt",
1613        ] {
1614            assert_eq!(
1615                to_local_path(&url::Url::parse(rejected).unwrap()),
1616                None,
1617                "{rejected}"
1618            );
1619        }
1620    }
1621
1622    tilo_test_env::scenario! {
1623        fn a_selection_maps_to_the_local_files_it_names;
1624
1625        phase empty_is_cancel;
1626        {
1627            assert_eq!(map_uri(&[]), PortalOutcome::Cancelled);
1628            assert_eq!(map_uris(&[]), MultiOutcome::Cancelled);
1629        }
1630
1631        phase single_takes_the_first_local_file;
1632        {
1633            let uris = [
1634                u("file:///home/alice/photo.png"),
1635                u("file:///home/alice/other.png"),
1636            ];
1637            assert_eq!(
1638                map_uri(&uris),
1639                PortalOutcome::Opened(local_path("/home/alice/photo.png"))
1640            );
1641        }
1642
1643        phase multi_collects_every_local_file;
1644        {
1645            let uris = [
1646                u("file:///home/alice/work.vcf"),
1647                u("file:///home/alice/family.vcard"),
1648            ];
1649            assert_eq!(
1650                map_uris(&uris),
1651                MultiOutcome::Selected(vec![
1652                    local_path("/home/alice/work.vcf"),
1653                    local_path("/home/alice/family.vcard"),
1654                ])
1655            );
1656        }
1657
1658        phase multi_skips_remote_but_keeps_local;
1659        {
1660            let uris = [
1661                u("https://example.com/remote.vcf"),
1662                u("file:///home/alice/local.vcf"),
1663            ];
1664            assert_eq!(
1665                map_uris(&uris),
1666                MultiOutcome::Selected(vec![local_path("/home/alice/local.vcf")]),
1667                "a mixed multi-selection keeps the files the user can actually read"
1668            );
1669        }
1670
1671        phase multi_all_remote_is_failure;
1672        {
1673            assert!(matches!(
1674                map_uris(&[
1675                    u("https://example.com/a.vcf"),
1676                    u("https://example.com/b.vcf")
1677                ]),
1678                MultiOutcome::Failed(_)
1679            ));
1680        }
1681    }
1682
1683    tilo_test_env::scenario! {
1684        #[cfg(any(target_os = "linux", target_os = "macos", windows))]
1685        fn descriptor_open_holds_the_file_it_opened_and_refuses_a_directory;
1686
1687        phase descriptor_open_retains_the_opened_file_and_a_separate_display_name;
1688        {
1689            use std::io::{Read, Write};
1690
1691            let dir = tempfile::tempdir().unwrap();
1692            let path = dir.path().join("original-installer.msi");
1693            let mut source = File::create(&path).unwrap();
1694            source.write_all(b"installer bytes").unwrap();
1695            source.flush().unwrap();
1696            let uri = url::Url::from_file_path(&path).unwrap();
1697
1698            let opened = match open_selected_uri(&uri) {
1699                OpenFileOutcome::Opened(opened) => opened,
1700                OpenFileOutcome::Cancelled | OpenFileOutcome::Failed(_) => {
1701                    panic!("regular temporary file must open")
1702                }
1703            };
1704            assert_eq!(opened.display_name(), "original-installer.msi");
1705            std::fs::remove_file(&path).unwrap();
1706            std::fs::write(&path, b"replacement bytes").unwrap();
1707            let mut contents = String::new();
1708            let mut file = opened.into_file();
1709            file.read_to_string(&mut contents).unwrap();
1710            assert_eq!(contents, "installer bytes");
1711        }
1712
1713        phase descriptor_open_refuses_a_non_regular_file;
1714        {
1715            let dir = tempfile::tempdir().unwrap();
1716            let uri = url::Url::from_file_path(dir.path()).unwrap();
1717
1718            assert!(matches!(
1719                open_selected_uri(&uri),
1720                OpenFileOutcome::Failed(_)
1721            ));
1722        }
1723    }
1724
1725    #[cfg(unix)]
1726    #[test]
1727    fn descriptor_open_refuses_a_symlink() {
1728        use std::os::unix::fs::symlink;
1729
1730        let dir = tempfile::tempdir().unwrap();
1731        let target = dir.path().join("installer.exe");
1732        std::fs::write(&target, b"installer bytes").unwrap();
1733        let link = dir.path().join("selected.exe");
1734        symlink(&target, &link).unwrap();
1735        let uri = url::Url::from_file_path(&link).unwrap();
1736
1737        assert!(matches!(
1738            open_selected_uri(&uri),
1739            OpenFileOutcome::Failed(_)
1740        ));
1741    }
1742}
1743#[cfg(any(test, feature = "test-support"))]
1744type ScopedPickerBackend = std::sync::Arc<dyn Fn(PickRequest) -> PortalOutcome + Send + Sync>;
1745#[cfg(any(test, feature = "test-support"))]
1746thread_local! {
1747    static SCOPED_PICKER_FIXTURE: std::cell::RefCell<Option<ScopedPickerBackend>> = const { std::cell::RefCell::new(None) };
1748}
1749#[cfg(any(test, feature = "test-support"))]
1750pub struct ScopedPickerFixture {
1751    _owner_thread: std::marker::PhantomData<std::rc::Rc<()>>,
1752}
1753#[cfg(any(test, feature = "test-support"))]
1754pub fn scoped_picker_fixture(backend: ScopedPickerBackend) -> Result<ScopedPickerFixture, String> {
1755    SCOPED_PICKER_FIXTURE.with(|current| {
1756        let mut current = current.borrow_mut();
1757        if current.is_some() {
1758            return Err("this UI thread already owns a picker fixture".into());
1759        }
1760        *current = Some(backend);
1761        Ok(ScopedPickerFixture {
1762            _owner_thread: std::marker::PhantomData,
1763        })
1764    })
1765}
1766#[cfg(any(test, feature = "test-support"))]
1767fn scoped_picker_fixture_backend() -> Option<ScopedPickerBackend> {
1768    SCOPED_PICKER_FIXTURE.with(|current| current.borrow().clone())
1769}
1770#[cfg(any(test, feature = "test-support"))]
1771impl Drop for ScopedPickerFixture {
1772    fn drop(&mut self) {
1773        SCOPED_PICKER_FIXTURE.with(|current| *current.borrow_mut() = None);
1774    }
1775}