Skip to main content

tilo_dialogs/portal/
destination.rs

1//! Saving where the person chooses, chosen now and written later: for an app
2//! that has to produce the bytes after the choice (an export it renders, a
3//! document a worker flattens). The choice is made inside the person's
4//! gesture; the write follows whenever the bytes are ready. On the web the
5//! destination is the browser's own Save dialog where it has one, else a
6//! download; elsewhere it is the path the host chooser answered. The app
7//! writes through the SDK's save path either way, and can keep the
8//! destination to write there again on the next Save without asking.
9
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use std::sync::mpsc::{Receiver, RecvError, TryRecvError};
13
14use super::{PortalChannel, PortalOutcome, SaveChannel, SaveOutcome};
15
16#[derive(Clone)]
17pub struct SaveDestination {
18    name: String,
19    target: Target,
20    /// What reopens the same file later (a documents-store reference), when the host names one.
21    reference: Option<PathBuf>,
22}
23
24type Writer = Arc<dyn Fn(Vec<u8>) -> SaveChannel + Send + Sync>;
25
26#[derive(Clone)]
27enum Target {
28    Path(PathBuf),
29    Kept(Writer),
30}
31
32impl std::fmt::Debug for SaveDestination {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        let target = match &self.target {
35            Target::Path(path) => format!("{}", path.display()),
36            Target::Kept(_) => "kept by the host".to_owned(),
37        };
38        f.debug_struct("SaveDestination")
39            .field("name", &self.name)
40            .field("target", &target)
41            .field("reference", &self.reference)
42            .finish()
43    }
44}
45
46impl SaveDestination {
47    pub fn at(path: impl Into<PathBuf>) -> Self {
48        let path = path.into();
49        Self {
50            name: super::file_name_of(&path),
51            target: Target::Path(path),
52            reference: None,
53        }
54    }
55
56    /// A destination the host keeps and the app cannot reach by path, named
57    /// `name`: [`write`](Self::write) hands the bytes to `write`, once per
58    /// save.
59    pub fn kept(
60        name: impl Into<String>,
61        write: impl Fn(Vec<u8>) -> SaveChannel + Send + Sync + 'static,
62    ) -> Self {
63        Self {
64            name: name.into(),
65            target: Target::Kept(Arc::new(write)),
66            reference: None,
67        }
68    }
69
70    /// A destination the host keeps and names by `reference`: the same place reopened for every
71    /// later Save, and what the window shows from then on.
72    pub fn kept_at(
73        name: impl Into<String>,
74        reference: PathBuf,
75        write: impl Fn(Vec<u8>) -> SaveChannel + Send + Sync + 'static,
76    ) -> Self {
77        Self {
78            name: name.into(),
79            target: Target::Kept(Arc::new(write)),
80            reference: Some(reference),
81        }
82    }
83
84    pub fn name(&self) -> &str {
85        &self.name
86    }
87
88    /// Where the saved file is on this device, when it has a path: to save
89    /// there again in place, never for showing. `None` on the web.
90    pub fn location(&self) -> Option<&Path> {
91        match &self.target {
92            Target::Path(path) => Some(path),
93            Target::Kept(_) => None,
94        }
95    }
96
97    /// What names the saved file on a host whose files have no path: the documents-store
98    /// reference the chooser answers to reopen it. `None` where [`Self::location`] has one.
99    pub fn reference(&self) -> Option<&Path> {
100        self.reference.as_deref()
101    }
102
103    /// The SDK's save path only: an app writes through `EffectCx::write_destination`,
104    /// whose job waits for the write.
105    #[doc(hidden)]
106    pub fn write(&self, bytes: Vec<u8>) -> SaveChannel {
107        match &self.target {
108            Target::Path(path) => write_path(path.clone(), bytes),
109            Target::Kept(write) => write(bytes),
110        }
111    }
112}
113
114fn answered<T>(outcome: T) -> Receiver<T> {
115    let (tx, rx) = std::sync::mpsc::channel();
116    let _ = tx.send(outcome);
117    rx
118}
119
120fn write_path(path: PathBuf, bytes: Vec<u8>) -> SaveChannel {
121    let (tx, rx) = std::sync::mpsc::channel();
122    let refused = tx.clone();
123    let spawned =
124        tilo_rt::background::Background::current().spawn("tilo-portal-write", move || {
125            let _ = tx.send(match super::replace_saved(&path, &bytes) {
126                Ok(()) => SaveOutcome::Saved,
127                Err(error) => SaveOutcome::Failed(format!("{}: {error}", path.display())),
128            });
129        });
130    if spawned.is_err() {
131        let _ = refused.send(SaveOutcome::Failed(
132            "this host runs no background work".to_owned(),
133        ));
134    }
135    rx
136}
137
138#[derive(Debug)]
139pub enum DestinationOutcome {
140    Chosen(SaveDestination),
141    Cancelled,
142    Failed(String),
143}
144
145#[derive(Debug)]
146pub struct DestinationChannel(Pending);
147
148#[derive(Debug)]
149enum Pending {
150    Path(PortalChannel),
151    Direct(Receiver<DestinationOutcome>),
152}
153
154impl DestinationChannel {
155    pub fn from_path(channel: PortalChannel) -> Self {
156        Self(Pending::Path(channel))
157    }
158
159    pub fn from_outcomes(channel: Receiver<DestinationOutcome>) -> Self {
160        Self(Pending::Direct(channel))
161    }
162
163    pub fn answered(outcome: DestinationOutcome) -> Self {
164        Self::from_outcomes(answered(outcome))
165    }
166
167    pub fn try_recv(&self) -> Result<DestinationOutcome, TryRecvError> {
168        match &self.0 {
169            Pending::Path(channel) => channel.try_recv().map(from_path),
170            Pending::Direct(channel) => channel.try_recv(),
171        }
172    }
173
174    /// Wait for the outcome. Only for tests and worker threads.
175    ///
176    /// # Errors
177    ///
178    /// The chooser went away without answering.
179    pub fn recv(&self) -> Result<DestinationOutcome, RecvError> {
180        match &self.0 {
181            Pending::Path(channel) => channel.recv().map(from_path),
182            Pending::Direct(channel) => channel.recv(),
183        }
184    }
185}
186
187fn from_path(outcome: PortalOutcome) -> DestinationOutcome {
188    match outcome {
189        PortalOutcome::Opened(path) => DestinationOutcome::Chosen(SaveDestination::at(path)),
190        PortalOutcome::Cancelled => DestinationOutcome::Cancelled,
191        PortalOutcome::Failed(reason) => DestinationOutcome::Failed(reason),
192    }
193}
194
195#[cfg(all(test, not(target_arch = "wasm32")))]
196mod tests {
197    use super::*;
198
199    tilo_test_env::scenario! {
200        fn a_save_destination_is_a_chosen_path_or_the_hosts_keeping_or_nothing;
201
202        phase a_chosen_path_is_written_in_place_and_named_by_its_file;
203        {
204            let dir = std::env::temp_dir().join(format!("tilo-dest-{}", std::process::id()));
205            std::fs::create_dir_all(&dir).unwrap();
206            let path = dir.join("report.pdf");
207            let (tx, rx) = std::sync::mpsc::channel();
208            tx.send(PortalOutcome::Opened(path.clone())).unwrap();
209            let DestinationOutcome::Chosen(destination) =
210                DestinationChannel::from_path(rx).try_recv().unwrap()
211            else {
212                panic!("a path was chosen");
213            };
214            assert_eq!(destination.name(), "report.pdf");
215            assert_eq!(destination.location(), Some(path.as_path()));
216            let work = tilo_rt::background::Pumped::new();
217            let _work = work.background().enter();
218            let saved = destination.write(b"%PDF".to_vec());
219            work.run_pending();
220            assert_eq!(saved.recv().unwrap(), SaveOutcome::Saved);
221            assert_eq!(std::fs::read(&path).unwrap(), b"%PDF");
222            std::fs::remove_dir_all(dir).unwrap();
223        }
224
225        phase a_kept_destination_hands_its_bytes_to_the_host;
226        {
227            let written = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
228            let into = std::sync::Arc::clone(&written);
229            let destination = SaveDestination::kept("notes.pdf", move |bytes| {
230                into.lock().unwrap().extend(bytes);
231                answered(SaveOutcome::Saved)
232            });
233            assert_eq!(destination.name(), "notes.pdf");
234            assert_eq!(destination.location(), None, "no path to save in place");
235            assert_eq!(
236                destination.write(b"%PDF".to_vec()).recv().unwrap(),
237                SaveOutcome::Saved
238            );
239            assert_eq!(*written.lock().unwrap(), b"%PDF");
240            assert_eq!(
241                destination.write(b"!".to_vec()).recv().unwrap(),
242                SaveOutcome::Saved,
243                "a kept destination takes the next save too"
244            );
245            assert_eq!(*written.lock().unwrap(), b"%PDF!");
246        }
247
248        phase cancelling_or_failing_the_chooser_chooses_nothing;
249        {
250            for (outcome, cancelled) in [
251                (PortalOutcome::Cancelled, true),
252                (PortalOutcome::Failed("gone".into()), false),
253            ] {
254                let (tx, rx) = std::sync::mpsc::channel();
255                tx.send(outcome).unwrap();
256                match DestinationChannel::from_path(rx).recv().unwrap() {
257                    DestinationOutcome::Cancelled => assert!(cancelled),
258                    DestinationOutcome::Failed(reason) => assert_eq!(reason, "gone"),
259                    DestinationOutcome::Chosen(_) => panic!("nothing was chosen"),
260                }
261            }
262        }
263    }
264}